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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/api/block/CommonBlockTypes.kt | 1 | 1254 | package com.fracturedskies.api.block
import com.fracturedskies.api.MAX_LIGHT_LEVEL
import com.fracturedskies.api.block.model.*
import com.fracturedskies.api.entity.*
import com.fracturedskies.engine.math.Color4
object BlockTypeAir : BlockType() {
override val model = NoopBlockModel
override val opaque = false
}
object BlockTypeDirt: BlockType() {
override val model = ColorBlockModel(Color4(178, 161, 130, 255))
override val itemDrop = ItemDirt
}
object BlockTypeGrass: BlockType() {
override val model = ColorBlockModel(Color4.GREEN)
override val itemDrop = ItemDirt
}
object BlockTypeWood: BlockType() {
override val model = ColorBlockModel(Color4.DARK_BROWN)
override val itemDrop = ItemWood
}
object BlockTypeLeaves: BlockType() {
override val model = ColorBlockModel(Color4.DARK_GREEN)
}
object BlockTypeStone: BlockType() {
override val model = ColorBlockModel(Color4.GRAY)
override val itemDrop = ItemStone
}
object BlockTypeLight: BlockType() {
override val model = ColorBlockModel(Color4.WHITE)
override val light: Int = MAX_LIGHT_LEVEL + 1
override val itemDrop = ItemLight
}
class ColorBlockType(private val color: Color4): BlockType() {
override val model: BlockModel get() = ColorBlockModel(color)
} | unlicense | db6927f358667dd16d85ad41a49d2be4 | 26.282609 | 66 | 0.76874 | 3.858462 | false | false | false | false |
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/crypto/CaPublicKeyTable.kt | 1 | 832 | package io.github.binaryfoo.crypto
import io.github.binaryfoo.res.ClasspathIO
/**
* Table of trust anchors.
*
* From https://www.eftlab.co.uk/index.php/site-map/knowledge-base/243-ca-public-keys
*/
class CaPublicKeyTable {
companion object {
val keys: List<CaPublicKey> = ClasspathIO.readLines("ca-public-keys.txt").map { line ->
try {
val fields = line.split(Regex("\\t"))
val exponent = fields[1]
val index = fields[2]
val rid = fields[3]
val modulus = fields[4]
CaPublicKey(rid, index, exponent, modulus)
} catch (e: Exception) {
throw RuntimeException("Failed reading CA public key: $line", e)
}
}
@JvmStatic
fun getEntry(aid: String, index: String): CaPublicKey? = keys.firstOrNull { it.rid == aid && it.index == index }
}
}
| mit | 82b72bc6308790f85c604c2fe7e8e67f | 27.689655 | 116 | 0.632212 | 3.570815 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/PaintingEntityProtocol.kt | 1 | 3187 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.entity.vanilla
import org.lanternpowered.api.data.Keys
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.EntityProtocolUpdateContext
import org.lanternpowered.server.network.entity.parameter.ParameterList
import org.lanternpowered.server.network.value.PackedAngle
import org.lanternpowered.server.network.vanilla.packet.type.play.EntityTeleportPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.SpawnPaintingPacket
import org.spongepowered.api.data.type.ArtType
import org.spongepowered.api.data.type.ArtTypes
import org.spongepowered.api.util.Direction
import org.spongepowered.math.vector.Vector3i
class PaintingEntityProtocol<E : LanternEntity>(entity: E) : EntityProtocol<E>(entity) {
private var lastArt: ArtType? = null
private var lastDirection: Direction? = null
private var lastBlockPos: Vector3i? = null
// We can only support cardinal directions, up and down are also
// not supported but they will also default to facing south
private val direction: Direction
get() {
val direction = this.entity.get(Keys.DIRECTION).orElse(Direction.SOUTH)
// We can only support cardinal directions, up and down are also
// not supported but they will also default to facing south
return if (!direction.isCardinal) {
Direction.getClosest(direction.asOffset(), Direction.Division.CARDINAL)
} else direction
}
private val art: ArtType
get() = this.entity.get(Keys.ART_TYPE).orElseGet(ArtTypes.KEBAB)
override fun spawn(context: EntityProtocolUpdateContext) {
this.spawn(context, this.art, this.direction, this.entity.position.toInt())
}
private fun spawn(context: EntityProtocolUpdateContext, art: ArtType, direction: Direction, position: Vector3i) {
context.sendToAll { SpawnPaintingPacket(this.rootEntityId, this.entity.uniqueId, art, position, direction) }
}
public override fun update(context: EntityProtocolUpdateContext) {
val art: ArtType = this.art
val direction = this.direction
val pos = this.entity.position
val blockPos = pos.toInt()
if (art != this.lastArt || direction != this.lastDirection) {
this.spawn(context, art, direction, blockPos)
this.lastDirection = direction
this.lastBlockPos = blockPos
this.lastArt = art
} else if (blockPos != this.lastBlockPos) {
context.sendToAll { EntityTeleportPacket(this.rootEntityId, pos, PackedAngle.Zero, PackedAngle.Zero, true) }
this.lastBlockPos = blockPos
}
}
public override fun spawn(parameterList: ParameterList) {}
public override fun update(parameterList: ParameterList) {}
}
| mit | 958e67029ca102825b56f3ba8f498ac0 | 43.263889 | 120 | 0.719485 | 4.238032 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/main/kotlin/com/google/api/kotlin/generator/grpc/Documentation.kt | 1 | 8643 | /*
* Copyright 2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.generator.grpc
import com.google.api.kotlin.GeneratorContext
import com.google.api.kotlin.config.FlattenedMethod
import com.google.api.kotlin.config.MethodOptions
import com.google.api.kotlin.config.SampleMethod
import com.google.api.kotlin.types.isNotProtobufEmpty
import com.google.api.kotlin.util.FieldNamer
import com.google.api.kotlin.util.ParameterInfo
import com.google.api.kotlin.util.RequestObject.getBuilder
import com.google.api.kotlin.util.formatSample
import com.google.api.kotlin.util.getMethodComments
import com.google.api.kotlin.util.getParameterComments
import com.google.api.kotlin.util.getProtoFieldInfoForPath
import com.google.api.kotlin.util.isMessageType
import com.google.api.kotlin.wrap
import com.google.protobuf.DescriptorProtos
import com.squareup.kotlinpoet.CodeBlock
/** Generates the KDoc documentation. */
internal interface Documentation {
fun generateClassKDoc(context: GeneratorContext): CodeBlock
fun generateMethodKDoc(
context: GeneratorContext,
method: DescriptorProtos.MethodDescriptorProto,
methodOptions: MethodOptions,
parameters: List<ParameterInfo> = listOf(),
flatteningConfig: FlattenedMethod? = null,
extras: List<CodeBlock> = listOf()
): CodeBlock
fun getClientInitializer(context: GeneratorContext, variableName: String = "client"): CodeBlock
}
internal class DocumentationImpl : Documentation {
override fun generateClassKDoc(context: GeneratorContext): CodeBlock {
val doc = CodeBlock.builder()
val m = context.metadata
// add primary (summary) section
doc.add(
"""
|%L
|
|%L
|
|[Product Documentation](%L)
|""".trimMargin(),
m.branding.name, m.branding.summary.wrap(), m.branding.url
)
// TODO: add other sections (quick start, etc.)
return doc.build()
}
// create method comments from proto comments
override fun generateMethodKDoc(
context: GeneratorContext,
method: DescriptorProtos.MethodDescriptorProto,
methodOptions: MethodOptions,
parameters: List<ParameterInfo>,
flatteningConfig: FlattenedMethod?,
extras: List<CodeBlock>
): CodeBlock {
val doc = CodeBlock.builder()
// remove the spacing from proto files
fun cleanupComment(text: String?) = text
?.replace("\\n\\s".toRegex(), "\n")
?.replace("/*", "/ *")
?.replace("*/", "* /")
?.trim()
// add proto comments
val text = context.proto.getMethodComments(context.service, method)
doc.add("%L\n\n", cleanupComment(text) ?: "")
// add any samples
if (methodOptions.samples.isEmpty()) {
doc.add(generateMethodSample(context, method, methodOptions, flatteningConfig))
} else {
for (sample in methodOptions.samples) {
doc.add(generateMethodSample(context, method, methodOptions, flatteningConfig, sample))
}
}
// add parameter comments
val paramComments = flatteningConfig?.parameters?.asSequence()?.mapIndexed { idx, path ->
val fieldInfo = getProtoFieldInfoForPath(
context, path, context.typeMap.getProtoTypeDescriptor(method.inputType)
)
val comment = fieldInfo.file.getParameterComments(fieldInfo)
Pair(parameters[idx].spec.name, cleanupComment(comment))
}?.filter { it.second != null }?.toList() ?: listOf()
paramComments.forEach { doc.add("\n@param %L %L\n", it.first, it.second) }
// add any extra comments at the bottom (only used for the pageSize currently)
extras.forEach { doc.add("\n%L\n", it) }
// put it all together
return doc.build()
}
// get code for instantiating a client
override fun getClientInitializer(context: GeneratorContext, variableName: String): CodeBlock {
val initMethod = if (context.commandLineOptions.authGoogleCloud) {
"fromServiceAccount(YOUR_KEY_FILE)"
} else {
"create()"
}
return CodeBlock.of(
"val %L = %L.%L",
variableName, context.className.simpleName, initMethod
)
}
private fun generateMethodSample(
context: GeneratorContext,
method: DescriptorProtos.MethodDescriptorProto,
methodOptions: MethodOptions,
flatteningConfig: FlattenedMethod?,
sample: SampleMethod? = null
): CodeBlock {
val name = methodOptions.name.decapitalize()
val call = CodeBlock.builder()
// create client
call.addStatement("%L", getClientInitializer(context))
// create inputs
val inputType = context.typeMap.getProtoTypeDescriptor(method.inputType)
val invokeClientParams = if (flatteningConfig != null) {
flatteningConfig.parameters.map { p ->
val type = getProtoFieldInfoForPath(context, p, inputType)
if (type.field.isMessageType()) {
getBuilder(
context, type.message, type.kotlinType, listOf(p.last), sample
).builder
} else {
val exampleValue = sample?.parameters?.find { it.parameterPath == p.toString() }?.value
CodeBlock.of("%L", exampleValue ?: FieldNamer.getNestedFieldName(p))
}
}
} else {
val inputKotlinType = context.typeMap.getKotlinType(method.inputType)
if (inputKotlinType.isNotProtobufEmpty()) {
listOf(getBuilder(context, inputType, inputKotlinType, listOf(), sample).builder)
} else {
listOf()
}
}
// fix indentation (can we make the formatter fix this somehow?)
val indentedParams = invokeClientParams.map { indentBuilder(context, it, 1) }
// invoke method
if (methodOptions.pagedResponse != null) {
call.add(
"""
|val pager = client.%N(
| ${invokeClientParams.joinToString(",\n ") { "%L" }}
|)
|val page = pager.next()
""".trimMargin(),
name,
*indentedParams.toTypedArray()
)
} else if (indentedParams.isEmpty()) {
call.add(
"""
|val result = client.%N()
""".trimMargin(),
name
)
} else {
call.add(
"""
|val result = client.%N(
| ${invokeClientParams.joinToString(",\n ") { "%L" }}
|)
""".trimMargin(),
name,
*indentedParams.toTypedArray()
)
}
// wrap the sample in KDoc
return CodeBlock.of(
"""
|For example:
|```
|%L
|```
|""".trimMargin(),
call.build().formatSample()
)
}
/**
* Kotlin Poet doesn't handle indented code within Kdoc well so we use this to
* correct the indentations for sample code. It would be nice to find an alternative.
*/
private fun indentBuilder(context: GeneratorContext, code: CodeBlock, level: Int): CodeBlock {
val indent = " ".repeat(level * 4)
// we will get the fully qualified names when turning the code block into a string
val specialPackages = "(${context.className.packageName}|com.google.api)"
// remove fully qualified names and adjust indent
val formatted = code.toString()
.replace("\n", "\n$indent")
.replace("^[ ]*$specialPackages\\.".toRegex(), "")
.replace(" = $specialPackages\\.".toRegex(), " = ")
return CodeBlock.of("%L", formatted)
}
}
| apache-2.0 | a5d089c9111c17efa75ee88c97bff88c | 35.778723 | 107 | 0.600486 | 4.793677 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/features/payment_result/mappers/PaymentResultRemediesModelMapper.kt | 1 | 1655 | package com.mercadopago.android.px.internal.features.payment_result.mappers
import com.mercadopago.android.px.internal.features.payment_result.remedies.RemediesModel
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.CvvRemedy
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.HighRiskRemedy
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.RetryPaymentFragment
import com.mercadopago.android.px.internal.viewmodel.mappers.Mapper
import com.mercadopago.android.px.model.internal.remedies.CvvRemedyResponse
import com.mercadopago.android.px.model.internal.remedies.RemediesResponse
internal object PaymentResultRemediesModelMapper : Mapper<RemediesResponse, RemediesModel>() {
override fun map(response: RemediesResponse): RemediesModel {
var title = ""
val retryPaymentModel = response.suggestedPaymentMethod?.let {
title = it.title
RetryPaymentFragment.Model(response.cvv?.run { message } ?: it.message, true, getCvvModel(response.cvv))
} ?: response.cvv?.let {
title = it.title
RetryPaymentFragment.Model(it.message, false, getCvvModel(it))
}
val highRiskModel = response.highRisk?.let {
title = it.title
HighRiskRemedy.Model(it.title, it.message, it.deepLink)
}
return RemediesModel(title, retryPaymentModel, highRiskModel, response.trackingData)
}
private fun getCvvModel(cvvResponse: CvvRemedyResponse?) =
cvvResponse?.fieldSetting?.run {
CvvRemedy.Model(hintMessage, title, length)
}
} | mit | 8a05a031547f84c6f22409c99d436c5c | 50.75 | 116 | 0.743807 | 4.168766 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/api/v2alpha/EventGroupMetadataParser.kt | 1 | 3457 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.api.v2alpha
import com.google.protobuf.DescriptorProtos.FileDescriptorProto
import com.google.protobuf.Descriptors.FileDescriptor
import com.google.protobuf.DynamicMessage
import com.google.protobuf.TypeRegistry
import org.wfanet.measurement.api.v2alpha.EventGroup.Metadata
class EventGroupMetadataParser(eventGroupMetadataDescriptors: List<EventGroupMetadataDescriptor>) {
private val typeRegistry: TypeRegistry
init {
val registryBuilder: TypeRegistry.Builder = TypeRegistry.newBuilder()
eventGroupMetadataDescriptors
.flatMap { buildFileDescriptors(it) }
.flatMap { it.messageTypes }
.forEach { registryBuilder.add(it) }
typeRegistry = registryBuilder.build()
}
private fun buildFileDescriptors(
eventGroupMetadataDescriptor: EventGroupMetadataDescriptor
): List<FileDescriptor> {
val fileList: List<FileDescriptorProto> = eventGroupMetadataDescriptor.descriptorSet.fileList
val fileDescriptorProtoMap = fileList.associateBy { it.name }
val fileDescriptorList: MutableList<FileDescriptor> = mutableListOf()
val builtFileDescriptorMap: MutableMap<String, FileDescriptor> = mutableMapOf()
for (proto in fileList) {
fileDescriptorList.add(
buildFileDescriptors(
proto = proto,
builtFileDescriptorMap = builtFileDescriptorMap,
fileDescriptorProtoMap = fileDescriptorProtoMap
)
)
}
return fileDescriptorList
}
private fun buildFileDescriptors(
proto: FileDescriptorProto,
builtFileDescriptorMap: MutableMap<String, FileDescriptor>,
fileDescriptorProtoMap: Map<String, FileDescriptorProto>
): FileDescriptor {
if (proto.name in builtFileDescriptorMap) return builtFileDescriptorMap.getValue(proto.name)
var dependenciesList: MutableList<FileDescriptor> = mutableListOf()
for (dependencyName in proto.dependencyList) {
if (dependencyName in builtFileDescriptorMap) {
dependenciesList.add(builtFileDescriptorMap.getValue(dependencyName))
} else {
dependenciesList.add(
buildFileDescriptors(
fileDescriptorProtoMap.getValue(dependencyName),
builtFileDescriptorMap,
fileDescriptorProtoMap
)
)
}
}
val builtDescriptor = FileDescriptor.buildFrom(proto, dependenciesList.toTypedArray())
builtFileDescriptorMap[proto.name] = builtDescriptor
return builtDescriptor
}
/** Returns the [DynamicMessage] from an [EventGroup.Metadata] message. */
fun convertToDynamicMessage(eventGroupMetadata: EventGroup.Metadata): DynamicMessage? {
val descriptor =
typeRegistry.getDescriptorForTypeUrl(eventGroupMetadata.metadata.typeUrl) ?: return null
return DynamicMessage.parseFrom(descriptor, eventGroupMetadata.metadata.value)
}
}
| apache-2.0 | 134dc0796f476c12cc59c8cf5b14ed2b | 38.284091 | 99 | 0.75499 | 4.917496 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RNotification.kt | 1 | 1654 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
/**
* create Notification Channel for Android Oreo and above.
* every options is optional, if you doesn't matter whatever value,
* leave them no parameters.
*
* @param[id] channel id, if this value is not present, it will be package name
* @param[name] channel name, if this value is not present, it will be app name
* @param[description] channel description, if this value is not present, it will be app name
* @param[importance] importance of channel, if this value is not present, it will be IMPORTANCE_LOW
* @return generated channel id
*/
@RequiresApi(Build.VERSION_CODES.O)
@JvmOverloads
fun Context.createNotificationChannel(id: String = "", name: String = "", description: String = "", importance: Int = NotificationManager.IMPORTANCE_HIGH): String {
if (Build.VERSION.SDK_INT < 26) {
return ""
}
val newId = id.isEmptyOrReturn(this.packageName)
val appName = if (applicationInfo.labelRes != 0) getString(applicationInfo.labelRes) else applicationInfo.nonLocalizedLabel.toString()
val newName = name.isEmptyOrReturn(appName)
val newDescription = description.isEmptyOrReturn(appName)
val notificationManager = this.notificationManager
val mChannel = NotificationChannel(newId, newName, importance)
mChannel.description = newDescription
notificationManager.createNotificationChannel(mChannel)
return newId
} | apache-2.0 | b8a80de5db3122d6ce32414641c9b18c | 39.365854 | 164 | 0.766626 | 4.47027 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/editor/folding/LatexImportFoldingBuilder.kt | 1 | 3229 | package nl.hannahsten.texifyidea.editor.folding
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilderEx
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexNoMathContent
import nl.hannahsten.texifyidea.util.allCommands
import nl.hannahsten.texifyidea.util.firstChildOfType
import nl.hannahsten.texifyidea.util.magic.PatternMagic
import nl.hannahsten.texifyidea.util.parentOfType
/**
* Folds multiple \\usepackage or \\RequirePackage statements.
* This is not DumbAware.
*
* @author Hannah Schellekens
*/
open class LatexImportFoldingBuilder : FoldingBuilderEx() {
companion object {
private val includesSet = setOf("\\usepackage", "\\RequirePackage")
private val includesArray = includesSet.toTypedArray()
}
override fun isCollapsedByDefault(node: ASTNode) = true
override fun getPlaceholderText(node: ASTNode) = if (node.text.contains("RequirePackage")) "\\RequirePackage{...}" else "\\usepackage{...}"
override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> {
val descriptors = ArrayList<FoldingDescriptor>()
val covered = HashSet<LatexCommands>()
val commands = root.allCommands().filter { it.name in includesArray }
for (command in commands) {
// Do not cover commands twice.
if (command in covered) {
continue
}
// Iterate over all consecutive commands.
var next: LatexCommands? = command
var last: LatexCommands = command
while (next != null && next.name in includesSet) {
covered += next
last = next
next = next.nextCommand()
}
descriptors.add(FoldingDescriptor(command, TextRange(command.startOffset, last.endOffset)))
}
return descriptors.toTypedArray()
}
private fun PsiElement.nextCommand(): LatexCommands? {
val content = if (this is LatexCommands) {
parentOfType(LatexNoMathContent::class) ?: return null
}
else this
val next = content.nextSibling
// When having multiple breaks, don't find new commands to fold.
// When whitespace without multiple breaks, look further.
if (next is PsiWhiteSpace) {
return if (PatternMagic.containsMultipleNewlines.matcher(next.text).matches()) {
null
}
else next.nextCommand()
}
// No next? Then there is no valid next command. This happens e.g. when it's the last element of the file.
next ?: return null
// Skip comments.
if (next is PsiComment) {
return next.nextCommand()
}
return next.firstChildOfType(LatexCommands::class)
}
} | mit | a4a2d40387b6513fe259f3adb2dfc659 | 34.888889 | 143 | 0.677919 | 4.892424 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/service/UserPreferenceSettingService.kt | 2 | 2727 | package org.worshipsongs.service
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import org.worshipsongs.CommonConstants
import org.worshipsongs.WorshipSongApplication
/**
* Author: Seenivasan
* Version: 1.0.0
*/
class UserPreferenceSettingService
{
private val context = WorshipSongApplication.context
private var sharedPreferences: SharedPreferences? = null
val portraitFontSize: Float
get() = sharedPreferences!!.getInt(CommonConstants.PRIMARY_FONT_SIZE_KEY, 18).toFloat()
val landScapeFontSize: Float
get() = sharedPreferences!!.getInt(CommonConstants.PRESENTATION_FONT_SIZE_KEY, 25).toFloat()
val primaryColor: Int
get()
{
val all = sharedPreferences!!.all
val color: Int
if (all.containsKey("primaryColor"))
{
color = Integer.parseInt(all["primaryColor"]!!.toString())
} else
{
color = -12303292
}
return color
}
val secondaryColor: Int
get()
{
val all = sharedPreferences!!.all
val color: Int
if (all.containsKey("secondaryColor"))
{
color = Integer.parseInt(all["secondaryColor"]!!.toString())
} else
{
color = -65536
}
return color
}
val presentationBackgroundColor: Int
get() = sharedPreferences!!.getInt("presentationBackgroundColor", -0x1000000)
val presentationPrimaryColor: Int
get() = sharedPreferences!!.getInt("presentationPrimaryColor", -0x1)
val presentationSecondaryColor: Int
get() = sharedPreferences!!.getInt("presentationSecondaryColor", -0x100)
val isKeepAwake: Boolean
get() = sharedPreferences!!.getBoolean("prefKeepAwakeOn", false)
val isPlayVideo: Boolean
get() = sharedPreferences!!.getBoolean("prefVideoPlay", true)
val isTamilLyrics: Boolean
get() = sharedPreferences!!.getBoolean("displayTamilLyrics", true)
val isRomanisedLyrics: Boolean
get() = sharedPreferences!!.getBoolean("displayRomanisedLyrics", true)
val isTamil: Boolean
get() = sharedPreferences!!.getInt(CommonConstants.LANGUAGE_INDEX_KEY, 0) == 0
val displaySongBook: Boolean
get() = sharedPreferences!!.getBoolean("prefDisplaySongbook", false)
constructor()
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
constructor(context: Context)
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
}
| gpl-3.0 | b966cd3113bb5265fb42370b33ecb500 | 28.641304 | 100 | 0.646498 | 5.214149 | false | false | false | false |
FHannes/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymap.kt | 11 | 4752 | /*
* 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.openapi.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.loadElement
import gnu.trove.THashMap
import org.jdom.Element
import java.util.*
private val LOG = Logger.getInstance("#com.intellij.openapi.keymap.impl.DefaultKeymap")
open class DefaultKeymap {
private val myKeymaps = ArrayList<Keymap>()
private val nameToScheme = THashMap<String, Keymap>()
protected open val providers: Array<BundledKeymapProvider>
get() = Extensions.getExtensions(BundledKeymapProvider.EP_NAME)
init {
for (provider in providers) {
for (fileName in provider.keymapFileNames) {
// backward compatibility (no external usages of BundledKeymapProvider, but maybe it is not published to plugin manager)
val key = when (fileName) {
"Keymap_Default.xml" -> "\$default.xml"
"Keymap_Mac.xml" -> "Mac OS X 10.5+.xml"
"Keymap_MacClassic.xml" -> "Mac OS X.xml"
"Keymap_GNOME.xml" -> "Default for GNOME.xml"
"Keymap_KDE.xml" -> "Default for KDE.xml"
"Keymap_XWin.xml" -> "Default for XWin.xml"
"Keymap_EclipseMac.xml" -> "Eclipse (Mac OS X).xml"
"Keymap_Eclipse.xml" -> "Eclipse.xml"
"Keymap_Emacs.xml" -> "Emacs.xml"
"JBuilderKeymap.xml" -> "JBuilder.xml"
"Keymap_Netbeans.xml" -> "NetBeans 6.5.xml"
"Keymap_ReSharper_OSX.xml" -> "ReSharper OSX.xml"
"Keymap_ReSharper.xml" -> "ReSharper.xml"
"RM_TextMateKeymap.xml" -> "TextMate.xml"
"Keymap_Xcode.xml" -> "Xcode.xml"
else -> fileName
}
LOG.runAndLogException {
loadKeymapsFromElement(object: SchemeDataHolder<KeymapImpl> {
override fun read() = provider.load(key) { loadElement(it) }
override fun updateDigest(scheme: KeymapImpl) {
}
override fun updateDigest(data: Element) {
}
}, FileUtilRt.getNameWithoutExtension(key))
}
}
}
}
companion object {
@JvmStatic
val instance: DefaultKeymap
get() = ServiceManager.getService(DefaultKeymap::class.java)
@JvmStatic
fun matchesPlatform(keymap: Keymap): Boolean {
val name = keymap.name
return when (name) {
KeymapManager.DEFAULT_IDEA_KEYMAP -> SystemInfo.isWindows
KeymapManager.MAC_OS_X_KEYMAP, KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> SystemInfo.isMac
KeymapManager.X_WINDOW_KEYMAP, KeymapManager.GNOME_KEYMAP, KeymapManager.KDE_KEYMAP -> SystemInfo.isXWindow
else -> true
}
}
}
private fun loadKeymapsFromElement(dataHolder: SchemeDataHolder<KeymapImpl>, keymapName: String) {
val keymap = if (keymapName.startsWith(KeymapManager.MAC_OS_X_KEYMAP)) MacOSDefaultKeymap(dataHolder, this) else DefaultKeymapImpl(dataHolder, this)
keymap.name = keymapName
myKeymaps.add(keymap)
nameToScheme.put(keymapName, keymap)
}
val keymaps: Array<Keymap>
get() = myKeymaps.toTypedArray()
internal fun findScheme(name: String) = nameToScheme.get(name)
open val defaultKeymapName: String
get() = when {
SystemInfo.isMac -> KeymapManager.MAC_OS_X_KEYMAP
SystemInfo.isGNOME -> KeymapManager.GNOME_KEYMAP
SystemInfo.isKDE -> KeymapManager.KDE_KEYMAP
SystemInfo.isXWindow -> KeymapManager.X_WINDOW_KEYMAP
else -> KeymapManager.DEFAULT_IDEA_KEYMAP
}
open fun getKeymapPresentableName(keymap: KeymapImpl): String {
val name = keymap.name
// Netbeans keymap is no longer for version 6.5, but we need to keep the id
if (name == "NetBeans 6.5") {
return "NetBeans"
}
return if (KeymapManager.DEFAULT_IDEA_KEYMAP == name) "Default" else name
}
}
| apache-2.0 | fdc426ba507f3d886e87324c0920c55e | 36.125 | 152 | 0.69234 | 4.107174 | false | false | false | false |
raziel057/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/com/hexagonkt/Benchmark.kt | 10 | 3869 | package com.hexagonkt
import com.hexagonkt.helpers.systemSetting
import com.hexagonkt.serialization.convertToMap
import com.hexagonkt.serialization.serialize
import com.hexagonkt.server.*
import com.hexagonkt.server.jetty.JettyServletEngine
import com.hexagonkt.server.servlet.ServletServer
import com.hexagonkt.server.undertow.UndertowEngine
import com.hexagonkt.settings.SettingsManager.settings
import com.hexagonkt.templates.pebble.PebbleEngine
import org.slf4j.Logger
import org.slf4j.LoggerFactory.getLogger
import java.util.*
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.annotation.WebListener
import java.net.InetAddress.getByName as address
// DATA CLASSES
internal data class Message(val message: String)
internal data class Fortune(val _id: Int, val message: String)
internal data class World(val _id: Int, val id: Int, val randomNumber: Int)
// CONSTANTS
private const val TEXT_MESSAGE: String = "Hello, World!"
private const val CONTENT_TYPE_JSON = "application/json"
private const val QUERIES_PARAM = "queries"
private val LOGGER: Logger = getLogger("BENCHMARK_LOGGER")
private val defaultLocale: Locale = Locale.getDefault()
// UTILITIES
internal fun randomWorld() = ThreadLocalRandom.current().nextInt(WORLD_ROWS) + 1
private fun Call.returnWorlds(worldsList: List<World>) {
val worlds = worldsList.map { it.convertToMap() - "_id" }
ok(worlds.serialize(), CONTENT_TYPE_JSON)
}
private fun Call.getWorldsCount() = (request[QUERIES_PARAM]?.toIntOrNull() ?: 1).let {
when {
it < 1 -> 1
it > 500 -> 500
else -> it
}
}
// HANDLERS
private fun Call.listFortunes(store: Store) {
val fortunes = store.findAllFortunes() + Fortune(0, "Additional fortune added at request time.")
val sortedFortunes = fortunes.sortedBy { it.message }
response.contentType = "text/html;charset=utf-8"
template(PebbleEngine, "fortunes.html", defaultLocale, "fortunes" to sortedFortunes)
}
private fun Call.dbQuery(store: Store) {
val world = store.findWorlds(1).first().convertToMap() - "_id"
ok(world.serialize(), CONTENT_TYPE_JSON)
}
private fun Call.getWorlds(store: Store) {
returnWorlds(store.findWorlds(getWorldsCount()))
}
private fun Call.updateWorlds(store: Store) {
returnWorlds(store.replaceWorlds(getWorldsCount()))
}
// CONTROLLER
private fun router(): Router = router {
val store = benchmarkStore ?: error("Invalid Store")
before {
response.addHeader("Server", "Servlet/3.1")
response.addHeader("Transfer-Encoding", "chunked")
response.addHeader("Date", httpDate())
}
get("/plaintext") { ok(TEXT_MESSAGE, "text/plain") }
get("/json") { ok(Message(TEXT_MESSAGE).serialize(), CONTENT_TYPE_JSON) }
get("/fortunes") { listFortunes(store) }
get("/db") { dbQuery(store) }
get("/query") { getWorlds(store) }
get("/update") { updateWorlds(store) }
}
@WebListener class Web : ServletServer () {
init {
if (benchmarkStore == null)
benchmarkStore = createStore(systemSetting("DBSTORE", "mongodb"))
}
override fun createRouter() = router()
}
internal var benchmarkStore: Store? = null
internal var benchmarkServer: Server? = null
internal fun createEngine(engine: String): ServerEngine = when (engine) {
"jetty" -> JettyServletEngine()
"undertow" -> UndertowEngine()
else -> error("Unsupported server engine")
}
fun main(vararg args: String) {
val engine = createEngine(systemSetting("WEBENGINE", "jetty"))
benchmarkStore = createStore(systemSetting("DBSTORE", "mongodb"))
LOGGER.info("""
Benchmark set up:
- Engine: {}
- Store: {}
""".trimIndent(),
engine.javaClass.name,
benchmarkStore?.javaClass?.name)
benchmarkServer = Server(engine, settings, router()).apply { run() }
}
| bsd-3-clause | 9606a34fce56473d700ce2cf06af11a1 | 31.512605 | 100 | 0.704575 | 3.947959 | false | false | false | false |
sys1yagi/mastodon4j | sample-kotlin/src/main/java/com/sys1yagi/mastodon4j/sample/Kotlindon.kt | 1 | 1501 | package com.sys1yagi.mastodon4j.sample
import com.sys1yagi.mastodon4j.MastodonClient
import com.sys1yagi.mastodon4j.api.Pageable
import com.sys1yagi.mastodon4j.api.Range
import com.sys1yagi.mastodon4j.api.entity.Status
import com.sys1yagi.mastodon4j.api.method.Timelines
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.runBlocking
object Kotlindon {
@JvmStatic
fun main(args: Array<String>) {
val instanceName = args[0]
val credentialFilePath = args[1]
val client = Authenticator.appRegistrationIfNeeded(instanceName, credentialFilePath)
listenHome(client)
}
fun listenHome(client: MastodonClient) {
runBlocking {
val timelines = Timelines(client)
var pageable: Pageable<Status>? = null
while (true) {
val result = pageable?.let {
timelines.getHome(it.prevRange(limit = 5)).execute()
} ?: timelines.getHome(Range(limit = 5)).execute()
result.part.sortedBy { it.createdAt }.forEach {
println(it.account?.displayName)
println(it.content)
println(it.createdAt)
println("------------------------")
}
if (result.part.isNotEmpty()) {
pageable = result
}
println("wait next load...")
delay(5000)
}
}
}
}
| mit | d0c6c667b95bd9d5dc166c6e3ae0e466 | 33.906977 | 92 | 0.582945 | 4.590214 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseIfEmptyOrIfBlank.kt | 1 | 6198 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
/**
* This rule detects `isEmpty` or `isBlank` calls to assign a default value. They can be replaced with `ifEmpty` or
* `ifBlank` calls.
*
* <noncompliant>
* fun test(list: List<Int>, s: String) {
* val a = if (list.isEmpty()) listOf(1) else list
* val b = if (list.isNotEmpty()) list else listOf(2)
* val c = if (s.isBlank()) "foo" else s
* val d = if (s.isNotBlank()) s else "bar"
* }
* </noncompliant>
*
* <compliant>
* fun test(list: List<Int>, s: String) {
* val a = list.ifEmpty { listOf(1) }
* val b = list.ifEmpty { listOf(2) }
* val c = s.ifBlank { "foo" }
* val d = s.ifBlank { "bar" }
* }
* </compliant>
*
*/
@RequiresTypeResolution
@Suppress("ReturnCount", "ComplexMethod")
class UseIfEmptyOrIfBlank(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue(
"UseIfEmptyOrIfBlank",
Severity.Style,
"Use 'ifEmpty' or 'ifBlank' instead of 'isEmpty' or 'isBlank' to assign default value.",
Debt.FIVE_MINS
)
override fun visitIfExpression(expression: KtIfExpression) {
super.visitIfExpression(expression)
if (bindingContext == BindingContext.EMPTY) return
if (expression.isElseIf()) return
val thenExpression = expression.then ?: return
val elseExpression = expression.`else` ?: return
if (elseExpression is KtIfExpression) return
val (condition, isNegatedCondition) = expression.condition() ?: return
val conditionCallExpression = condition.getPossiblyQualifiedCallExpression() ?: return
val conditionCalleeExpression = conditionCallExpression.calleeExpression ?: return
val conditionCalleeExpressionText = conditionCalleeExpression.text
if (conditionCalleeExpressionText !in conditionFunctionShortNames) return
val replacement = conditionCallExpression.replacement() ?: return
val selfBranch = if (isNegatedCondition xor replacement.negativeCondition) thenExpression else elseExpression
val selfValueExpression = selfBranch.blockExpressionsOrSingle().singleOrNull() ?: return
if (condition is KtDotQualifiedExpression) {
if (selfValueExpression.text != condition.receiverExpression.text) return
} else if (selfValueExpression !is KtThisExpression) {
return
}
val message =
"This '$conditionCalleeExpressionText' call can be replaced with '${replacement.replacementFunctionName}'"
report(CodeSmell(issue, Entity.from(conditionCalleeExpression), message))
}
private fun KtExpression.isElseIf(): Boolean = parent.node.elementType == KtNodeTypes.ELSE
private fun KtIfExpression.condition(): Pair<KtExpression, Boolean>? {
val condition = this.condition ?: return null
return if (condition is KtPrefixExpression) {
if (condition.operationToken != KtTokens.EXCL) return null
val baseExpression = condition.baseExpression ?: return null
baseExpression to true
} else {
condition to false
}
}
private fun KtCallExpression.replacement(): Replacement? {
val descriptor = getResolvedCall(bindingContext)?.resultingDescriptor ?: return null
val receiverParameter = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter
val receiverType = receiverParameter?.type ?: return null
if (KotlinBuiltIns.isArrayOrPrimitiveArray(receiverType)) return null
val conditionCallFqName = descriptor.fqNameOrNull() ?: return null
return replacements[conditionCallFqName]
}
private data class Replacement(
val conditionFunctionFqName: FqName,
val replacementFunctionName: String,
val negativeCondition: Boolean = false
)
companion object {
private const val ifBlank = "ifBlank"
private const val ifEmpty = "ifEmpty"
private val replacements = listOf(
Replacement(FqName("kotlin.text.isBlank"), ifBlank),
Replacement(FqName("kotlin.text.isEmpty"), ifEmpty),
Replacement(FqName("kotlin.collections.List.isEmpty"), ifEmpty),
Replacement(FqName("kotlin.collections.Set.isEmpty"), ifEmpty),
Replacement(FqName("kotlin.collections.Map.isEmpty"), ifEmpty),
Replacement(FqName("kotlin.collections.Collection.isEmpty"), ifEmpty),
Replacement(FqName("kotlin.text.isNotBlank"), ifBlank, negativeCondition = true),
Replacement(FqName("kotlin.text.isNotEmpty"), ifEmpty, negativeCondition = true),
Replacement(FqName("kotlin.collections.isNotEmpty"), ifEmpty, negativeCondition = true),
Replacement(FqName("kotlin.String.isEmpty"), ifEmpty)
).associateBy { it.conditionFunctionFqName }
private val conditionFunctionShortNames = replacements.keys.map { it.shortName().asString() }.toSet()
}
}
| apache-2.0 | 95ce387dfd2fcd3082f3aff2fe25b9f7 | 44.240876 | 118 | 0.718296 | 4.812112 | false | false | false | false |
nickthecoder/paratask | paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/HorizontalGroupExample.kt | 1 | 2412 | package uk.co.nickthecoder.paratask.examples
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.TaskParser
import uk.co.nickthecoder.paratask.parameters.*
class HorizontalGroupExample : AbstractTask() {
val horizontalIntP = IntParameter("horizontalInt", label = "Int")
val horizontalStringP = StringParameter("horizontalString", label = "String", columns = 10)
val horizontalGroupP = SimpleGroupParameter("horizontalGroup")
.addParameters(horizontalIntP, horizontalStringP)
.asHorizontal()
val boolAP = BooleanParameter("a")
val boolBP = BooleanParameter("b")
val noStretchP = SimpleGroupParameter("No stretchy fields")
.addParameters(boolAP, boolBP)
.asHorizontal()
val boolCP = BooleanParameter("c")
val midStringP = StringParameter("midStr", label = "String", columns = 10)
val boolDP = BooleanParameter("d")
val middleStretchyP = SimpleGroupParameter("middleStretchy")
.addParameters(boolCP, midStringP, boolDP)
.asHorizontal()
val infoP = InformationParameter("info", information = "\nNote, that only the first stretchy field in a horizontal group stretches. Resize the window to see.")
val stringAP = StringParameter("stringA", columns = 10)
val stringBP = StringParameter("stringB", columns = 10)
val twoStringsP = SimpleGroupParameter("twoStrings")
.addParameters(stringAP, stringBP)
.asHorizontal()
val info2P = InformationParameter("info2", information = "\nHere we see a group without labels, and the first StringParameter is made non-stretchy.")
val houseNumberP = StringParameter("houseNumber", columns = 6, stretchy = false)
val roadNameP = StringParameter("roadName")
val addressLine1P = SimpleGroupParameter("addressLine1")
.addParameters(houseNumberP, roadNameP)
.asHorizontal(LabelPosition.NONE)
override val taskD = TaskDescription("horizontalGroupExample",
description = "Demonstrates the use of SimpleGroupParameter.asHorizontal(…)")
.addParameters(horizontalGroupP, noStretchP, middleStretchyP, infoP, twoStringsP, info2P, addressLine1P)
override fun run() {
}
}
fun main(args: Array<String>) {
TaskParser(HorizontalGroupExample()).go(args, prompt = true)
}
| gpl-3.0 | f9cb1ab02e8e842d9a2fde922737bf80 | 40.551724 | 163 | 0.716183 | 4.318996 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilerenderers/Filter.kt | 2 | 2154 | package com.cout970.magneticraft.systems.tilerenderers
enum class FilterTarget {
BRANCH, LEAF, ANIMATION
}
sealed class Filter {
abstract operator fun invoke(name: String, type: FilterTarget): Boolean
}
@JvmField
val IGNORE_ANIMATION = FilterNot(FilterAlways)
data class ModelSelector(val name: String, val componentFilter: Filter, val animationFilter: Filter = IGNORE_ANIMATION)
class FilterRegex(expression: String, val target: FilterTarget = FilterTarget.LEAF) : Filter() {
val regex = expression.toRegex()
override operator fun invoke(name: String, type: FilterTarget): Boolean {
if (type != target) return true
return regex.matches(name)
}
}
class FilterNotRegex(expression: String, val target: FilterTarget = FilterTarget.LEAF) : Filter() {
val regex = expression.toRegex()
override operator fun invoke(name: String, type: FilterTarget): Boolean {
if (type != target) return true
return !regex.matches(name)
}
}
class FilterString(val value: String, vararg val target: FilterTarget = arrayOf(FilterTarget.LEAF)) : Filter() {
override operator fun invoke(name: String, type: FilterTarget): Boolean {
if (type !in target) return true
return value == name
}
}
class FilterNotString(val value: String, vararg val target: FilterTarget = arrayOf(FilterTarget.LEAF)) : Filter() {
override operator fun invoke(name: String, type: FilterTarget): Boolean {
if (type !in target) return true
return value != name
}
}
object FilterAlways : Filter() {
override operator fun invoke(name: String, type: FilterTarget): Boolean = true
}
class FilterAnd(vararg val children: Filter) : Filter() {
override operator fun invoke(name: String, type: FilterTarget): Boolean = children.all { it.invoke(name, type) }
}
class FilterOr(vararg val children: Filter) : Filter() {
override operator fun invoke(name: String, type: FilterTarget): Boolean = children.any { it.invoke(name, type) }
}
class FilterNot(val child: Filter) : Filter() {
override fun invoke(name: String, type: FilterTarget): Boolean = !child.invoke(name, type)
} | gpl-2.0 | e7c017809395cea27acaf1bc9662d83c | 32.671875 | 119 | 0.710771 | 4.158301 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/PreferencesMutations.kt | 1 | 2453 | package net.nemerosa.ontrack.graphql.schema
import graphql.schema.GraphQLObjectType
import net.nemerosa.ontrack.graphql.support.GraphQLBeanConverter
import net.nemerosa.ontrack.graphql.support.TypedMutationProvider
import net.nemerosa.ontrack.graphql.support.getDescription
import net.nemerosa.ontrack.model.preferences.Preferences
import net.nemerosa.ontrack.model.preferences.PreferencesService
import net.nemerosa.ontrack.model.security.SecurityService
import org.springframework.stereotype.Component
import javax.validation.Validator
/**
* Settings the current's user preferences.
*/
@Component
class PreferencesMutations(
validator: Validator,
private val preferencesService: PreferencesService,
private val securityService: SecurityService,
) : TypedMutationProvider(validator) {
override val mutations: List<Mutation> = listOf(
simpleMutation(
name = "setPreferences",
description = "Setting the preferences of the current user",
input = SetPreferencesInput::class,
outputName = "preferences",
outputDescription = "Saved preferences",
outputType = Preferences::class,
) { input ->
// Gets the current account
val account = securityService.currentAccount?.account ?: error("Authentication is required.")
// Gets the current preferences
val current = preferencesService.getPreferences(account)
// Adapts the preferences
val new = Preferences(
branchViewVsNames = input.branchViewVsNames ?: current.branchViewVsNames,
branchViewVsGroups = input.branchViewVsGroups ?: current.branchViewVsGroups,
)
// Saves the preferences...
preferencesService.setPreferences(account, new)
// ... and returns them
new
}
)
}
@Component
class GQLTypePreferences : GQLType {
override fun getTypeName(): String = Preferences::class.java.simpleName
override fun createType(cache: GQLTypeCache): GraphQLObjectType =
GraphQLObjectType.newObject()
.name(typeName)
.description(getDescription(Preferences::class))
.fields(GraphQLBeanConverter.asObjectFields(Preferences::class, cache))
.build()
}
data class SetPreferencesInput(
val branchViewVsNames: Boolean? = null,
val branchViewVsGroups: Boolean? = null,
) | mit | 1f2d91c6b78b964e2ce338e2e3f1e01b | 35.088235 | 105 | 0.698329 | 5.121086 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/payload/IngestionHookPayload.kt | 1 | 3586 | package net.nemerosa.ontrack.extension.github.ingestion.payload
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.extension.github.ingestion.processing.IngestionEventProcessingResult
import net.nemerosa.ontrack.extension.github.ingestion.processing.model.Repository
import net.nemerosa.ontrack.model.annotations.APIDescription
import java.time.LocalDateTime
import java.util.*
/**
* Payload for an ingestion to be processed.
*
* @property uuid Unique ID for this payload
* @property timestamp Timestamp of reception for this payload
* @property gitHubDelivery Mapped to the `X-GitHub-Delivery` header
* @property gitHubEvent Mapped to the `X-GitHub-Event` header
* @property gitHubHookID Mapped to the `X-GitHub-Hook-ID` header
* @property gitHubHookInstallationTargetID Mapped to the `X-GitHub-Hook-Installation-Target-ID` header
* @property gitHubHookInstallationTargetType Mapped to the `X-GitHub-Hook-Installation-Target-Type` header
* @property payload JSON payload, raw from GitHub
* @property repository Repository this payload refers to
* @property source Summary of the payload/event for display purpose
* @property status Status of the processing
* @property outcome Outcome of the processing
* @property started Timestamp for the start of the processing
* @property message Status message (exception stack trace in case of error)
* @property completion Timestamp for the end of the processing
* @property configuration Name of the GitHub configuration to use
* @property routing Routing information
* @property queue Queue information
*/
data class IngestionHookPayload(
@APIDescription("Unique ID for this payload")
val uuid: UUID = UUID.randomUUID(),
@APIDescription("Timestamp of reception for this payload")
val timestamp: LocalDateTime = Time.now(),
@APIDescription("Mapped to the `X-GitHub-Delivery` header")
val gitHubDelivery: String,
@APIDescription("Mapped to the `X-GitHub-Event` header")
val gitHubEvent: String,
@APIDescription("Mapped to the `X-GitHub-Hook-ID` header")
val gitHubHookID: Int,
@APIDescription("Mapped to the `X-GitHub-Hook-Installation-Target-ID` header")
val gitHubHookInstallationTargetID: Int,
@APIDescription("Mapped to the `X-GitHub-Hook-Installation-Target-Type` header")
val gitHubHookInstallationTargetType: String,
@APIDescription("JSON payload, raw from GitHub")
val payload: JsonNode,
@APIDescription("Repository this payload refers to")
val repository: Repository?,
@APIDescription("Source/name of the payload/event")
val source: String? = null,
@APIDescription("Status of the processing")
val status: IngestionHookPayloadStatus = IngestionHookPayloadStatus.SCHEDULED,
@APIDescription("Outcome of the processing")
val outcome: IngestionEventProcessingResult? = null,
@APIDescription("Details about the outcome of the processing")
val outcomeDetails: String? = null,
@APIDescription("Timestamp for the start of the processing")
val started: LocalDateTime? = null,
@APIDescription("Status message (exception stack trace in case of error)")
val message: String? = null,
@APIDescription("Timestamp for the end of the processing")
val completion: LocalDateTime? = null,
@APIDescription("Name of the GitHub configuration to use")
val configuration: String? = null,
@APIDescription("Routing information")
val routing: String? = null,
@APIDescription("Queue information")
val queue: String? = null,
)
| mit | aa92af8fa244ce5323c0662b441b8231 | 48.805556 | 107 | 0.764361 | 4.579821 | false | true | false | false |
nemerosa/ontrack | ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/git/GitBranchConfigurationPropertyExtensions.kt | 1 | 1750 | package net.nemerosa.ontrack.kdsl.spec.extension.git
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.kdsl.spec.Branch
import net.nemerosa.ontrack.kdsl.spec.deleteProperty
import net.nemerosa.ontrack.kdsl.spec.getProperty
import net.nemerosa.ontrack.kdsl.spec.setProperty
import net.nemerosa.ontrack.kdsl.spec.support.ServiceConfiguration
const val GIT_BRANCH_CONFIGURATION_PROPERTY =
"net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationPropertyType"
var Branch.gitBranchConfigurationProperty: GitBranchConfigurationProperty?
get() = getProperty(GIT_BRANCH_CONFIGURATION_PROPERTY)?.parse()
set(value) {
if (value != null) {
setProperty(GIT_BRANCH_CONFIGURATION_PROPERTY, value)
} else {
deleteProperty(GIT_BRANCH_CONFIGURATION_PROPERTY)
}
}
var Branch.gitBranchConfigurationPropertyBranch: String?
get() = gitBranchConfigurationProperty?.branch
set(value) {
gitBranchConfigurationProperty = if (value != null) {
GitBranchConfigurationProperty(branch = value)
} else {
null
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
class GitBranchConfigurationProperty(
/**
* Git branch or pull request ID
*/
val branch: String,
/**
* Build link
*/
val buildCommitLink: ServiceConfiguration? = ServiceConfiguration(
id = "git-commit-property",
data = null,
),
/**
* Build overriding policy when synchronizing
*/
val isOverride: Boolean = false,
/**
* Interval in minutes for build/tag synchronization
*/
val buildTagInterval: Int = 0,
)
| mit | c2f65d31ebba51312b23d6d5d9b694e3 | 28.166667 | 84 | 0.7 | 4.581152 | false | true | false | false |
langara/MyIntent | myintent/src/main/java/pl/mareklangiewicz/myintent/MIAboutFragment.kt | 1 | 1279 | package pl.mareklangiewicz.myintent
import android.os.Bundle
import android.view.View
import hu.supercluster.paperwork.Paperwork
import pl.mareklangiewicz.myfragments.MyAboutFragment
import pl.mareklangiewicz.myutils.str
import java.util.*
/**
* Created by Marek Langiewicz on 06.04.16.
*/
@Suppress("unused")
class MIAboutFragment : MyAboutFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
manager?.name = BuildConfig.NAME_PREFIX + getString(R.string.mi_about)
val paperwork = Paperwork(activity)
title = "My Intent"
description = "This app allows user to start any android intent easily."
details = listOf(
"build type" to BuildConfig.BUILD_TYPE,
"version code" to BuildConfig.VERSION_CODE.str,
"version name" to BuildConfig.VERSION_NAME,
"build time" to paperwork.get("buildTime"),
"app start time" to "%tF %tT".format(Locale.getDefault(), APP_START_TIME, APP_START_TIME),
"git sha" to paperwork.get("gitSha"),
"git tag" to paperwork.get("gitTag"),
"git info" to paperwork.get("gitInfo")
)
}
}
| apache-2.0 | ca90a57daa721463e80d43dd5fbfab2d | 31.794872 | 106 | 0.650508 | 4.179739 | false | true | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/stub/StubRepository.kt | 2 | 1134 | package io.mockk.impl.stub
import io.mockk.MockKException
import io.mockk.impl.InternalPlatform
import io.mockk.impl.MultiNotifier.Session
import io.mockk.impl.WeakRef
import io.mockk.impl.log.SafeToString
class StubRepository(
val safeToString: SafeToString
) {
private val stubs = InternalPlatform.weakMap<Any, WeakRef>()
private val recordCallMultiNotifier = InternalPlatform.multiNotifier()
fun stubFor(mock: Any): Stub = get(mock)
?: throw MockKException(safeToString.exec { "can't find stub $mock" })
fun add(mock: Any, stub: Stub) {
stubs[mock] = InternalPlatform.weakRef(stub)
}
fun remove(mock: Any) = stubs.remove(mock)?.value as? Stub
operator fun get(mock: Any): Stub? = stubs[mock]?.value as? Stub
val allStubs: List<Stub>
get() = stubs.values.mapNotNull { it.value as? Stub }
fun notifyCallRecorded(stub: MockKStub) {
recordCallMultiNotifier.notify(stub)
}
fun openRecordCallAwaitSession(
stubs: List<Stub>,
timeout: Long
): Session {
return recordCallMultiNotifier.openSession(stubs, timeout)
}
}
| apache-2.0 | 1e212f30d3f5d8981cf9bd1d93825017 | 27.35 | 78 | 0.695767 | 3.870307 | false | false | false | false |
dna2github/NodeBase | android/app/src/main/kotlin/net/seven/nodebase/Permission.kt | 1 | 1380 | package net.seven.nodebase
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.PowerManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
object Permission {
private var power_wake_lock: PowerManager.WakeLock? = null
private var PERMISSIONS_EXTERNAL_STORAGE = 1
fun request(activity: Activity) {
val permission: Int
permission = ContextCompat.checkSelfPermission(
activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
PERMISSIONS_EXTERNAL_STORAGE)
}
}
fun keepScreen(activity: Activity, on: Boolean) {
val pm = activity.getSystemService(Context.POWER_SERVICE) as PowerManager
if (power_wake_lock == null) {
power_wake_lock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, Permission::class.java!!.getName()
)
}
if (on) {
power_wake_lock!!.acquire()
} else {
power_wake_lock!!.release()
}
}
}
| apache-2.0 | 356dceee68ac091456e41fc2a89f2974 | 33.5 | 115 | 0.650725 | 4.808362 | false | false | false | false |
Ztiany/Repository | Java/Java-Socket/src/main/kotlin/me/ztiany/socket/udp/UDP_A.kt | 2 | 1966 | package me.ztiany.socket.udp
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
/*
### UDP示例
DatagramSocket具有发送和接收数据的功能,因为数据包中包含的信息较多,为了操作这些信息方便,也一样会将其封装成对象。这个数据包对象就是DatagramPacket
udp的发送端:
1. 建立udp的socket服务,创建对象时如果没有明确端口,系统会自动分配一个未被使用的端口。
2. 明确要发送的具体数据。
3. 将数据封装成了数据包。
4. 用socket服务的send方法将数据包发送出去。
5. 关闭资源。
udp的接收端:
1. 创建udp的socket服务,必须要明确一个端口,作用在于,只有发送到这个端口的数据才是这个接收端可以处理的数据。
2. 定义数据包,用于存储接收到数据。
3. 通过socket服务的接收方法将收到的数据存储到数据包中。
4. 通过数据包的方法获取数据包中的具体数据内容,比如ip、端口、数据等等。
5. 关闭资源。
*/
/**
*
* @author Ztiany
* Email [email protected]
* Date 17.12.2 13:10
*/
fun main(args: Array<String>) {
// 创建Udp服务 设置端口
val datagramSocket = DatagramSocket(12990)
// 定义数据包 用于存储数据
val bufferedReader = BufferedReader(InputStreamReader(System.`in`))
var line: String?
line = bufferedReader.readLine()
while (line != null) {
if ("over" == line) {
break
}
val buf = line.toByteArray()
// 发送数据
val datagramPacket = DatagramPacket(buf, buf.size, InetAddress.getLocalHost(), 12980)
//阻塞方法用于发送数据
datagramSocket.send(datagramPacket)
line = bufferedReader.readLine()
}
bufferedReader.close()
datagramSocket.close()
}
| apache-2.0 | c2ef02e9b963862a93ce1480ca074fbd | 18.852941 | 93 | 0.694815 | 2.755102 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/data/collector/obddata/obdinitializer/BluetoothObdInitializer.kt | 1 | 1744 | package com.telenav.osv.data.collector.obddata.obdinitializer
import android.bluetooth.BluetoothSocket
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.obddata.ObdHelper
import com.telenav.osv.data.collector.obddata.manager.ObdDataListener
import timber.log.Timber
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
/**
* Created by ovidiuc2 on 13.04.2017.
*/
class BluetoothObdInitializer(deviceVersion: String?, obdDataListener: ObdDataListener?, private val bluetoothClientSocket: BluetoothSocket?) : AbstractOBDInitializer(obdDataListener, deviceVersion) {
private var outputStream: OutputStream? = null
private var inputStream: InputStream? = null
/**
* sends an AT command to setup the OBD interface(spaces off, echo off)
*
* @param sendingCommand
* @return - OK if the command was executed successfully
*/
override fun getAtResponse(sendingCommand: String): String? {
try {
if (bluetoothClientSocket != null) {
outputStream = bluetoothClientSocket.outputStream
inputStream = bluetoothClientSocket.inputStream
ObdHelper.sendCommand(outputStream, sendingCommand)
delay(AT_WAITING_TIME)
return ObdHelper.getRawData(inputStream)
} else {
obdDataListener!!.onConnectionStateChanged(LibraryUtil.OBD_BLUETOOTH_SOURCE, LibraryUtil.OBD_SOCKET_ERROR)
}
} catch (e: IOException) {
Timber.tag(TAG).e(e)
obdDataListener!!.onConnectionStateChanged(LibraryUtil.OBD_BLUETOOTH_SOURCE, LibraryUtil.OBD_SOCKET_ERROR)
}
return null
}
} | lgpl-3.0 | e5969f1ea5d3588a5850f01d0641e7cb | 40.547619 | 200 | 0.708142 | 4.675603 | false | false | false | false |
lare96/luna | plugins/world/player/command/CommandHandler.kt | 1 | 769 | package world.player.command
import api.event.Matcher
import api.predef.*
import io.luna.game.event.impl.CommandEvent
import io.luna.game.model.mob.Player
import io.luna.game.model.mob.PlayerRights
/**
* The [CommandEvent] matcher function.
*/
fun cmd(name: String, rights: PlayerRights, action: CommandEvent.() -> Unit) {
val matcher = Matcher.get<CommandEvent, CommandKey>()
matcher[CommandKey(name, rights)] = {
if (plr.rights >= rights) {
action(this)
}
}
}
/**
* Performs a lookup for a player based on the arguments from [index] onwards. By default, it starts from index 0.
*/
fun getPlayer(msg: CommandEvent, index: Int = 0, action: (Player) -> Unit) =
world.getPlayer(msg.getInputFrom(index)).ifPresent(action) | mit | 46e0e010069942130ba84f0e4475644e | 29.8 | 114 | 0.694408 | 3.560185 | false | false | false | false |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/match/MatchDisplayable.kt | 1 | 4501 | package com.benoitquenaudon.tvfoot.red.app.domain.match
import android.os.Parcelable
import com.benoitquenaudon.tvfoot.red.app.data.entity.Broadcaster
import com.benoitquenaudon.tvfoot.red.app.data.entity.Competition
import com.benoitquenaudon.tvfoot.red.app.data.entity.Match
import com.benoitquenaudon.tvfoot.red.app.data.entity.Team
import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.BroadcasterRowDisplayable
import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.MatchesItemDisplayable
import java.text.DateFormat
import java.text.SimpleDateFormat
import kotlinx.android.parcel.Parcelize
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
@Parcelize
data class MatchDisplayable(
val headerKey: String,
val startAt: Long,
val startTime: String,
val broadcasters: List<BroadcasterRowDisplayable>,
val headline: String,
val competition: String,
val matchDay: String,
val live: Boolean,
val startTimeInText: String,
val homeTeamLogoPath: String,
val awayTeamLogoPath: String,
val location: String?,
val matchId: String
) : Parcelable, MatchesItemDisplayable {
override fun isSameAs(other: MatchesItemDisplayable): Boolean {
return other is MatchDisplayable && this.matchId == other.matchId
}
companion object {
private val shortDateFormat = object : ThreadLocal<DateFormat>() {
override fun initialValue(): DateFormat {
val format = SimpleDateFormat("HH:mm", Locale.getDefault())
format.timeZone = TimeZone.getDefault()
return format
}
}
private val mediumDateFormat = object : ThreadLocal<DateFormat>() {
override fun initialValue(): DateFormat {
val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
format.timeZone = TimeZone.getDefault()
return format
}
}
private val fullTextDateFormat = object : ThreadLocal<DateFormat>() {
override fun initialValue(): DateFormat {
val format = SimpleDateFormat("EEEE dd MMMM yyyy HH'h'mm", Locale.getDefault())
format.timeZone = TimeZone.getDefault()
return format
}
}
fun fromMatch(match: Match): MatchDisplayable {
return MatchDisplayable(
parseHeaderKey(match.startAt),
match.startAt.time,
parseStartTime(match.startAt),
parseBroadcasters(match.broadcasters),
parseHeadLine(match.homeTeam, match.awayTeam, match.label),
parseCompetition(match.competition),
parseMatchDay(match.label, match.matchDay),
isMatchLive(match.startAt),
parseStartTimeInText(match.startAt),
match.homeTeam.logoPath,
match.awayTeam.logoPath,
parseLocation(match),
match.id)
}
private fun parseHeaderKey(startAt: Date): String {
return mediumDateFormat.get().format(startAt)
}
private fun parseStartTime(startAt: Date): String {
return shortDateFormat.get().format(startAt)
}
private fun parseBroadcasters(
broadcasters: List<Broadcaster>?
): List<BroadcasterRowDisplayable> =
broadcasters
?.filter { it.name != null }
?.map { BroadcasterRowDisplayable(it.name!!, it.code) }
?: emptyList()
private fun parseHeadLine(homeTeam: Team, awayTeam: Team, matchLabel: String?): String =
if (homeTeam.isEmpty || awayTeam.isEmpty) {
matchLabel.toString()
} else {
homeTeam.name.toString().toUpperCase() + " - " + awayTeam.name.toString().toUpperCase()
}
private fun parseCompetition(competition: Competition): String = competition.name
private fun parseMatchDay(matchLabel: String?, matchDay: String?): String =
if (matchLabel != null && !matchLabel.isEmpty()) {
matchLabel
} else if (matchDay != null && !matchDay.isEmpty()) {
"J. $matchDay"
} else {
""
}
private fun isMatchLive(startAt: Date): Boolean {
val now = Calendar.getInstance().timeInMillis
val startTimeInMillis = startAt.time
return now >= startTimeInMillis && now <= startTimeInMillis + TimeUnit.MINUTES.toMillis(105)
}
private fun parseStartTimeInText(startAt: Date): String =
fullTextDateFormat.get().format(startAt).capitalize()
private fun parseLocation(match: Match): String? = match.place
}
}
| apache-2.0 | 2fb9b7592d119248b7c42115a5114a63 | 35.008 | 98 | 0.688069 | 4.546465 | false | false | false | false |
stripe/stripe-android | stripe-core/src/test/java/com/stripe/android/core/networking/ApiRequestTest.kt | 1 | 2824 | package com.stripe.android.core.networking
import com.stripe.android.core.ApiKeyFixtures
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.ByteArrayOutputStream
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
@RunWith(RobolectricTestRunner::class)
internal class ApiRequestTest {
@Test
fun getContentType() {
val contentType = FACTORY.createGet(
SOURCES_URL,
OPTIONS
).postHeaders?.get(HEADER_CONTENT_TYPE)
assertEquals("application/x-www-form-urlencoded; charset=UTF-8", contentType)
}
@Test
fun writeBody_withEmptyBody_shouldHaveZeroLength() {
ByteArrayOutputStream().use {
FACTORY.createPost(
PAYMENT_METHODS_URL,
OPTIONS
).writePostBody(it)
assertTrue(it.size() == 0)
}
}
@Test
fun writeBody_withNonEmptyBody_shouldHaveNonZeroLength() {
ByteArrayOutputStream().use {
FACTORY.createPost(
PAYMENT_METHODS_URL,
OPTIONS,
mapOf("customer" to "cus_123")
).writePostBody(it)
assertEquals(16, it.size())
}
}
@Test
fun testEquals() {
val params = mapOf("customer" to "cus_123")
assertEquals(
FACTORY.createPost(
PAYMENT_METHODS_URL,
OPTIONS,
params
),
FACTORY.createPost(
PAYMENT_METHODS_URL,
OPTIONS,
params
)
)
assertNotEquals(
FACTORY.createPost(
PAYMENT_METHODS_URL,
OPTIONS,
params
),
FACTORY.createPost(
PAYMENT_METHODS_URL,
ApiRequest.Options(ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, "acct"),
params
)
)
}
@Test
fun getIncludesQueryParametersInUrl() {
val url = FACTORY.createGet(
SOURCES_URL,
OPTIONS,
mapOf("param" to "123")
).url
assertEquals(url, "sources?param=123")
}
@Test
fun deleteIncludesQueryParametersInUrl() {
val url = FACTORY.createDelete(
SOURCES_URL,
OPTIONS,
mapOf("param" to "123")
).url
assertEquals(url, "sources?param=123")
}
private companion object {
private val OPTIONS = ApiRequest.Options(ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY)
private val FACTORY = ApiRequest.Factory()
private const val SOURCES_URL = "sources"
private const val PAYMENT_METHODS_URL = "payment_methods"
}
}
| mit | 0602deb13d9106ee9892d94231fe8dec | 25.641509 | 88 | 0.56551 | 4.99823 | false | true | false | false |
AndroidX/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/NavigationRail.kt | 3 | 16203 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.VectorizedAnimationSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.max
import kotlin.math.roundToInt
/**
* <a href="https://material.io/components/navigation-rail" class="external" target="_blank">Material Design navigation rail</a>.
*
* A Navigation Rail is a side navigation component that allows movement between primary
* destinations in an app. A navigation rail should be used to display three to seven app
* destinations and, optionally, a [FloatingActionButton] or a logo inside [header]. Each
* destination is typically represented by an icon and an optional text label.
*
* 
*
* NavigationRail should contain multiple [NavigationRailItem]s, each representing a singular
* destination.
*
* A simple example looks like:
*
* @sample androidx.compose.material.samples.NavigationRailSample
*
* See [NavigationRailItem] for configuration specific to each item, and not the overall
* NavigationRail component.
*
* For more information, see [Navigation Rail](https://material.io/components/navigation-rail/)
*
* @param modifier optional [Modifier] for this NavigationRail
* @param backgroundColor The background color for this NavigationRail
* @param contentColor The preferred content color provided by this NavigationRail to its
* children. Defaults to either the matching content color for [backgroundColor], or if
* [backgroundColor] is not a color from the theme, this will keep the same value set above this
* NavigationRail.
* @param elevation elevation for this NavigationRail
* @param header an optional header that may hold a [FloatingActionButton] or a logo
* @param content destinations inside this NavigationRail, this should contain multiple
* [NavigationRailItem]s
*/
@Composable
fun NavigationRail(
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = NavigationRailDefaults.Elevation,
header: @Composable (ColumnScope.() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit
) {
Surface(
modifier = modifier,
color = backgroundColor,
contentColor = contentColor,
elevation = elevation
) {
Column(
Modifier
.fillMaxHeight()
.padding(vertical = NavigationRailPadding)
.selectableGroup(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
if (header != null) {
header()
Spacer(Modifier.height(HeaderPadding))
}
content()
}
}
}
/**
* <a href="https://material.io/components/navigation-rail" class="external" target="_blank">Material Design navigation rail</a> item.
*
* A NavigationRailItem always shows text labels (if it exists) when selected. Showing text
* labels if not selected is controlled by [alwaysShowLabel].
*
* @param selected whether this item is selected (active)
* @param onClick the callback to be invoked when this item is selected
* @param icon icon for this item, typically this will be an [Icon]
* @param modifier optional [Modifier] for this item
* @param enabled controls the enabled state of this item. When `false`, this item will not
* be clickable and will appear disabled to accessibility services.
* @param label optional text label for this item
* @param alwaysShowLabel whether to always show the label for this item. If false, the label will
* only be shown when this item is selected.
* @param interactionSource the [MutableInteractionSource] representing the stream of
* [Interaction]s for this NavigationRailItem. You can create and pass in your own remembered
* [MutableInteractionSource] if you want to observe [Interaction]s and customize the
* appearance / behavior of this NavigationRailItem in different [Interaction]s.
* @param selectedContentColor the color of the text label and icon when this item is selected,
* and the color of the ripple.
* @param unselectedContentColor the color of the text label and icon when this item is not selected
*/
@Composable
fun NavigationRailItem(
selected: Boolean,
onClick: () -> Unit,
icon: @Composable () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
label: @Composable (() -> Unit)? = null,
alwaysShowLabel: Boolean = true,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
selectedContentColor: Color = MaterialTheme.colors.primary,
unselectedContentColor: Color = LocalContentColor.current.copy(alpha = ContentAlpha.medium)
) {
val styledLabel: @Composable (() -> Unit)? = label?.let {
@Composable {
val style = MaterialTheme.typography.caption.copy(textAlign = TextAlign.Center)
ProvideTextStyle(style, content = label)
}
}
// Default to compact size when the item has no label, or a regular size when it does.
// Any size value that was set on the given Modifier will take precedence and allow custom
// sizing.
val itemSize = if (label == null) NavigationRailItemCompactSize else NavigationRailItemSize
// The color of the Ripple should always the selected color, as we want to show the color
// before the item is considered selected, and hence before the new contentColor is
// provided by NavigationRailTransition.
val ripple = rememberRipple(
bounded = false,
color = selectedContentColor
)
Box(
modifier
.selectable(
selected = selected,
onClick = onClick,
enabled = enabled,
role = Role.Tab,
interactionSource = interactionSource,
indication = ripple
).size(itemSize),
contentAlignment = Alignment.Center
) {
NavigationRailTransition(
selectedContentColor,
unselectedContentColor,
selected
) { progress ->
val animationProgress = if (alwaysShowLabel) 1f else progress
NavigationRailItemBaselineLayout(
icon = icon,
label = styledLabel,
iconPositionAnimationProgress = animationProgress
)
}
}
}
/**
* Contains default values used for [NavigationRail].
*/
object NavigationRailDefaults {
/**
* Default elevation used for [NavigationRail].
*/
val Elevation = 8.dp
}
/**
* Transition that animates [LocalContentColor] between [inactiveColor] and [activeColor], depending
* on [selected]. This component also provides the animation fraction as a parameter to [content],
* to allow animating the position of the icon and the scale of the label alongside this color
* animation.
*
* @param activeColor [LocalContentColor] when this item is [selected]
* @param inactiveColor [LocalContentColor] when this item is not [selected]
* @param selected whether this item is selected
* @param content the content of the [NavigationRailItem] to animate [LocalContentColor] for,
* where the animationProgress is the current progress of the animation from 0f to 1f.
*/
@Composable
private fun NavigationRailTransition(
activeColor: Color,
inactiveColor: Color,
selected: Boolean,
content: @Composable (animationProgress: Float) -> Unit
) {
val animationProgress by animateFloatAsState(
targetValue = if (selected) 1f else 0f,
animationSpec = NavigationRailAnimationSpec
)
val color = lerp(inactiveColor, activeColor, animationProgress)
CompositionLocalProvider(
LocalContentColor provides color.copy(alpha = 1f),
LocalContentAlpha provides color.alpha,
) {
content(animationProgress)
}
}
/**
* Base layout for a [NavigationRailItem]
*
* @param icon icon for this item
* @param label text label for this item
* @param iconPositionAnimationProgress progress of the animation that controls icon position,
* where 0 represents its unselected position and 1 represents its selected position. If both the
* [icon] and [label] should be shown at all times, this will always be 1, as the icon position
* should remain constant.
*/
@Composable
private fun NavigationRailItemBaselineLayout(
icon: @Composable () -> Unit,
label: @Composable (() -> Unit)?,
/*@FloatRange(from = 0.0, to = 1.0)*/
iconPositionAnimationProgress: Float
) {
Layout(
{
Box(Modifier.layoutId("icon")) { icon() }
if (label != null) {
Box(
Modifier
.layoutId("label")
.alpha(iconPositionAnimationProgress)
) { label() }
}
}
) { measurables, constraints ->
val iconPlaceable = measurables.first { it.layoutId == "icon" }.measure(constraints)
val labelPlaceable = label?.let {
measurables.first { it.layoutId == "label" }.measure(
// Measure with loose constraints for height as we don't want the label to take up more
// space than it needs
constraints.copy(minHeight = 0)
)
}
// If there is no label, just place the icon.
if (label == null) {
placeIcon(iconPlaceable, constraints)
} else {
placeLabelAndIcon(
labelPlaceable!!,
iconPlaceable,
constraints,
iconPositionAnimationProgress
)
}
}
}
/**
* Places the provided [iconPlaceable] in the vertical center of the provided [constraints]
*/
private fun MeasureScope.placeIcon(
iconPlaceable: Placeable,
constraints: Constraints
): MeasureResult {
val iconX = max(0, (constraints.maxWidth - iconPlaceable.width) / 2)
val iconY = max(0, (constraints.maxHeight - iconPlaceable.height) / 2)
return layout(constraints.maxWidth, constraints.maxHeight) {
iconPlaceable.placeRelative(iconX, iconY)
}
}
/**
* Places the provided [labelPlaceable] and [iconPlaceable] in the correct position, depending on
* [iconPositionAnimationProgress].
*
* When [iconPositionAnimationProgress] is 0, [iconPlaceable] will be placed in the center, as with
* [placeIcon], and [labelPlaceable] will not be shown.
*
* When [iconPositionAnimationProgress] is 1, [iconPlaceable] will be placed near the top of item,
* and [labelPlaceable] will be placed at the bottom of the item, according to the spec.
*
* When [iconPositionAnimationProgress] is animating between these values, [iconPlaceable] will be
* placed at an interpolated position between its centered position and final resting position.
*
* @param labelPlaceable text label placeable inside this item
* @param iconPlaceable icon placeable inside this item
* @param iconPositionAnimationProgress the progress of the icon position animation, where 0
* represents centered icon and no label, and 1 represents top aligned icon with label.
* Values between 0 and 1 interpolate the icon position so we can smoothly move the icon.
*/
private fun MeasureScope.placeLabelAndIcon(
labelPlaceable: Placeable,
iconPlaceable: Placeable,
constraints: Constraints,
/*@FloatRange(from = 0.0, to = 1.0)*/
iconPositionAnimationProgress: Float
): MeasureResult {
val baseline = labelPlaceable[LastBaseline]
val labelBaselineOffset = ItemLabelBaselineBottomOffset.roundToPx()
// Label should be [ItemLabelBaselineBottomOffset] from the bottom
val labelY = constraints.maxHeight - baseline - labelBaselineOffset
val labelX = (constraints.maxWidth - labelPlaceable.width) / 2
// Icon should be [ItemIconTopOffset] from the top when selected
val selectedIconY = ItemIconTopOffset.roundToPx()
val unselectedIconY = (constraints.maxHeight - iconPlaceable.height) / 2
val iconX = (constraints.maxWidth - iconPlaceable.width) / 2
// How far the icon needs to move between unselected and selected states
val iconDistance = unselectedIconY - selectedIconY
// When selected the icon is above the unselected position, so we will animate moving
// downwards from the selected state, so when progress is 1, the total distance is 0, and we
// are at the selected state.
val offset = (iconDistance * (1 - iconPositionAnimationProgress)).roundToInt()
return layout(constraints.maxWidth, constraints.maxHeight) {
if (iconPositionAnimationProgress != 0f) {
labelPlaceable.placeRelative(labelX, labelY + offset)
}
iconPlaceable.placeRelative(iconX, selectedIconY + offset)
}
}
/**
* [VectorizedAnimationSpec] controlling the transition between unselected and selected
* [NavigationRailItem]s.
*/
private val NavigationRailAnimationSpec = TweenSpec<Float>(
durationMillis = 300,
easing = FastOutSlowInEasing
)
/**
* Size of a regular [NavigationRailItem].
*/
private val NavigationRailItemSize = 72.dp
/**
* Size of a compact [NavigationRailItem].
*/
private val NavigationRailItemCompactSize = 56.dp
/**
* Padding at the top and the bottom of the [NavigationRail]
*/
private val NavigationRailPadding = 8.dp
/**
* Padding at the bottom of the [NavigationRail]'s header [Composable]. This padding will only be
* added when the header is not null.
*/
private val HeaderPadding = 8.dp
/**
* The space between the text label's baseline and the bottom of the container.
*/
private val ItemLabelBaselineBottomOffset = 16.dp
/**
* The space between the icon and the top of the container when an item contains a label and icon.
*/
private val ItemIconTopOffset = 14.dp | apache-2.0 | 8a14e7da3db7b2b9290ceba362040be7 | 39.009877 | 134 | 0.717892 | 4.668107 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/ListNumberToListNumber.kt | 1 | 5302 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import java.lang.IllegalArgumentException
abstract class ListNumberToListNumber<
GRAPH_DEF : GeneratedMessageV3,
OP_DEF_TYPE : GeneratedMessageV3,
NODE_TYPE : GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum>(
mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>
) :
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(
name = "listnumbertolistnumber",
mappingNamesToPerform = mappingNamesToPerform,
transformerArgs = transformerArgs
) {
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.INT ||
argDescriptorType == AttributeValueType.FLOAT ||
argDescriptorType == AttributeValueType.LIST_INT ||
argDescriptorType == AttributeValueType.LIST_FLOAT
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64) ||
argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.DOUBLE)
}
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
for ((k, v) in mappingNamesToPerform()) {
val irAttribute = mappingCtx.irAttributeValueForNode(v)
when (irAttribute.attributeValueType()) {
AttributeValueType.LIST_INT -> {
val baseIndex = if(mappingCtx.descriptorsSoFar().isEmpty()) lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
) else mappingCtx.descriptorsSoFar().size
val listInts = irAttribute.listIntValue()
listInts.forEachIndexed { index, element ->
val finalName = if (index > 0) k + "$index" else k
val argDescriptor = ArgDescriptor {
name = finalName
int64Value = element
argType = OpNamespace.ArgDescriptor.ArgType.INT64
argIndex = baseIndex + index
}
ret.add(argDescriptor)
}
}
AttributeValueType.LIST_FLOAT -> {
val baseIndex = if(mappingCtx.descriptorsSoFar().isEmpty()) lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.DOUBLE
) else mappingCtx.descriptorsSoFar().size
val listFloats = irAttribute.listFloatValue()
listFloats.forEachIndexed { index, element ->
val finalName = if (index > 0) k + "$index" else k
val argDescriptor = ArgDescriptor {
name = finalName
doubleValue = element.toDouble()
argType = OpNamespace.ArgDescriptor.ArgType.DOUBLE
argIndex = baseIndex + index
}
ret.add(argDescriptor)
}
}
else -> {throw IllegalArgumentException("Illegal type ${irAttribute.attributeValueType()}")}
}
}
return ret
}
} | apache-2.0 | 47971c7863ed40000afafb4dd8efe324 | 47.209091 | 183 | 0.602603 | 5.360971 | false | false | false | false |
nextras/orm-intellij | src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReferenceProvider.kt | 1 | 3307 | package org.nextras.orm.intellij.reference
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceProvider
import com.intellij.util.ProcessingContext
import com.jetbrains.php.lang.parser.PhpElementTypes
import com.jetbrains.php.lang.psi.elements.*
import org.nextras.orm.intellij.utils.OrmUtils
import java.util.regex.Pattern
class CollectionPropertyReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(psiElement: PsiElement, processingContext: ProcessingContext): Array<PsiReference> {
val ref = getMethodReference(psiElement) ?: return emptyArray()
val content = (psiElement as StringLiteralExpression).contents
val isV3 = OrmUtils.isV3(psiElement.project)
val matcher = when (isV3) {
true -> fieldExpressionV3.matcher(content)
false -> fieldExpressionV4.matcher(content)
}
if (!matcher.matches()) {
return emptyArray()
}
val (sourceCls, path) = OrmUtils.parsePathExpression(matcher.group(1), isV3)
if (sourceCls == null && path.isEmpty()) {
return emptyArray()
}
val result = processExpression(
el = psiElement,
ref = ref,
sourceCls = sourceCls,
path = path,
fieldName = processingContext.get("field") as String?
)
return result.toTypedArray()
}
private fun getMethodReference(el: PsiElement): MethodReference? {
// incomplete array
if (el.parent.node.elementType === PhpElementTypes.ARRAY_VALUE
&& (el.parent as PhpPsiElement).prevPsiSibling == null
&& el.parent.parent is ArrayCreationExpression
&& el.parent.parent.parent is ParameterList
&& el.parent.parent.parent.parent is MethodReference
) {
val ref = el.parent.parent.parent.parent as MethodReference
return when (ref.name) {
"findBy", "getBy", "getByChecked", "orderBy" -> ref
else -> null
}
}
if (el.parent.node.elementType === PhpElementTypes.ARRAY_KEY
&& el.parent.parent is ArrayHashElement
&& el.parent.parent.parent is ArrayCreationExpression
&& el.parent.parent.parent.parent is ParameterList
&& el.parent.parent.parent.parent.parent is MethodReference
) {
val ref = el.parent.parent.parent.parent.parent as MethodReference
return when (ref.name) {
"findBy", "getBy", "getByChecked", "orderBy" -> ref
else -> null
}
}
if (el.parent is ParameterList && el.parent.parent is MethodReference) {
val ref = el.parent.parent as MethodReference
if (ref.name == "orderBy") {
return ref
}
}
return null
}
private fun processExpression(
el: StringLiteralExpression,
ref: MethodReference,
sourceCls: String?,
path: Array<String>,
fieldName: String?
): Collection<PsiReference> {
val result = mutableListOf<PsiReference>()
if (sourceCls != null && fieldName == null) {
result.add(CollectionClassReference(el, ref, sourceCls))
}
for (i in path.indices) {
if ((path[i] != "" && fieldName == null) || (fieldName != null && fieldName == path[i])) {
result.add(CollectionPropertyReference(el, ref, sourceCls, path, i))
}
}
return result
}
companion object {
private val fieldExpressionV3 = Pattern.compile("^([\\w\\\\]+(?:->\\w*)*)(!|!=|<=|>=|=|>|<)?$")
private val fieldExpressionV4 = Pattern.compile("^((?:[\\w\\\\]+::)?(\\w*)?(?:->\\w*)*)(!|!=|<=|>=|=|>|<)?$")
}
}
| mit | 1d7abf105ecce3c6d078f5e3b6ae1adb | 30.495238 | 121 | 0.697611 | 3.536898 | false | false | false | false |
liuche/focus-android | app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteAddFragment.kt | 1 | 2904 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.autocomplete
import android.app.Fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_autocomplete_add_domain.*
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import org.mozilla.focus.R
import org.mozilla.focus.ext.removePrefixesIgnoreCase
import org.mozilla.focus.settings.BaseSettingsFragment
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.ViewUtils
/**
* Fragment showing settings UI to add custom autocomplete domains.
*/
class AutocompleteAddFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onResume() {
super.onResume()
val updater = activity as BaseSettingsFragment.ActionBarUpdater
updater.updateTitle(R.string.preference_autocomplete_title_add)
updater.updateIcon(R.drawable.ic_close)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater!!.inflate(R.layout.fragment_autocomplete_add_domain, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
ViewUtils.showKeyboard(domainView)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_autocomplete_add, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.save) {
val domain = domainView.text.toString()
.trim()
.toLowerCase()
.removePrefixesIgnoreCase("http://", "https://", "www.")
if (domain.isEmpty()) {
domainView.error = getString(R.string.preference_autocomplete_add_error)
} else {
saveDomainAndClose(activity.applicationContext, domain)
}
return true
}
return super.onOptionsItemSelected(item)
}
private fun saveDomainAndClose(context: Context, domain: String) {
launch(CommonPool) {
CustomAutocomplete.addDomain(context, domain)
TelemetryWrapper.saveAutocompleteDomainEvent()
}
ViewUtils.showBrandedSnackbar(view, R.string.preference_autocomplete_add_confirmation, 0)
fragmentManager.popBackStack()
}
}
| mpl-2.0 | 5b6b8d678a7ae8defe8941011605da91 | 33.164706 | 116 | 0.703512 | 4.699029 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/ui/IssueList.kt | 1 | 4867 | package com.github.jk1.ytplugin.ui
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.issues.model.Issue
import com.github.jk1.ytplugin.setup.SetupDialog
import com.github.jk1.ytplugin.tasks.YouTrackServer
import com.intellij.ui.ListSpeedSearch
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER
import com.intellij.ui.components.JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import java.awt.event.MouseListener
import javax.swing.AbstractAction
import javax.swing.AbstractListModel
import javax.swing.KeyStroke
import javax.swing.SwingUtilities
class IssueList(val repo: YouTrackServer) : JBLoadingPanel(BorderLayout(), repo.project), ComponentAware {
override val project = repo.project
private val issueList: JBList<Issue> = JBList()
private val issueListModel: IssueListModel = IssueListModel()
val renderer: IssueListCellRenderer
init {
val issueListScrollPane = JBScrollPane(issueList, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER)
renderer = IssueListCellRenderer({ issueListScrollPane.viewport.width }, IssueListCellIconProvider(project))
issueList.cellRenderer = renderer
add(issueListScrollPane, BorderLayout.CENTER)
initIssueListModel()
ListSpeedSearch(issueList)
}
private fun initIssueListModel() {
issueList.emptyText.clear()
issueList.model = issueListModel
startLoading()
if (issueStoreComponent[repo].getAllIssues().isEmpty()) {
issueStoreComponent[repo].update(repo).doWhenDone {
issueListModel.update()
stopLoading()
}
} else {
stopLoading()
}
// listen to IssueStore updates and repaint issue list accordingly
issueUpdaterComponent.subscribe {
SwingUtilities.invokeLater {
val placeholder = issueList.emptyText
placeholder.clear()
if (issueStoreComponent[repo].getAllIssues().isEmpty()) {
placeholder.appendText("No issues found. Edit search request or ")
placeholder.appendText("configuration", SimpleTextAttributes.LINK_ATTRIBUTES
) { SetupDialog(project, repo, false).show() }
}
issueListModel.update()
val updatedSelectedIssueIndex = issueStoreComponent[repo].indexOf(getSelectedIssue())
if (updatedSelectedIssueIndex == -1) {
issueList.clearSelection()
} else {
issueList.selectedIndex = updatedSelectedIssueIndex
}
stopLoading()
}
}
}
fun getSelectedIssue() = when {
issueList.selectedIndex == -1 -> null
issueList.selectedIndex >= issueListModel.size -> null
else -> issueListModel.getElementAt(issueList.selectedIndex)
}
fun getIssueById(id: String) = when {
issueList.selectedIndex == -1 -> null
issueList.selectedIndex >= issueListModel.size -> null
else -> issueListModel.getElementById(id)
}
fun setSelectedIssue(issue: Issue) {
issueList.selectedIndex = issueListModel.getIndexOfElement(issue)
}
fun getIssueCount() = issueListModel.size
fun update() = issueListModel.update()
fun addListSelectionListener(listener: () -> Unit) {
issueList.addListSelectionListener { listener.invoke() }
}
fun addComponentInput(key: String, keyStroke: KeyStroke) {
issueList.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, key)
}
fun addComponentAction(key: String, action: () -> Unit) {
issueList.actionMap.put(key, object: AbstractAction(){
override fun actionPerformed(e: ActionEvent) {
action.invoke()
}
})
}
override fun addMouseListener(l: MouseListener) {
issueList.addMouseListener(l)
}
inner class IssueListModel : AbstractListModel<Issue>() {
override fun getElementAt(index: Int) = issueStoreComponent[repo].getIssue(index)
fun getIndexOfElement(issue: Issue) = issueStoreComponent[repo].getIndex(issue)
fun getElementById(id: String) = issueStoreComponent[repo].getIssueById(id)
// we still can get this method invoked from swing focus lost handler on project close
override fun getSize() = if (project.isDisposed) 0 else issueStoreComponent[repo].getAllIssues().size
fun update() {
fireContentsChanged(this, 0, size)
}
}
} | apache-2.0 | cda00ccd0828e7b59efef449cb79d8e1 | 37.03125 | 116 | 0.67783 | 4.981576 | false | false | false | false |
stuartcarnie/toml-plugin | src/main/kotlin/org/toml/lang/TomlFileType.kt | 1 | 678 | package org.toml.lang
import com.intellij.icons.AllIcons
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import org.toml.lang.icons.TomlIcons
public object TomlFileType : LanguageFileType(TomlLanguage) {
public object DEFAULTS {
val EXTENSION = "toml";
val DESCRIPTION = "TOML file";
}
override fun getName() = DEFAULTS.DESCRIPTION
override fun getDescription() = DEFAULTS.DESCRIPTION
override fun getDefaultExtension() = DEFAULTS.EXTENSION
override fun getIcon() = TomlIcons.TOML
override fun getCharset(file: VirtualFile, content: ByteArray) = "UTF-8"
}
| mit | d104e9f1d59883016d73d0e2cc8290ac | 31.285714 | 76 | 0.724189 | 4.550336 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/MainNavigationController.kt | 1 | 2107 | package com.habitrpg.android.habitica.helpers
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.navigation.NavController
import androidx.navigation.NavDeepLinkRequest
import androidx.navigation.NavDirections
import java.lang.ref.WeakReference
import java.util.Date
import kotlin.math.abs
object MainNavigationController {
var lastNavigation: Date? = null
private var controllerReference: WeakReference<NavController>? = null
private val navController: NavController?
get() { return controllerReference?.get() }
fun setup(navController: NavController) {
this.controllerReference = WeakReference(navController)
}
fun navigate(transactionId: Int, args: Bundle? = null) {
if (abs((lastNavigation?.time ?: 0) - Date().time) > 500) {
lastNavigation = Date()
try {
navController?.navigate(transactionId, args)
} catch (e: IllegalArgumentException) {
Log.e("Main Navigation", e.localizedMessage ?: "")
} catch (error: Exception) {
Log.e("Main Navigation", error.localizedMessage ?: "")
}
}
}
fun navigate(directions: NavDirections) {
if (abs((lastNavigation?.time ?: 0) - Date().time) > 500) {
lastNavigation = Date()
try {
navController?.navigate(directions)
} catch (_: IllegalArgumentException) {}
}
}
fun navigate(uriString: String) {
val uri = Uri.parse(uriString)
navigate(uri)
}
fun navigate(uri: Uri) {
if (navController?.graph?.hasDeepLink(uri) == true) {
navController?.navigate(uri)
}
}
fun navigate(request: NavDeepLinkRequest) {
if (navController?.graph?.hasDeepLink(request) == true) {
navController?.navigate(request)
}
}
fun handle(deeplink: Intent) {
navController?.handleDeepLink(deeplink)
}
fun navigateBack() {
navController?.navigateUp()
}
}
| gpl-3.0 | 95783fb0aab863ae1e2cc55997dbb898 | 28.263889 | 73 | 0.627432 | 4.766968 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/StreamFormat.kt | 3 | 5347 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe
import androidx.annotation.RequiresApi
/**
* Platform-independent Android ImageFormats and their associated values.
*
* Using this inline class prevents missing values on platforms where the format is not present
* or not listed.
* // TODO: Consider adding data-space as a separate property, or finding a way to work it in.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@JvmInline
public value class StreamFormat(public val value: Int) {
public companion object {
public val UNKNOWN: StreamFormat = StreamFormat(0)
public val PRIVATE: StreamFormat = StreamFormat(0x22)
public val DEPTH16: StreamFormat = StreamFormat(0x44363159)
public val DEPTH_JPEG: StreamFormat = StreamFormat(0x69656963)
public val DEPTH_POINT_CLOUD: StreamFormat = StreamFormat(0x101)
public val FLEX_RGB_888: StreamFormat = StreamFormat(0x29)
public val FLEX_RGBA_8888: StreamFormat = StreamFormat(0x2A)
public val HEIC: StreamFormat = StreamFormat(0x48454946)
public val JPEG: StreamFormat = StreamFormat(0x100)
public val NV16: StreamFormat = StreamFormat(0x10)
public val NV21: StreamFormat = StreamFormat(0x11)
public val RAW10: StreamFormat = StreamFormat(0x25)
public val RAW12: StreamFormat = StreamFormat(0x26)
public val RAW_DEPTH: StreamFormat = StreamFormat(0x1002)
public val RAW_PRIVATE: StreamFormat = StreamFormat(0x24)
public val RAW_SENSOR: StreamFormat = StreamFormat(0x20)
public val RGB_565: StreamFormat = StreamFormat(4)
public val Y12: StreamFormat = StreamFormat(0x32315659)
public val Y16: StreamFormat = StreamFormat(0x20363159)
public val Y8: StreamFormat = StreamFormat(0x20203859)
public val YUV_420_888: StreamFormat = StreamFormat(0x23)
public val YUV_422_888: StreamFormat = StreamFormat(0x27)
public val YUV_444_888: StreamFormat = StreamFormat(0x28)
public val YUY2: StreamFormat = StreamFormat(0x14)
public val YV12: StreamFormat = StreamFormat(0x32315659)
}
override fun toString(): String {
return "StreamFormat($name)"
}
/**
* This function returns the number of bits per pixel for a given stream format.
*
* @return the number of bits per pixel or -1 if the format does not have a well defined
* number of bits per pixel.
*/
public val bitsPerPixel: Int
get() {
when (this) {
DEPTH16 -> return 16
FLEX_RGB_888 -> return 24
FLEX_RGBA_8888 -> return 32
NV16 -> return 16
NV21 -> return 12
RAW10 -> return 10
RAW12 -> return 12
RAW_DEPTH -> return 16
RAW_SENSOR -> return 16
RGB_565 -> return 16
Y12 -> return 12
Y16 -> return 16
Y8 -> return 8
YUV_420_888 -> return 12
YUV_422_888 -> return 16
YUV_444_888 -> return 24
YUY2 -> return 16
YV12 -> return 12
}
return -1
}
/**
* This function returns a human readable string for the associated format.
*
* @return a human readable string representation of the StreamFormat.
*/
public val name: String
get() {
when (this) {
UNKNOWN -> return "UNKNOWN"
PRIVATE -> return "PRIVATE"
DEPTH16 -> return "DEPTH16"
DEPTH_JPEG -> return "DEPTH_JPEG"
DEPTH_POINT_CLOUD -> return "DEPTH_POINT_CLOUD"
FLEX_RGB_888 -> return "FLEX_RGB_888"
FLEX_RGBA_8888 -> return "FLEX_RGBA_8888"
HEIC -> return "HEIC"
JPEG -> return "JPEG"
NV16 -> return "NV16"
NV21 -> return "NV21"
RAW10 -> return "RAW10"
RAW12 -> return "RAW12"
RAW_DEPTH -> return "RAW_DEPTH"
RAW_PRIVATE -> return "RAW_PRIVATE"
RAW_SENSOR -> return "RAW_SENSOR"
RGB_565 -> return "RGB_565"
Y12 -> return "Y12"
Y16 -> return "Y16"
Y8 -> return "Y8"
YUV_420_888 -> return "YUV_420_888"
YUV_422_888 -> return "YUV_422_888"
YUV_444_888 -> return "YUV_444_888"
YUY2 -> return "YUY2"
YV12 -> return "YV12"
}
return "UNKNOWN-${this.value.toString(16)}"
}
} | apache-2.0 | 7b655171b93ea394d3de2775b467c012 | 39.210526 | 95 | 0.596222 | 4.16433 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/timeline/BaseTimelineAdapter.kt | 1 | 4616 | /*
* Copyright (C) 2015-2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.timeline
import android.view.View
import android.widget.BaseAdapter
import android.widget.TextView
import org.andstatus.app.R
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.SharedPreferencesUtil
abstract class BaseTimelineAdapter<T : ViewItem<T>>(
protected val myContext: MyContext,
private val listData: TimelineData<T>) : BaseAdapter(), View.OnClickListener {
protected val showAvatars = MyPreferences.getShowAvatars()
protected val showAttachedImages = MyPreferences.getDownloadAndDisplayAttachedImages()
protected val markRepliesToMe = SharedPreferencesUtil.getBoolean(
MyPreferences.KEY_MARK_REPLIES_TO_ME_IN_TIMELINE, true)
private val displayDensity: Float
@Volatile
private var positionRestored = false
/** Single page data */
constructor(myContext: MyContext, timeline: Timeline, items: MutableList<T>) : this(myContext,
TimelineData<T>(
null,
TimelinePage<T>(TimelineParameters(myContext, timeline, WhichPage.EMPTY), items)
)
) {
}
fun getListData(): TimelineData<T> {
return listData
}
override fun getCount(): Int {
return listData.size()
}
override fun getItemId(position: Int): Long {
return getItem(position).getId()
}
override fun getItem(position: Int): T {
return listData.getItem(position)
}
fun getItem(view: View): T {
return getItem(getPosition(view))
}
/** @return -1 if not found
*/
fun getPosition(view: View): Int {
val positionView = getPositionView(view) ?: return -1
return positionView.text.toString().toInt()
}
private fun getPositionView(view: View?): TextView? {
var parentView: View = view ?: return null
for (i in 0..9) {
val positionView = parentView.findViewById<TextView?>(R.id.position)
if (positionView != null) {
return positionView
}
parentView = if (parentView.getParent() != null &&
View::class.java.isAssignableFrom(parentView.getParent().javaClass)) {
parentView.getParent() as View
} else {
break
}
}
return null
}
protected fun setPosition(view: View, position: Int) {
val positionView = getPositionView(view)
if (positionView != null) {
positionView.text = Integer.toString(position)
}
}
fun getPositionById(itemId: Long): Int {
return listData.getPositionById(itemId)
}
fun setPositionRestored(positionRestored: Boolean) {
this.positionRestored = positionRestored
}
fun isPositionRestored(): Boolean {
return positionRestored
}
protected fun mayHaveYoungerPage(): Boolean {
return listData.mayHaveYoungerPage()
}
protected fun isCombined(): Boolean {
return listData.params.isTimelineCombined()
}
override fun onClick(v: View) {
if (!MyPreferences.isLongPressToOpenContextMenu() && v.getParent() != null) {
v.showContextMenu()
}
}
// See http://stackoverflow.com/questions/2238883/what-is-the-correct-way-to-specify-dimensions-in-dip-from-java-code
fun dpToPixes(dp: Int): Int {
return (dp * displayDensity).toInt()
}
override fun toString(): String {
return MyStringBuilder.formatKeyValue(this, listData)
}
init {
if (myContext.isEmpty) {
displayDensity = 1f
} else {
displayDensity = myContext.context.resources.displayMetrics.density
MyLog.v(this) { "density=$displayDensity" }
}
}
}
| apache-2.0 | e69c79537fff302d4ea2503195bc990c | 30.834483 | 122 | 0.653813 | 4.477207 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/PrvMessengerActivity.kt | 1 | 4080 | package me.proxer.app.chat.prv
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.fragment.app.commitNow
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.chat.prv.conference.ConferenceFragment
import me.proxer.app.chat.prv.message.MessengerFragment
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.util.extension.intentFor
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.startActivity
import timber.log.Timber
/**
* @author Ruben Gees
*/
class PrvMessengerActivity : DrawerActivity() {
companion object {
private const val CONFERENCE_EXTRA = "conference"
fun navigateTo(context: Activity, conference: LocalConference, initialMessage: String? = null) {
context.startActivity<PrvMessengerActivity>(
CONFERENCE_EXTRA to conference,
Intent.EXTRA_TEXT to initialMessage
)
}
fun getIntent(context: Context, conference: LocalConference, initialMessage: String? = null): Intent {
return context.intentFor<PrvMessengerActivity>(
CONFERENCE_EXTRA to conference,
Intent.EXTRA_TEXT to initialMessage
)
}
fun getIntent(context: Context, conferenceId: String, initialMessage: String? = null): Intent {
return context.intentFor<PrvMessengerActivity>(
ShortcutManagerCompat.EXTRA_SHORTCUT_ID to conferenceId,
Intent.EXTRA_TEXT to initialMessage
)
}
}
private val messengerDao by safeInject<MessengerDao>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (supportFragmentManager.fragments.isEmpty()) {
val conference = intent.getParcelableExtra<LocalConference>(CONFERENCE_EXTRA)
val initialMessage = intent.getStringExtra(Intent.EXTRA_TEXT)
if (conference != null) {
supportFragmentManager.commitNow {
replace(R.id.container, MessengerFragment.newInstance(conference, initialMessage))
}
} else {
val conferenceId = intent.getStringExtra(ShortcutManagerCompat.EXTRA_SHORTCUT_ID)?.toLongOrNull()
if (conferenceId != null) {
title = getString(R.string.fragment_chat_loading_message)
messengerDao.getConferenceMaybe(conferenceId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this.scope())
.subscribe(
{
if (it != null) {
supportFragmentManager.commitNow {
replace(R.id.container, MessengerFragment.newInstance(it, initialMessage))
}
} else {
error("No conference found for id $conferenceId")
}
},
{
Timber.e(it)
finish()
}
)
} else {
title = getString(R.string.activity_prv_messenger_send_to)
supportFragmentManager.commitNow {
replace(R.id.container, ConferenceFragment.newInstance(initialMessage))
}
}
}
}
}
}
| gpl-3.0 | cbc0c5ddcc2c8562c47ab647b5ab1e68 | 38.230769 | 114 | 0.589461 | 5.491252 | false | false | false | false |
wealthfront/magellan | magellan-library/src/test/java/com/wealthfront/magellan/navigation/NavigationTraverserTest.kt | 1 | 6156 | package com.wealthfront.magellan.navigation
import android.app.Activity
import android.content.Context
import com.google.common.truth.Truth.assertThat
import com.wealthfront.magellan.core.Journey
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.internal.test.databinding.MagellanDummyLayoutBinding
import com.wealthfront.magellan.lifecycle.LifecycleState.Created
import com.wealthfront.magellan.lifecycle.transitionToState
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric.buildActivity
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
internal class NavigationTraverserTest {
private lateinit var traverser: NavigationTraverser
private lateinit var oneStepRoot: Journey<*>
private lateinit var multiStepRoot: Journey<*>
private lateinit var siblingRoot: Journey<*>
private lateinit var customRoot: Journey<*>
private lateinit var journey1: Journey<*>
private lateinit var step1: Step<*>
private lateinit var step2: Step<*>
private lateinit var step3: Step<*>
private lateinit var journey2: Journey<*>
private lateinit var step4: Step<*>
private lateinit var journey3: DummyJourney3
private lateinit var customStep: Step<*>
private lateinit var context: Activity
@Before
fun setUp() {
context = buildActivity(Activity::class.java).get()
oneStepRoot = RootJourney()
multiStepRoot = MultiStepJourney()
siblingRoot = SiblingJourney()
customRoot = CustomJourney()
journey1 = DummyJourney1()
journey2 = DummyJourney2()
journey3 = DummyJourney3((siblingRoot as SiblingJourney)::goToJourney2)
customStep = CustomStep(DummyStep1())
step1 = DummyStep1()
step2 = DummyStep2()
step3 = DummyStep3()
step4 = DummyStep4()
}
@Test
fun globalBackStackWithOneStep() {
traverser = NavigationTraverser(oneStepRoot)
oneStepRoot.transitionToState(Created(context))
assertThat(traverser.getGlobalBackstackDescription()).isEqualTo(
"""
RootJourney
└ DummyJourney1
└ DummyStep1
""".trimIndent()
)
}
@Test
fun globalBackStackWithMultipleStep() {
traverser = NavigationTraverser(multiStepRoot)
multiStepRoot.transitionToState(Created(context))
assertThat(traverser.getGlobalBackstackDescription()).isEqualTo(
"""
MultiStepJourney
└ DummyJourney2
├ DummyStep1
└ DummyStep2
""".trimIndent()
)
}
@Test
fun globalBackStackWithSiblingJourney() {
traverser = NavigationTraverser(siblingRoot)
siblingRoot.transitionToState(Created(context))
journey3.goToAnotherJourney()
assertThat(traverser.getGlobalBackstackDescription()).isEqualTo(
"""
SiblingJourney
├ DummyJourney3
| ├ DummyStep3
| └ DummyStep4
└ DummyJourney2
├ DummyStep1
└ DummyStep2
""".trimIndent()
)
}
@Test
fun globalBackStackWithCustomNavigable() {
traverser = NavigationTraverser(customRoot)
customRoot.transitionToState(Created(context))
assertThat(traverser.getGlobalBackstackDescription()).isEqualTo(
"""
CustomJourney
└ CustomStep
└ DummyStep1
""".trimIndent()
)
}
private inner class RootJourney : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(journey1)
}
}
private inner class MultiStepJourney : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(journey2)
}
}
private inner class SiblingJourney : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(journey3)
}
fun goToJourney2() {
navigator.goTo(journey2)
}
}
private inner class CustomJourney : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(customStep)
}
}
private inner class DummyJourney1 : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(step1)
}
}
private inner class DummyJourney2 : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(step1)
navigator.goTo(step2)
}
}
private inner class DummyJourney3(
private val goToOtherJourney: () -> Unit
) : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
) {
override fun onCreate(context: Context) {
navigator.goTo(step3)
navigator.goTo(step4)
}
fun goToAnotherJourney() = goToOtherJourney()
}
private inner class DummyStep1 :
Step<MagellanDummyLayoutBinding>(MagellanDummyLayoutBinding::inflate)
private inner class DummyStep2 :
Step<MagellanDummyLayoutBinding>(MagellanDummyLayoutBinding::inflate)
private inner class DummyStep3 :
Step<MagellanDummyLayoutBinding>(MagellanDummyLayoutBinding::inflate)
private inner class DummyStep4 :
Step<MagellanDummyLayoutBinding>(MagellanDummyLayoutBinding::inflate)
private inner class CustomStep(val customChild: NavigableCompat) : Step<MagellanDummyLayoutBinding>(MagellanDummyLayoutBinding::inflate) {
override fun createSnapshot(): NavigationNode {
return object : NavigationNode {
override val value: NavigableCompat
get() = this@CustomStep
override val children: List<NavigationNode>
get() = listOf(customChild.createSnapshot())
}
}
}
}
| apache-2.0 | c9f96ec84fd624c73c1c895e50026e55 | 26.366071 | 140 | 0.732137 | 4.527326 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/ads/dto/AdsPromotedPostReach.kt | 1 | 3133 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.ads.dto
import com.google.gson.annotations.SerializedName
import kotlin.Int
/**
* @param hide - Hides amount
* @param id - Object ID from 'ids' parameter
* @param joinGroup - Community joins
* @param links - Link clicks
* @param reachSubscribers - Subscribers reach
* @param reachTotal - Total reach
* @param report - Reports amount
* @param toGroup - Community clicks
* @param unsubscribe - 'Unsubscribe' events amount
* @param videoViews100p - Video views for 100 percent
* @param videoViews25p - Video views for 25 percent
* @param videoViews3s - Video views for 3 seconds
* @param videoViews50p - Video views for 50 percent
* @param videoViews75p - Video views for 75 percent
* @param videoViewsStart - Video starts
*/
data class AdsPromotedPostReach(
@SerializedName("hide")
val hide: Int,
@SerializedName("id")
val id: Int,
@SerializedName("join_group")
val joinGroup: Int,
@SerializedName("links")
val links: Int,
@SerializedName("reach_subscribers")
val reachSubscribers: Int,
@SerializedName("reach_total")
val reachTotal: Int,
@SerializedName("report")
val report: Int,
@SerializedName("to_group")
val toGroup: Int,
@SerializedName("unsubscribe")
val unsubscribe: Int,
@SerializedName("video_views_100p")
val videoViews100p: Int? = null,
@SerializedName("video_views_25p")
val videoViews25p: Int? = null,
@SerializedName("video_views_3s")
val videoViews3s: Int? = null,
@SerializedName("video_views_50p")
val videoViews50p: Int? = null,
@SerializedName("video_views_75p")
val videoViews75p: Int? = null,
@SerializedName("video_views_start")
val videoViewsStart: Int? = null
)
| mit | 04f4abe0817c5a69d433a8fe2d3a98a8 | 37.679012 | 81 | 0.687201 | 4.171771 | false | false | false | false |
jk1/pmd-kotlin | src/test/resources/org/jetbrains/pmdkotlin/ignoreIdentifiersAndLiteralsTest/IgnoreIdentifiers.kt | 1 | 351 | fun testfun(z : Double, x : Char, y : Int) {
var a = 2 * x;
var b = 3 * a;
val c = 1 * 2 * 3 * 4 * 5;
var t = y;
y = 'a';
return;
}
fun factorial10() : Int {
/* it's comment */
var start = 1
for (i in (1..10)) {
start *= i
}
return start
}
fun mus(x : Int, y : Int) : Int {
return y + x
}
| apache-2.0 | 32461366a9a1664d0ba3b59c7280d31c | 13.04 | 44 | 0.418803 | 2.7 | false | false | false | false |
sybila/ode-generator | src/main/java/com/github/sybila/ode/generator/smt/remote/Z3Solver.kt | 1 | 7579 | package com.github.sybila.ode.generator.smt.remote
import com.github.sybila.checker.Solver
import com.github.sybila.checker.solver.SolverStats
import com.github.sybila.ode.generator.smt.remote.bridge.RemoteZ3
import com.github.sybila.ode.generator.smt.remote.bridge.SMT
import com.github.sybila.ode.generator.smt.remote.bridge.readSMT
import com.github.sybila.ode.model.OdeModel
import java.io.Closeable
import java.nio.ByteBuffer
private fun pow (a: Int, b: Int): Int {
if ( b == 0) return 1
if ( b == 1) return a
if ( b % 2 == 0) return pow (a * a, b / 2) //even a=(a^2)^b/2
else return a * pow (a * a, b / 2) //odd a=a*(a^2)^b/2
}
class Z3Solver(bounds: List<Pair<Double, Double>>, names: List<String> = bounds.indices.map { "p$it" })
: Solver<Z3Params>, Closeable, Z3SolverBase {
private val z3 = RemoteZ3(bounds.zip(names).map { OdeModel.Parameter(it.second, it.first) }, verbose = false)
private val cornerPoints = (0 until pow(2, bounds.size)).map { mask ->
bounds.mapIndexed { i, pair -> if (mask.shl(i).and(1) == 1) pair.second else pair.first }
}.map { names.zip(it).toMap() }.plus(names.zip(bounds.map { (it.first + it.second) / 2 }).toMap())
override val bounds: String
get() = z3.bounds
override fun close() {
z3.close()
}
override val ff: Z3Params = Z3Params("false", false, true)
override val tt: Z3Params = Z3Params("true", true, true)
private var coreSize = 0
override fun Z3Params.isSat(): Boolean {
SolverStats.solverCall()
if (this.formula.checkCorners()) {
return true
}
this.sat ?: run {
val sat = z3.checkSat(this.formula)
this.sat = sat
sat
}
return this.sat ?: true
}
private fun String.checkCorners(): Boolean {
val smt = this.readSMT()
for (point in cornerPoints) {
val sat = smt.checkAt(point)
if (sat) return true
}
return false
}
private fun SMT.checkAt(point: Map<String, Double>): Boolean {
return when (this) {
is SMT.Terminal -> data == "true"
is SMT.Expression -> when (this.funName) {
"not" -> !this.funArgs.first().checkAt(point)
"and" -> this.funArgs.fold(true) { a, i -> a && i.checkAt(point) }
"or" -> this.funArgs.fold(false) { a, i -> a || i.checkAt(point) }
">" -> this.funArgs[0].evalExpr(point) > this.funArgs[1].evalExpr(point)
"<" -> this.funArgs[0].evalExpr(point) < this.funArgs[1].evalExpr(point)
">=" -> this.funArgs[0].evalExpr(point) >= this.funArgs[1].evalExpr(point)
"<=" -> this.funArgs[0].evalExpr(point) <= this.funArgs[1].evalExpr(point)
else -> throw IllegalArgumentException(this.toString())
}
}
}
private fun SMT.evalExpr(point: Map<String, Double>): Double {
return when (this) {
is SMT.Terminal -> point[data] ?: data.toDouble()
is SMT.Expression -> when (this.funName) {
"+" -> funArgs.map { it.evalExpr(point) }.sum()
"-" -> funArgs.map { it.evalExpr(point) }.fold(0.0) { a, i -> a - i }
"*" -> funArgs.map { it.evalExpr(point) }.fold(1.0) { a, i -> a * i }
"/" -> funArgs[0].evalExpr(point) / funArgs[1].evalExpr(point)
else -> throw IllegalArgumentException(this.toString())
}
}
}
override fun Z3Params.minimize(force: Boolean) {
if (force || (!minimal && this.formula.length > 16 * coreSize)) {
val isSat = this.sat ?: z3.checkSat(this.formula)
this.sat = isSat
if (!isSat) {
this.formula = "false"
this.minimal = true
return
}
val simplified = z3.minimize(this.formula)
this.formula = simplified
sat = simplified != "false"
if (simplified.length > coreSize) {
coreSize = simplified.length
}
minimal = true
}
}
override fun Z3Params.minimize() {
this.minimize(false)
}
override fun Z3Params.and(other: Z3Params): Z3Params {
return Z3Params("(and ${this.formula} ${other.formula})", null)
/*
WHAT THE SHIT?!
val r = Z3Params("(and ${this.formula} ${other.formula})", null)
println("R: ${r.formula.length}")
c1 += 1
return if (r equals this) {
c2 += 1
this.apply { minimize() }
} else r.apply { minimize() }*/
}
override fun Z3Params.not(): Z3Params {
//note: double negation is not very common, we don't have to care...
return Z3Params("(not ${this.formula})", null).apply { minimize() }
}
override fun Z3Params.or(other: Z3Params): Z3Params {
return Z3Params("(or ${this.formula} ${other.formula})", if (this.sat == true || other.sat == true) true else null).apply { minimize() }
/*c1 += 1
//happens quite often, but won't help us when minimizing
if (z3.checkSat("(and (not (and ${this.formula} ${other.formula})) (or ${this.formula} ${other.formula}))")) {
c2 += 1
return Z3Params("(or ${this.formula} ${other.formula})", if (this.sat == true || other.sat == true) true else null).apply { minimize() }
} else {
return this
}*/
}
override fun Z3Params.prettyPrint(): String {
//this.minimize()
return "{$sat: $formula}"
}
override fun Z3Params.byteSize(): Int = ensureBytes().size + 4 + 1
override fun ByteBuffer.putColors(colors: Z3Params): ByteBuffer {
val bytes = colors.ensureBytes()
this.putInt(bytes.size)
bytes.forEach { this.put(it) }
colors.bytes = null //release bytes - chance we will be sending the same data again is very small
when (colors.sat) {
null -> put((-1).toByte())
true -> put(1.toByte())
false -> put(0.toByte())
}
return this
}
override fun ByteBuffer.getColors(): Z3Params {
val size = this.int
val array = ByteArray(size)
(0 until size).forEach { array[it] = this.get() }
return Z3Params(
String(array),
when (this.get().toInt()) {
1 -> true
0 -> false
else -> null
}
)
}
override fun Z3Params.transferTo(solver: Solver<Z3Params>): Z3Params {
return Z3Params(this.formula, this.sat, this.minimal)
}
private fun Z3Params.ensureBytes(): ByteArray {
val bytes = this.formula.toByteArray()
this.bytes = bytes
return bytes
}
}
interface Z3SolverBase {
val bounds: String
infix fun String.and(other: String) = "(and $this $other)"
infix fun String.or(other: String) = "(or $this $other)"
infix fun String.gt(other: String) = "(> $this $other)"
infix fun String.ge(other: String) = "(>= $this $other)"
infix fun String.lt(other: String) = "(< $this $other)"
infix fun String.le(other: String) = "(<= $this $other)"
infix fun String.plus(other: String) = "(+ $this $other)"
infix fun String.times(other: String) = "(* $this $other)"
infix fun String.div(other: String) = "(/ $this $other)"
fun Z3Params.minimize(force: Boolean)
} | gpl-3.0 | 799fbadc5f3f8c93c4bca26dc917b164 | 35.442308 | 148 | 0.555614 | 3.633269 | false | false | false | false |
elect86/jAssimp | src/test/kotlin/assimp/obj/spider.kt | 2 | 10086 | package assimp.obj
import assimp.*
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.shouldBe
import java.io.File
import java.net.URL
import java.util.*
object spider {
var isObj = false
var isFbx = false
fun reset() {
isObj = false
isFbx = false
}
object obj {
operator fun invoke(directory: String) {
isObj = true
val urls = File(getResource(directory).toURI())
.listFiles()!!
.filterNot { it.absolutePath.endsWith("spider.obj", ignoreCase = true) }
.map { it.toURI().toURL() }
.toTypedArray()
val objFile = getResource("$directory/spider.obj")
check(objFile, *urls)
reset()
}
}
object fbx {
operator fun invoke(directory: String,
objFileMeshIndices: Boolean = true) {
isFbx = true
check(getResource("$directory/spider.fbx"))
reset()
}
}
fun check(vararg urls: URL) =
Importer().testURLs(*urls) {
with(rootNode) {
transformation shouldBe Mat4()
numChildren shouldBe 19
val remainingNames = mutableListOf("HLeib01", "OK", "Bein1Li", "Bein1Re", "Bein2Li", "Bein2Re", "Bein3Re", "Bein3Li", "Bein4Re",
"Bein4Li", "Zahn", "klZahn", "Kopf", "Brust", "Kopf2", "Zahn2", "klZahn2", "Auge", "Duplicate05")
(0 until numChildren).map {
val childNode = children[it]
when {
isObj -> remainingNames[0] shouldBe childNode.name
else -> remainingNames shouldContain childNode.name
}
remainingNames -= childNode.name
childNode.meshes[0] shouldBe it
}
numMeshes shouldBe 0
}
numMeshes shouldBe 19
with(meshes.find { it.name == "HLeib01" }!!) {
primitiveTypes shouldBe AiPrimitiveType.TRIANGLE.i
numVertices shouldBe 240
numFaces shouldBe 80
vertices[0].shouldEqual(Vec3(x = 1.160379, y = 4.512684, z = 6.449167), epsilon)
vertices[numVertices - 1].shouldEqual(Vec3(x = -4.421391, y = -3.605049, z = -20.462471), epsilon)
normals[0].shouldEqual(Vec3(-0.537588000, -0.0717979968, 0.840146005), epsilon)
normals[numVertices - 1].shouldEqual(Vec3(-0.728103995, -0.400941998, -0.555975974), epsilon)
// TODO check for kotlintest 2.0 array check
textureCoords[0][0].contentEquals(floatArrayOf(0.186192f, 0.222718f)) shouldBe true
textureCoords[0][numVertices - 1].contentEquals(floatArrayOf(0.103881f, 0.697021f)) shouldBe true
textureCoords[0][0].size shouldBe 2
faces[0] shouldBe listOf(0, 1, 2)
faces[numFaces - 1] shouldBe listOf(237, 238, 239)
materials[materialIndex].name shouldBe "HLeibTex"
}
with(meshes.find { it.name == "OK" }!!) {
primitiveTypes shouldBe AiPrimitiveType.TRIANGLE.i
numVertices shouldBe 180
numFaces shouldBe 60
vertices[0].shouldEqual(Vec3(x = -41.8566132f, y = -0.754845977f, z = 9.43077183f), epsilon)
vertices[numVertices - 1].shouldEqual(Vec3(x = -49.7138367f, y = -2.98359, z = -21.4211159f), epsilon)
normals[0].shouldEqual(Vec3(x = -0.236278996f, y = 0.0291850008f, z = 0.971247017f), epsilon)
normals[numVertices - 1].shouldEqual(Vec3(x = -0.862017989f, y = 0.0830229968f, z = -0.500032008f), epsilon)
textureCoords[0][0].contentEquals(floatArrayOf(-0.0658710003f, -0.410016000f)) shouldBe true
textureCoords[0][numVertices - 1].contentEquals(floatArrayOf(-0.318565995f, 1.05051804f)) shouldBe true
textureCoords[0][0].size shouldBe 2
faces[0] shouldBe listOf(0, 1, 2)
faces[numFaces - 1] shouldBe listOf(177, 178, 179)
materials[materialIndex].name shouldBe "Skin"
}
with(meshes.find { it.name == "Duplicate05" }!!) {
primitiveTypes shouldBe AiPrimitiveType.TRIANGLE.i
numVertices shouldBe 114
numFaces shouldBe 38
vertices[0].shouldEqual(Vec3(x = -59.4670486f, y = 18.1400757f, z = -17.1943588), epsilon)
vertices[numVertices - 1].shouldEqual(Vec3(x = -62.2673569f, y = 15.2776031f, z = -14.7453232f), epsilon)
normals[0].shouldEqual(Vec3(x = 0.0751359984f, y = 0.741809011f, z = -0.666388988f), epsilon)
normals[numVertices - 1].shouldEqual(Vec3(x = -0.776385009f, y = -0.629855990f, z = 0.0225169994f), epsilon)
textureCoords[0][0].contentEquals(floatArrayOf(0.899282992f, 0.970311999f)) shouldBe true
textureCoords[0][numVertices - 1].contentEquals(floatArrayOf(0.372330993f, 0.198948994f)) shouldBe true
textureCoords[0][0].size shouldBe 2
faces[0] shouldBe listOf(0, 1, 2)
faces[numFaces - 1] shouldBe listOf(111, 112, 113)
materials[materialIndex].name shouldBe "Augentex"
}
if (isObj) {
/*
TODO the material data in the fbx file is different from the obj file(mat file)
because of that we just don't check the material data in the fbx file right now.
*/
with(materials.find { it.name == "Skin" }!!) {
shadingModel shouldBe AiShadingMode.gouraud
with(color!!) {
ambient!!.shouldEqual(Vec3(0.200000003f), epsilon)
diffuse!!.shouldEqual(Vec3(0.827450991f, 0.792156994f, 0.772548974f), epsilon)
specular!!.shouldEqual(Vec3(0), epsilon)
emissive!!.shouldEqual(Vec3(0), epsilon)
shininess shouldBe 0f
opacity shouldBe 1f
refracti shouldBe 1f
}
textures[0].file shouldBe ".\\wal67ar_small.jpg"
}
with(materials.find { it.name == "Brusttex" }!!) {
shadingModel shouldBe AiShadingMode.gouraud
with(color!!) {
ambient!!.shouldEqual(Vec3(0.200000003f), epsilon)
diffuse!!.shouldEqual(Vec3(0.800000012f), epsilon)
specular!!.shouldEqual(Vec3(0), epsilon)
emissive!!.shouldEqual(Vec3(0), epsilon)
shininess shouldBe 0f
opacity shouldBe 1f
refracti shouldBe 1f
}
textures[0].file shouldBe ".\\wal69ar_small.jpg"
}
with(materials.find { it.name == "HLeibTex" }!!) {
shadingModel shouldBe AiShadingMode.gouraud
with(color!!) {
ambient!!.shouldEqual(Vec3(0.200000003f), epsilon)
diffuse!!.shouldEqual(Vec3(0.690195978f, 0.639216006f, 0.615685999f), epsilon)
specular!!.shouldEqual(Vec3(0), epsilon)
emissive!!.shouldEqual(Vec3(0), epsilon)
shininess shouldBe 0f
opacity shouldBe 1f
refracti shouldBe 1f
}
textures[0].file shouldBe ".\\SpiderTex.jpg"
}
with(materials.find { it.name == "BeinTex" }!!) {
shadingModel shouldBe AiShadingMode.gouraud
with(color!!) {
ambient!!.shouldEqual(Vec3(0.200000003f), epsilon)
diffuse!!.shouldEqual(Vec3(0.800000012f), epsilon)
specular!!.shouldEqual(Vec3(0), epsilon)
emissive!!.shouldEqual(Vec3(0), epsilon)
shininess shouldBe 0f
opacity shouldBe 1f
refracti shouldBe 1f
}
textures[0].file shouldBe ".\\drkwood2.jpg"
}
with(materials.find { it.name == "Augentex" }!!) {
name shouldBe "Augentex"
shadingModel shouldBe AiShadingMode.gouraud
with(color!!) {
ambient!!.shouldEqual(Vec3(0.200000003f), epsilon)
diffuse!!.shouldEqual(Vec3(0.800000012f), epsilon)
specular!!.shouldEqual(Vec3(0), epsilon)
emissive!!.shouldEqual(Vec3(0), epsilon)
shininess shouldBe 0f
opacity shouldBe 1f
refracti shouldBe 1f
}
textures[0].file shouldBe ".\\engineflare1.jpg"
}
if (!isObj)
numTextures shouldBe 5 // TODO numTextures is not set in obj
textures.size shouldBe 5
}
}
} | mit | 7d37cde3b2f9ae816abdac90687a9f62 | 41.382353 | 148 | 0.489292 | 4.622365 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/stack/topbar/TopBarController.kt | 1 | 4941 | package com.reactnativenavigation.viewcontrollers.stack.topbar
import android.animation.Animator
import android.content.Context
import android.view.MenuItem
import android.view.View
import androidx.viewpager.widget.ViewPager
import com.reactnativenavigation.options.Alignment
import com.reactnativenavigation.options.AnimationOptions
import com.reactnativenavigation.options.Options
import com.reactnativenavigation.utils.CollectionUtils.forEachIndexed
import com.reactnativenavigation.utils.ViewUtils
import com.reactnativenavigation.utils.resetViewProperties
import com.reactnativenavigation.viewcontrollers.stack.topbar.button.ButtonController
import com.reactnativenavigation.viewcontrollers.stack.topbar.title.TitleBarReactViewController
import com.reactnativenavigation.views.stack.StackLayout
import com.reactnativenavigation.views.stack.topbar.TopBar
import com.reactnativenavigation.views.stack.topbar.titlebar.ButtonBar
open class TopBarController(private val animator: TopBarAnimator = TopBarAnimator()) {
lateinit var view: TopBar
private lateinit var leftButtonBar: ButtonBar
private lateinit var rightButtonBar: ButtonBar
val height: Int
get() = view.height
val rightButtonCount: Int
get() = rightButtonBar.buttonCount
val leftButtonCount: Int
get() = leftButtonBar.buttonCount
fun getRightButton(index: Int): MenuItem = rightButtonBar.getButton(index)
fun createView(context: Context, parent: StackLayout): TopBar {
if (!::view.isInitialized) {
view = createTopBar(context, parent)
leftButtonBar = view.leftButtonBar
rightButtonBar = view.rightButtonBar
animator.bindView(view)
}
return view
}
protected open fun createTopBar(context: Context, stackLayout: StackLayout): TopBar {
return TopBar(context)
}
fun initTopTabs(viewPager: ViewPager?) = view.initTopTabs(viewPager)
fun clearTopTabs() = view.clearTopTabs()
fun getPushAnimation(appearingOptions: Options, additionalDy: Float = 0f): Animator? {
if (appearingOptions.topBar.animate.isFalse) return null
return animator.getPushAnimation(
appearingOptions.animations.push.topBar,
appearingOptions.topBar.visible,
additionalDy
)
}
fun getPopAnimation(appearingOptions: Options, disappearingOptions: Options): Animator? {
if (appearingOptions.topBar.animate.isFalse) return null
return animator.getPopAnimation(
disappearingOptions.animations.pop.topBar,
appearingOptions.topBar.visible
)
}
fun getSetStackRootAnimation(appearingOptions: Options, additionalDy: Float = 0f): Animator? {
if (appearingOptions.topBar.animate.isFalse) return null
return animator.getSetStackRootAnimation(
appearingOptions.animations.setStackRoot.topBar,
appearingOptions.topBar.visible,
additionalDy
)
}
fun show() {
if (ViewUtils.isVisible(view) || animator.isAnimatingShow()) return
view.resetViewProperties()
view.visibility = View.VISIBLE
}
fun showAnimate(options: AnimationOptions, additionalDy: Float) {
if (ViewUtils.isVisible(view) || animator.isAnimatingShow()) return
animator.show(options, additionalDy)
}
fun hide() {
if (!animator.isAnimatingHide()) view.visibility = View.GONE
}
fun hideAnimate(options: AnimationOptions, additionalDy: Float) {
if (!ViewUtils.isVisible(view) || animator.isAnimatingHide()) return
animator.hide(options, additionalDy)
}
fun setTitleComponent(component: TitleBarReactViewController) {
view.setTitleComponent(component.view, component.component?.alignment ?: Alignment.Default)
}
fun alignTitleComponent(alignment: Alignment) {
view.alignTitleComponent(alignment)
}
fun applyRightButtons(toAdd: List<ButtonController>) {
view.clearRightButtons()
toAdd.reversed().forEachIndexed { i, b -> b.addToMenu(rightButtonBar, i * 10) }
}
fun mergeRightButtons(toAdd: List<ButtonController>, toRemove: List<ButtonController>) {
toRemove.forEach { view.removeRightButton(it) }
toAdd.reversed().forEachIndexed { i, b -> b.addToMenu(rightButtonBar, i * 10) }
}
open fun applyLeftButtons(toAdd: List<ButtonController>) {
view.clearBackButton()
view.clearLeftButtons()
forEachIndexed(toAdd) { b: ButtonController, i: Int -> b.addToMenu(leftButtonBar, i * 10) }
}
open fun mergeLeftButtons(toAdd: List<ButtonController>, toRemove: List<ButtonController>) {
view.clearBackButton()
toRemove.forEach { view.removeLeftButton(it) }
forEachIndexed(toAdd) { b: ButtonController, i: Int -> b.addToMenu(leftButtonBar, i * 10) }
}
} | mit | 35f7bc0a39962211ea422dd4c30870fd | 37.310078 | 99 | 0.714835 | 4.723709 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/commit/CommitCommentsFragment.kt | 1 | 4635 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.commit
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.adapters.CommitCommentAdapter
import giuliolodi.gitnav.ui.base.BaseFragment
import giuliolodi.gitnav.ui.user.UserActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.commit_fragment_comments.*
import org.eclipse.egit.github.core.CommitComment
import javax.inject.Inject
/**
* Created by giulio on 29/12/2017.
*/
class CommitCommentsFragment : BaseFragment(), CommitCommentsContract.View {
@Inject lateinit var mPresenter: CommitCommentsContract.Presenter<CommitCommentsContract.View>
private var mOwner: String? = null
private var mName: String? = null
private var mSha: String? = null
companion object {
fun newInstance(owner: String, name: String, sha: String): CommitCommentsFragment {
val commitCommentsFragment: CommitCommentsFragment = CommitCommentsFragment()
val bundle: Bundle = Bundle()
bundle.putString("owner", owner)
bundle.putString("name", name)
bundle.putString("sha", sha)
commitCommentsFragment.arguments = bundle
return commitCommentsFragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
getActivityComponent()?.inject(this)
mOwner = arguments.getString("owner")
mName = arguments.getString("name")
mSha = arguments.getString("sha")
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.commit_fragment_comments, container, false)
}
override fun initLayout(view: View?, savedInstanceState: Bundle?) {
mPresenter.onAttach(this)
val llmComments = LinearLayoutManager(context)
llmComments.orientation = LinearLayoutManager.VERTICAL
commit_fragment_comments_rv.layoutManager = llmComments
commit_fragment_comments_rv.itemAnimator = DefaultItemAnimator()
commit_fragment_comments_rv.adapter = CommitCommentAdapter()
(commit_fragment_comments_rv.adapter as CommitCommentAdapter).getImageClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { username -> mPresenter.onUserClick(username)}
mPresenter.subscribe(isNetworkAvailable(), mOwner, mName, mSha)
}
override fun showComments(commitCommentList: List<CommitComment>) {
(commit_fragment_comments_rv.adapter as CommitCommentAdapter).addCommitCommentList(commitCommentList)
}
override fun showLoading() {
commit_fragment_comments_progressbar.visibility = View.VISIBLE
}
override fun hideLoading() {
commit_fragment_comments_progressbar.visibility = View.GONE
}
override fun showNoComments() {
commit_fragment_comments_nocomments.visibility = View.VISIBLE
}
override fun showError(error: String) {
Toasty.error(context, error, Toast.LENGTH_LONG).show()
}
override fun showNoConnectionError() {
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
override fun intentToUserActivity(username: String) {
startActivity(UserActivity.getIntent(context).putExtra("username", username))
activity.overridePendingTransition(0,0)
}
override fun onDestroyView() {
mPresenter.onDetachView()
super.onDestroyView()
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
} | apache-2.0 | 129236f78470cfd41491546a8932514e | 34.937984 | 117 | 0.719094 | 4.734423 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/PressureUnit.kt | 1 | 2626 | package wangdaye.com.geometricweather.common.basic.models.options.unit
import android.content.Context
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum
import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils
import wangdaye.com.geometricweather.common.utils.DisplayUtils
// actual pressure = pressure(mb) * factor.
enum class PressureUnit(
override val id: String,
override val unitFactor: Float
): UnitEnum<Float> {
MB("mb", 1f),
KPA("kpa", 0.1f),
HPA("hpa", 1f),
ATM("atm", 0.0009869f),
MMHG("mmhg", 0.75006f),
INHG("inhg", 0.02953f),
KGFPSQCM("kgfpsqcm", 0.00102f);
companion object {
@JvmStatic
fun getInstance(
value: String
) = when (value) {
"kpa" -> KPA
"hpa" -> HPA
"atm" -> ATM
"mmhg" -> MMHG
"inhg" -> INHG
"kgfpsqcm" -> KGFPSQCM
else -> MB
}
}
override val valueArrayId = R.array.pressure_unit_values
override val nameArrayId = R.array.pressure_units
override val voiceArrayId = R.array.pressure_unit_voices
override fun getName(context: Context) = Utils.getName(context, this)
override fun getVoice(context: Context) = Utils.getVoice(context, this)
override fun getValueWithoutUnit(valueInDefaultUnit: Float) = valueInDefaultUnit * unitFactor
override fun getValueInDefaultUnit(valueInCurrentUnit: Float) = valueInCurrentUnit / unitFactor
override fun getValueTextWithoutUnit(
valueInDefaultUnit: Float
) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit, 2)!!
override fun getValueText(
context: Context,
valueInDefaultUnit: Float
) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueText(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getValueText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float
) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getVoiceText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
} | lgpl-3.0 | ff35c7bb9ef0770eb9d7eea00666a282 | 28.852273 | 99 | 0.656512 | 3.942943 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/viewHolder/TodoViewHolder.kt | 2 | 1773 | package com.commit451.gitlab.viewHolder
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 coil.api.load
import coil.transform.CircleCropTransformation
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.Todo
import com.commit451.gitlab.util.DateUtil
import com.commit451.gitlab.util.ImageUtil
/**
* issues, yay!
*/
class TodoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): TodoViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_todo, parent, false)
return TodoViewHolder(view)
}
}
private val textProject: TextView by bindView(R.id.text_project)
private val image: ImageView by bindView(R.id.issue_image)
private val textMessage: TextView by bindView(R.id.issue_message)
private val textCreator: TextView by bindView(R.id.issue_creator)
fun bind(todo: Todo) {
textProject.text = todo.project!!.nameWithNamespace
if (todo.author != null) {
image.load(ImageUtil.getAvatarUrl(todo.author, itemView.resources.getDimensionPixelSize(R.dimen.image_size))) {
transformations(CircleCropTransformation())
}
} else {
image.setImageBitmap(null)
}
textMessage.text = todo.body
var time = ""
if (todo.createdAt != null) {
time += DateUtil.getRelativeTimeSpanString(itemView.context, todo.createdAt)
}
textCreator.text = time
}
}
| apache-2.0 | 4e9509dc720fb6ec9e2f89cd327f3629 | 31.236364 | 123 | 0.697688 | 4.272289 | false | false | false | false |
realm/realm-java | realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmProxyClassGenerator.kt | 1 | 226274 | /*
* Copyright 2019 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.processor
import com.squareup.javawriter.JavaWriter
import io.realm.processor.Utils.fieldTypeHasPrimaryKey
import io.realm.processor.Utils.getGenericType
import io.realm.processor.ext.beginMethod
import io.realm.processor.ext.beginType
import java.io.BufferedWriter
import java.io.IOException
import java.util.*
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Modifier
import javax.lang.model.element.VariableElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.tools.JavaFileObject
/**
* This class is responsible for generating the Realm Proxy classes for each model class defined
* by the user. This is the main entrypoint for users interacting with Realm, but it is hidden
* from them as an implementation detail generated by the annotation processor.
*
* See [RealmProcessor] for a more detailed description on what files Realm creates internally and
* why.
*
* NOTE: This file will look strangely formatted to you. This is on purpose. The intent of the
* formatting it is to better represent the outputted code, not make _this_ code as readable as
* possible. This mean two things:
*
* 1. Attempt to keep code that emit a single line to one line here.
* 2. Attempt to indent the emit functions that would emulate the blocks created by the generated code.
*/
class RealmProxyClassGenerator(private val processingEnvironment: ProcessingEnvironment,
private val typeMirrors: TypeMirrors,
private val metadata: ClassMetaData,
private val classCollection: ClassCollection) {
private val simpleJavaClassName: SimpleClassName = metadata.simpleJavaClassName
private val qualifiedJavaClassName: QualifiedClassName = metadata.qualifiedClassName
private val internalClassName: String = metadata.internalClassName
private val interfaceName: SimpleClassName = Utils.getProxyInterfaceName(qualifiedJavaClassName)
private val generatedClassName: QualifiedClassName = QualifiedClassName(String.format(Locale.US, "%s.%s", Constants.REALM_PACKAGE_NAME, Utils.getProxyClassName(qualifiedJavaClassName)))
// See the configuration for the Android debug build type,
// in the realm-library project, for an example of how to set this flag.
private val suppressWarnings: Boolean = !"false".equals(processingEnvironment.options[OPTION_SUPPRESS_WARNINGS], ignoreCase = true)
lateinit var sourceFile: JavaFileObject
@Throws(IOException::class, UnsupportedOperationException::class)
fun generate() {
sourceFile = processingEnvironment.filer.createSourceFile(generatedClassName.toString())
val imports = ArrayList(IMPORTS)
if (metadata.backlinkFields.isNotEmpty()) {
imports.add("io.realm.internal.UncheckedRow")
}
val writer = JavaWriter(BufferedWriter(sourceFile.openWriter()))
writer.apply {
indent = Constants.INDENT // Set source code indent
emitPackage(Constants.REALM_PACKAGE_NAME)
emitEmptyLine()
emitImports(imports)
emitEmptyLine()
// Begin the class definition
if (suppressWarnings) {
emitAnnotation("SuppressWarnings(\"all\")")
}
beginType(generatedClassName, "class", setOf(Modifier.PUBLIC), qualifiedJavaClassName, arrayOf("RealmObjectProxy", interfaceName.toString()))
emitEmptyLine()
// Emit class content
emitColumnInfoClass(writer)
emitClassFields(writer)
emitInstanceFields(writer)
emitConstructor(writer)
emitInjectContextMethod(writer)
emitPersistedFieldAccessors(writer)
emitBacklinkFieldAccessors(writer)
emitCreateExpectedObjectSchemaInfo(writer)
emitGetExpectedObjectSchemaInfo(writer)
emitCreateColumnInfoMethod(writer)
emitGetSimpleClassNameMethod(writer)
emitCreateOrUpdateUsingJsonObject(writer)
emitCreateUsingJsonStream(writer)
emitNewProxyInstance(writer)
emitCopyOrUpdateMethod(writer)
emitCopyMethod(writer)
emitInsertMethod(writer)
emitInsertListMethod(writer)
emitInsertOrUpdateMethod(writer)
emitInsertOrUpdateListMethod(writer)
emitCreateDetachedCopyMethod(writer)
emitUpdateMethod(writer)
emitUpdateEmbeddedObjectMethod(writer)
emitToStringMethod(writer)
emitRealmObjectProxyImplementation(writer)
emitHashcodeMethod(writer)
emitEqualsMethod(writer)
// End the class definition
endType()
close()
}
}
@Throws(IOException::class)
private fun emitColumnInfoClass(writer: JavaWriter) {
writer.apply {
beginType(columnInfoClassName(), "class", EnumSet.of(Modifier.STATIC, Modifier.FINAL), "ColumnInfo") // base class
// fields
for (variableElement in metadata.fields) {
emitField("long", columnKeyVarName(variableElement))
}
emitEmptyLine()
// constructor #1
beginConstructor(EnumSet.noneOf(Modifier::class.java), "OsSchemaInfo", "schemaInfo")
emitStatement("super(%s)", metadata.fields.size)
emitStatement("OsObjectSchemaInfo objectSchemaInfo = schemaInfo.getObjectSchemaInfo(\"%1\$s\")", internalClassName)
for (field in metadata.fields) {
emitStatement("this.%1\$sColKey = addColumnDetails(\"%1\$s\", \"%2\$s\", objectSchemaInfo)", field.javaName, field.internalFieldName)
}
for (backlink in metadata.backlinkFields) {
val sourceClass = classCollection.getClassFromQualifiedName(backlink.sourceClass!!)
val internalSourceClassName = sourceClass.internalClassName
val internalSourceFieldName = sourceClass.getInternalFieldName(backlink.sourceField!!)
emitStatement("addBacklinkDetails(schemaInfo, \"%s\", \"%s\", \"%s\")", backlink.targetField, internalSourceClassName, internalSourceFieldName)
}
endConstructor()
emitEmptyLine()
// constructor #2
beginConstructor(EnumSet.noneOf(Modifier::class.java),"ColumnInfo", "src", "boolean", "mutable")
emitStatement("super(src, mutable)")
emitStatement("copy(src, this)")
endConstructor()
emitEmptyLine()
// no-args copy method
emitAnnotation("Override")
beginMethod("ColumnInfo", "copy", EnumSet.of(Modifier.PROTECTED, Modifier.FINAL), "boolean", "mutable")
emitStatement("return new %s(this, mutable)", columnInfoClassName())
endMethod()
emitEmptyLine()
// copy method
emitAnnotation("Override")
beginMethod("void", "copy", EnumSet.of(Modifier.PROTECTED, Modifier.FINAL), "ColumnInfo", "rawSrc", "ColumnInfo", "rawDst")
emitStatement("final %1\$s src = (%1\$s) rawSrc", columnInfoClassName())
emitStatement("final %1\$s dst = (%1\$s) rawDst", columnInfoClassName())
for (variableElement in metadata.fields) {
emitStatement("dst.%1\$s = src.%1\$s", columnKeyVarName(variableElement))
}
endMethod()
endType()
}
}
@Throws(IOException::class)
private fun emitClassFields(writer: JavaWriter) {
writer.apply {
emitEmptyLine()
// This should ideally have been placed outside the Proxy classes, but due to an unknown
// issue in the compile-testing framework, this kept failing tests. Keeping it here
// fixes that.
emitField("String", "NO_ALIAS", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL), "\"\"")
emitField("OsObjectSchemaInfo", "expectedObjectSchemaInfo", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL),"createExpectedObjectSchemaInfo()")
}
}
@Throws(IOException::class)
private fun emitInstanceFields(writer: JavaWriter) {
writer.apply {
emitEmptyLine()
emitField(columnInfoClassName(), "columnInfo", EnumSet.of(Modifier.PRIVATE))
emitField("ProxyState<$qualifiedJavaClassName>", "proxyState", EnumSet.of(Modifier.PRIVATE))
for (variableElement in metadata.fields) {
if (Utils.isMutableRealmInteger(variableElement)) {
emitMutableRealmIntegerField(writer, variableElement)
} else if (Utils.isRealmList(variableElement)) {
val genericType = Utils.getGenericTypeQualifiedName(variableElement)
emitField("RealmList<$genericType>", "${variableElement.simpleName}RealmList", EnumSet.of(Modifier.PRIVATE))
} else if (Utils.isRealmDictionary(variableElement)) {
val valueType = Utils.getDictionaryValueTypeQualifiedName(variableElement)
emitField("RealmDictionary<$valueType>", "${variableElement.simpleName}RealmDictionary", EnumSet.of(Modifier.PRIVATE))
} else if (Utils.isRealmSet(variableElement)) {
val valueType = Utils.getGenericTypeQualifiedName(variableElement)
emitField("RealmSet<$valueType>", "${variableElement.simpleName}RealmSet", EnumSet.of(Modifier.PRIVATE))
}
}
for (backlink in metadata.backlinkFields) {
emitField(backlink.targetFieldType, backlink.targetField + BACKLINKS_FIELD_EXTENSION, EnumSet.of(Modifier.PRIVATE))
}
}
}
// The anonymous subclass of MutableRealmInteger.Managed holds a reference to this proxy.
// Even if all other references to the proxy are dropped, the proxy will not be GCed until
// the MutableInteger that it owns, also becomes unreachable.
@Throws(IOException::class)
private fun emitMutableRealmIntegerField(writer: JavaWriter, variableElement: VariableElement) {
writer.apply {
emitField("MutableRealmInteger.Managed",
mutableRealmIntegerFieldName(variableElement),
EnumSet.of(Modifier.PRIVATE, Modifier.FINAL),
String.format(
"new MutableRealmInteger.Managed<%1\$s>() {\n"
+ " @Override protected ProxyState<%1\$s> getProxyState() { return proxyState; }\n"
+ " @Override protected long getColumnIndex() { return columnInfo.%2\$s; }\n"
+ "}",
qualifiedJavaClassName, columnKeyVarName(variableElement)))
}
}
@Throws(IOException::class)
private fun emitConstructor(writer: JavaWriter) {
writer.apply {
emitEmptyLine()
beginConstructor(EnumSet.noneOf(Modifier::class.java))
emitStatement("proxyState.setConstructionFinished()")
endConstructor()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitPersistedFieldAccessors(writer: JavaWriter) {
for (field in metadata.fields) {
val fieldName = field.simpleName.toString()
val fieldTypeCanonicalName = field.asType().toString()
when {
Constants.JAVA_TO_REALM_TYPES.containsKey(fieldTypeCanonicalName) -> emitPrimitiveType(writer, field, fieldName, fieldTypeCanonicalName)
Utils.isMutableRealmInteger(field) -> emitMutableRealmInteger(writer, field, fieldName, fieldTypeCanonicalName)
Utils.isRealmAny(field) -> emitRealmAny(writer, field, fieldName, fieldTypeCanonicalName)
Utils.isRealmModel(field) -> emitRealmModel(writer, field, fieldName, fieldTypeCanonicalName)
Utils.isRealmList(field) -> {
val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field)
emitRealmList(writer, field, fieldName, fieldTypeCanonicalName, elementTypeMirror)
}
Utils.isRealmDictionary(field) -> {
val valueTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field)
emitRealmDictionary(writer, field, fieldName, fieldTypeCanonicalName, requireNotNull(valueTypeMirror))
}
Utils.isRealmSet(field) -> {
val valueTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field)
emitRealmSet(writer, field, fieldName, fieldTypeCanonicalName, requireNotNull(valueTypeMirror))
}
else -> throw UnsupportedOperationException(String.format(Locale.US, "Field \"%s\" of type \"%s\" is not supported.", fieldName, fieldTypeCanonicalName))
}
writer.emitEmptyLine()
}
}
/**
* Emit Set/Get methods for Primitives and boxed types
*/
@Throws(IOException::class)
private fun emitPrimitiveType(
writer: JavaWriter,
field: VariableElement,
fieldName: String,
fieldTypeCanonicalName: String) {
val fieldJavaType: String? = getRealmTypeChecked(field).javaType
writer.apply {
// Getter - Start
emitAnnotation("Override")
emitAnnotation("SuppressWarnings", "\"cast\"")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
// For String and bytes[], null value will be returned by JNI code. Try to save one JNI call here.
if (metadata.isNullable(field) && !Utils.isString(field) && !Utils.isByteArray(field)) {
beginControlFlow("if (proxyState.getRow\$realm().isNull(%s))", fieldColKeyVariableReference(field))
emitStatement("return null")
endControlFlow()
}
// For Boxed types, this should be the corresponding primitive types. Others remain the same.
val castingBackType: String = if (Utils.isBoxedType(fieldTypeCanonicalName)) {
val typeUtils = processingEnvironment.typeUtils
typeUtils.unboxedType(field.asType()).toString()
} else {
fieldTypeCanonicalName
}
emitStatement("return (%s) proxyState.getRow\$realm().get%s(%s)", castingBackType, fieldJavaType, fieldColKeyVariableReference(field))
endMethod()
emitEmptyLine()
// Getter - End
// Setter - Start
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) {
// set value as default value
emitStatement("final Row row = proxyState.getRow\$realm()")
if (metadata.isNullable(field)) {
beginControlFlow("if (value == null)")
emitStatement("row.getTable().setNull(%s, row.getObjectKey(), true)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
} else if (!metadata.isNullable(field) && !Utils.isPrimitiveType(field)) {
beginControlFlow("if (value == null)")
emitStatement(Constants.STATEMENT_EXCEPTION_ILLEGAL_NULL_VALUE, fieldName)
endControlFlow()
}
emitStatement("row.getTable().set%s(%s, row.getObjectKey(), value, true)", fieldJavaType, fieldColKeyVariableReference(field))
emitStatement("return")
}
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
// Although setting null value for String and bytes[] can be handled by the JNI code, we still generate the same code here.
// Compared with getter, null value won't trigger more native calls in setter which is relatively cheaper.
if (metadata.isPrimaryKey(field)) {
// Primary key is not allowed to be changed after object created.
emitStatement(Constants.STATEMENT_EXCEPTION_PRIMARY_KEY_CANNOT_BE_CHANGED, fieldName)
} else {
if (metadata.isNullable(field)) {
beginControlFlow("if (value == null)")
emitStatement("proxyState.getRow\$realm().setNull(%s)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
} else if (!metadata.isNullable(field) && !Utils.isPrimitiveType(field)) {
// Same reason, throw IAE earlier.
beginControlFlow("if (value == null)")
emitStatement(Constants.STATEMENT_EXCEPTION_ILLEGAL_NULL_VALUE, fieldName)
endControlFlow()
}
emitStatement("proxyState.getRow\$realm().set%s(%s, value)", fieldJavaType, fieldColKeyVariableReference(field))
}
endMethod()
// Setter - End
}
}
/**
* Emit Get method for mutable Realm Integer fields.
*/
@Throws(IOException::class)
private fun emitMutableRealmInteger(writer: JavaWriter, field: VariableElement, fieldName: String, fieldTypeCanonicalName: String) {
writer.apply {
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitStatement("return this.%s", mutableRealmIntegerFieldName(field))
endMethod()
}
}
/**
* Emit Get method for RealmAny fields.
*/
@Throws(IOException::class)
private fun emitRealmAny(writer: JavaWriter, field: VariableElement, fieldName: String, fieldTypeCanonicalName: String) {
writer.apply {
// Getter - Start
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitStatement("NativeRealmAny nativeRealmAny = proxyState.getRow\$realm().getNativeRealmAny(%s)", fieldColKeyVariableReference(field))
emitStatement("return new RealmAny(RealmAnyOperator.fromNativeRealmAny(proxyState.getRealm\$realm(), nativeRealmAny))")
endMethod()
// Getter - End
emitEmptyLine()
// Setter - Start
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) {
beginControlFlow("if (proxyState.getExcludeFields\$realm().contains(\"%1\$s\"))", field.simpleName.toString())
emitStatement("return")
endControlFlow()
emitEmptyLine()
emitStatement("value = ProxyUtils.copyToRealmIfNeeded(proxyState, value)")
emitEmptyLine()
emitStatement("final Row row = proxyState.getRow\$realm()")
beginControlFlow("if (value == null)")
emitStatement("row.getTable().setNull(%s, row.getObjectKey(), true)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
emitStatement("row.getTable().setRealmAny(%s, row.getObjectKey(), value.getNativePtr(), true)", fieldColKeyVariableReference(field))
emitStatement("return")
}
emitEmptyLine()
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitEmptyLine()
beginControlFlow("if (value == null)")
emitStatement("proxyState.getRow\$realm().setNull(%s)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
emitStatement("value = ProxyUtils.copyToRealmIfNeeded(proxyState, value)")
emitStatement("proxyState.getRow\$realm().setRealmAny(%s, value.getNativePtr())", fieldColKeyVariableReference(field))
endMethod()
// Setter - End
}
}
/**
* Emit Set/Get methods for RealmModel fields.
*/
@Throws(IOException::class)
private fun emitRealmModel(writer: JavaWriter,
field: VariableElement,
fieldName: String,
fieldTypeCanonicalName: String) {
writer.apply {
// Getter - Start
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
beginControlFlow("if (proxyState.getRow\$realm().isNullLink(%s))", fieldColKeyVariableReference(field))
emitStatement("return null")
endControlFlow()
emitStatement("return proxyState.getRealm\$realm().get(%s.class, proxyState.getRow\$realm().getLink(%s), false, Collections.<String>emptyList())", fieldTypeCanonicalName, fieldColKeyVariableReference(field))
endMethod()
emitEmptyLine()
// Getter - End
// Setter - Start
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
val linkedQualifiedClassName: QualifiedClassName = Utils.getFieldTypeQualifiedName(field)
val linkedProxyClass: SimpleClassName = Utils.getProxyClassSimpleName(field)
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitStatement("Realm realm = (Realm) proxyState.getRealm\$realm()")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) {
// check excludeFields
beginControlFlow("if (proxyState.getExcludeFields\$realm().contains(\"%1\$s\"))", field.simpleName.toString())
emitStatement("return")
endControlFlow()
beginControlFlow("if (value != null && !RealmObject.isManaged(value))")
if (isEmbedded) {
emitStatement("%1\$s proxyObject = realm.createEmbeddedObject(%1\$s.class, this, \"%2\$s\")", linkedQualifiedClassName, fieldName)
emitStatement("%s.updateEmbeddedObject(realm, value, proxyObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)", linkedProxyClass)
emitStatement("value = proxyObject")
} else {
if (fieldTypeHasPrimaryKey(field.asType(), classCollection)) {
emitStatement("value = realm.copyToRealmOrUpdate(value)")
} else {
emitStatement("value = realm.copyToRealm(value)")
}
}
endControlFlow()
// set value as default value
emitStatement("final Row row = proxyState.getRow\$realm()")
beginControlFlow("if (value == null)")
emitSingleLineComment("Table#nullifyLink() does not support default value. Just using Row.")
emitStatement("row.nullifyLink(%s)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
emitStatement("proxyState.checkValidObject(value)")
emitStatement("row.getTable().setLink(%s, row.getObjectKey(), ((RealmObjectProxy) value).realmGet\$proxyState().getRow\$realm().getObjectKey(), true)", fieldColKeyVariableReference(field))
emitStatement("return")
}
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
beginControlFlow("if (value == null)")
emitStatement("proxyState.getRow\$realm().nullifyLink(%s)", fieldColKeyVariableReference(field))
emitStatement("return")
endControlFlow()
if (isEmbedded) {
beginControlFlow("if (RealmObject.isManaged(value))")
emitStatement("proxyState.checkValidObject(value)")
endControlFlow()
emitStatement("%1\$s proxyObject = realm.createEmbeddedObject(%1\$s.class, this, \"%2\$s\")", linkedQualifiedClassName, fieldName)
emitStatement("%s.updateEmbeddedObject(realm, value, proxyObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)", linkedProxyClass)
} else {
emitStatement("proxyState.checkValidObject(value)")
emitStatement("proxyState.getRow\$realm().setLink(%s, ((RealmObjectProxy) value).realmGet\$proxyState().getRow\$realm().getObjectKey())", fieldColKeyVariableReference(field))
}
endMethod()
// Setter - End
}
}
@Throws(IOException::class)
private fun emitRealmDictionary(
writer: JavaWriter,
field: VariableElement,
fieldName: String,
fieldTypeCanonicalName: String,
valueTypeMirror: TypeMirror
) {
val forRealmAny = Utils.isRealmAny(valueTypeMirror)
val forRealmModel = Utils.isRealmModel(valueTypeMirror)
with(writer) {
val genericType: QualifiedClassName? = Utils.getGenericTypeQualifiedName(field)
// Getter
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitSingleLineComment("use the cached value if available")
beginControlFlow("if (${fieldName}RealmDictionary != null)")
emitStatement("return ${fieldName}RealmDictionary")
nextControlFlow("else")
if (forRealmAny) {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getRealmAnyMap(%s)", fieldColKeyVariableReference(field))
} else if (forRealmModel) {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getModelMap(%s)", fieldColKeyVariableReference(field))
} else {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getValueMap(%s, RealmFieldType.%s)", fieldColKeyVariableReference(field), Utils.getValueDictionaryFieldType(field).name)
}
emitStatement("${fieldName}RealmDictionary = new RealmDictionary<%s>(proxyState.getRealm\$realm(), osMap, %s.class)", genericType, genericType)
emitStatement("return ${fieldName}RealmDictionary")
endControlFlow()
endMethod()
emitEmptyLine()
// Setter
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) emitter@{
// check excludeFields
beginControlFlow("if (proxyState.getExcludeFields\$realm().contains(\"%s\"))", field.simpleName.toString())
emitStatement("return")
endControlFlow()
// Either realmAny, which may or may not contain RealmObjects inside...
if (forRealmAny) {
emitSingleLineComment("if the dictionary contains unmanaged RealmModel instances boxed in RealmAny objects, convert them to managed.")
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmDictionary<%s> original = value", genericType)
emitStatement("value = new RealmDictionary<%s>()", genericType)
beginControlFlow("for (java.util.Map.Entry<String, %s> item : original.entrySet())", genericType)
emitStatement("String entryKey = item.getKey()")
emitStatement("%s entryValue = item.getValue()", genericType)
emitSingleLineComment("ensure (potential) RealmModel instances are copied to Realm if generic type is RealmAny")
beginControlFlow("if (entryValue == null)")
emitStatement("value.put(entryKey, null)")
nextControlFlow("else if (entryValue.getType() == RealmAny.Type.OBJECT)")
emitStatement("RealmModel realmModel = entryValue.asRealmModel(RealmModel.class)")
emitStatement("RealmModel modelFromRealm = realm.copyToRealmOrUpdate(realmModel)")
emitStatement("value.put(entryKey, RealmAny.valueOf(modelFromRealm))")
nextControlFlow("else")
emitStatement("value.put(entryKey, entryValue)")
endControlFlow()
endControlFlow()
endControlFlow()
} else if (forRealmModel) {
// ... Or Realm Models
emitSingleLineComment("if the dictionary contains unmanaged RealmModel instances, convert them to managed.")
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmDictionary<%s> original = value", genericType)
emitStatement("value = new RealmDictionary<%s>()", genericType)
beginControlFlow("for (java.util.Map.Entry<String, %s> entry : original.entrySet())", genericType)
emitStatement("String entryKey = entry.getKey()")
emitStatement("%s entryValue = entry.getValue()", genericType)
beginControlFlow("if (entryValue == null || RealmObject.isManaged(entryValue))")
emitStatement("value.put(entryKey, entryValue)")
nextControlFlow("else")
emitStatement("value.put(entryKey, realm.copyToRealmOrUpdate(entryValue))")
endControlFlow()
endControlFlow()
endControlFlow()
}
}
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
if (forRealmAny) {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getRealmAnyMap(%s)", fieldColKeyVariableReference(field))
} else if (forRealmModel) {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getModelMap(%s)", fieldColKeyVariableReference(field))
} else {
emitStatement("OsMap osMap = proxyState.getRow\$realm().getValueMap(%s, RealmFieldType.%s)", fieldColKeyVariableReference(field), Utils.getValueDictionaryFieldType(field).name)
}
beginControlFlow("if (value == null)")
emitStatement("return")
endControlFlow()
emitStatement("osMap.clear()")
beginControlFlow("for (java.util.Map.Entry<String, %s> item : value.entrySet())", genericType)
emitStatement("String entryKey = item.getKey()")
emitStatement("%s entryValue = item.getValue()", genericType)
if (forRealmAny) {
beginControlFlow("if (entryValue == null)")
emitStatement("osMap.put(entryKey, null)")
nextControlFlow("else")
emitStatement("osMap.putRealmAny(entryKey, ProxyUtils.copyToRealmIfNeeded(proxyState, entryValue).getNativePtr())")
endControlFlow()
} else if (forRealmModel) {
beginControlFlow("if (entryValue == null)")
emitStatement("osMap.put(entryKey, null)")
nextControlFlow("else")
emitStatement("proxyState.checkValidObject(entryValue)")
emitStatement("osMap.putRow(entryKey, ((RealmObjectProxy) entryValue).realmGet\$proxyState().getRow\$realm().getObjectKey())")
endControlFlow()
} else {
emitStatement("osMap.put(entryKey, entryValue)")
}
endControlFlow()
endMethod()
}
}
@Throws(IOException::class)
private fun emitRealmSet(
writer: JavaWriter,
field: VariableElement,
fieldName: String,
fieldTypeCanonicalName: String,
valueTypeMirror: TypeMirror
) {
val forRealmAny = Utils.isRealmAny(valueTypeMirror)
val forRealmModel = Utils.isRealmModel(valueTypeMirror)
with(writer) {
val genericType: QualifiedClassName? = Utils.getGenericTypeQualifiedName(field)
// Getter
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitSingleLineComment("use the cached value if available")
beginControlFlow("if (${fieldName}RealmSet != null)")
emitStatement("return ${fieldName}RealmSet")
nextControlFlow("else")
if (forRealmAny) {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getRealmAnySet(%s)", fieldColKeyVariableReference(field))
} else if (forRealmModel) {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getModelSet(%s)", fieldColKeyVariableReference(field))
} else {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getValueSet(%s, RealmFieldType.%s)", fieldColKeyVariableReference(field), Utils.getValueSetFieldType(field).name)
}
emitStatement("${fieldName}RealmSet = new RealmSet<%s>(proxyState.getRealm\$realm(), osSet, %s.class)", genericType, genericType)
emitStatement("return ${fieldName}RealmSet")
endControlFlow()
endMethod()
emitEmptyLine()
// Setter
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) emitter@{
// check excludeFields
beginControlFlow("if (proxyState.getExcludeFields\$realm().contains(\"%s\"))", field.simpleName.toString())
emitStatement("return")
endControlFlow()
// Either realmAny, which may or may not contain RealmObjects inside...
if (forRealmAny) {
emitSingleLineComment("if the set contains unmanaged RealmModel instances boxed in RealmAny objects, convert them to managed.")
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmSet<%s> original = value", genericType)
emitStatement("value = new RealmSet<%s>()", genericType)
beginControlFlow("for (%s item : original)", genericType)
emitStatement("value.add(ProxyUtils.copyToRealmIfNeeded(proxyState, item))")
endControlFlow()
endControlFlow()
} else if (forRealmModel) {
// ... Or Realm Models
emitSingleLineComment("if the set contains unmanaged RealmModel instances, convert them to managed.")
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmSet<%s> original = value", genericType)
emitStatement("value = new RealmSet<%s>()", genericType)
beginControlFlow("for (%s item : original)", genericType)
beginControlFlow("if (item == null || RealmObject.isManaged(item))")
emitStatement("value.add(item)")
nextControlFlow("else")
emitStatement("value.add(realm.copyToRealmOrUpdate(item))")
endControlFlow()
endControlFlow()
endControlFlow()
}
}
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
when {
forRealmAny -> {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getRealmAnySet(${fieldColKeyVariableReference(field)})")
}
forRealmModel -> {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getModelSet(%s)", fieldColKeyVariableReference(field))
}
else -> {
emitStatement("OsSet osSet = proxyState.getRow\$realm().getValueSet(%s, RealmFieldType.%s)", fieldColKeyVariableReference(field), Utils.getValueSetFieldType(field).name)
}
}
beginControlFlow("if (value == null)")
emitStatement("return")
endControlFlow()
emitSingleLineComment("We need to create a copy of the set before clearing as the input and target sets might be the same.")
emitStatement("List<$genericType> unmanagedList = new ArrayList<>(value)")
emitStatement("osSet.clear()")
beginControlFlow("for (%s item : unmanagedList)", genericType)
when {
forRealmAny -> {
emitStatement("osSet.addRealmAny(ProxyUtils.copyToRealmIfNeeded(proxyState, item).getNativePtr())")
}
forRealmModel -> {
emitStatement("proxyState.checkValidObject(item)")
emitStatement("Row row\$realm = ((RealmObjectProxy) item).realmGet\$proxyState().getRow\$realm()")
emitStatement("osSet.addRow(row\$realm.getObjectKey())")
}
else -> {
emitStatement("osSet.add(item)")
}
}
endControlFlow()
endMethod()
}
}
/**
* Emit Set/Get methods for Realm Model Lists and Lists of primitives.
*/
@Throws(IOException::class)
private fun emitRealmList(
writer: JavaWriter,
field: VariableElement,
fieldName: String,
fieldTypeCanonicalName: String,
elementTypeMirror: TypeMirror?) {
val genericType: QualifiedClassName? = Utils.getGenericTypeQualifiedName(field)
val forRealmModel: Boolean = Utils.isRealmModel(elementTypeMirror)
val forRealmAny: Boolean = Utils.isRealmAny(elementTypeMirror)
writer.apply {
// Getter - Start
emitAnnotation("Override")
beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
emitSingleLineComment("use the cached value if available")
beginControlFlow("if (${fieldName}RealmList != null)")
emitStatement("return ${fieldName}RealmList")
nextControlFlow("else")
if (Utils.isRealmModelList(field)) {
emitStatement("OsList osList = proxyState.getRow\$realm().getModelList(%s)", fieldColKeyVariableReference(field))
} else {
emitStatement("OsList osList = proxyState.getRow\$realm().getValueList(%1\$s, RealmFieldType.%2\$s)", fieldColKeyVariableReference(field), Utils.getValueListFieldType(field).name)
}
emitStatement("${fieldName}RealmList = new RealmList<%s>(%s.class, osList, proxyState.getRealm\$realm())", genericType, genericType)
emitStatement("return ${fieldName}RealmList")
endControlFlow()
endMethod()
emitEmptyLine()
// Getter - End
// Setter - Start
emitAnnotation("Override")
beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value")
emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field)) emitter@{
// check excludeFields
beginControlFlow("if (proxyState.getExcludeFields\$realm().contains(\"%1\$s\"))", field.simpleName.toString())
emitStatement("return")
endControlFlow()
if (!forRealmModel) {
return@emitter
}
emitSingleLineComment("if the list contains unmanaged RealmObjects, convert them to managed.")
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmList<%1\$s> original = value", genericType)
emitStatement("value = new RealmList<%1\$s>()", genericType)
beginControlFlow("for (%1\$s item : original)", genericType)
beginControlFlow("if (item == null || RealmObject.isManaged(item))")
emitStatement("value.add(item)")
nextControlFlow("else")
val type = getGenericType(field) ?:
throw IllegalArgumentException("Unable to derive generic type of ${fieldName}")
if (fieldTypeHasPrimaryKey(type, classCollection)) {
emitStatement("value.add(realm.copyToRealmOrUpdate(item))")
} else {
emitStatement("value.add(realm.copyToRealm(item))");
}
endControlFlow()
endControlFlow()
endControlFlow()
// LinkView currently does not support default value feature. Just fallback to normal code.
}
emitStatement("proxyState.getRealm\$realm().checkIfValid()")
if (Utils.isRealmModelList(field)) {
emitStatement("OsList osList = proxyState.getRow\$realm().getModelList(%s)", fieldColKeyVariableReference(field))
} else {
emitStatement("OsList osList = proxyState.getRow\$realm().getValueList(%1\$s, RealmFieldType.%2\$s)", fieldColKeyVariableReference(field), Utils.getValueListFieldType(field).name)
}
if (forRealmModel) {
// Model lists.
emitSingleLineComment("For lists of equal lengths, we need to set each element directly as clearing the receiver list can be wrong if the input and target list are the same.")
beginControlFlow("if (value != null && value.size() == osList.size())")
emitStatement("int objects = value.size()")
beginControlFlow("for (int i = 0; i < objects; i++)")
emitStatement("%s linkedObject = value.get(i)", genericType)
emitStatement("proxyState.checkValidObject(linkedObject)")
emitStatement("osList.setRow(i, ((RealmObjectProxy) linkedObject).realmGet\$proxyState().getRow\$realm().getObjectKey())")
endControlFlow()
nextControlFlow("else")
emitStatement("osList.removeAll()")
beginControlFlow("if (value == null)")
emitStatement("return")
endControlFlow()
emitStatement("int objects = value.size()")
beginControlFlow("for (int i = 0; i < objects; i++)")
emitStatement("%s linkedObject = value.get(i)", genericType)
emitStatement("proxyState.checkValidObject(linkedObject)")
emitStatement("osList.addRow(((RealmObjectProxy) linkedObject).realmGet\$proxyState().getRow\$realm().getObjectKey())")
endControlFlow()
endControlFlow()
} else {
if(forRealmAny){
beginControlFlow("if (value != null && !value.isManaged())")
emitStatement("final Realm realm = (Realm) proxyState.getRealm\$realm()")
emitStatement("final RealmList<RealmAny> original = value")
emitStatement("value = new RealmList<RealmAny>()")
beginControlFlow("for (int i = 0; i < original.size(); i++)")
emitStatement("value.add(ProxyUtils.copyToRealmIfNeeded(proxyState, original.get(i)))")
endControlFlow()
endControlFlow()
}
// Value lists
emitStatement("osList.removeAll()")
beginControlFlow("if (value == null)")
emitStatement("return")
endControlFlow()
beginControlFlow("for (%1\$s item : value)", genericType)
beginControlFlow("if (item == null)")
emitStatement(if (metadata.isElementNullable(field)) "osList.addNull()" else "throw new IllegalArgumentException(\"Storing 'null' into $fieldName' is not allowed by the schema.\")")
nextControlFlow("else")
emitStatement(getStatementForAppendingValueToOsList("osList", "item", elementTypeMirror))
endControlFlow()
endControlFlow()
}
endMethod()
// Setter - End
}
}
private fun getStatementForAppendingValueToOsList(
osListVariableName: String,
valueVariableName: String,
elementTypeMirror: TypeMirror?): String {
val typeUtils = processingEnvironment.typeUtils
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.STRING_MIRROR)) {
return "$osListVariableName.addString($valueVariableName)"
}
if ((typeUtils.isSameType(elementTypeMirror, typeMirrors.LONG_MIRROR)
|| typeUtils.isSameType(elementTypeMirror, typeMirrors.INTEGER_MIRROR)
|| typeUtils.isSameType(elementTypeMirror, typeMirrors.SHORT_MIRROR)
|| typeUtils.isSameType(elementTypeMirror, typeMirrors.BYTE_MIRROR))) {
return "$osListVariableName.addLong($valueVariableName.longValue())"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.BINARY_MIRROR)) {
return "$osListVariableName.addBinary($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.DATE_MIRROR)) {
return "$osListVariableName.addDate($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.BOOLEAN_MIRROR)) {
return "$osListVariableName.addBoolean($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.DOUBLE_MIRROR)) {
return "$osListVariableName.addDouble($valueVariableName.doubleValue())"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.FLOAT_MIRROR)) {
return "$osListVariableName.addFloat($valueVariableName.floatValue())"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.DECIMAL128_MIRROR)) {
return "$osListVariableName.addDecimal128($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.OBJECT_ID_MIRROR)) {
return "$osListVariableName.addObjectId($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.UUID_MIRROR)) {
return "$osListVariableName.addUUID($valueVariableName)"
}
if (typeUtils.isSameType(elementTypeMirror, typeMirrors.MIXED_MIRROR)) {
return "$osListVariableName.addRealmAny($valueVariableName.getNativePtr())"
}
throw RuntimeException("unexpected element type: $elementTypeMirror")
}
@Throws(IOException::class)
private fun emitCodeForUnderConstruction(writer: JavaWriter, isPrimaryKey: Boolean, emitCode: () -> Unit) {
writer.apply {
beginControlFlow("if (proxyState.isUnderConstruction())")
if (isPrimaryKey) {
emitSingleLineComment("default value of the primary key is always ignored.")
emitStatement("return")
} else {
beginControlFlow("if (!proxyState.getAcceptDefaultValue\$realm())")
emitStatement("return")
endControlFlow()
emitCode()
}
endControlFlow()
emitEmptyLine()
}
}
// Note that because of bytecode hackery, this method may run before the constructor!
// It may even run before fields have been initialized.
@Throws(IOException::class)
private fun emitInjectContextMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("void","realm\$injectObjectContext", EnumSet.of(Modifier.PUBLIC))
beginControlFlow("if (this.proxyState != null)")
emitStatement("return")
endControlFlow()
emitStatement("final BaseRealm.RealmObjectContext context = BaseRealm.objectContext.get()")
emitStatement("this.columnInfo = (%1\$s) context.getColumnInfo()", columnInfoClassName())
emitStatement("this.proxyState = new ProxyState<%1\$s>(this)", qualifiedJavaClassName)
emitStatement("proxyState.setRealm\$realm(context.getRealm())")
emitStatement("proxyState.setRow\$realm(context.getRow())")
emitStatement("proxyState.setAcceptDefaultValue\$realm(context.getAcceptDefaultValue())")
emitStatement("proxyState.setExcludeFields\$realm(context.getExcludeFields())")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitBacklinkFieldAccessors(writer: JavaWriter) {
for (backlink in metadata.backlinkFields) {
val cacheFieldName = backlink.targetField + BACKLINKS_FIELD_EXTENSION
val realmResultsType = "RealmResults<" + backlink.sourceClass + ">"
when (backlink.exposeAsRealmResults) {
true -> {
// Getter, no setter
writer.apply {
emitAnnotation("Override")
beginMethod(realmResultsType, metadata.getInternalGetter(backlink.targetField), EnumSet.of(Modifier.PUBLIC))
emitStatement("BaseRealm realm = proxyState.getRealm\$realm()")
emitStatement("realm.checkIfValid()")
emitStatement("proxyState.getRow\$realm().checkIfAttached()")
beginControlFlow("if ($cacheFieldName == null)")
emitStatement("$cacheFieldName = RealmResults.createBacklinkResults(realm, proxyState.getRow\$realm(), %s.class, \"%s\")", backlink.sourceClass, backlink.sourceField)
endControlFlow()
emitStatement("return $cacheFieldName")
endMethod()
emitEmptyLine()
}
}
false -> {
// Getter, no setter
writer.apply {
emitAnnotation("Override")
beginMethod(backlink.sourceClass.toString(), metadata.getInternalGetter(backlink.targetField), EnumSet.of(Modifier.PUBLIC))
emitStatement("BaseRealm realm = proxyState.getRealm\$realm()")
emitStatement("realm.checkIfValid()")
emitStatement("proxyState.getRow\$realm().checkIfAttached()")
beginControlFlow("if ($cacheFieldName == null)")
emitStatement("$cacheFieldName = RealmResults.createBacklinkResults(realm, proxyState.getRow\$realm(), %s.class, \"%s\").first()", backlink.sourceClass, backlink.sourceField)
endControlFlow()
emitStatement("return $cacheFieldName") // TODO: Figure out the exact API for this
endMethod()
emitEmptyLine()
}
}
}
}
}
@Throws(IOException::class)
private fun emitRealmObjectProxyImplementation(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("ProxyState<?>", "realmGet\$proxyState", EnumSet.of(Modifier.PUBLIC))
emitStatement("return proxyState")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateExpectedObjectSchemaInfo(writer: JavaWriter) {
writer.apply {
beginMethod("OsObjectSchemaInfo", "createExpectedObjectSchemaInfo", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC))
// Guess capacity for Arrays used by OsObjectSchemaInfo.
// Used to prevent array resizing at runtime
val persistedFields = metadata.fields.size
val computedFields = metadata.backlinkFields.size
val embeddedClass = if (metadata.embedded) "true" else "false"
val publicClassName = if (simpleJavaClassName.name != internalClassName) "\"${simpleJavaClassName.name}\"" else "NO_ALIAS"
emitStatement("OsObjectSchemaInfo.Builder builder = new OsObjectSchemaInfo.Builder($publicClassName, \"$internalClassName\", $embeddedClass, $persistedFields, $computedFields)")
// For each field generate corresponding table index constant
for (field in metadata.fields) {
val internalFieldName = field.internalFieldName
val publicFieldName = if (field.javaName == internalFieldName) "NO_ALIAS" else "\"${field.javaName}\""
when (val fieldType = getRealmTypeChecked(field)) {
Constants.RealmFieldType.NOTYPE -> {
// Perhaps this should fail quickly?
}
Constants.RealmFieldType.OBJECT -> {
val fieldTypeQualifiedName = Utils.getFieldTypeQualifiedName(field)
val internalClassName = Utils.getReferencedTypeInternalClassNameStatement(fieldTypeQualifiedName, classCollection)
emitStatement("builder.addPersistedLinkProperty(%s, \"%s\", RealmFieldType.OBJECT, %s)", publicFieldName, internalFieldName, internalClassName)
}
Constants.RealmFieldType.LIST -> {
val genericTypeQualifiedName = Utils.getGenericTypeQualifiedName(field)
val internalClassName = Utils.getReferencedTypeInternalClassNameStatement(genericTypeQualifiedName, classCollection)
emitStatement("builder.addPersistedLinkProperty(%s, \"%s\", RealmFieldType.LIST, %s)", publicFieldName, internalFieldName, internalClassName)
}
Constants.RealmFieldType.INTEGER_LIST,
Constants.RealmFieldType.BOOLEAN_LIST,
Constants.RealmFieldType.STRING_LIST,
Constants.RealmFieldType.BINARY_LIST,
Constants.RealmFieldType.DATE_LIST,
Constants.RealmFieldType.FLOAT_LIST,
Constants.RealmFieldType.DECIMAL128_LIST,
Constants.RealmFieldType.OBJECT_ID_LIST,
Constants.RealmFieldType.UUID_LIST,
Constants.RealmFieldType.MIXED_LIST,
Constants.RealmFieldType.DOUBLE_LIST -> {
val requiredFlag = if (metadata.isElementNullable(field)) "!Property.REQUIRED" else "Property.REQUIRED"
emitStatement("builder.addPersistedValueListProperty(%s, \"%s\", %s, %s)", publicFieldName, internalFieldName, fieldType.realmType, requiredFlag)
}
Constants.RealmFieldType.BACKLINK -> {
throw IllegalArgumentException("LinkingObject field should not be added to metadata")
}
Constants.RealmFieldType.INTEGER,
Constants.RealmFieldType.FLOAT,
Constants.RealmFieldType.DOUBLE,
Constants.RealmFieldType.BOOLEAN,
Constants.RealmFieldType.STRING,
Constants.RealmFieldType.DATE,
Constants.RealmFieldType.BINARY,
Constants.RealmFieldType.DECIMAL128,
Constants.RealmFieldType.OBJECT_ID,
Constants.RealmFieldType.UUID,
Constants.RealmFieldType.MIXED,
Constants.RealmFieldType.REALM_INTEGER -> {
val nullableFlag = (if (metadata.isNullable(field)) "!" else "") + "Property.REQUIRED"
val indexedFlag = (if (metadata.isIndexed(field)) "" else "!") + "Property.INDEXED"
val primaryKeyFlag = (if (metadata.isPrimaryKey(field)) "" else "!") + "Property.PRIMARY_KEY"
emitStatement("builder.addPersistedProperty(%s, \"%s\", %s, %s, %s, %s)", publicFieldName, internalFieldName, fieldType.realmType, primaryKeyFlag, indexedFlag, nullableFlag)
}
Constants.RealmFieldType.STRING_TO_BOOLEAN_MAP,
Constants.RealmFieldType.STRING_TO_STRING_MAP,
Constants.RealmFieldType.STRING_TO_INTEGER_MAP,
Constants.RealmFieldType.STRING_TO_FLOAT_MAP,
Constants.RealmFieldType.STRING_TO_DOUBLE_MAP,
Constants.RealmFieldType.STRING_TO_BINARY_MAP,
Constants.RealmFieldType.STRING_TO_DATE_MAP,
Constants.RealmFieldType.STRING_TO_DECIMAL128_MAP,
Constants.RealmFieldType.STRING_TO_OBJECT_ID_MAP,
Constants.RealmFieldType.STRING_TO_UUID_MAP,
Constants.RealmFieldType.STRING_TO_MIXED_MAP -> {
val valueNullable = metadata.isDictionaryValueNullable(field)
val requiredFlag = if (valueNullable) "!Property.REQUIRED" else "Property.REQUIRED"
emitStatement("builder.addPersistedMapProperty(%s, \"%s\", %s, %s)", publicFieldName, internalFieldName, fieldType.realmType, requiredFlag)
}
Constants.RealmFieldType.STRING_TO_LINK_MAP -> {
val genericTypeQualifiedName = Utils.getGenericTypeQualifiedName(field)
val internalClassName = Utils.getReferencedTypeInternalClassNameStatement(genericTypeQualifiedName, classCollection)
emitStatement("builder.addPersistedLinkProperty(%s, \"%s\", RealmFieldType.STRING_TO_LINK_MAP, %s)", publicFieldName, internalFieldName, internalClassName)
}
Constants.RealmFieldType.BOOLEAN_SET,
Constants.RealmFieldType.STRING_SET,
Constants.RealmFieldType.INTEGER_SET,
Constants.RealmFieldType.FLOAT_SET,
Constants.RealmFieldType.DOUBLE_SET,
Constants.RealmFieldType.BINARY_SET,
Constants.RealmFieldType.DATE_SET,
Constants.RealmFieldType.DECIMAL128_SET,
Constants.RealmFieldType.OBJECT_ID_SET,
Constants.RealmFieldType.UUID_SET,
Constants.RealmFieldType.MIXED_SET -> {
val valueNullable = metadata.isSetValueNullable(field)
val requiredFlag = if (valueNullable) "!Property.REQUIRED" else "Property.REQUIRED"
emitStatement("builder.addPersistedSetProperty(%s, \"%s\", %s, %s)", publicFieldName, internalFieldName, fieldType.realmType, requiredFlag)
}
Constants.RealmFieldType.LINK_SET -> {
val genericTypeQualifiedName = Utils.getGenericTypeQualifiedName(field)
val internalClassName = Utils.getReferencedTypeInternalClassNameStatement(genericTypeQualifiedName, classCollection)
emitStatement("builder.addPersistedLinkProperty(${publicFieldName}, \"${internalFieldName}\", RealmFieldType.LINK_SET, ${internalClassName})")
}
}
}
for (backlink in metadata.backlinkFields) {
// Backlinks can only be created between classes in the current round of annotation processing
// as the forward link cannot be created unless you know the type already.
val sourceClass = classCollection.getClassFromQualifiedName(backlink.sourceClass!!)
val targetField = backlink.targetField // Only in the model, so no internal name exists
val internalSourceField = sourceClass.getInternalFieldName(backlink.sourceField!!)
emitStatement("""builder.addComputedLinkProperty("%s", "%s", "%s")""", targetField, sourceClass.internalClassName, internalSourceField)
}
emitStatement("return builder.build()")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetExpectedObjectSchemaInfo(writer: JavaWriter) {
writer.apply {
beginMethod("OsObjectSchemaInfo", "getExpectedObjectSchemaInfo", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC))
emitStatement("return expectedObjectSchemaInfo")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateColumnInfoMethod(writer: JavaWriter) {
writer.apply {
beginMethod(columnInfoClassName(), "createColumnInfo", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), "OsSchemaInfo", "schemaInfo")
emitStatement("return new %1\$s(schemaInfo)", columnInfoClassName())
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetSimpleClassNameMethod(writer: JavaWriter) {
writer.apply {
beginMethod("String", "getSimpleClassName", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC))
emitStatement("return \"%s\"", internalClassName)
endMethod()
emitEmptyLine()
// Helper class for the annotation processor so it can access the internal class name
// without needing to load the parent class (which we cannot do as it transitively loads
// native code, which cannot be loaded on the JVM).
beginType("ClassNameHelper", "class", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL))
emitField("String", "INTERNAL_CLASS_NAME", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL), "\"$internalClassName\"")
endType()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitNewProxyInstance(writer: JavaWriter) {
writer.apply {
beginMethod(generatedClassName, "newProxyInstance", EnumSet.of(Modifier.STATIC), "BaseRealm", "realm", "Row", "row")
emitSingleLineComment("Ignore default values to avoid creating unexpected objects from RealmModel/RealmList fields")
emitStatement("final BaseRealm.RealmObjectContext objectContext = BaseRealm.objectContext.get()")
emitStatement("objectContext.set(realm, row, realm.getSchema().getColumnInfo(%s.class), false, Collections.<String>emptyList())", qualifiedJavaClassName)
emitStatement("%1\$s obj = new %1\$s()", generatedClassName)
emitStatement("objectContext.clear()")
emitStatement("return obj")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCopyOrUpdateMethod(writer: JavaWriter) {
writer.apply {
beginMethod(qualifiedJavaClassName,"copyOrUpdate", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC),
"Realm", "realm",
columnInfoClassName(), "columnInfo",
qualifiedJavaClassName.toString(), "object",
"boolean", "update",
"Map<RealmModel,RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags")
beginControlFlow("if (object instanceof RealmObjectProxy && !RealmObject.isFrozen(object) && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm() != null)")
emitStatement("final BaseRealm otherRealm = ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm()")
beginControlFlow("if (otherRealm.threadId != realm.threadId)")
emitStatement("throw new IllegalArgumentException(\"Objects which belong to Realm instances in other threads cannot be copied into this Realm instance.\")")
endControlFlow()
// If object is already in the Realm there is nothing to update
beginControlFlow("if (otherRealm.getPath().equals(realm.getPath()))")
emitStatement("return object")
endControlFlow()
endControlFlow()
emitStatement("final BaseRealm.RealmObjectContext objectContext = BaseRealm.objectContext.get()")
emitStatement("RealmObjectProxy cachedRealmObject = cache.get(object)")
beginControlFlow("if (cachedRealmObject != null)")
emitStatement("return (%s) cachedRealmObject", qualifiedJavaClassName)
endControlFlow()
emitEmptyLine()
if (!metadata.hasPrimaryKey()) {
emitStatement("return copy(realm, columnInfo, object, update, cache, flags)")
} else {
emitStatement("%s realmObject = null", qualifiedJavaClassName)
emitStatement("boolean canUpdate = update")
beginControlFlow("if (canUpdate)")
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
val primaryKeyGetter = metadata.primaryKeyGetter
val primaryKeyElement = metadata.primaryKey
if (metadata.isNullable(primaryKeyElement!!)) {
if (Utils.isString(primaryKeyElement)) {
emitStatement("String value = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (value == null)")
emitStatement("objKey = table.findFirstNull(pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = table.findFirstString(pkColumnKey, value)")
endControlFlow()
} else if (Utils.isObjectId(primaryKeyElement)) {
emitStatement("org.bson.types.ObjectId value = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (value == null)")
emitStatement("objKey = table.findFirstNull(pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = table.findFirstObjectId(pkColumnKey, value)")
endControlFlow()
} else if (Utils.isUUID(primaryKeyElement)) {
emitStatement("java.util.UUID value = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (value == null)")
emitStatement("objKey = table.findFirstNull(pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = table.findFirstUUID(pkColumnKey, value)")
endControlFlow()
} else {
emitStatement("Number value = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (value == null)")
emitStatement("objKey = table.findFirstNull(pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = table.findFirstLong(pkColumnKey, value.longValue())")
endControlFlow()
}
} else {
if (Utils.isString(primaryKeyElement)) {
emitStatement("long objKey = table.findFirstString(pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
} else if (Utils.isObjectId(primaryKeyElement)) {
emitStatement("long objKey = table.findFirstObjectId(pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
} else if (Utils.isUUID(primaryKeyElement)) {
emitStatement("long objKey = table.findFirstUUID(pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
} else {
emitStatement("long objKey = table.findFirstLong(pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
}
}
beginControlFlow("if (objKey == Table.NO_MATCH)")
emitStatement("canUpdate = false")
nextControlFlow("else")
beginControlFlow("try")
emitStatement("objectContext.set(realm, table.getUncheckedRow(objKey), columnInfo, false, Collections.<String> emptyList())")
emitStatement("realmObject = new %s()", generatedClassName)
emitStatement("cache.put(object, (RealmObjectProxy) realmObject)")
nextControlFlow("finally")
emitStatement("objectContext.clear()")
endControlFlow()
endControlFlow()
endControlFlow()
emitEmptyLine()
emitStatement("return (canUpdate) ? update(realm, columnInfo, realmObject, object, cache, flags) : copy(realm, columnInfo, object, update, cache, flags)")
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun setTableValues(writer: JavaWriter, fieldType: String, fieldName: String, interfaceName: SimpleClassName, getter: String, isUpdate: Boolean) {
writer.apply {
when(fieldType) {
"long",
"int",
"short",
"byte" -> {
emitStatement("Table.nativeSetLong(tableNativePtr, columnInfo.%sColKey, objKey, ((%s) object).%s(), false)", fieldName, interfaceName, getter)
}
"java.lang.Long",
"java.lang.Integer",
"java.lang.Short",
"java.lang.Byte" -> {
emitStatement("Number %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetLong(tableNativePtr, columnInfo.%sColKey, objKey, %s.longValue(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"io.realm.MutableRealmInteger" -> {
emitStatement("Long %s = ((%s) object).%s().get()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetLong(tableNativePtr, columnInfo.%sColKey, objKey, %s.longValue(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"double" -> {
emitStatement("Table.nativeSetDouble(tableNativePtr, columnInfo.%sColKey, objKey, ((%s) object).%s(), false)", fieldName, interfaceName, getter)
}
"java.lang.Double" -> {
emitStatement("Double %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetDouble(tableNativePtr, columnInfo.%sColKey, objKey, %s, false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"float" -> {
emitStatement("Table.nativeSetFloat(tableNativePtr, columnInfo.%sColKey, objKey, ((%s) object).%s(), false)", fieldName, interfaceName, getter)
}
"java.lang.Float" -> {
emitStatement("Float %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetFloat(tableNativePtr, columnInfo.%sColKey, objKey, %s, false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"boolean" -> {
emitStatement("Table.nativeSetBoolean(tableNativePtr, columnInfo.%sColKey, objKey, ((%s) object).%s(), false)", fieldName, interfaceName, getter)
}
"java.lang.Boolean" -> {
emitStatement("Boolean %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetBoolean(tableNativePtr, columnInfo.%sColKey, objKey, %s, false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"byte[]" -> {
emitStatement("byte[] %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetByteArray(tableNativePtr, columnInfo.%sColKey, objKey, %s, false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"java.util.Date" -> {
emitStatement("java.util.Date %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetTimestamp(tableNativePtr, columnInfo.%sColKey, objKey, %s.getTime(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"java.lang.String" -> {
emitStatement("String %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetString(tableNativePtr, columnInfo.%sColKey, objKey, %s, false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"org.bson.types.Decimal128" -> {
emitStatement("org.bson.types.Decimal128 %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetDecimal128(tableNativePtr, columnInfo.%1\$sColKey, objKey, %2\$s.getLow(), %2\$s.getHigh(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"org.bson.types.ObjectId" -> {
emitStatement("org.bson.types.ObjectId %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetObjectId(tableNativePtr, columnInfo.%sColKey, objKey, %s.toString(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
"java.util.UUID" -> {
emitStatement("java.util.UUID %s = ((%s) object).%s()", getter, interfaceName, getter)
beginControlFlow("if (%s != null)", getter)
emitStatement("Table.nativeSetUUID(tableNativePtr, columnInfo.%sColKey, objKey, %s.toString(), false)", fieldName, getter)
if (isUpdate) {
nextControlFlow("else")
emitStatement("Table.nativeSetNull(tableNativePtr, columnInfo.%sColKey, objKey, false)", fieldName)
}
endControlFlow()
}
else -> {
throw IllegalStateException("Unsupported type $fieldType")
}
}
}
}
@Throws(IOException::class)
private fun emitInsertInternal(writer: JavaWriter){
writer.apply {
addPrimaryKeyCheckIfNeeded(metadata, true, writer)
for (field in metadata.fields) {
val fieldName = field.simpleName.toString()
val fieldType = QualifiedClassName(field.asType().toString())
val getter = metadata.getInternalGetter(fieldName)
when {
Utils.isRealmModel(field) -> {
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
emitEmptyLine()
emitStatement("%s %sObj = ((%s) object).%s()", fieldType, fieldName, interfaceName, getter)
beginControlFlow("if (%sObj != null)", fieldName)
emitStatement("Long cache%1\$s = cache.get(%1\$sObj)", fieldName)
if (isEmbedded) {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: \" + cache%s.toString())", fieldName)
nextControlFlow("else")
emitStatement("cache%1\$s = %2\$s.insert(realm, table, columnInfo.%3\$sColKey, objKey, %3\$sObj, cache)", fieldName, Utils.getProxyClassSimpleName(field), fieldName)
endControlFlow()
} else {
beginControlFlow("if (cache%s == null)", fieldName)
emitStatement("cache%s = %s.insert(realm, %sObj, cache)", fieldName, Utils.getProxyClassSimpleName(field), fieldName)
endControlFlow()
emitStatement("Table.nativeSetLink(tableNativePtr, columnInfo.%1\$sColKey, objKey, cache%1\$s, false)", fieldName)
}
endControlFlow()
}
Utils.isRealmModelList(field) -> {
val genericType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(genericType, classCollection)
emitEmptyLine()
emitStatement("RealmList<%s> %sList = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
beginControlFlow("if (%sList != null)", fieldName)
emitStatement("OsList %1\$sOsList = new OsList(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sList)", genericType, fieldName)
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
if (isEmbedded) {
beginControlFlow("if (cacheItemIndex%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: \" + cacheItemIndex%s.toString())", fieldName)
nextControlFlow("else")
emitStatement("cacheItemIndex%1\$s = %2\$s.insert(realm, table, columnInfo.%3\$sColKey, objKey, %3\$sItem, cache)", fieldName, Utils.getProxyClassName(QualifiedClassName(genericType.toString())), fieldName)
endControlFlow()
} else {
beginControlFlow("if (cacheItemIndex%s == null)", fieldName)
emitStatement("cacheItemIndex%1\$s = %2\$s.insert(realm, %1\$sItem, cache)", fieldName, Utils.getProxyClassSimpleName(field))
endControlFlow()
emitStatement("%1\$sOsList.addRow(cacheItemIndex%1\$s)", fieldName)
}
endControlFlow()
endControlFlow()
}
Utils.isRealmValueList(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field)
emitEmptyLine()
emitStatement("RealmList<%s> %sList = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
beginControlFlow("if (%sList != null)", fieldName)
emitStatement("OsList %1\$sOsList = new OsList(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sList)", genericType, fieldName)
beginControlFlow("if (%1\$sItem == null)", fieldName)
emitStatement(fieldName + "OsList.addNull()")
nextControlFlow("else")
emitStatement(getStatementForAppendingValueToOsList(fieldName + "OsList", fieldName + "Item", elementTypeMirror))
endControlFlow()
endControlFlow()
endControlFlow()
}
Utils.isRealmAny(field) -> {
emitEmptyLine()
emitStatement("RealmAny ${fieldName}RealmAny = ((${interfaceName}) object).${getter}()")
emitStatement("${fieldName}RealmAny = ProxyUtils.insert(${fieldName}RealmAny, realm, cache)")
emitStatement("Table.nativeSetRealmAny(tableNativePtr, columnInfo.${fieldName}ColKey, objKey, ${fieldName}RealmAny.getNativePtr(), false)")
}
Utils.isRealmAnyList(field) -> {
emitEmptyLine()
emitStatement("RealmList<RealmAny> ${fieldName}UnmanagedList = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedList != null)")
emitStatement("OsList ${fieldName}OsList = new OsList(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
beginControlFlow("for (int i = 0; i < ${fieldName}UnmanagedList.size(); i++)")
emitStatement("RealmAny realmAnyItem = ${fieldName}UnmanagedList.get(i)")
emitStatement("realmAnyItem = ProxyUtils.insert(realmAnyItem, realm, cache)")
emitStatement("${fieldName}OsList.addRealmAny(realmAnyItem.getNativePtr())")
endControlFlow()
endControlFlow()
}
Utils.isRealmValueDictionary(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field)
emitEmptyLine()
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)", fieldName)
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
emitStatement("${fieldName}OsMap.put(entryKey, ${fieldName}UnmanagedEntryValue)")
endControlFlow()
endControlFlow()
}
Utils.isRealmAnyDictionary(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitStatement("RealmDictionary<RealmAny> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
emitStatement("java.util.List<String> keys = new java.util.ArrayList<>()")
emitStatement("java.util.List<Long> realmAnyPointers = new java.util.ArrayList<>()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("RealmAny realmAnyItem = entry.getValue()")
emitStatement("realmAnyItem = ProxyUtils.insert(realmAnyItem, realm, cache)")
emitStatement("${fieldName}OsMap.putRealmAny(entry.getKey(), realmAnyItem.getNativePtr())")
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmModelDictionary(field) -> {
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val listElementType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(listElementType, classCollection)
val linkedProxyClass: SimpleClassName = Utils.getDictionaryGenericProxyClassSimpleName(field)
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
beginControlFlow("if(${fieldName}UnmanagedEntryValue == null)")
emitStatement("${fieldName}OsMap.put(entryKey, null)")
nextControlFlow("else")
// here goes the rest
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}UnmanagedEntryValue)")
if (isEmbedded) {
beginControlFlow("if (cacheItemIndex${fieldName} != null)")
emitStatement("""throw new IllegalArgumentException("Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache${fieldName}.toString()")""")
nextControlFlow("else")
emitStatement("cacheItemIndex${fieldName} = ${linkedProxyClass}.insert(realm, table, columnInfo.${fieldName}ColKey, objKey, ${fieldName}UnmanagedEntryValue, cache)")
endControlFlow()
emitStatement("${fieldName}OsMap.putRow(entryKey, cacheItemIndex${fieldName})")
} else {
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("cacheItemIndex${fieldName} = ${linkedProxyClass}.insert(realm, ${fieldName}UnmanagedEntryValue, cache)")
endControlFlow()
emitStatement("${fieldName}OsMap.putRow(entryKey, cacheItemIndex${fieldName})")
}
endControlFlow()
endControlFlow()
endControlFlow()
}
Utils.isRealmModelSet(field) -> {
val genericType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(genericType, classCollection)
emitEmptyLine()
emitStatement("RealmSet<${genericType}> ${fieldName}Set = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}Set != null)")
emitStatement("OsSet ${fieldName}OsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
beginControlFlow("for (${genericType} ${fieldName}Item: ${fieldName}Set)")
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}Item)")
if (isEmbedded) {
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: \" + cacheItemIndex${fieldName}.toString())")
} else {
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("cacheItemIndex${fieldName} = ${Utils.getSetGenericProxyClassSimpleName(field)}.insert(realm, ${fieldName}Item, cache)")
endControlFlow()
emitStatement("${fieldName}OsSet.addRow(cacheItemIndex${fieldName})")
}
endControlFlow()
endControlFlow()
}
Utils.isRealmValueSet(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitEmptyLine()
emitStatement("RealmSet<${genericType}> ${fieldName}Set = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}Set != null)")
emitStatement("OsSet ${fieldName}OsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
beginControlFlow("for (${genericType} ${fieldName}Item: ${fieldName}Set)")
beginControlFlow("if (${fieldName}Item == null)")
emitStatement(fieldName + "OsSet.add(($genericType) null)")
nextControlFlow("else")
emitStatement("${fieldName}OsSet.add(${fieldName}Item)")
endControlFlow()
endControlFlow()
endControlFlow()
}
Utils.isRealmAnySet(field) -> {
emitEmptyLine()
emitStatement("RealmSet<RealmAny> ${fieldName}UnmanagedSet = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedSet != null)")
emitStatement("OsSet ${fieldName}OsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
beginControlFlow("for (RealmAny realmAnyItem: ${fieldName}UnmanagedSet)")
emitStatement("realmAnyItem = ProxyUtils.insert(realmAnyItem, realm, cache)")
emitStatement("${fieldName}OsSet.addRealmAny(realmAnyItem.getNativePtr())")
endControlFlow()
endControlFlow()
}
else -> {
if (metadata.primaryKey !== field) {
setTableValues(writer, fieldType.toString(), fieldName, interfaceName, getter, false)
}
}
}
}
}
}
@Throws(IOException::class)
private fun emitInsertMethod(writer: JavaWriter) {
writer.apply {
val topLevelArgs = arrayOf("Realm", "realm",
qualifiedJavaClassName.toString(), "object",
"Map<RealmModel,Long>", "cache")
val embeddedArgs = arrayOf("Realm", "realm",
"Table", "parentObjectTable",
"long", "parentColumnKey",
"long", "parentObjectKey",
qualifiedJavaClassName.toString(), "object",
"Map<RealmModel,Long>", "cache")
val args = if (metadata.embedded) embeddedArgs else topLevelArgs
beginMethod("long","insert", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), *args)
// If object is already in the Realm there is nothing to update, unless it is an embedded
// object. In which case we always update the underlying object.
if (!metadata.embedded) {
beginControlFlow("if (object instanceof RealmObjectProxy && !RealmObject.isFrozen(object) && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm() != null && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm().getPath().equals(realm.getPath()))")
emitStatement("return ((RealmObjectProxy) object).realmGet\$proxyState().getRow\$realm().getObjectKey()")
endControlFlow()
}
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("long tableNativePtr = table.getNativePtr()")
emitStatement("%s columnInfo = (%s) realm.getSchema().getColumnInfo(%s.class)", columnInfoClassName(), columnInfoClassName(), qualifiedJavaClassName)
if (metadata.hasPrimaryKey()) {
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
}
emitInsertInternal(this)
emitStatement("return objKey")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertListMethod(writer: JavaWriter) {
writer.apply {
val topLevelArgs = arrayOf("Realm", "realm",
"Iterator<? extends RealmModel>", "objects",
"Map<RealmModel,Long>", "cache")
val embeddedArgs = arrayOf("Realm", "realm",
"Table", "parentObjectTable",
"long", "parentColumnKey",
"long", "parentObjectKey",
"Iterator<? extends RealmModel>", "objects",
"Map<RealmModel,Long>", "cache")
val args = if (metadata.embedded) embeddedArgs else topLevelArgs
beginMethod("void", "insert", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), *args)
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("long tableNativePtr = table.getNativePtr()")
emitStatement("%s columnInfo = (%s) realm.getSchema().getColumnInfo(%s.class)", columnInfoClassName(), columnInfoClassName(), qualifiedJavaClassName)
if (metadata.hasPrimaryKey()) {
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
}
emitStatement("%s object = null", qualifiedJavaClassName)
beginControlFlow("while (objects.hasNext())")
emitStatement("object = (%s) objects.next()", qualifiedJavaClassName)
beginControlFlow("if (cache.containsKey(object))")
emitStatement("continue")
endControlFlow()
beginControlFlow("if (object instanceof RealmObjectProxy && !RealmObject.isFrozen(object) && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm() != null && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm().getPath().equals(realm.getPath()))")
emitStatement("cache.put(object, ((RealmObjectProxy) object).realmGet\$proxyState().getRow\$realm().getObjectKey())")
emitStatement("continue")
endControlFlow()
emitInsertInternal(this)
endControlFlow()
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun insertOrUpdateInternal(writer: JavaWriter){
writer.apply {
addPrimaryKeyCheckIfNeeded(metadata, false, writer)
for (field in metadata.fields) {
val fieldName = field.simpleName.toString()
val fieldType = QualifiedClassName(field.asType().toString())
val getter = metadata.getInternalGetter(fieldName)
when {
Utils.isRealmModel(field) -> {
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
emitEmptyLine()
emitStatement("%s %sObj = ((%s) object).%s()", fieldType, fieldName, interfaceName, getter)
beginControlFlow("if (%sObj != null)", fieldName)
emitStatement("Long cache%1\$s = cache.get(%1\$sObj)", fieldName)
if (isEmbedded) {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: \" + cache%s.toString())", fieldName)
nextControlFlow("else")
emitStatement("cache%1\$s = %2\$s.insertOrUpdate(realm, table, columnInfo.%3\$sColKey, objKey, %3\$sObj, cache)", fieldName, Utils.getProxyClassSimpleName(field), fieldName)
endControlFlow()
} else {
beginControlFlow("if (cache%s == null)", fieldName)
emitStatement("cache%1\$s = %2\$s.insertOrUpdate(realm, %1\$sObj, cache)", fieldName, Utils.getProxyClassSimpleName(field))
endControlFlow()
emitStatement("Table.nativeSetLink(tableNativePtr, columnInfo.%1\$sColKey, objKey, cache%1\$s, false)", fieldName)
}
nextControlFlow("else")
// No need to throw exception here if the field is not nullable. A exception will be thrown in setter.
emitStatement("Table.nativeNullifyLink(tableNativePtr, columnInfo.%sColKey, objKey)", fieldName)
endControlFlow()
}
Utils.isRealmModelList(field) -> {
val genericType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(genericType, classCollection)
emitEmptyLine()
emitStatement("OsList %1\$sOsList = new OsList(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
emitStatement("RealmList<%s> %sList = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
if (isEmbedded) {
emitStatement("%1\$sOsList.removeAll()", fieldName)
beginControlFlow("if (%sList != null)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sList)", genericType, fieldName)
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
beginControlFlow("if (cacheItemIndex%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: \" + cacheItemIndex%s.toString())", fieldName)
nextControlFlow("else")
emitStatement("cacheItemIndex%1\$s = %2\$s.insertOrUpdate(realm, table, columnInfo.%3\$sColKey, objKey, %3\$sItem, cache)", fieldName, Utils.getProxyClassName(QualifiedClassName(genericType.toString())), fieldName)
endControlFlow()
endControlFlow()
endControlFlow()
} else {
beginControlFlow("if (%1\$sList != null && %1\$sList.size() == %1\$sOsList.size())", fieldName)
emitSingleLineComment("For lists of equal lengths, we need to set each element directly as clearing the receiver list can be wrong if the input and target list are the same.")
emitStatement("int objectCount = %1\$sList.size()", fieldName)
beginControlFlow("for (int i = 0; i < objectCount; i++)")
emitStatement("%1\$s %2\$sItem = %2\$sList.get(i)", genericType, fieldName)
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
beginControlFlow("if (cacheItemIndex%s == null)", fieldName)
emitStatement("cacheItemIndex%1\$s = %2\$s.insertOrUpdate(realm, %1\$sItem, cache)", fieldName, Utils.getProxyClassSimpleName(field))
endControlFlow()
emitStatement("%1\$sOsList.setRow(i, cacheItemIndex%1\$s)", fieldName)
endControlFlow()
nextControlFlow("else")
emitStatement("%1\$sOsList.removeAll()", fieldName)
beginControlFlow("if (%sList != null)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sList)", genericType, fieldName)
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
beginControlFlow("if (cacheItemIndex%s == null)", fieldName)
emitStatement("cacheItemIndex%1\$s = %2\$s.insertOrUpdate(realm, %1\$sItem, cache)", fieldName, Utils.getProxyClassSimpleName(field))
endControlFlow()
emitStatement("%1\$sOsList.addRow(cacheItemIndex%1\$s)", fieldName)
endControlFlow()
endControlFlow()
endControlFlow()
}
emitEmptyLine()
}
Utils.isRealmValueList(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field)
emitEmptyLine()
emitStatement("OsList %1\$sOsList = new OsList(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
emitStatement("%1\$sOsList.removeAll()", fieldName)
emitStatement("RealmList<%s> %sList = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
beginControlFlow("if (%sList != null)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sList)", genericType, fieldName)
beginControlFlow("if (%1\$sItem == null)", fieldName)
emitStatement("%1\$sOsList.addNull()", fieldName)
nextControlFlow("else")
emitStatement(getStatementForAppendingValueToOsList(fieldName + "OsList", fieldName + "Item", elementTypeMirror))
endControlFlow()
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmAny(field) -> {
emitStatement("RealmAny ${fieldName}RealmAny = ((${interfaceName}) object).${getter}()")
emitStatement("${fieldName}RealmAny = ProxyUtils.insertOrUpdate(${fieldName}RealmAny, realm, cache)")
emitStatement("Table.nativeSetRealmAny(tableNativePtr, columnInfo.${fieldName}ColKey, objKey, ${fieldName}RealmAny.getNativePtr(), false)")
}
Utils.isRealmAnyList(field) -> {
emitEmptyLine()
emitStatement("OsList ${fieldName}OsList = new OsList(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("RealmList<RealmAny> ${fieldName}List = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}List != null && ${fieldName}List.size() == ${fieldName}OsList.size())")
emitSingleLineComment("For lists of equal lengths, we need to set each element directly as clearing the receiver list can be wrong if the input and target list are the same.")
emitStatement("int objectCount = ${fieldName}List.size()")
beginControlFlow("for (int i = 0; i < objectCount; i++)")
emitStatement("RealmAny ${fieldName}Item = ${fieldName}List.get(i)")
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}Item)")
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("${fieldName}Item = ProxyUtils.insertOrUpdate(${fieldName}Item, realm, cache)")
endControlFlow()
emitStatement("${fieldName}OsList.setRealmAny(i, ${fieldName}Item.getNativePtr())")
endControlFlow()
nextControlFlow("else")
emitStatement("${fieldName}OsList.removeAll()")
beginControlFlow("if (${fieldName}List != null)")
beginControlFlow("for (RealmAny ${fieldName}Item : ${fieldName}List)")
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}Item)")
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("${fieldName}Item = ProxyUtils.insertOrUpdate(${fieldName}Item, realm, cache)")
endControlFlow()
emitStatement("${fieldName}OsList.addRealmAny(${fieldName}Item.getNativePtr())")
endControlFlow()
endControlFlow()
endControlFlow()
}
Utils.isRealmModelDictionary(field) -> {
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val dictElementType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(dictElementType, classCollection)
val linkedProxyClass: SimpleClassName = Utils.getDictionaryGenericProxyClassSimpleName(field)
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
beginControlFlow("if(${fieldName}UnmanagedEntryValue == null)")
emitStatement("${fieldName}OsMap.put(entryKey, null)")
nextControlFlow("else")
// here goes the rest
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}UnmanagedEntryValue)")
if (isEmbedded) {
beginControlFlow("if (cacheItemIndex${fieldName} != null)")
emitStatement("""throw new IllegalArgumentException("Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache${fieldName}.toString()")""")
nextControlFlow("else")
emitStatement("cacheItemIndex${fieldName} = ${linkedProxyClass}.insertOrUpdate(realm, table, columnInfo.${fieldName}ColKey, objKey, ${fieldName}UnmanagedEntryValue, cache)")
endControlFlow()
emitStatement("${fieldName}OsMap.putRow(entryKey, cacheItemIndex${fieldName})")
} else {
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("cacheItemIndex${fieldName} = ${linkedProxyClass}.insertOrUpdate(realm, ${fieldName}UnmanagedEntryValue, cache)")
endControlFlow()
emitStatement("${fieldName}OsMap.putRow(entryKey, cacheItemIndex${fieldName})")
}
endControlFlow()
endControlFlow()
endControlFlow()
}
Utils.isRealmValueDictionary(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitEmptyLine()
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)", fieldName)
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
emitStatement("${fieldName}OsMap.put(entryKey, ${fieldName}UnmanagedEntryValue)")
endControlFlow()
endControlFlow()
}
Utils.isRealmAnyDictionary(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitStatement("RealmDictionary<RealmAny> ${fieldName}UnmanagedDictionary = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("OsMap ${fieldName}OsMap = new OsMap(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
emitStatement("java.util.List<String> keys = new java.util.ArrayList<>()")
emitStatement("java.util.List<Long> realmAnyPointers = new java.util.ArrayList<>()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("RealmAny realmAnyItem = entry.getValue()")
emitStatement("realmAnyItem = ProxyUtils.insertOrUpdate(realmAnyItem, realm, cache)")
emitStatement("${fieldName}OsMap.putRealmAny(entry.getKey(), realmAnyItem.getNativePtr())")
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmModelSet(field) -> {
val genericType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(genericType, classCollection)
emitEmptyLine()
emitStatement("OsSet %1\$sOsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
emitStatement("RealmSet<%s> %sSet = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
if (isEmbedded) {
// throw not supported
throw UnsupportedOperationException("Field $fieldName of type RealmSet<${genericType}>, RealmSet does not support embedded objects.")
} else {
beginControlFlow("if (%1\$sSet != null && %1\$sSet.size() == %1\$sOsSet.size())", fieldName)
emitSingleLineComment("For Sets of equal lengths, we need to set each element directly as clearing the receiver Set can be wrong if the input and target Set are the same.")
emitStatement("int objectCount = %1\$sSet.size()", fieldName)
beginControlFlow("for (${genericType} ${fieldName}Item: ${fieldName}Set)")
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
beginControlFlow("if (cacheItemIndex%s == null)", fieldName)
emitStatement("cacheItemIndex%1\$s = %2\$s.insertOrUpdate(realm, %1\$sItem, cache)", fieldName, Utils.getSetGenericProxyClassSimpleName(field))
endControlFlow()
emitStatement("%1\$sOsSet.addRow(cacheItemIndex%1\$s)", fieldName)
endControlFlow()
nextControlFlow("else")
emitStatement("%1\$sOsSet.clear()", fieldName)
beginControlFlow("if (%sSet != null)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sSet)", genericType, fieldName)
emitStatement("Long cacheItemIndex%1\$s = cache.get(%1\$sItem)", fieldName)
beginControlFlow("if (cacheItemIndex%s == null)", fieldName)
emitStatement("cacheItemIndex%1\$s = %2\$s.insertOrUpdate(realm, %1\$sItem, cache)", fieldName, Utils.getSetGenericProxyClassSimpleName(field))
endControlFlow()
emitStatement("%1\$sOsSet.addRow(cacheItemIndex%1\$s)", fieldName)
endControlFlow()
endControlFlow()
endControlFlow()
}
emitEmptyLine()
}
Utils.isRealmValueSet(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitEmptyLine()
emitStatement("OsSet %1\$sOsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.%1\$sColKey)", fieldName)
emitStatement("%1\$sOsSet.clear()", fieldName)
emitStatement("RealmSet<%s> %sSet = ((%s) object).%s()", genericType, fieldName, interfaceName, getter)
beginControlFlow("if (%sSet != null)", fieldName)
beginControlFlow("for (%1\$s %2\$sItem : %2\$sSet)", genericType, fieldName)
beginControlFlow("if (%1\$sItem == null)", fieldName)
emitStatement("%1\$sOsSet.add(($genericType) null)", fieldName)
nextControlFlow("else")
emitStatement("${fieldName}OsSet.add(${fieldName}Item)")
endControlFlow()
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmAnySet(field) -> {
emitEmptyLine()
emitStatement("OsSet ${fieldName}OsSet = new OsSet(table.getUncheckedRow(objKey), columnInfo.${fieldName}ColKey)")
emitStatement("RealmSet<RealmAny> ${fieldName}Set = ((${interfaceName}) object).${getter}()")
beginControlFlow("if (${fieldName}Set != null && ${fieldName}Set.size() == ${fieldName}OsSet.size())")
emitSingleLineComment("For Sets of equal lengths, we need to set each element directly as clearing the receiver Set can be wrong if the input and target Set are the same.")
emitStatement("int objectCount = ${fieldName}Set.size()")
beginControlFlow("for (RealmAny ${fieldName}Item: ${fieldName}Set)")
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}Item)")
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("${fieldName}Item = ProxyUtils.insertOrUpdate(${fieldName}Item, realm, cache)")
endControlFlow()
emitStatement("${fieldName}OsSet.addRealmAny(${fieldName}Item.getNativePtr())")
endControlFlow()
nextControlFlow("else")
emitStatement("${fieldName}OsSet.clear()")
beginControlFlow("if (${fieldName}Set != null)")
beginControlFlow("for (RealmAny ${fieldName}Item : ${fieldName}Set)")
emitStatement("Long cacheItemIndex${fieldName} = cache.get(${fieldName}Item)")
beginControlFlow("if (cacheItemIndex${fieldName} == null)")
emitStatement("${fieldName}Item = ProxyUtils.insertOrUpdate(${fieldName}Item, realm, cache)")
endControlFlow()
emitStatement("${fieldName}OsSet.addRealmAny(${fieldName}Item.getNativePtr())")
endControlFlow()
endControlFlow()
endControlFlow()
}
else -> {
if (metadata.primaryKey !== field) {
setTableValues(writer, fieldType.toString(), fieldName, interfaceName, getter, true)
}
}
}
}
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateMethod(writer: JavaWriter) {
writer.apply {
val topLevelArgs = arrayOf("Realm", "realm",
qualifiedJavaClassName.toString(), "object",
"Map<RealmModel,Long>", "cache")
val embeddedArgs = arrayOf("Realm", "realm",
"Table", "parentObjectTable",
"long", "parentColumnKey",
"long", "parentObjectKey",
qualifiedJavaClassName.toString(), "object",
"Map<RealmModel,Long>", "cache")
val args = if (metadata.embedded) embeddedArgs else topLevelArgs
beginMethod("long", "insertOrUpdate", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), *args)
// If object is already in the Realm there is nothing to update
beginControlFlow("if (object instanceof RealmObjectProxy && !RealmObject.isFrozen(object) && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm() != null && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm().getPath().equals(realm.getPath()))")
emitStatement("return ((RealmObjectProxy) object).realmGet\$proxyState().getRow\$realm().getObjectKey()")
endControlFlow()
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("long tableNativePtr = table.getNativePtr()")
emitStatement("%s columnInfo = (%s) realm.getSchema().getColumnInfo(%s.class)", columnInfoClassName(), columnInfoClassName(), qualifiedJavaClassName)
if (metadata.hasPrimaryKey()) {
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
}
insertOrUpdateInternal(this)
emitStatement("return objKey")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateListMethod(writer: JavaWriter) {
writer.apply {
val topLevelArgs = arrayOf("Realm", "realm",
"Iterator<? extends RealmModel>", "objects",
"Map<RealmModel,Long>", "cache")
val embeddedArgs = arrayOf("Realm", "realm",
"Table", "parentObjectTable",
"long", "parentColumnKey",
"long", "parentObjectKey",
"Iterator<? extends RealmModel>", "objects",
"Map<RealmModel,Long>", "cache")
val args = if (metadata.embedded) embeddedArgs else topLevelArgs
beginMethod("void", "insertOrUpdate", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), *args)
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("long tableNativePtr = table.getNativePtr()")
emitStatement("%s columnInfo = (%s) realm.getSchema().getColumnInfo(%s.class)", columnInfoClassName(), columnInfoClassName(), qualifiedJavaClassName)
if (metadata.hasPrimaryKey()) {
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
}
emitStatement("%s object = null", qualifiedJavaClassName)
beginControlFlow("while (objects.hasNext())")
emitStatement("object = (%s) objects.next()", qualifiedJavaClassName)
beginControlFlow("if (cache.containsKey(object))")
emitStatement("continue")
endControlFlow()
beginControlFlow("if (object instanceof RealmObjectProxy && !RealmObject.isFrozen(object) && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm() != null && ((RealmObjectProxy) object).realmGet\$proxyState().getRealm\$realm().getPath().equals(realm.getPath()))")
emitStatement("cache.put(object, ((RealmObjectProxy) object).realmGet\$proxyState().getRow\$realm().getObjectKey())")
emitStatement("continue")
endControlFlow()
insertOrUpdateInternal(this)
endControlFlow()
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun addPrimaryKeyCheckIfNeeded(metadata: ClassMetaData, throwIfPrimaryKeyDuplicate: Boolean, writer: JavaWriter) {
writer.apply {
if (metadata.hasPrimaryKey()) {
val primaryKeyGetter = metadata.primaryKeyGetter
val primaryKeyElement = metadata.primaryKey
if (metadata.isNullable(primaryKeyElement!!)) {
if (Utils.isString(primaryKeyElement)) {
emitStatement("String primaryKeyValue = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (primaryKeyValue == null)")
emitStatement("objKey = Table.nativeFindFirstNull(tableNativePtr, pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = Table.nativeFindFirstString(tableNativePtr, pkColumnKey, primaryKeyValue)")
endControlFlow()
} else if (Utils.isObjectId(primaryKeyElement)) {
emitStatement("org.bson.types.ObjectId primaryKeyValue = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (primaryKeyValue == null)")
emitStatement("objKey = Table.nativeFindFirstNull(tableNativePtr, pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = Table.nativeFindFirstObjectId(tableNativePtr, pkColumnKey, primaryKeyValue.toString())")
endControlFlow()
} else if (Utils.isUUID(primaryKeyElement)) {
emitStatement("java.util.UUID primaryKeyValue = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (primaryKeyValue == null)")
emitStatement("objKey = Table.nativeFindFirstNull(tableNativePtr, pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = Table.nativeFindFirstUUID(tableNativePtr, pkColumnKey, primaryKeyValue.toString())")
endControlFlow()
} else {
emitStatement("Object primaryKeyValue = ((%s) object).%s()", interfaceName, primaryKeyGetter)
emitStatement("long objKey = Table.NO_MATCH")
beginControlFlow("if (primaryKeyValue == null)")
emitStatement("objKey = Table.nativeFindFirstNull(tableNativePtr, pkColumnKey)")
nextControlFlow("else")
emitStatement("objKey = Table.nativeFindFirstInt(tableNativePtr, pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
endControlFlow()
}
} else {
emitStatement("long objKey = Table.NO_MATCH")
emitStatement("Object primaryKeyValue = ((%s) object).%s()", interfaceName, primaryKeyGetter)
beginControlFlow("if (primaryKeyValue != null)")
if (Utils.isString(metadata.primaryKey)) {
emitStatement("objKey = Table.nativeFindFirstString(tableNativePtr, pkColumnKey, (String)primaryKeyValue)")
} else if (Utils.isObjectId(metadata.primaryKey)) {
emitStatement("objKey = Table.nativeFindFirstObjectId(tableNativePtr, pkColumnKey, ((org.bson.types.ObjectId)primaryKeyValue).toString())")
} else if (Utils.isUUID(metadata.primaryKey)) {
emitStatement("objKey = Table.nativeFindFirstUUID(tableNativePtr, pkColumnKey, ((java.util.UUID)primaryKeyValue).toString())")
} else {
emitStatement("objKey = Table.nativeFindFirstInt(tableNativePtr, pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
}
endControlFlow()
}
beginControlFlow("if (objKey == Table.NO_MATCH)")
if (Utils.isString(metadata.primaryKey) || Utils.isObjectId(metadata.primaryKey) || Utils.isUUID(metadata.primaryKey)) {
emitStatement("objKey = OsObject.createRowWithPrimaryKey(table, pkColumnKey, primaryKeyValue)")
} else {
emitStatement("objKey = OsObject.createRowWithPrimaryKey(table, pkColumnKey, ((%s) object).%s())", interfaceName, primaryKeyGetter)
}
if (throwIfPrimaryKeyDuplicate) {
nextControlFlow("else")
emitStatement("Table.throwDuplicatePrimaryKeyException(primaryKeyValue)")
}
endControlFlow()
emitStatement("cache.put(object, objKey)")
} else {
if (metadata.embedded) {
emitStatement("long objKey = OsObject.createEmbeddedObject(parentObjectTable, parentObjectKey, parentColumnKey)")
emitStatement("cache.put(object, objKey)")
} else {
emitStatement("long objKey = OsObject.createRow(table)")
emitStatement("cache.put(object, objKey)")
}
}
}
}
@Throws(IOException::class)
private fun emitCopyMethod(writer: JavaWriter) {
writer.apply {
beginMethod(qualifiedJavaClassName, "copy", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC),
"Realm", "realm",
columnInfoClassName(), "columnInfo",
qualifiedJavaClassName.toString(), "newObject",
"boolean", "update",
"Map<RealmModel,RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitStatement("RealmObjectProxy cachedRealmObject = cache.get(newObject)")
beginControlFlow("if (cachedRealmObject != null)")
emitStatement("return (%s) cachedRealmObject", qualifiedJavaClassName)
endControlFlow()
emitEmptyLine()
emitStatement("%1\$s unmanagedSource = (%1\$s) newObject", interfaceName)
emitEmptyLine()
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("OsObjectBuilder builder = new OsObjectBuilder(table, flags)")
// Copy basic types
emitEmptyLine()
emitSingleLineComment("Add all non-\"object reference\" fields")
for (field in metadata.getBasicTypeFields()) {
val fieldColKey = fieldColKeyVariableReference(field)
val fieldName = field.simpleName.toString()
val getter = metadata.getInternalGetter(fieldName)
emitStatement("builder.%s(%s, unmanagedSource.%s())", OsObjectBuilderTypeHelper.getOsObjectBuilderName(field), fieldColKey, getter)
}
// Create the underlying object
emitEmptyLine()
emitSingleLineComment("Create the underlying object and cache it before setting any object/objectlist references")
emitSingleLineComment("This will allow us to break any circular dependencies by using the object cache.")
emitStatement("Row row = builder.createNewObject()")
emitStatement("%s managedCopy = newProxyInstance(realm, row)", generatedClassName)
emitStatement("cache.put(newObject, managedCopy)")
// Copy all object references or lists-of-objects
emitEmptyLine()
if (metadata.objectReferenceFields.isNotEmpty()) {
emitSingleLineComment("Finally add all fields that reference other Realm Objects, either directly or through a list")
}
for (field in metadata.objectReferenceFields) {
val fieldType = QualifiedClassName(field.asType())
val fieldName: String = field.simpleName.toString()
val getter: String = metadata.getInternalGetter(fieldName)
val setter: String = metadata.getInternalSetter(fieldName)
val parentPropertyType: Constants.RealmFieldType = getRealmType(field)
when {
Utils.isRealmModel(field) -> {
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
val fieldColKey: String = fieldColKeyVariableReference(field)
val linkedQualifiedClassName: QualifiedClassName = Utils.getFieldTypeQualifiedName(field)
val linkedProxyClass: SimpleClassName = Utils.getProxyClassSimpleName(field)
emitStatement("%s %sObj = unmanagedSource.%s()", fieldType, fieldName, getter)
beginControlFlow("if (%sObj == null)", fieldName)
emitStatement("managedCopy.%s(null)", setter)
nextControlFlow("else")
emitStatement("%s cache%s = (%s) cache.get(%sObj)", fieldType, fieldName, fieldType, fieldName)
if (isEmbedded) {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache%s.toString()\")", fieldName)
nextControlFlow("else")
emitStatement("long objKey = ((RealmObjectProxy) managedCopy).realmGet\$proxyState().getRow\$realm().createEmbeddedObject(%s, RealmFieldType.%s)", fieldColKey, parentPropertyType.name)
emitStatement("Row linkedObjectRow = realm.getTable(%s.class).getUncheckedRow(objKey)", linkedQualifiedClassName)
emitStatement("%s linkedObject = %s.newProxyInstance(realm, linkedObjectRow)", linkedQualifiedClassName, linkedProxyClass)
emitStatement("cache.put(%sObj, (RealmObjectProxy) linkedObject)", fieldName)
emitStatement("%s.updateEmbeddedObject(realm, %sObj, linkedObject, cache, flags)", linkedProxyClass, fieldName)
endControlFlow()
} else {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("managedCopy.%s(cache%s)", setter, fieldName)
nextControlFlow("else")
emitStatement("managedCopy.%s(%s.copyOrUpdate(realm, (%s) realm.getSchema().getColumnInfo(%s.class), %sObj, update, cache, flags))", setter, linkedProxyClass, columnInfoClassName(field), linkedQualifiedClassName, fieldName)
endControlFlow()
}
// No need to throw exception here if the field is not nullable. A exception will be thrown in setter.
endControlFlow()
emitEmptyLine()
}
Utils.isRealmModelList(field) -> {
val listElementType: TypeMirror = Utils.getGenericType(field)!!
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val linkedProxyClass: SimpleClassName = Utils.getProxyClassSimpleName(field)
val isEmbedded = Utils.isFieldTypeEmbedded(listElementType, classCollection)
emitStatement("RealmList<%s> %sUnmanagedList = unmanagedSource.%s()", genericType, fieldName, getter)
beginControlFlow("if (%sUnmanagedList != null)", fieldName)
emitStatement("RealmList<%s> %sManagedList = managedCopy.%s()", genericType, fieldName, getter)
// Clear is needed. See bug https://github.com/realm/realm-java/issues/4957
emitStatement("%sManagedList.clear()", fieldName)
beginControlFlow("for (int i = 0; i < %sUnmanagedList.size(); i++)", fieldName)
emitStatement("%1\$s %2\$sUnmanagedItem = %2\$sUnmanagedList.get(i)", genericType, fieldName)
emitStatement("%1\$s cache%2\$s = (%1\$s) cache.get(%2\$sUnmanagedItem)", genericType, fieldName)
if (isEmbedded) {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache%s.toString()\")", fieldName)
nextControlFlow("else")
emitStatement("long objKey = %sManagedList.getOsList().createAndAddEmbeddedObject()", fieldName)
emitStatement("Row linkedObjectRow = realm.getTable(%s.class).getUncheckedRow(objKey)", genericType)
emitStatement("%s linkedObject = %s.newProxyInstance(realm, linkedObjectRow)", genericType, linkedProxyClass)
emitStatement("cache.put(%sUnmanagedItem, (RealmObjectProxy) linkedObject)", fieldName)
emitStatement("%s.updateEmbeddedObject(realm, %sUnmanagedItem, linkedObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)", linkedProxyClass, fieldName)
endControlFlow()
} else {
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("%1\$sManagedList.add(cache%1\$s)", fieldName)
nextControlFlow("else")
emitStatement("%1\$sManagedList.add(%2\$s.copyOrUpdate(realm, (%3\$s) realm.getSchema().getColumnInfo(%4\$s.class), %1\$sUnmanagedItem, update, cache, flags))", fieldName, Utils.getProxyClassSimpleName(field), columnInfoClassName(field), Utils.getGenericTypeQualifiedName(field))
endControlFlow()
}
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmAny(field) -> {
emitStatement("RealmAny ${fieldName}RealmAny = unmanagedSource.${getter}()")
emitStatement("${fieldName}RealmAny = ProxyUtils.copyOrUpdate(${fieldName}RealmAny, realm, update, cache, flags)")
emitStatement("managedCopy.${setter}(${fieldName}RealmAny)")
emitEmptyLine()
}
Utils.isRealmAnyList(field) -> {
emitStatement("RealmList<RealmAny> ${fieldName}UnmanagedList = unmanagedSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedList != null)")
emitStatement("RealmList<RealmAny> ${fieldName}ManagedList = managedCopy.${getter}()")
emitStatement("${fieldName}ManagedList.clear()")
beginControlFlow("for (int i = 0; i < ${fieldName}UnmanagedList.size(); i++)")
emitStatement("RealmAny realmAnyItem = ${fieldName}UnmanagedList.get(i)")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, update, cache, flags)")
emitStatement("${fieldName}ManagedList.add(realmAnyItem)")
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmAnyDictionary(field) -> {
val genericType = Utils.getGenericTypeQualifiedName(field)
emitStatement("RealmDictionary<RealmAny> ${fieldName}UnmanagedDictionary = unmanagedSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("RealmDictionary<RealmAny> ${fieldName}ManagedDictionary = managedCopy.${getter}()")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
emitStatement("java.util.List<String> keys = new java.util.ArrayList<>()")
emitStatement("java.util.List<Long> realmAnyPointers = new java.util.ArrayList<>()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("RealmAny realmAnyItem = entry.getValue()")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, update, cache, flags)")
emitStatement("${fieldName}ManagedDictionary.put(entry.getKey(), realmAnyItem)")
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmDictionary(field) -> {
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val listElementType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(listElementType, classCollection)
val linkedProxyClass: SimpleClassName = Utils.getDictionaryGenericProxyClassSimpleName(field)
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = unmanagedSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("RealmDictionary<${genericType}> ${fieldName}ManagedDictionary = managedCopy.${getter}()")
// Mimicking lists, maybe not needed...?
emitStatement("${fieldName}ManagedDictionary.clear()")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
emitStatement("$genericType cache${fieldName} = (${genericType}) cache.get(${fieldName}UnmanagedEntryValue)")
if (isEmbedded) {
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("""throw new IllegalArgumentException("Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache${fieldName}.toString()")""")
nextControlFlow("else")
emitStatement("long objKey = ${fieldName}ManagedDictionary.getOsMap().createAndPutEmbeddedObject(entryKey)")
emitStatement("Row linkedObjectRow = realm.getTable(${genericType}.class).getUncheckedRow(objKey)")
emitStatement("$genericType linkedObject = ${linkedProxyClass}.newProxyInstance(realm, linkedObjectRow)")
emitStatement("cache.put(${fieldName}UnmanagedEntryValue, (RealmObjectProxy) linkedObject)")
emitStatement("${linkedProxyClass}.updateEmbeddedObject(realm, ${fieldName}UnmanagedEntryValue, linkedObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)")
endControlFlow()
} else {
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("${fieldName}ManagedDictionary.put(entryKey, cache${fieldName})")
nextControlFlow("else")
beginControlFlow("if (${fieldName}UnmanagedEntryValue == null)")
emitStatement("${fieldName}ManagedDictionary.put(entryKey, null)")
nextControlFlow("else")
emitStatement(
"%sManagedDictionary.put(entryKey, %s.copyOrUpdate(realm, (%s) realm.getSchema().getColumnInfo(%s.class), %sUnmanagedEntryValue, update, cache, flags))",
fieldName,
Utils.getDictionaryGenericProxyClassSimpleName(field),
columnInfoClassNameDictionaryGeneric(field),
Utils.getGenericTypeQualifiedName(field),
fieldName
)
endControlFlow()
endControlFlow()
}
endControlFlow()
endControlFlow()
}
Utils.isRealmAnySet(field) -> {
emitStatement("RealmSet<RealmAny> ${fieldName}UnmanagedSet = unmanagedSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedSet != null)")
emitStatement("RealmSet<RealmAny> ${fieldName}ManagedSet = managedCopy.${getter}()")
emitStatement("${fieldName}ManagedSet.clear()")
beginControlFlow("for (RealmAny realmAnyItem: ${fieldName}UnmanagedSet)")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, update, cache, flags)")
emitStatement("${fieldName}ManagedSet.add(realmAnyItem)")
endControlFlow()
endControlFlow()
emitEmptyLine()
}
Utils.isRealmModelSet(field) -> {
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val linkedProxyClass: SimpleClassName = Utils.getSetGenericProxyClassSimpleName(field)
emitStatement("RealmSet<${genericType}> ${fieldName}UnmanagedSet = unmanagedSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedSet != null)")
emitStatement("RealmSet<${genericType}> ${fieldName}ManagedSet = managedCopy.${getter}()")
// Clear is needed. See bug https://github.com/realm/realm-java/issues/4957
emitStatement("${fieldName}ManagedSet.clear()")
beginControlFlow("for ($genericType ${fieldName}UnmanagedItem: ${fieldName}UnmanagedSet)")
emitStatement("$genericType cache${fieldName} = (${genericType}) cache.get(${fieldName}UnmanagedItem)")
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("${fieldName}ManagedSet.add(cache${fieldName})")
nextControlFlow("else")
emitStatement("${fieldName}ManagedSet.add(${linkedProxyClass}.copyOrUpdate(realm, (${columnInfoClassNameSetGeneric(field)}) realm.getSchema().getColumnInfo(${Utils.getGenericTypeQualifiedName(field)}.class), ${fieldName}UnmanagedItem, update, cache, flags))")
endControlFlow()
endControlFlow()
endControlFlow()
emitEmptyLine()
}
else -> {
throw IllegalStateException("Unsupported field: $field")
}
}
}
emitStatement("return managedCopy")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateDetachedCopyMethod(writer: JavaWriter) {
writer.apply {
beginMethod(qualifiedJavaClassName, "createDetachedCopy", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), qualifiedJavaClassName.toString(), "realmObject", "int", "currentDepth", "int", "maxDepth", "Map<RealmModel, CacheData<RealmModel>>", "cache")
beginControlFlow("if (currentDepth > maxDepth || realmObject == null)")
emitStatement("return null")
endControlFlow()
emitStatement("CacheData<RealmModel> cachedObject = cache.get(realmObject)")
emitStatement("%s unmanagedObject", qualifiedJavaClassName)
beginControlFlow("if (cachedObject == null)")
emitStatement("unmanagedObject = new %s()", qualifiedJavaClassName)
emitStatement("cache.put(realmObject, new RealmObjectProxy.CacheData<RealmModel>(currentDepth, unmanagedObject))")
nextControlFlow("else")
emitSingleLineComment("Reuse cached object or recreate it because it was encountered at a lower depth.")
beginControlFlow("if (currentDepth >= cachedObject.minDepth)")
emitStatement("return (%s) cachedObject.object", qualifiedJavaClassName)
endControlFlow()
emitStatement("unmanagedObject = (%s) cachedObject.object", qualifiedJavaClassName)
emitStatement("cachedObject.minDepth = currentDepth")
endControlFlow()
// may cause an unused variable warning if the object contains only null lists
emitStatement("%1\$s unmanagedCopy = (%1\$s) unmanagedObject", interfaceName)
emitStatement("%1\$s realmSource = (%1\$s) realmObject", interfaceName)
emitStatement("Realm objectRealm = (Realm) ((RealmObjectProxy) realmObject).realmGet\$proxyState().getRealm\$realm()")
for (field in metadata.fields) {
val fieldName = field.simpleName.toString()
val setter = metadata.getInternalSetter(fieldName)
val getter = metadata.getInternalGetter(fieldName)
when {
Utils.isRealmModel(field) -> {
emitEmptyLine()
emitSingleLineComment("Deep copy of %s", fieldName)
emitStatement("unmanagedCopy.%s(%s.createDetachedCopy(realmSource.%s(), currentDepth + 1, maxDepth, cache))", setter, Utils.getProxyClassSimpleName(field), getter)
}
Utils.isRealmModelList(field) -> {
emitEmptyLine()
emitSingleLineComment("Deep copy of %s", fieldName)
beginControlFlow("if (currentDepth == maxDepth)")
emitStatement("unmanagedCopy.%s(null)", setter)
nextControlFlow("else")
emitStatement("RealmList<%s> managed%sList = realmSource.%s()", Utils.getGenericTypeQualifiedName(field), fieldName, getter)
emitStatement("RealmList<%1\$s> unmanaged%2\$sList = new RealmList<%1\$s>()", Utils.getGenericTypeQualifiedName(field), fieldName)
emitStatement("unmanagedCopy.%s(unmanaged%sList)", setter, fieldName)
emitStatement("int nextDepth = currentDepth + 1")
emitStatement("int size = managed%sList.size()", fieldName)
beginControlFlow("for (int i = 0; i < size; i++)")
emitStatement("%s item = %s.createDetachedCopy(managed%sList.get(i), nextDepth, maxDepth, cache)", Utils.getGenericTypeQualifiedName(field), Utils.getProxyClassSimpleName(field), fieldName)
emitStatement("unmanaged%sList.add(item)", fieldName)
endControlFlow()
endControlFlow()
}
Utils.isRealmValueList(field) -> {
emitEmptyLine()
emitStatement("unmanagedCopy.%1\$s(new RealmList<%2\$s>())", setter, Utils.getGenericTypeQualifiedName(field))
emitStatement("unmanagedCopy.%1\$s().addAll(realmSource.%1\$s())", getter)
}
Utils.isMutableRealmInteger(field) -> // If the user initializes the unmanaged MutableRealmInteger to null, this will fail mysteriously.
emitStatement("unmanagedCopy.%s().set(realmSource.%s().get())", getter, getter)
Utils.isRealmAny(field) -> {
emitEmptyLine()
emitSingleLineComment("Deep copy of %s", fieldName)
emitStatement("unmanagedCopy.${setter}(ProxyUtils.createDetachedCopy(realmSource.${getter}(), objectRealm, currentDepth + 1, maxDepth, cache))")
}
Utils.isRealmAnyList(field) -> {
emitEmptyLine()
emitSingleLineComment("Deep copy of %s", fieldName)
beginControlFlow("if (currentDepth == maxDepth)")
emitStatement("unmanagedCopy.%s(null)", setter)
nextControlFlow("else")
emitStatement("RealmList<RealmAny> managed${fieldName}List = realmSource.${getter}()", fieldName, getter)
emitStatement("RealmList<RealmAny> unmanaged${fieldName}List = new RealmList<RealmAny>()")
emitStatement("unmanagedCopy.${setter}(unmanaged${fieldName}List)")
emitStatement("int nextDepth = currentDepth + 1")
emitStatement("int size = managed${fieldName}List.size()")
beginControlFlow("for (int i = 0; i < size; i++)")
emitStatement("RealmAny item = ProxyUtils.createDetachedCopy(managed${fieldName}List.get(i), objectRealm, nextDepth, maxDepth, cache)")
emitStatement("unmanaged${fieldName}List.add(item)")
endControlFlow()
endControlFlow()
}
Utils.isRealmModelDictionary(field) -> {
val proxyClassSimpleName = Utils.getDictionaryGenericProxyClassSimpleName(field)
val genericType = requireNotNull(Utils.getGenericTypeQualifiedName(field))
emitEmptyLine()
emitSingleLineComment("Deep copy of $fieldName")
beginControlFlow("if (currentDepth == maxDepth)")
emitStatement("unmanagedCopy.${setter}(null)")
nextControlFlow("else")
emitStatement("RealmDictionary<${genericType}> managed${fieldName}Dictionary = realmSource.${getter}()")
emitStatement("RealmDictionary<${genericType}> unmanaged${fieldName}Dictionary = new RealmDictionary<${genericType}>()")
emitStatement("unmanagedCopy.${setter}(unmanaged${fieldName}Dictionary)")
emitStatement("int nextDepth = currentDepth + 1")
beginControlFlow("for (Map.Entry<String, ${genericType}> entry : managed${fieldName}Dictionary.entrySet())")
emitStatement("$genericType detachedValue = ${proxyClassSimpleName}.createDetachedCopy(entry.getValue(), nextDepth, maxDepth, cache)")
emitStatement("unmanaged${fieldName}Dictionary.put(entry.getKey(), detachedValue)")
endControlFlow()
endControlFlow()
}
Utils.isRealmValueDictionary(field) -> {
val genericType = requireNotNull(Utils.getGenericTypeQualifiedName(field))
emitEmptyLine()
emitStatement("unmanagedCopy.%1\$s(new RealmDictionary<%2\$s>())", setter, Utils.getDictionaryValueTypeQualifiedName(field))
emitStatement("RealmDictionary<${genericType}> managed${fieldName}Dictionary = realmSource.${getter}()")
beginControlFlow("for (Map.Entry<String, ${genericType}> entry : managed${fieldName}Dictionary.entrySet())")
emitStatement("unmanagedCopy.${getter}().put(entry.getKey(), entry.getValue())")
endControlFlow()
}
Utils.isRealmAnyDictionary(field) -> {
emitEmptyLine()
emitSingleLineComment("Deep copy of %s", fieldName)
beginControlFlow("if (currentDepth == maxDepth)")
emitStatement("unmanagedCopy.%s(null)", setter)
nextControlFlow("else")
emitStatement("RealmDictionary<RealmAny> managed${fieldName}Dictionary = realmSource.${getter}()")
emitStatement("RealmDictionary<RealmAny> unmanaged${fieldName}Dictionary = new RealmDictionary<RealmAny>()")
emitStatement("unmanagedCopy.${setter}(unmanaged${fieldName}Dictionary)")
emitStatement("int nextDepth = currentDepth + 1")
beginControlFlow("for (Map.Entry<String, RealmAny> entry : managed${fieldName}Dictionary.entrySet())")
emitStatement("RealmAny detachedValue = ProxyUtils.createDetachedCopy(entry.getValue(), objectRealm, nextDepth, maxDepth, cache)")
emitStatement("unmanaged${fieldName}Dictionary.put(entry.getKey(), detachedValue)")
endControlFlow()
endControlFlow()
}
Utils.isRealmValueDictionary(field) -> {
val genericType = requireNotNull(Utils.getGenericTypeQualifiedName(field))
emitEmptyLine()
emitStatement("unmanagedCopy.%1\$s(new RealmSet<%2\$s>())", setter, Utils.getSetValueTypeQualifiedName(field))
emitStatement("RealmSet<${genericType}> managed${fieldName}Set = realmSource.${getter}()")
beginControlFlow("for (${genericType} value : managed${fieldName}Set)")
emitStatement("unmanagedCopy.${getter}().add(value)")
endControlFlow()
}
else -> {
emitStatement("unmanagedCopy.%s(realmSource.%s())", setter, getter)
}
}
}
emitEmptyLine()
emitStatement("return unmanagedObject")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitUpdateMethod(writer: JavaWriter) {
if (!metadata.hasPrimaryKey() && !metadata.embedded) {
return
}
writer.apply {
beginMethod(qualifiedJavaClassName, "update", EnumSet.of(Modifier.STATIC),
"Realm", "realm", // Argument type & argument name
columnInfoClassName(), "columnInfo",
qualifiedJavaClassName.toString(), "realmObject",
qualifiedJavaClassName.toString(), "newObject",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitStatement("%1\$s realmObjectTarget = (%1\$s) realmObject", interfaceName)
emitStatement("%1\$s realmObjectSource = (%1\$s) newObject", interfaceName)
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("OsObjectBuilder builder = new OsObjectBuilder(table, flags)")
for (field in metadata.fields) {
val fieldType = QualifiedClassName(field.asType())
val fieldName = field.simpleName.toString()
val getter = metadata.getInternalGetter(fieldName)
val fieldColKey = fieldColKeyVariableReference(field)
val parentPropertyType: Constants.RealmFieldType = getRealmType(field)
when {
Utils.isRealmModel(field) -> {
emitEmptyLine()
emitStatement("%s %sObj = realmObjectSource.%s()", fieldType, fieldName, getter)
beginControlFlow("if (%sObj == null)", fieldName)
emitStatement("builder.addNull(%s)", fieldColKeyVariableReference(field))
nextControlFlow("else")
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
if (isEmbedded) {
// Embedded objects are created in-place as we need to know the
// parent object + the property containing it.
// After this we know that changing values will always be considered
// an "update
emitSingleLineComment("Embedded objects are created directly instead of using the builder.")
emitStatement("%s cache%s = (%s) cache.get(%sObj)", fieldType, fieldName, fieldType, fieldName)
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache%s.toString()\")", fieldName)
endControlFlow()
emitEmptyLine()
emitStatement("long objKey = ((RealmObjectProxy) realmObject).realmGet\$proxyState().getRow\$realm().createEmbeddedObject(%s, RealmFieldType.%s)", fieldColKey, parentPropertyType.name)
emitStatement("Row row = realm.getTable(%s.class).getUncheckedRow(objKey)", Utils.getFieldTypeQualifiedName(field))
emitStatement("%s proxyObject = %s.newProxyInstance(realm, row)", fieldType, Utils.getProxyClassSimpleName(field))
emitStatement("cache.put(%sObj, (RealmObjectProxy) proxyObject)", fieldName)
emitStatement("%s.updateEmbeddedObject(realm, %sObj, proxyObject, cache, flags)", Utils.getProxyClassSimpleName(field), fieldName)
} else {
// Non-embedded classes are updating using normal recursive bottom-up approach
emitStatement("%s cache%s = (%s) cache.get(%sObj)", fieldType, fieldName, fieldType, fieldName)
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("builder.addObject(%s, cache%s)", fieldColKey, fieldName)
nextControlFlow("else")
emitStatement("builder.addObject(%s, %s.copyOrUpdate(realm, (%s) realm.getSchema().getColumnInfo(%s.class), %sObj, true, cache, flags))", fieldColKey, Utils.getProxyClassSimpleName(field), columnInfoClassName(field), Utils.getFieldTypeQualifiedName(field), fieldName)
endControlFlow()
}
// No need to throw exception here if the field is not nullable. A exception will be thrown in setter.
endControlFlow()
}
Utils.isRealmModelList(field) -> {
val genericType: QualifiedClassName = Utils.getRealmListType(field)!!
val fieldTypeMetaData: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(fieldTypeMetaData, classCollection)
val proxyClass: SimpleClassName = Utils.getProxyClassSimpleName(field)
emitEmptyLine()
emitStatement("RealmList<%s> %sUnmanagedList = realmObjectSource.%s()", genericType, fieldName, getter)
beginControlFlow("if (%sUnmanagedList != null)", fieldName)
emitStatement("RealmList<%s> %sManagedCopy = new RealmList<%s>()", genericType, fieldName, genericType)
if (isEmbedded) {
emitStatement("OsList targetList = realmObjectTarget.realmGet\$%s().getOsList()", fieldName)
emitStatement("targetList.deleteAll()")
beginControlFlow("for (int i = 0; i < %sUnmanagedList.size(); i++)", fieldName)
emitStatement("%1\$s %2\$sUnmanagedItem = %2\$sUnmanagedList.get(i)", genericType, fieldName)
emitStatement("%1\$s cache%2\$s = (%1\$s) cache.get(%2\$sUnmanagedItem)", genericType, fieldName)
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("throw new IllegalArgumentException(\"Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache%s.toString()\")", fieldName)
nextControlFlow("else")
emitStatement("long objKey = targetList.createAndAddEmbeddedObject()")
emitStatement("Row row = realm.getTable(%s.class).getUncheckedRow(objKey)", genericType)
emitStatement("%s proxyObject = %s.newProxyInstance(realm, row)", genericType, proxyClass)
emitStatement("cache.put(%sUnmanagedItem, (RealmObjectProxy) proxyObject)", fieldName)
emitStatement("%sManagedCopy.add(proxyObject)", fieldName)
emitStatement("%s.updateEmbeddedObject(realm, %sUnmanagedItem, proxyObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)", Utils.getProxyClassSimpleName(field), fieldName)
endControlFlow()
endControlFlow()
} else {
beginControlFlow("for (int i = 0; i < %sUnmanagedList.size(); i++)", fieldName)
emitStatement("%1\$s %2\$sItem = %2\$sUnmanagedList.get(i)", genericType, fieldName)
emitStatement("%1\$s cache%2\$s = (%1\$s) cache.get(%2\$sItem)", genericType, fieldName)
beginControlFlow("if (cache%s != null)", fieldName)
emitStatement("%1\$sManagedCopy.add(cache%1\$s)", fieldName)
nextControlFlow("else")
emitStatement("%1\$sManagedCopy.add(%2\$s.copyOrUpdate(realm, (%3\$s) realm.getSchema().getColumnInfo(%4\$s.class), %1\$sItem, true, cache, flags))", fieldName, proxyClass, columnInfoClassName(field), genericType)
endControlFlow()
endControlFlow()
emitStatement("builder.addObjectList(%s, %sManagedCopy)", fieldColKey, fieldName)
}
nextControlFlow("else")
emitStatement("builder.addObjectList(%s, new RealmList<%s>())", fieldColKey, genericType)
endControlFlow()
}
Utils.isRealmAny(field) -> {
emitEmptyLine()
emitStatement("RealmAny ${fieldName}RealmAny = realmObjectSource.${getter}()")
emitStatement("${fieldName}RealmAny = ProxyUtils.copyOrUpdate(${fieldName}RealmAny, realm, true, cache, flags)")
emitStatement("builder.addRealmAny(${fieldColKey}, ${fieldName}RealmAny.getNativePtr())")
}
Utils.isRealmAnyList(field) -> {
emitEmptyLine()
emitStatement("RealmList<RealmAny> ${fieldName}UnmanagedList = realmObjectSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedList != null)")
emitStatement("RealmList<RealmAny> ${fieldName}ManagedCopy = new RealmList<RealmAny>()")
beginControlFlow("for (int i = 0; i < ${fieldName}UnmanagedList.size(); i++)")
emitStatement("RealmAny realmAnyItem = ${fieldName}UnmanagedList.get(i)")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, true, cache, flags)")
emitStatement("${fieldName}ManagedCopy.add(realmAnyItem)")
endControlFlow()
emitStatement("builder.addRealmAnyList(${fieldColKey}, ${fieldName}ManagedCopy)")
nextControlFlow("else")
emitStatement("builder.addRealmAnyList(${fieldColKey}, new RealmList<RealmAny>())")
endControlFlow()
}
Utils.isRealmAnyDictionary(field) -> {
emitEmptyLine()
val genericType = Utils.getGenericTypeQualifiedName(field)
emitStatement("RealmDictionary<RealmAny> ${fieldName}UnmanagedDictionary = realmObjectSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("RealmDictionary<RealmAny> ${fieldName}ManagedDictionary = new RealmDictionary<>()")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
emitStatement("java.util.List<String> keys = new java.util.ArrayList<>()")
emitStatement("java.util.List<Long> realmAnyPointers = new java.util.ArrayList<>()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("RealmAny realmAnyItem = entry.getValue()")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, true, cache, flags)")
emitStatement("${fieldName}ManagedDictionary.put(entry.getKey(), realmAnyItem)")
endControlFlow()
emitStatement("builder.addRealmAnyValueDictionary(${fieldColKey}, ${fieldName}ManagedDictionary)")
nextControlFlow("else")
emitStatement("builder.addRealmAnyValueDictionary(${fieldColKey}, null)")
endControlFlow()
emitEmptyLine()
}
Utils.isRealmModelDictionary(field) -> {
emitEmptyLine()
val genericType: QualifiedClassName = Utils.getGenericTypeQualifiedName(field)!!
val listElementType: TypeMirror = Utils.getGenericType(field)!!
val isEmbedded = Utils.isFieldTypeEmbedded(listElementType, classCollection)
val linkedProxyClass: SimpleClassName = Utils.getDictionaryGenericProxyClassSimpleName(field)
emitStatement("RealmDictionary<${genericType}> ${fieldName}UnmanagedDictionary = realmObjectSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedDictionary != null)")
emitStatement("RealmDictionary<${genericType}> ${fieldName}ManagedDictionary = new RealmDictionary<>()")
emitStatement("java.util.Set<java.util.Map.Entry<String, ${genericType}>> entries = ${fieldName}UnmanagedDictionary.entrySet()")
beginControlFlow("for (java.util.Map.Entry<String, ${genericType}> entry : entries)")
emitStatement("String entryKey = entry.getKey()")
emitStatement("$genericType ${fieldName}UnmanagedEntryValue = entry.getValue()")
emitStatement("$genericType cache${fieldName} = (${genericType}) cache.get(${fieldName}UnmanagedEntryValue)")
if (isEmbedded) {
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("""throw new IllegalArgumentException("Embedded objects can only have one parent pointing to them. This object was already copied, so another object is pointing to it: cache${fieldName}.toString()")""")
nextControlFlow("else")
emitStatement("long objKey = ${fieldName}ManagedDictionary.getOsMap().createAndPutEmbeddedObject(entryKey)")
emitStatement("Row linkedObjectRow = realm.getTable(${genericType}.class).getUncheckedRow(objKey)")
emitStatement("$genericType linkedObject = ${linkedProxyClass}.newProxyInstance(realm, linkedObjectRow)")
emitStatement("cache.put(${fieldName}UnmanagedEntryValue, (RealmObjectProxy) linkedObject)")
emitStatement("${linkedProxyClass}.updateEmbeddedObject(realm, ${fieldName}UnmanagedEntryValue, linkedObject, new HashMap<RealmModel, RealmObjectProxy>(), Collections.EMPTY_SET)")
endControlFlow()
} else {
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("${fieldName}ManagedDictionary.put(entryKey, cache${fieldName})")
nextControlFlow("else")
beginControlFlow("if (${fieldName}UnmanagedEntryValue == null)")
emitStatement("${fieldName}ManagedDictionary.put(entryKey, null)")
nextControlFlow("else")
emitStatement(
"%sManagedDictionary.put(entryKey, %s.copyOrUpdate(realm, (%s) realm.getSchema().getColumnInfo(%s.class), %sUnmanagedEntryValue, true, cache, flags))",
fieldName,
Utils.getDictionaryGenericProxyClassSimpleName(field),
columnInfoClassNameDictionaryGeneric(field),
Utils.getGenericTypeQualifiedName(field),
fieldName
)
endControlFlow()
endControlFlow()
}
endControlFlow()
emitStatement("builder.addObjectDictionary(${fieldColKey}, ${fieldName}ManagedDictionary)")
nextControlFlow("else")
emitStatement("builder.addObjectDictionary(${fieldColKey}, null)")
endControlFlow()
}
Utils.isRealmValueDictionary(field) -> {
emitStatement("builder.${OsObjectBuilderTypeHelper.getOsObjectBuilderName(field)}(${fieldColKey}, realmObjectSource.${getter}())")
}
Utils.isRealmAnySet(field) -> {
emitEmptyLine()
emitStatement("RealmSet<RealmAny> ${fieldName}UnmanagedSet = realmObjectSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedSet != null)")
emitStatement("RealmSet<RealmAny> ${fieldName}ManagedCopy = new RealmSet<RealmAny>()")
beginControlFlow("for (RealmAny realmAnyItem: ${fieldName}UnmanagedSet)")
emitStatement("realmAnyItem = ProxyUtils.copyOrUpdate(realmAnyItem, realm, true, cache, flags)")
emitStatement("${fieldName}ManagedCopy.add(realmAnyItem)")
endControlFlow()
emitStatement("builder.addRealmAnySet(${fieldColKey}, ${fieldName}ManagedCopy)")
nextControlFlow("else")
emitStatement("builder.addRealmAnySet(${fieldColKey}, new RealmSet<RealmAny>())")
endControlFlow()
}
Utils.isRealmModelSet(field) -> {
val genericType: QualifiedClassName = Utils.getSetType(field)!!
val proxyClass: SimpleClassName = Utils.getSetGenericProxyClassSimpleName(field)
emitEmptyLine()
emitStatement("RealmSet<${genericType}> ${fieldName}UnmanagedSet = realmObjectSource.${getter}()")
beginControlFlow("if (${fieldName}UnmanagedSet != null)")
emitStatement("RealmSet<${genericType}> ${fieldName}ManagedCopy = new RealmSet<${genericType}>()")
beginControlFlow("for (${genericType} ${fieldName}Item: ${fieldName}UnmanagedSet)")
emitStatement("$genericType cache${fieldName} = (${genericType}) cache.get(${fieldName}Item)")
beginControlFlow("if (cache${fieldName} != null)")
emitStatement("${fieldName}ManagedCopy.add(cache${fieldName})")
nextControlFlow("else")
emitStatement("${fieldName}ManagedCopy.add(${proxyClass}.copyOrUpdate(realm, (${columnInfoClassNameSetGeneric(field)}) realm.getSchema().getColumnInfo(${genericType}.class), ${fieldName}Item, true, cache, flags))")
endControlFlow()
endControlFlow()
emitStatement("builder.addObjectSet(${fieldColKey}, ${fieldName}ManagedCopy)")
nextControlFlow("else")
emitStatement("builder.addObjectSet(${fieldColKey}, new RealmSet<${genericType}>())")
endControlFlow()
}
Utils.isRealmValueSet(field) -> {
emitStatement("builder.${OsObjectBuilderTypeHelper.getOsObjectBuilderName(field)}(${fieldColKey}, realmObjectSource.${getter}())")
}
else -> {
emitStatement("builder.%s(%s, realmObjectSource.%s())", OsObjectBuilderTypeHelper.getOsObjectBuilderName(field), fieldColKey, getter)
}
}
}
emitEmptyLine()
if (metadata.embedded) {
emitStatement("builder.updateExistingEmbeddedObject((RealmObjectProxy) realmObject)")
} else {
emitStatement("builder.updateExistingTopLevelObject()")
}
emitStatement("return realmObject")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitUpdateEmbeddedObjectMethod(writer: JavaWriter) {
if (!metadata.embedded) {
return
}
writer.apply {
beginMethod("void", "updateEmbeddedObject", EnumSet.of(Modifier.STATIC, Modifier.PUBLIC),
"Realm", "realm", // Argument type & argument name
qualifiedJavaClassName.toString(), "unmanagedObject",
qualifiedJavaClassName.toString(), "managedObject",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitStatement("update(realm, (%s) realm.getSchema().getColumnInfo(%s.class), managedObject, unmanagedObject, cache, flags)", Utils.getSimpleColumnInfoClassName(metadata.qualifiedClassName), metadata.qualifiedClassName)
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitToStringMethod(writer: JavaWriter) {
if (metadata.containsToString()) {
return
}
writer.apply {
emitAnnotation("Override")
emitAnnotation("SuppressWarnings", "\"ArrayToString\"")
beginMethod("String", "toString", EnumSet.of(Modifier.PUBLIC))
beginControlFlow("if (!RealmObject.isValid(this))")
emitStatement("return \"Invalid object\"")
endControlFlow()
emitStatement("StringBuilder stringBuilder = new StringBuilder(\"%s = proxy[\")", simpleJavaClassName)
val fields = metadata.fields
var i = fields.size - 1
for (field in fields) {
val fieldName = field.simpleName.toString()
emitStatement("stringBuilder.append(\"{%s:\")", fieldName)
when {
Utils.isRealmModel(field) -> {
val fieldTypeSimpleName = Utils.getFieldTypeQualifiedName(field).getSimpleName()
emitStatement("stringBuilder.append(%s() != null ? \"%s\" : \"null\")", metadata.getInternalGetter(fieldName), fieldTypeSimpleName)
}
Utils.isRealmList(field) -> {
val genericTypeSimpleName = Utils.getGenericTypeQualifiedName(field)?.getSimpleName()
emitStatement("stringBuilder.append(\"RealmList<%s>[\").append(%s().size()).append(\"]\")", genericTypeSimpleName, metadata.getInternalGetter(fieldName))
}
Utils.isMutableRealmInteger(field) -> {
emitStatement("stringBuilder.append(%s().get())", metadata.getInternalGetter(fieldName))
}
Utils.isByteArray(field) -> {
if (metadata.isNullable(field)) {
emitStatement("stringBuilder.append((%1\$s() == null) ? \"null\" : \"binary(\" + %1\$s().length + \")\")", metadata.getInternalGetter(fieldName))
} else {
emitStatement("stringBuilder.append(\"binary(\" + %1\$s().length + \")\")", metadata.getInternalGetter(fieldName))
}
}
Utils.isRealmAny(field) -> {
emitStatement("stringBuilder.append((%1\$s().isNull()) ? \"null\" : \"%s()\")", metadata.getInternalGetter(fieldName), metadata.getInternalGetter(fieldName))
}
Utils.isRealmDictionary(field) -> {
val genericTypeSimpleName: SimpleClassName? = Utils.getDictionaryValueTypeQualifiedName(field)?.getSimpleName()
emitStatement("stringBuilder.append(\"RealmDictionary<%s>[\").append(%s().size()).append(\"]\")", genericTypeSimpleName, metadata.getInternalGetter(fieldName))
}
Utils.isRealmSet(field) -> {
val genericTypeSimpleName: SimpleClassName? = Utils.getSetValueTypeQualifiedName(field)?.getSimpleName()
emitStatement("stringBuilder.append(\"RealmSet<%s>[\").append(%s().size()).append(\"]\")", genericTypeSimpleName, metadata.getInternalGetter(fieldName))
}
else -> {
if (metadata.isNullable(field)) {
emitStatement("stringBuilder.append(%s() != null ? %s() : \"null\")", metadata.getInternalGetter(fieldName), metadata.getInternalGetter(fieldName))
} else {
emitStatement("stringBuilder.append(%s())", metadata.getInternalGetter(fieldName))
}
}
}
emitStatement("stringBuilder.append(\"}\")")
if (i-- > 0) {
emitStatement("stringBuilder.append(\",\")")
}
}
emitStatement("stringBuilder.append(\"]\")")
emitStatement("return stringBuilder.toString()")
endMethod()
emitEmptyLine()
}
}
/**
* Currently, the hash value emitted from this could suddenly change as an object's index might
* alternate due to Realm Java using `Table#moveLastOver()`. Hash codes should therefore not
* be considered stable, i.e. don't save them in a HashSet or use them as a key in a HashMap.
*/
@Throws(IOException::class)
private fun emitHashcodeMethod(writer: JavaWriter) {
if (metadata.containsHashCode()) {
return
}
writer.apply {
emitAnnotation("Override")
beginMethod("int", "hashCode", EnumSet.of(Modifier.PUBLIC))
emitStatement("String realmName = proxyState.getRealm\$realm().getPath()")
emitStatement("String tableName = proxyState.getRow\$realm().getTable().getName()")
emitStatement("long objKey = proxyState.getRow\$realm().getObjectKey()")
emitEmptyLine()
emitStatement("int result = 17")
emitStatement("result = 31 * result + ((realmName != null) ? realmName.hashCode() : 0)")
emitStatement("result = 31 * result + ((tableName != null) ? tableName.hashCode() : 0)")
emitStatement("result = 31 * result + (int) (objKey ^ (objKey >>> 32))")
emitStatement("return result")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitEqualsMethod(writer: JavaWriter) {
if (metadata.containsEquals()) {
return
}
val proxyClassName = Utils.getProxyClassName(qualifiedJavaClassName)
val otherObjectVarName = "a$simpleJavaClassName"
writer.apply {
emitAnnotation("Override")
beginMethod("boolean", "equals", EnumSet.of(Modifier.PUBLIC), "Object", "o")
emitStatement("if (this == o) return true")
emitStatement("if (o == null || getClass() != o.getClass()) return false")
emitStatement("%s %s = (%s)o", proxyClassName, otherObjectVarName, proxyClassName) // FooRealmProxy aFoo = (FooRealmProxy)o
emitEmptyLine()
emitStatement("BaseRealm realm = proxyState.getRealm\$realm()")
emitStatement("BaseRealm otherRealm = %s.proxyState.getRealm\$realm()", otherObjectVarName)
emitStatement("String path = realm.getPath()")
emitStatement("String otherPath = otherRealm.getPath()")
emitStatement("if (path != null ? !path.equals(otherPath) : otherPath != null) return false")
emitStatement("if (realm.isFrozen() != otherRealm.isFrozen()) return false")
beginControlFlow("if (!realm.sharedRealm.getVersionID().equals(otherRealm.sharedRealm.getVersionID()))")
emitStatement("return false")
endControlFlow()
emitEmptyLine()
emitStatement("String tableName = proxyState.getRow\$realm().getTable().getName()")
emitStatement("String otherTableName = %s.proxyState.getRow\$realm().getTable().getName()", otherObjectVarName)
emitStatement("if (tableName != null ? !tableName.equals(otherTableName) : otherTableName != null) return false")
emitEmptyLine()
emitStatement("if (proxyState.getRow\$realm().getObjectKey() != %s.proxyState.getRow\$realm().getObjectKey()) return false", otherObjectVarName)
emitEmptyLine()
emitStatement("return true")
endMethod()
}
}
@Throws(IOException::class)
private fun emitCreateOrUpdateUsingJsonObject(writer: JavaWriter) {
writer.apply {
val embedded = metadata.embedded
emitAnnotation("SuppressWarnings", "\"cast\"")
if (!embedded) {
beginMethod(qualifiedJavaClassName, "createOrUpdateUsingJsonObject", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), Arrays.asList("Realm", "realm", "JSONObject", "json", "boolean", "update"), listOf("JSONException"))
} else {
beginMethod(qualifiedJavaClassName, "createOrUpdateEmbeddedUsingJsonObject", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), Arrays.asList("Realm", "realm", "RealmModel", "parent", "String", "parentProperty", "JSONObject", "json", "boolean", "update"), listOf("JSONException"))
}
// Throw if model contains a dictionary field until we add support for it
if (containsDictionary(metadata.fields)) {
emitStatement("throw new UnsupportedOperationException(\"Creation of RealmModels from JSON containing RealmDictionary properties is not supported yet.\")")
endMethod()
emitEmptyLine()
return@apply
}
// Throw if model contains a set field until we add support for it
if (containsSet(metadata.fields)) {
emitStatement("throw new UnsupportedOperationException(\"Creation of RealmModels from JSON containing RealmSet properties is not supported yet.\")")
endMethod()
emitEmptyLine()
return@apply
}
val modelOrListCount = countModelOrListFields(metadata.fields)
if (modelOrListCount == 0) {
emitStatement("final List<String> excludeFields = Collections.<String> emptyList()")
} else {
emitStatement("final List<String> excludeFields = new ArrayList<String>(%1\$d)", modelOrListCount)
}
if (!metadata.hasPrimaryKey()) {
buildExcludeFieldsList(writer, metadata.fields)
if (!embedded) {
emitStatement("%s obj = realm.createObjectInternal(%s.class, true, excludeFields)", qualifiedJavaClassName, qualifiedJavaClassName)
} else {
emitStatement("%s obj = realm.createEmbeddedObject(%s.class, parent, parentProperty)", qualifiedJavaClassName, qualifiedJavaClassName)
}
} else {
var pkType = "Long"
var jsonAccessorMethodSuffix = "Long"
var findFirstCast = ""
if (Utils.isString(metadata.primaryKey)) {
pkType = "String"
jsonAccessorMethodSuffix= "String"
} else if (Utils.isObjectId(metadata.primaryKey)) {
pkType = "ObjectId"
findFirstCast = "(org.bson.types.ObjectId)"
jsonAccessorMethodSuffix = ""
} else if (Utils.isUUID(metadata.primaryKey)) {
pkType = "UUID"
findFirstCast = "(java.util.UUID)"
jsonAccessorMethodSuffix = ""
}
val nullableMetadata = if (Utils.isObjectId(metadata.primaryKey)) {
"objKey = table.findFirst%s(pkColumnKey, new org.bson.types.ObjectId((String)json.get%s(\"%s\")))".format(pkType, jsonAccessorMethodSuffix, metadata.primaryKey!!.simpleName)
} else {
"objKey = table.findFirst%s(pkColumnKey, %sjson.get%s(\"%s\"))".format(pkType, findFirstCast, jsonAccessorMethodSuffix, metadata.primaryKey!!.simpleName)
}
val nonNullableMetadata = "objKey = table.findFirst%s(pkColumnKey, %sjson.get%s(\"%s\"))".format(pkType, findFirstCast, jsonAccessorMethodSuffix, metadata.primaryKey!!.simpleName)
emitStatement("%s obj = null", qualifiedJavaClassName)
beginControlFlow("if (update)")
emitStatement("Table table = realm.getTable(%s.class)", qualifiedJavaClassName)
emitStatement("%s columnInfo = (%s) realm.getSchema().getColumnInfo(%s.class)", columnInfoClassName(), columnInfoClassName(), qualifiedJavaClassName)
emitStatement("long pkColumnKey = %s", fieldColKeyVariableReference(metadata.primaryKey))
emitStatement("long objKey = Table.NO_MATCH")
if (metadata.isNullable(metadata.primaryKey!!)) {
beginControlFlow("if (json.isNull(\"%s\"))", metadata.primaryKey!!.simpleName)
emitStatement("objKey = table.findFirstNull(pkColumnKey)")
nextControlFlow("else")
emitStatement(nullableMetadata)
endControlFlow()
} else {
beginControlFlow("if (!json.isNull(\"%s\"))", metadata.primaryKey!!.simpleName)
emitStatement(nonNullableMetadata)
endControlFlow()
}
beginControlFlow("if (objKey != Table.NO_MATCH)")
emitStatement("final BaseRealm.RealmObjectContext objectContext = BaseRealm.objectContext.get()")
beginControlFlow("try")
emitStatement("objectContext.set(realm, table.getUncheckedRow(objKey), realm.getSchema().getColumnInfo(%s.class), false, Collections.<String> emptyList())", qualifiedJavaClassName)
emitStatement("obj = new %s()", generatedClassName)
nextControlFlow("finally")
emitStatement("objectContext.clear()")
endControlFlow()
endControlFlow()
endControlFlow()
beginControlFlow("if (obj == null)")
buildExcludeFieldsList(writer, metadata.fields)
val primaryKeyFieldType = QualifiedClassName(metadata.primaryKey!!.asType().toString())
val primaryKeyFieldName = metadata.primaryKey!!.simpleName.toString()
RealmJsonTypeHelper.emitCreateObjectWithPrimaryKeyValue(qualifiedJavaClassName, generatedClassName, primaryKeyFieldType, primaryKeyFieldName, writer)
endControlFlow()
}
emitEmptyLine()
emitStatement("final %1\$s objProxy = (%1\$s) obj", interfaceName)
for (field in metadata.fields) {
val fieldName = field.simpleName.toString()
val qualifiedFieldType = QualifiedClassName(field.asType().toString())
if (metadata.isPrimaryKey(field)) {
continue // Primary key has already been set when adding new row or finding the existing row.
}
when {
Utils.isRealmModel(field) -> {
val isEmbedded = Utils.isFieldTypeEmbedded(field.asType(), classCollection)
RealmJsonTypeHelper.emitFillRealmObjectWithJsonValue(
"objProxy",
metadata.getInternalSetter(fieldName),
fieldName,
qualifiedFieldType,
Utils.getProxyClassSimpleName(field),
isEmbedded,
writer)
}
Utils.isRealmModelList(field) -> {
val fieldType = (field.asType() as DeclaredType).typeArguments[0]
RealmJsonTypeHelper.emitFillRealmListWithJsonValue(
"objProxy",
metadata.getInternalGetter(fieldName),
metadata.getInternalSetter(fieldName),
fieldName,
(field.asType() as DeclaredType).typeArguments[0].toString(),
Utils.getProxyClassSimpleName(field),
Utils.isFieldTypeEmbedded(fieldType, classCollection),
writer)
}
Utils.isRealmValueList(field) || Utils.isRealmAnyList(field) -> emitStatement("ProxyUtils.setRealmListWithJsonObject(realm, objProxy.%1\$s(), json, \"%2\$s\", update)", metadata.getInternalGetter(fieldName), fieldName)
Utils.isMutableRealmInteger(field) -> RealmJsonTypeHelper.emitFillJavaTypeWithJsonValue(
"objProxy",
metadata.getInternalGetter(fieldName),
fieldName,
qualifiedFieldType,
writer)
Utils.isRealmDictionary(field) -> {
// TODO: dictionary
emitSingleLineComment("TODO: Dictionary")
}
Utils.isRealmSet(field) -> {
// TODO: sets
emitSingleLineComment("TODO: Set")
}
else -> RealmJsonTypeHelper.emitFillJavaTypeWithJsonValue(
"objProxy",
metadata.getInternalSetter(fieldName),
fieldName,
qualifiedFieldType,
writer)
}
}
emitStatement("return obj")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun buildExcludeFieldsList(writer: JavaWriter, fields: Collection<RealmFieldElement>) {
writer.apply {
for (field in fields) {
if (Utils.isRealmModel(field) || Utils.isRealmList(field)) {
val fieldName = field.simpleName.toString()
beginControlFlow("if (json.has(\"%1\$s\"))", fieldName)
emitStatement("excludeFields.add(\"%1\$s\")", fieldName)
endControlFlow()
}
}
}
}
// Since we need to check the PK in stream before creating the object, this is now using copyToRealm
// instead of createObject() to avoid parsing the stream twice.
@Throws(IOException::class)
private fun emitCreateUsingJsonStream(writer: JavaWriter) {
writer.apply {
emitAnnotation("SuppressWarnings", "\"cast\"")
emitAnnotation("TargetApi", "Build.VERSION_CODES.HONEYCOMB")
beginMethod(qualifiedJavaClassName,"createUsingJsonStream", setOf(Modifier.PUBLIC, Modifier.STATIC), listOf("Realm", "realm", "JsonReader", "reader"), listOf("IOException"))
// Throw if model contains a dictionary field until we add support for it
if (containsDictionary(metadata.fields)) {
emitStatement("throw new UnsupportedOperationException(\"Creation of RealmModels from JSON containing RealmDictionary properties is not supported yet.\")")
endMethod()
emitEmptyLine()
return@apply
}
// Throw if model contains a set field until we add support for it
if (containsSet(metadata.fields)) {
emitStatement("throw new UnsupportedOperationException(\"Creation of RealmModels from JSON containing RealmSet properties is not supported yet.\")")
endMethod()
emitEmptyLine()
return@apply
}
if (metadata.hasPrimaryKey()) {
emitStatement("boolean jsonHasPrimaryKey = false")
}
emitStatement("final %s obj = new %s()", qualifiedJavaClassName, qualifiedJavaClassName)
emitStatement("final %1\$s objProxy = (%1\$s) obj", interfaceName)
emitStatement("reader.beginObject()")
beginControlFlow("while (reader.hasNext())")
emitStatement("String name = reader.nextName()")
beginControlFlow("if (false)")
val fields = metadata.fields
for (field in fields) {
val fieldName = field.simpleName.toString()
val fieldType = QualifiedClassName(field.asType().toString())
nextControlFlow("else if (name.equals(\"%s\"))", fieldName)
when {
Utils.isRealmModel(field) -> {
RealmJsonTypeHelper.emitFillRealmObjectFromStream(
"objProxy",
metadata.getInternalSetter(fieldName),
fieldName,
fieldType,
Utils.getProxyClassSimpleName(field),
writer)
}
Utils.isRealmModelList(field) -> {
RealmJsonTypeHelper.emitFillRealmListFromStream(
"objProxy",
metadata.getInternalGetter(fieldName),
metadata.getInternalSetter(fieldName),
QualifiedClassName((field.asType() as DeclaredType).typeArguments[0].toString()),
Utils.getProxyClassSimpleName(field),
writer)
}
Utils.isRealmValueList(field) || Utils.isRealmAnyList(field) -> {
emitStatement("objProxy.%1\$s(ProxyUtils.createRealmListWithJsonStream(%2\$s.class, reader))", metadata.getInternalSetter(fieldName), Utils.getRealmListType(field))
}
Utils.isMutableRealmInteger(field) -> {
RealmJsonTypeHelper.emitFillJavaTypeFromStream(
"objProxy",
metadata,
metadata.getInternalGetter(fieldName),
fieldName,
fieldType,
writer)
}
Utils.isRealmDictionary(field) -> {
// TODO: add support for dictionary
emitSingleLineComment("TODO: Dictionary")
}
Utils.isRealmSet(field) -> {
// TODO: add support for sets
emitSingleLineComment("TODO: Set")
}
else -> {
RealmJsonTypeHelper.emitFillJavaTypeFromStream(
"objProxy",
metadata,
metadata.getInternalSetter(fieldName),
fieldName,
fieldType,
writer)
}
}
}
nextControlFlow("else")
emitStatement("reader.skipValue()")
endControlFlow()
endControlFlow()
emitStatement("reader.endObject()")
if (metadata.hasPrimaryKey()) {
beginControlFlow("if (!jsonHasPrimaryKey)")
emitStatement(Constants.STATEMENT_EXCEPTION_NO_PRIMARY_KEY_IN_JSON, metadata.primaryKey)
endControlFlow()
}
if (!metadata.embedded) {
if (metadata.hasPrimaryKey()) {
emitStatement("return realm.copyToRealmOrUpdate(obj)")
} else {
emitStatement("return realm.copyToRealm(obj)")
}
} else {
// Embedded objects are left unmanaged and assumed to be added by their parent. This
// is safe as json import is blocked for embedded objects without a parent.
emitStatement("return obj")
}
endMethod()
emitEmptyLine()
}
}
private fun columnInfoClassName(): String {
return "${simpleJavaClassName}ColumnInfo"
}
/**
* Returns the name of the ColumnInfo class for the model class referenced in the field.
* I.e. for `com.test.Person`, it returns `Person.PersonColumnInfo`
*/
private fun columnInfoClassName(field: VariableElement): String {
val qualifiedModelClassName = Utils.getModelClassQualifiedName(field)
return Utils.getSimpleColumnInfoClassName(qualifiedModelClassName)
}
private fun columnInfoClassNameDictionaryGeneric(field: VariableElement): String {
val qualifiedModelClassName = Utils.getDictionaryGenericModelClassQualifiedName(field)
return Utils.getSimpleColumnInfoClassName(qualifiedModelClassName)
}
private fun columnInfoClassNameSetGeneric(field: VariableElement): String {
val qualifiedModelClassName = Utils.getSetGenericModelClassQualifiedName(field)
return Utils.getSimpleColumnInfoClassName(qualifiedModelClassName)
}
private fun columnKeyVarName(variableElement: VariableElement): String {
return "${variableElement.simpleName}ColKey"
}
private fun mutableRealmIntegerFieldName(variableElement: VariableElement): String {
return "${variableElement.simpleName}MutableRealmInteger"
}
private fun realmAnyFieldName(variableElement: VariableElement): String {
return "${variableElement.simpleName}RealmAny"
}
private fun fieldColKeyVariableReference(variableElement: VariableElement?): String {
return "columnInfo.${columnKeyVarName(variableElement!!)}"
}
private fun getRealmType(field: VariableElement): Constants.RealmFieldType {
val fieldTypeCanonicalName: String = field.asType().toString()
val type: Constants.RealmFieldType? = Constants.JAVA_TO_REALM_TYPES[fieldTypeCanonicalName]
if (type != null) {
return type
}
if (Utils.isMutableRealmInteger(field)) {
return Constants.RealmFieldType.REALM_INTEGER
}
if (Utils.isRealmAny(field)){
return Constants.RealmFieldType.MIXED
}
if (Utils.isRealmModel(field)) {
return Constants.RealmFieldType.OBJECT
}
if (Utils.isRealmModelList(field)) {
return Constants.RealmFieldType.LIST
}
if (Utils.isRealmValueList(field) || Utils.isRealmAnyList(field)) {
return Utils.getValueListFieldType(field)
}
if (Utils.isRealmModelDictionary(field)) {
return Constants.RealmFieldType.STRING_TO_LINK_MAP
}
if (Utils.isRealmDictionary(field)) {
return Utils.getValueDictionaryFieldType(field)
}
if (Utils.isRealmModelSet(field)) {
return Constants.RealmFieldType.LINK_SET
}
if (Utils.isRealmSet(field)) {
return Utils.getValueSetFieldType(field)
}
return Constants.RealmFieldType.NOTYPE
}
private fun getRealmTypeChecked(field: VariableElement): Constants.RealmFieldType {
val type = getRealmType(field)
if (type === Constants.RealmFieldType.NOTYPE) {
throw IllegalStateException("Unsupported type " + field.asType().toString())
}
return type
}
companion object {
private val OPTION_SUPPRESS_WARNINGS = "realm.suppressWarnings"
private val BACKLINKS_FIELD_EXTENSION = "Backlinks"
private val IMPORTS: List<String>
init {
val l = Arrays.asList(
"android.annotation.TargetApi",
"android.os.Build",
"android.util.JsonReader",
"android.util.JsonToken",
"io.realm.ImportFlag",
"io.realm.exceptions.RealmMigrationNeededException",
"io.realm.internal.ColumnInfo",
"io.realm.internal.NativeContext",
"io.realm.internal.OsList",
"io.realm.internal.OsMap",
"io.realm.internal.OsSet",
"io.realm.internal.OsObject",
"io.realm.internal.OsSchemaInfo",
"io.realm.internal.OsObjectSchemaInfo",
"io.realm.internal.Property",
"io.realm.internal.core.NativeRealmAny",
"io.realm.internal.objectstore.OsObjectBuilder",
"io.realm.ProxyUtils",
"io.realm.internal.RealmObjectProxy",
"io.realm.internal.Row",
"io.realm.internal.Table",
"io.realm.internal.android.JsonUtils",
"io.realm.log.RealmLog",
"java.io.IOException",
"java.util.ArrayList",
"java.util.Collections",
"java.util.List",
"java.util.Iterator",
"java.util.Date",
"java.util.Map",
"java.util.HashMap",
"java.util.HashSet",
"java.util.Set",
"org.json.JSONObject",
"org.json.JSONException",
"org.json.JSONArray")
IMPORTS = Collections.unmodifiableList(l)
}
private fun countModelOrListFields(fields: Collection<RealmFieldElement>): Int {
var count = 0
for (f in fields) {
if (Utils.isRealmModel(f) || Utils.isRealmList(f)) {
count++
}
}
return count
}
}
private fun containsDictionary(fields: ArrayList<RealmFieldElement>): Boolean {
for (field in fields) {
if (Utils.isRealmDictionary(field)) {
return true
}
}
return false
}
private fun containsSet(fields: ArrayList<RealmFieldElement>): Boolean {
for (field in fields) {
if (Utils.isRealmSet(field)) {
return true
}
}
return false
}
}
| apache-2.0 | 43ad2f4a6682b458ce38505c7207d1ab | 64.700929 | 323 | 0.545582 | 5.805768 | false | false | false | false |
Tandrial/Advent_of_Code | src/aoc2017/kot/Day08.kt | 1 | 1372 | package aoc2017.kot
import java.io.File
import java.util.regex.Pattern
object Day08 {
fun solve(input: List<String>): Pair<Int, Int> {
val memory = mutableMapOf<String, Int>()
val regex = Pattern.compile("(\\w+) (inc|dec) (-?\\d+) if (\\w+) (>|<|==|>=|<=|!=) (-?\\d+)")
var maxCurr = -1
for (line in input) {
val m = regex.matcher(line)
if (m.find()) {
val reg = m.group(1).toString()
var mod = m.group(3).toInt()
if (m.group(2).toString() == "dec") mod *= -1
val checkReg = m.group(4).toString()
val value = m.group(6).toInt()
val cmp: (Int, Int) -> Boolean = when (m.group(5)) {
">" -> { r, v -> r > v }
"<" -> { r, v -> r < v }
">=" -> { r, v -> r >= v }
"<=" -> { r, v -> r <= v }
"==" -> { r, v -> r == v }
"!=" -> { r, v -> r != v }
else -> { _, _ -> false }
}
if (cmp(memory.getOrPut(checkReg) { 0 }, value)) memory[reg] = memory.getOrPut(reg) { 0 } + mod
maxCurr = maxOf(memory.getOrPut(reg) { 0 }, maxCurr)
}
}
return Pair(memory.values.max()!!, maxCurr)
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day08_input.txt").readLines()
val (partOne, partTwo) = Day08.solve(input)
println("Part One = $partOne")
println("Part Two = $partTwo")
}
| mit | 79226d64d6bdb6b3f6c50db3f1050943 | 29.488889 | 103 | 0.482507 | 3.111111 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheClassLoaderScopeRegistryListener.kt | 1 | 5080 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.api.internal.initialization.ClassLoaderScopeIdentifier
import org.gradle.api.internal.initialization.loadercache.ClassLoaderId
import org.gradle.configurationcache.serialization.ClassLoaderRole
import org.gradle.configurationcache.serialization.ScopeLookup
import org.gradle.initialization.ClassLoaderScopeId
import org.gradle.initialization.ClassLoaderScopeRegistryListener
import org.gradle.initialization.ClassLoaderScopeRegistryListenerManager
import org.gradle.internal.buildtree.BuildTreeLifecycleListener
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.hash.HashCode
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import java.io.Closeable
@ServiceScope(Scopes.BuildTree::class)
internal
class ConfigurationCacheClassLoaderScopeRegistryListener(
private
val listenerManager: ClassLoaderScopeRegistryListenerManager
) : ClassLoaderScopeRegistryListener, ScopeLookup, BuildTreeLifecycleListener, Closeable {
private
val lock = Any()
private
val scopeSpecs = mutableMapOf<ClassLoaderScopeId, ClassLoaderScopeSpec>()
private
val loaders = mutableMapOf<ClassLoader, Pair<ClassLoaderScopeSpec, ClassLoaderRole>>()
override fun afterStart() {
listenerManager.add(this)
}
/**
* Stops recording [ClassLoaderScopeSpec]s and releases any recorded state.
*/
fun dispose() {
synchronized(lock) {
// TODO:configuration-cache find a way to make `dispose` unnecessary;
// maybe by extracting an `ConfigurationCacheBuildDefinition` service
// from DefaultConfigurationCacheHost so a decision based on the configured
// configuration cache strategy (none, store or load) can be taken early on.
// The listener only needs to be attached in the `store` state.
scopeSpecs.clear()
loaders.clear()
listenerManager.remove(this)
}
}
override fun close() {
dispose()
}
override fun scopeFor(classLoader: ClassLoader?): Pair<ClassLoaderScopeSpec, ClassLoaderRole>? {
synchronized(lock) {
return loaders[classLoader]
}
}
override fun childScopeCreated(parentId: ClassLoaderScopeId, childId: ClassLoaderScopeId) {
synchronized(lock) {
if (scopeSpecs.containsKey(childId)) {
// scope is being reused
return
}
val parentIsRoot = parentId.parent == null
val parent = if (parentIsRoot) {
null
} else {
val lookupParent = scopeSpecs[parentId]
require(lookupParent != null) {
"Cannot find parent $parentId for child scope $childId"
}
lookupParent
}
val child = ClassLoaderScopeSpec(parent, childId.name)
scopeSpecs[childId] = child
}
}
override fun classloaderCreated(scopeId: ClassLoaderScopeId, classLoaderId: ClassLoaderId, classLoader: ClassLoader, classPath: ClassPath, implementationHash: HashCode?) {
synchronized(lock) {
val spec = scopeSpecs[scopeId]
require(spec != null)
// TODO - a scope can currently potentially have multiple export and local ClassLoaders but we're assuming one here
// Rather than fix the assumption here, it would be better to rework the scope implementation so that it produces no more than one export and one local ClassLoader
val local = scopeId is ClassLoaderScopeIdentifier && scopeId.localId() == classLoaderId
if (local) {
spec.localClassPath = classPath
spec.localImplementationHash = implementationHash
} else {
spec.exportClassPath = classPath
}
loaders[classLoader] = Pair(spec, ClassLoaderRole(local))
}
}
}
internal
class ClassLoaderScopeSpec(
val parent: ClassLoaderScopeSpec?,
val name: String
) {
var localClassPath: ClassPath = ClassPath.EMPTY
var localImplementationHash: HashCode? = null
var exportClassPath: ClassPath = ClassPath.EMPTY
override fun toString(): String {
return if (parent != null) {
"$parent:$name"
} else {
name
}
}
}
| apache-2.0 | 62e166c6c1d73594fa746176ed3d82be | 35.546763 | 176 | 0.682874 | 5.09018 | false | true | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/commands/Kick.kt | 1 | 7808 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.commands
import be.duncanc.discordmodbot.bot.services.GuildLogger
import be.duncanc.discordmodbot.bot.utils.extractReason
import be.duncanc.discordmodbot.bot.utils.findMemberAndCheckCanInteract
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.ChannelType
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.PrivateChannel
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.requests.RestAction
import org.springframework.stereotype.Component
import java.awt.Color
import java.util.*
import java.util.concurrent.TimeUnit
/**
* This class create a kick command that will be logged.
*/
@Component
class Kick : CommandModule(
arrayOf("Kick"),
"[User mention] [Reason~]",
"This command will kick the mentioned users and log this to the log channel. A reason is required.",
true,
true
) {
public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
event.author.openPrivateChannel().queue(
{ privateChannel -> commandExec(event, arguments, privateChannel) }
) { commandExec(event, arguments, null) }
}
private fun commandExec(event: MessageReceivedEvent, arguments: String?, privateChannel: PrivateChannel?) {
if (!event.isFromType(ChannelType.TEXT)) {
privateChannel?.sendMessage("This command only works in a guild.")?.queue()
} else if (event.member?.hasPermission(Permission.KICK_MEMBERS) != true) {
privateChannel?.sendMessage(event.author.asMention + " you need kick members permission to use this command!")
?.queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) }
} else if (event.message.mentionedUsers.size < 1) {
privateChannel?.sendMessage("Illegal argumentation, you need to mention a user that is still in the server.")
?.queue()
} else {
val reason: String = extractReason(arguments)
val toKick = findMemberAndCheckCanInteract(event)
val kickRestAction = event.guild.kick(toKick)
val userKickNotification = EmbedBuilder()
.setColor(Color.RED)
.setAuthor(event.member?.nicknameAndUsername, null, event.author.effectiveAvatarUrl)
.setTitle("${event.guild.name}: You have been kicked by ${event.member?.nicknameAndUsername}", null)
.setDescription("Reason: $reason")
.build()
toKick.user.openPrivateChannel().queue(
{ privateChannelUserToMute ->
privateChannelUserToMute.sendMessageEmbeds(userKickNotification).queue(
{ message: Message ->
onSuccessfulInformUser(event, reason, privateChannel, toKick, message, kickRestAction)
}
) { throwable ->
onFailToInformUser(
event,
reason,
privateChannel,
toKick,
throwable,
kickRestAction
)
}
}
) { throwable -> onFailToInformUser(event, reason, privateChannel, toKick, throwable, kickRestAction) }
}
}
private fun logKick(event: MessageReceivedEvent, reason: String, toKick: Member) {
val guildLogger = event.jda.registeredListeners.firstOrNull { it is GuildLogger } as GuildLogger?
if (guildLogger != null) {
val logEmbed = EmbedBuilder()
.setColor(Color.RED)
.setTitle("User kicked")
.addField("UUID", UUID.randomUUID().toString(), false)
.addField("User", toKick.nicknameAndUsername, true)
.addField("Moderator", event.member!!.nicknameAndUsername, true)
.addField("Reason", reason, false)
guildLogger.log(logEmbed, toKick.user, event.guild, null, GuildLogger.LogTypeAction.MODERATOR)
}
}
private fun onSuccessfulInformUser(
event: MessageReceivedEvent,
reason: String,
privateChannel: PrivateChannel?,
toKick: Member,
userKickWarning: Message,
kickRestAction: RestAction<Void>
) {
kickRestAction.queue({
logKick(event, reason, toKick)
if (privateChannel == null) {
return@queue
}
val creatorMessage = MessageBuilder()
.append("Kicked ").append(toKick.toString()).append(".\n\nThe following message was sent to the user:")
.setEmbeds(userKickWarning.embeds)
.build()
privateChannel.sendMessage(creatorMessage).queue()
}) { throwable ->
userKickWarning.delete().queue()
if (privateChannel == null) {
return@queue
}
val creatorMessage = MessageBuilder()
.append("Kick failed ").append(toKick.toString())
.append(throwable.javaClass.simpleName).append(": ").append(throwable.message)
.append(".\n\nThe following message was sent to the user but was automatically deleted:")
.setEmbeds(userKickWarning.embeds)
.build()
privateChannel.sendMessage(creatorMessage).queue()
}
}
private fun onFailToInformUser(
event: MessageReceivedEvent,
reason: String,
privateChannel: PrivateChannel?,
toKick: Member,
throwable: Throwable,
kickRestAction: RestAction<Void>
) {
kickRestAction.queue({
logKick(event, reason, toKick)
if (privateChannel == null) {
return@queue
}
val creatorMessage = MessageBuilder()
.append("Kicked ").append(toKick.toString())
.append(".\n\nWas unable to send a DM to the user please inform the user manually, if possible.\n")
.append(throwable.javaClass.simpleName).append(": ").append(throwable.message)
.build()
privateChannel.sendMessage(creatorMessage).queue()
}) { banThrowable ->
if (privateChannel == null) {
return@queue
}
val creatorMessage = MessageBuilder()
.append("Kick failed ").append(toKick.toString())
.append("\n\nWas unable to ban the user\n")
.append(banThrowable.javaClass.simpleName).append(": ").append(banThrowable.message)
.append(".\n\nWas unable to send a DM to the user.\n")
.append(throwable.javaClass.simpleName).append(": ").append(throwable.message)
.build()
privateChannel.sendMessage(creatorMessage).queue()
}
}
}
| apache-2.0 | f6b2fdd48e928431122348755c0d72b3 | 41.434783 | 122 | 0.617316 | 4.790184 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/layoutpicker/CategoriesDiffCallback.kt | 1 | 862 | package org.wordpress.android.ui.layoutpicker
import androidx.recyclerview.widget.DiffUtil.Callback
/**
* Implements the Recyclerview list items diff to avoid unneeded UI refresh
*/
class CategoriesDiffCallback(
private val oldList: List<CategoryListItemUiState>,
private val newList: List<CategoryListItemUiState>
) : Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
newList[newItemPosition].slug == oldList[oldItemPosition].slug
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val new = newList[newItemPosition]
val old = oldList[oldItemPosition]
return new.selected == old.selected && new.slug == old.slug
}
}
| gpl-2.0 | 57f071b422e20f52de5ec78d2ba8c13f | 34.916667 | 90 | 0.736659 | 5.011628 | false | false | false | false |
DiUS/pact-jvm | core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/MatchingConfig.kt | 1 | 1302 | package au.com.dius.pact.core.matchers
import kotlin.reflect.full.createInstance
object MatchingConfig {
val bodyMatchers = mapOf(
"application/.*xml" to "au.com.dius.pact.core.matchers.XmlBodyMatcher",
"text/xml" to "au.com.dius.pact.core.matchers.XmlBodyMatcher",
"application/.*json" to "au.com.dius.pact.core.matchers.JsonBodyMatcher",
"application/json-rpc" to "au.com.dius.pact.core.matchers.JsonBodyMatcher",
"application/jsonrequest" to "au.com.dius.pact.core.matchers.JsonBodyMatcher",
"text/plain" to "au.com.dius.pact.core.matchers.PlainTextBodyMatcher",
"multipart/form-data" to "au.com.dius.pact.core.matchers.MultipartMessageBodyMatcher",
"multipart/mixed" to "au.com.dius.pact.core.matchers.MultipartMessageBodyMatcher",
"application/x-www-form-urlencoded" to "au.com.dius.pact.core.matchers.FormPostBodyMatcher"
)
@JvmStatic
fun lookupBodyMatcher(contentType: String?): BodyMatcher? {
return if (contentType != null) {
val matcher = bodyMatchers.entries.find { contentType.matches(Regex(it.key)) }?.value
if (matcher != null) {
val clazz = Class.forName(matcher).kotlin
(clazz.objectInstance ?: clazz.createInstance()) as BodyMatcher?
} else {
null
}
} else {
null
}
}
}
| apache-2.0 | 5148b1349dd497f64cc6b35c58c65c0c | 39.6875 | 95 | 0.708141 | 3.547684 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/fragments/news/details/ArticleContentFragment.kt | 1 | 4105 | package forpdateam.ru.forpda.ui.fragments.news.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import moxy.MvpAppCompatFragment
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.common.webview.CustomWebChromeClient
import forpdateam.ru.forpda.common.webview.CustomWebViewClient
import forpdateam.ru.forpda.common.webview.DialogsHelper
import forpdateam.ru.forpda.entity.remote.news.DetailsPage
import forpdateam.ru.forpda.model.interactors.news.ArticleInteractor
import forpdateam.ru.forpda.presentation.articles.detail.content.ArticleContentPresenter
import forpdateam.ru.forpda.presentation.articles.detail.content.ArticleContentView
import forpdateam.ru.forpda.ui.activities.MainActivity
import forpdateam.ru.forpda.ui.fragments.TabTopScroller
import forpdateam.ru.forpda.ui.fragments.WebViewTopScroller
import forpdateam.ru.forpda.ui.views.ExtendedWebView
/**
* Created by radiationx on 03.09.17.
*/
class ArticleContentFragment : MvpAppCompatFragment(), ArticleContentView, TabTopScroller {
private lateinit var webView: ExtendedWebView
private lateinit var topScroller: WebViewTopScroller
@InjectPresenter
lateinit var presenter: ArticleContentPresenter
@ProvidePresenter
fun providePresenter(): ArticleContentPresenter = ArticleContentPresenter(
(parentFragment as NewsDetailsFragment).provideChildInteractor(),
App.get().Di().mainPreferencesHolder,
App.get().Di().templateManager,
App.get().Di().errorHandler
)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
webView = ExtendedWebView(context)
(parentFragment as? NewsDetailsFragment)?.attachWebView(webView)
topScroller = WebViewTopScroller(webView, (parentFragment as NewsDetailsFragment).getAppBar())
webView.setDialogsHelper(DialogsHelper(
webView.context,
App.get().Di().linkHandler,
App.get().Di().systemLinkHandler,
App.get().Di().router
))
registerForContextMenu(webView)
webView.webViewClient = CustomWebViewClient()
webView.webChromeClient = CustomWebChromeClient()
webView.addJavascriptInterface(this, JS_INTERFACE)
return webView
}
override fun toggleScrollTop() {
topScroller.toggleScrollTop()
}
override fun setRefreshing(isRefreshing: Boolean) {}
override fun showData(article: DetailsPage) {
webView.loadDataWithBaseURL("https://4pda.to/forum/", article.html, "text/html", "utf-8", null)
}
override fun setStyleType(type: String) {
webView.evalJs("changeStyleType(\"$type\")")
}
override fun setFontSize(size: Int) {
webView.setRelativeFontSize(size)
}
@JavascriptInterface
fun toComments() {
if (context == null)
return
webView.runInUiThread { (parentFragment as NewsDetailsFragment).fragmentsPager.currentItem = 1 }
}
@JavascriptInterface
fun sendPoll(id: String, answer: String, from: String) {
if (context == null)
return
webView.runInUiThread {
val pollId = Integer.parseInt(id)
val answers = answer.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val answersId = IntArray(answers.size)
for (i in answers.indices) {
answersId[i] = Integer.parseInt(answers[i])
}
presenter.sendPoll(from, pollId, answersId)
}
}
override fun onResume() {
super.onResume()
webView.onResume()
}
override fun onPause() {
super.onPause()
webView.onPause()
}
override fun onDestroy() {
super.onDestroy()
webView.endWork()
}
companion object {
const val JS_INTERFACE = "INews"
}
}
| gpl-3.0 | ebc297252c2e4622d525f7f6183b56c4 | 32.92562 | 116 | 0.699391 | 4.767712 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidKotlindoc/src/main/kotlin/com/eden/orchid/kotlindoc/resources/KotlinClassdocResource.kt | 1 | 1085 | package com.eden.orchid.kotlindoc.resources
import com.copperleaf.dokka.json.models.KotlinClassDoc
import com.eden.common.json.JSONElement
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.utilities.asInputStream
import org.json.JSONObject
import java.io.InputStream
class KotlinClassdocResource(
context: OrchidContext,
val classDoc: KotlinClassDoc
) : BaseKotlindocResource(context, classDoc.qualifiedName, classDoc) {
override fun getContentStream(): InputStream {
var rawContent = doc.comment
rawContent += classDoc.constructors.map { "${it.name}\n${it.comment}" }.joinToString("\n")
rawContent += "\n"
rawContent += classDoc.fields.map { "${it.name}\n${it.comment}" }.joinToString("\n")
rawContent += "\n"
rawContent += classDoc.methods.map { "${it.name}\n${it.comment}" }.joinToString("\n")
rawContent += "\n"
rawContent += classDoc.extensions.map { "${it.name}\n${it.comment}" }.joinToString("\n")
rawContent += "\n"
return rawContent.asInputStream()
}
}
| mit | 6f69778996722d079e940bf83b65b93d | 36.413793 | 98 | 0.682028 | 4.205426 | false | false | false | false |
carltonwhitehead/crispy-fish | library/src/main/kotlin/org/coner/crispyfish/filetype/staging/StagingLineModelReader.kt | 1 | 2604 | package org.coner.crispyfish.filetype.staging
import org.coner.crispyfish.model.PenaltyType
import org.coner.crispyfish.model.Run
class StagingLineModelReader<L>(
private val stagingFileAssistant: StagingFileAssistant,
private val stagingLineReader: StagingLineReader<L>
) {
fun readRegistration(stagingLine: L): StagingLineRegistration? {
val registration = StagingLineRegistration(
number = stagingLineReader.getRegisteredDriverNumber(stagingLine),
classing = stagingLineReader.getRegisteredDriverClass(stagingLine)?.toUpperCase(),
name = stagingLineReader.getRegisteredDriverName(stagingLine),
car = stagingLineReader.getRegisteredDriverCar(stagingLine),
carColor = stagingLineReader.getRegisteredDriverCarColor(stagingLine)
)
return when {
registration.number.isNullOrBlank() -> null
registration.classing.isNullOrBlank() -> null
else -> registration
}
}
fun readRun(stagingFileLine: L): Run? {
val run = Run()
val raw = stagingLineReader.getRunRawTime(stagingFileLine)
val pax = stagingLineReader.getRunPaxTime(stagingFileLine)
val penalty = stagingLineReader.getRunPenalty(stagingFileLine)
try {
run.rawTime = stagingFileAssistant.convertStagingTimeStringToDuration(raw)
run.penaltyType = stagingFileAssistant.convertStagingRunPenaltyStringToPenaltyType(penalty)
try {
run.paxTime = stagingFileAssistant.convertStagingTimeStringToDuration(pax)
} catch (e: StagingLineException) {
when (run.penaltyType) {
PenaltyType.CONE -> throw StagingLineException("Unable to parse pax time from coned run", e)
PenaltyType.DID_NOT_FINISH,
PenaltyType.DISQUALIFIED,
PenaltyType.RERUN -> { /* no-op */ }
PenaltyType.CLEAN -> throw StagingLineException("Unable to parse pax time from clean run", e)
else -> throw IllegalStateException("Unrecognized run.penaltyType: " + run.penaltyType!!, e)
}
}
run.cones = when {
run.penaltyType === PenaltyType.CONE -> stagingFileAssistant.convertStagingRunPenaltyStringToConeCount(penalty!!)
run.penaltyType === PenaltyType.CLEAN -> 0
else -> null
}
} catch (e: StagingLineException) {
return null
}
return run
}
}
| gpl-2.0 | 1622996268e869ed2e1677c9d37e1ee8 | 43.896552 | 129 | 0.639785 | 4.913208 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt | 1 | 8968 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.ide.util.TreeChooser
import com.intellij.ide.util.gotoByName.GotoSymbolModel2
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.ui.TextAccessor
import com.intellij.util.ProcessingContext
import com.intellij.util.Processor
import com.intellij.util.TextFieldCompletionProvider
import com.intellij.util.indexing.DumbModeAccessType
import com.intellij.util.indexing.FindSymbolParameters
import com.intellij.util.indexing.IdFilter
import com.intellij.util.textCompletion.TextFieldWithCompletion
import com.jetbrains.extensions.ContextAnchor
import com.jetbrains.extensions.QNameResolveContext
import com.jetbrains.extensions.getQName
import com.jetbrains.extensions.python.toPsi
import com.jetbrains.extensions.resolveToElement
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyGotoSymbolContributor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyTreeChooserDialog
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.stubs.PyClassNameIndex
import com.jetbrains.python.psi.stubs.PyFunctionNameIndex
import com.jetbrains.python.psi.types.PyModuleType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
/**
* Python module is file or package with init.py.
* Only source based packages are supported.
* [PySymbolFieldWithBrowseButton] use this function to get list of root names
*/
fun isPythonModule(element: PsiElement): Boolean = element is PyFile || (element as? PsiDirectory)?.let {
it.findFile(PyNames.INIT_DOT_PY) != null
} ?: false
/**
* Text field to enter python symbols and browse button (from [PyGotoSymbolContributor]).
* Supports auto-completion for symbol fully qualified names inside of textbox
* @param filter lambda to filter symbols
* @param startFromDirectory symbols resolved against module, but may additionally be resolved against this folder if provided like in [QNameResolveContext.folderToStart]
*
*/
class PySymbolFieldWithBrowseButton(contextAnchor: ContextAnchor,
filter: ((PsiElement) -> Boolean)? = null,
startFromDirectory: (() -> VirtualFile)? = null) : TextAccessor, ComponentWithBrowseButton<TextFieldWithCompletion>(
TextFieldWithCompletion(contextAnchor.project, PyNameCompletionProvider(contextAnchor, filter, startFromDirectory), "", true, true, true),
null) {
init {
addActionListener {
val dialog = PySymbolChooserDialog(contextAnchor.project, contextAnchor.scope, filter)
dialog.showDialog()
val element = dialog.selected
if (element is PyQualifiedNameOwner) {
childComponent.setText(element.qualifiedName)
}
if (element is PyFile) {
childComponent.setText(element.getQName()?.toString())
}
}
}
override fun setText(text: String?) {
childComponent.setText(text)
}
override fun getText(): String = childComponent.text
}
private fun PyType.getVariants(element: PsiElement): Array<LookupElement> =
this.getCompletionVariants("", element, ProcessingContext()).filterIsInstance(LookupElement::class.java).toTypedArray()
private class PyNameCompletionProvider(private val contextAnchor: ContextAnchor,
private val filter: ((PsiElement) -> Boolean)?,
private val startFromDirectory: (() -> VirtualFile)? = null) : TextFieldCompletionProvider(), DumbAware {
override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) {
val lookups: Array<LookupElement>
var name: QualifiedName? = null
if ('.' !in text) {
lookups = contextAnchor.getRoots()
.map { rootFolder -> rootFolder.children.map { it.toPsi(contextAnchor.project) } }
.flatten()
.filterNotNull()
.filter { isPythonModule(it) }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
.distinctBy { it.lookupString }
.toTypedArray()
}
else {
val evalContext = TypeEvalContext.userInitiated(contextAnchor.project, null)
name = QualifiedName.fromDottedString(text)
val resolveContext = QNameResolveContext(contextAnchor, evalContext = evalContext, allowInaccurateResult = false,
folderToStart = startFromDirectory?.invoke())
var element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
if (element == null && name.componentCount > 1) {
name = name.removeLastComponent()
element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
}
if (element == null) {
return
}
lookups = when (element) {
is PyFile -> PyModuleType(element).getVariants(element)
is PsiDirectory -> {
val init = PyUtil.turnDirIntoInit(element) as? PyFile ?: return
PyModuleType(init).getVariants(element) +
element.children.filterIsInstance(PsiFileSystemItem::class.java)
// For package we need all symbols in initpy and all filesystem children of this folder except initpy itself
.filterNot { it.name == PyNames.INIT_DOT_PY }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
}
is PyTypedElement -> {
evalContext.getType(element)?.getVariants(element) ?: return
}
else -> return
}
}
result.addAllElements(lookups
.filter { it.psiElement != null }
.filter { filter?.invoke(it.psiElement!!) ?: true }
.map { if (name != null) LookupElementBuilder.create("$name.${it.lookupString}") else it })
}
}
private class PySymbolChooserDialog(project: Project, scope: GlobalSearchScope, private val filter: ((PsiElement) -> Boolean)?)
: PyTreeChooserDialog<PsiNamedElement>(PyBundle.message("python.symbol.chooser.dialog.title"), PsiNamedElement::class.java,
project,
scope,
TreeChooser.Filter { filter?.invoke(it) ?: true }, null) {
override fun findElements(name: String, searchScope: GlobalSearchScope): Collection<PsiNamedElement> {
return PyClassNameIndex.find(name, project, searchScope) + PyFunctionNameIndex.find(name, project, searchScope)
}
override fun createChooseByNameModel() = GotoSymbolModel2(project, arrayOf(object : PyGotoSymbolContributor(), DumbAware {
override fun getNames(project: Project?, includeNonProjectItems: Boolean): Array<String> {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<Array<String>, RuntimeException> {
super.getNames(project, includeNonProjectItems)
}
}
override fun getItemsByName(name: String?,
pattern: String?,
project: Project?,
includeNonProjectItems: Boolean): Array<NavigationItem> {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<Array<NavigationItem>, RuntimeException> {
super.getItemsByName(name, pattern, project, includeNonProjectItems)
}
}
override fun processNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?) {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode {
super.processNames(processor, scope, filter)
}
}
override fun processElementsWithName(name: String, processor: Processor<in NavigationItem>, parameters: FindSymbolParameters) {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode {
super.processElementsWithName(name, processor, parameters)
}
}
override fun getQualifiedName(item: NavigationItem): String? {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<String?, RuntimeException> {
super.getQualifiedName(item)
}
}
}), disposable)
}
| apache-2.0 | 3ccdc695ebe7cb870795b93f05d9daf3 | 45.708333 | 170 | 0.715321 | 4.943771 | false | false | false | false |
walleth/kethereum | erc681/src/test/kotlin/org/kethereum/erc681/TheERC681Detection.kt | 1 | 1193 | package org.kethereum.erc681
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.kethereum.model.EthereumURI
class TheERC681Detection {
@Test
fun detects681URLWithPrefix() {
assertThat(EthereumURI("ethereum:pay-0x00AB42@23?value=42&gas=3&yay").isERC681()).isTrue()
}
@Test
fun detects681URLWithPrefixSimple() {
assertThat(EthereumURI("ethereum:pay-0x00AB42").isERC681()).isTrue()
}
@Test
fun detects681URLNoPrefix() {
assertThat(EthereumURI("ethereum:0x00AB42@23?value=42&gas=3&yay").isERC681()).isTrue()
}
@Test
fun detects681URLNoPrefixSimple() {
assertThat(EthereumURI("ethereum:0x00AB42").isERC681()).isTrue()
}
@Test
fun detectsNon681URLNoPrefix() {
assertThat(EthereumURI("ethereum:somethingelse-0x00AB42@23?value=42&gas=3&yay").isERC681()).isFalse()
}
@Test
fun detectsNon681URLForSomethingClose() {
assertThat(EthereumURI("ethereum:payy-0x00AB42@23?value=42&gas=3&yay").isERC681()).isFalse()
}
@Test
fun detectsNon681ForGarbage() {
assertThat(EthereumURI("garbage").isERC681()).isFalse()
}
} | mit | 3e4e2340d88ac84290c35380455f5627 | 25.533333 | 109 | 0.687343 | 3.447977 | false | true | false | false |
neverwoodsS/MagicPen | lib/src/main/java/com/lab/zhangll/magicpen/lib/shapes/MagicShape.kt | 1 | 2178 | package com.lab.zhangll.magicpen.lib.shapes
import android.graphics.PointF
import android.util.Log
import android.view.View
import com.lab.zhangll.magicpen.lib.base.MagicDraw
import com.lab.zhangll.magicpen.lib.base.MagicGesture
import com.lab.zhangll.magicpen.lib.base.MagicLocation
import com.lab.zhangll.magicpen.lib.base.MagicMotion
/**
* Created by zhangll on 2017/5/20.
* Shape 基类,用于整合多个协议的实现
*/
abstract class MagicShape : MagicLocation(), MagicDraw, MagicMotion {
lateinit var parent: View
open var gesture: MagicGesture? = null
open fun reBounds() {
left = start?.x ?: 0f
top = start?.y ?: 0f
right = end?.x ?: 0f
bottom = end?.y ?: 0f
}
override fun invalidate() {
relations.forEach { it.invoke() }
parent.invalidate()
}
override fun invalidateDirectly() {
parent.invalidate()
}
/**
* MagicView将会调用此方法将Shape放置到View中间
* 此方法可能对某些Shape无效,由子类决定是否复写
*/
open fun centerHorizontal(centerX: Double) {
Log.i("MagicLine", "centerX=$centerX " +
"start=$start end=$end")
val center = (start!!.x + end!!.x) / 2.0
val dis = centerX - center
Log.i("MagicLine", "dis=$dis center=$center")
val startX = start!!.x + dis
val endX = end!!.x + dis
start = PointF(startX.toFloat(), start!!.y)
end = PointF(endX.toFloat(), end!!.y)
Log.i("MagicLine", "start=$start end=$end")
}
/**
* MagicView将会调用此方法将Shape放置到View中间
* 此方法可能对某些Shape无效,由子类决定是否复写
*/
open fun centerVertical(centerY: Double) {
Log.i("MagicLine", "centerY=$centerY " +
"start=$start end=$end")
val center = (start!!.y + end!!.y) / 2.0
val dis = centerY - center
val startY = start!!.y + dis
val endY = end!!.y + dis
start = PointF(start!!.x, startY.toFloat())
end = PointF(end!!.x, endY.toFloat())
Log.i("MagicLine", "start=$start end=$end")
}
} | mit | 99273e1814a8bc582671d0d46c01a4bc | 29.134328 | 69 | 0.599604 | 3.437819 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/base_mvp/api/ApiPresenter.kt | 1 | 2781 | package io.armcha.ribble.presentation.base_mvp.api
import android.support.annotation.CallSuper
import io.armcha.ribble.domain.fetcher.Fetcher
import io.armcha.ribble.domain.fetcher.Status
import io.armcha.ribble.domain.fetcher.result_listener.RequestType
import io.armcha.ribble.domain.fetcher.result_listener.ResultListener
import io.armcha.ribble.presentation.base_mvp.base.BaseContract
import io.armcha.ribble.presentation.base_mvp.base.BasePresenter
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
import javax.inject.Inject
/**
* Created by Chatikyan on 04.08.2017.
*/
abstract class ApiPresenter<VIEW : BaseContract.View> : BasePresenter<VIEW>(), ResultListener {
@Inject
protected lateinit var fetcher: Fetcher
private val TYPE_NONE = RequestType.TYPE_NONE
protected val AUTH: RequestType = RequestType.AUTH
protected val POPULAR_SHOTS = RequestType.POPULAR_SHOTS
protected val RECENT_SHOTS = RequestType.RECENT_SHOTS
protected val FOLLOWINGS_SHOTS = RequestType.FOLLOWINGS_SHOTS
protected val LIKED_SHOTS = RequestType.LIKED_SHOTS
protected val COMMENTS = RequestType.COMMENTS
protected val LIKE = RequestType.LIKE
protected val SUCCESS = Status.SUCCESS
protected val LOADING = Status.LOADING
protected val ERROR = Status.ERROR
protected val EMPTY_SUCCESS = Status.EMPTY_SUCCESS
protected infix fun RequestType.statusIs(status: Status) = fetcher.getRequestStatus(this) == status
protected val RequestType.status
get() = fetcher.getRequestStatus(this)
fun <TYPE> fetch(flowable: Flowable<TYPE>,
requestType: RequestType = TYPE_NONE, success: (TYPE) -> Unit) {
fetcher.fetch(flowable, requestType, this, success)
}
fun <TYPE> fetch(observable: Observable<TYPE>,
requestType: RequestType = TYPE_NONE, success: (TYPE) -> Unit) {
fetcher.fetch(observable, requestType, this, success)
}
fun <TYPE> fetch(single: Single<TYPE>,
requestType: RequestType = TYPE_NONE, success: (TYPE) -> Unit) {
fetcher.fetch(single, requestType, this, success)
}
fun complete(completable: Completable,
requestType: RequestType = TYPE_NONE, success: () -> Unit = {}) {
fetcher.complete(completable, requestType, this, success)
}
@CallSuper
override fun onPresenterDestroy() {
super.onPresenterDestroy()
fetcher.clear()
}
@CallSuper
override fun onRequestStart(requestType: RequestType) {
onRequestStart()
}
@CallSuper
override fun onRequestError(requestType: RequestType, errorMessage: String?) {
onRequestError(errorMessage)
}
} | apache-2.0 | 6fe0ceda85670f927ad78a8e128fb93d | 34.666667 | 103 | 0.717008 | 4.372642 | false | false | false | false |
JetBrains-Research/viktor | src/main/kotlin/org/jetbrains/bio/viktor/Loader.kt | 1 | 3719 | package org.jetbrains.bio.viktor
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
internal class ResourceLibrary(private val name: String) {
fun install() {
val resource = System.mapLibraryName(name)
val inputStream = ResourceLibrary::class.java.getResourceAsStream("/$resource")
if (inputStream != null) {
val libraryPath = LIBRARY_DIR.resolve(resource)
Files.copy(inputStream, libraryPath, REPLACE_EXISTING)
System.load(libraryPath.toString())
} else {
System.loadLibrary(name)
}
}
companion object {
private val LIBRARY_DIR: Path by lazy {
val path = Files.createTempDirectory("simd")
Runtime.getRuntime().addShutdownHook(Thread {
path.toFile().deleteRecursively()
})
path
}
}
}
internal object Loader {
private val LOG = LoggerFactory.getLogger(Loader::class.java)
/** If `true` vector operations will be SIMD-optimized. */
internal var nativeLibraryLoaded: Boolean = false
private set
private var optimizationSupported = false
private var architectureSupported = false
fun ensureLoaded() {}
private val arch: String get() {
return when (val arch = System.getProperty("os.arch").toLowerCase()) {
"amd64", "x86_64" -> "x86_64"
else -> error("unsupported architecture: $arch")
}
}
init {
try {
architectureSupported = arch.let { true }
ResourceLibrary("simd.$arch").install()
nativeLibraryLoaded = true
when {
isAvxSupported() -> {
ResourceLibrary("simd.avx.$arch").install()
optimizationSupported = true
}
isSse2Supported() -> {
ResourceLibrary("simd.sse2.$arch").install()
optimizationSupported = true
}
else -> warnNoOptimization()
}
} catch (e: Throwable) {
LOG.info(e.message)
warnNoOptimization()
}
}
private fun warnNoOptimization() {
if (!architectureSupported) {
LOG.info("SIMD optimization is not available for your architecture, enable debug output for more details.")
LOG.debug(
"""Currently supported architectures: x86_64, amd64.
Fallback Kotlin implementation will be used.
Build viktor for your system from source as described in https://github.com/JetBrains-Research/viktor"""
)
} else if (!nativeLibraryLoaded) {
LOG.info("Couldn't load native SIMD library, enable debug output for more details.")
LOG.debug(
"""Native SIMD library couldn't be loaded.
Currently supported operational systems: Linux, Windows, MacOS.
Fallback Kotlin implementation will be used.
Build viktor for your system from source as described in https://github.com/JetBrains-Research/viktor"""
)
}
else if (!optimizationSupported) {
LOG.info("SIMD optimization is not available for your system, enable debug output for more details.")
LOG.debug(
"""No supported SIMD instruction sets were detected on your system.
Currently supported SIMD instruction sets: SSE2, AVX.
Fallback Kotlin implementation will be used.
Build viktor for your system from source as described in https://github.com/JetBrains-Research/viktor"""
)
}
}
}
internal external fun isAvxSupported(): Boolean
internal external fun isSse2Supported(): Boolean
| mit | 5447cec3812bcd3b084791c1949c603b | 33.435185 | 119 | 0.626513 | 4.817358 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/EXT_point_parameters.kt | 4 | 3234 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val EXT_point_parameters = "EXTPointParameters".nativeClassGL("EXT_point_parameters", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension supports additional geometric characteristics of points. It can be used to render particles or tiny light sources, commonly referred as
"Light points".
The raster brightness of a point is a function of the point area, point color, point transparency, and the response of the display's electron gun and
phosphor. The point area and the point transparency are derived from the point size, currently provided with the {@code size} parameter of
#PointSize().
The primary motivation is to allow the size of a point to be affected by distance attenuation. When distance attenuation has an effect, the final point
size decreases as the distance of the point from the eye increases.
The secondary motivation is a mean to control the mapping from the point size to the raster point area and point transparency. This is done in order to
increase the dynamic range of the raster brightness of points. In other words, the alpha component of a point may be decreased (and its transparency
increased) as its area shrinks below a defined threshold.
This extension defines a derived point size to be closely related to point brightness. The brightness of a point is given by:
${codeBlock("""
1
dist_atten(d) = -------------------
a + b * d + c * d^2
brightness(Pe) = Brightness * dist_atten(|Pe|)""")}
where 'Pe' is the point in eye coordinates, and 'Brightness' is some initial value proportional to the square of the size provided with glPointSize.
Here we simplify the raster brightness to be a function of the rasterized point area and point transparency.
${codeBlock("""
brightness(Pe) brightness(Pe) >= Threshold_Area
area(Pe) =
Threshold_Area Otherwise
factor(Pe) = brightness(Pe)/Threshold_Area
alpha(Pe) = Alpha * factor(Pe)""")}
where 'Alpha' comes with the point color (possibly modified by lighting).
'Threshold_Area' above is in area units. Thus, it is proportional to the square of the threshold provided by the programmer through this extension.
The new point size derivation method applies to all points, while the threshold applies to multisample points only.
"""
IntConstant(
"Accepted by the {@code pname} parameter of glPointParameterfvEXT, and the {@code pname} of glGet.",
"POINT_SIZE_MIN_EXT"..0x8126,
"POINT_SIZE_MAX_EXT"..0x8127,
"POINT_FADE_THRESHOLD_SIZE_EXT"..0x8128,
"DISTANCE_ATTENUATION_EXT"..0x8129
)
void(
"PointParameterfEXT",
"",
GLenum("pname", ""),
GLfloat("param", "")
)
void(
"PointParameterfvEXT",
"",
GLenum("pname", ""),
Check(1)..GLfloat.const.p("params", "")
)
} | bsd-3-clause | 61872e95d5029964e733bb863bb12b44 | 41.012987 | 159 | 0.670068 | 4.613409 | false | false | false | false |
mdanielwork/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ReprocessContentRootDataActivity.kt | 3 | 2069 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.model.ProjectKeys.CONTENT_ROOT
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
class ReprocessContentRootDataActivity : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val dataManager = ProjectDataManager.getInstance()
val service = ContentRootDataService()
val externalProjectsManager = ExternalProjectsManagerImpl.getInstance(project)
externalProjectsManager.init()
externalProjectsManager.runWhenInitialized {
val haveModulesToProcess = ModuleManager.getInstance(project).modules.isNotEmpty()
if (!haveModulesToProcess) {
return@runWhenInitialized
}
var modifiableModelsProvider: IdeModifiableModelsProviderImpl? = null
try {
modifiableModelsProvider = IdeModifiableModelsProviderImpl(project)
ExternalSystemApiUtil.getAllManagers()
.flatMap { dataManager.getExternalProjectsData(project, it.getSystemId()) }
.mapNotNull { it.externalProjectStructure }
.map { ExternalSystemApiUtil.findAllRecursively(it, CONTENT_ROOT) }
.forEach {
service.importData(it, null, project, modifiableModelsProvider)
}
}
finally {
ExternalSystemApiUtil.doWriteAction { modifiableModelsProvider?.commit() }
}
}
}
}
| apache-2.0 | 88f713c233948e9250ba9ed715525287 | 43.978261 | 140 | 0.771387 | 5.360104 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/adventofcode/day6/Part2.kt | 1 | 857 | package katas.kotlin.adventofcode.day6
import java.io.*
fun main() {
val lines = File("src/katas/kotlin/adventofcode/day6/input.txt").readLines()
val treeById = HashMap<String, Tree>()
lines.forEach { line ->
val (parentId, childId) = line.split(")")
val parent = treeById.getOrPut(parentId) { Tree(parentId) }
val child = treeById.getOrPut(childId) { Tree(childId) }
parent.children.add(child)
}
var pathToYOU: List<Tree> = emptyList()
var pathToSAN: List<Tree> = emptyList()
treeById["COM"]!!.traverse { path, id ->
if (id == "YOU") pathToYOU = path
if (id == "SAN") pathToSAN = path
}
val prefix = pathToYOU.zip(pathToSAN).takeWhile { it.first == it.second }
val distance = (pathToYOU.size - prefix.size) + (pathToSAN.size - prefix.size)
println(distance)
}
| unlicense | 40c1b7dbc822204be96ff2b2b4cc697e | 33.28 | 82 | 0.631272 | 3.616034 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-api/src/com/intellij/openapi/observable/properties/transformations.kt | 5 | 3736 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.observable.properties
import com.intellij.openapi.Disposable
import org.jetbrains.annotations.ApiStatus
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform(transform, { it })", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <T> GraphProperty<T>.map(transform: (T) -> T) = transform(transform, { it })
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform({ it }, transform)", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <T> GraphProperty<T>.comap(transform: (T) -> T) = transform({ it }, transform)
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform(map, comap)", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <S, T> GraphProperty<S>.transform(map: (S) -> T, comap: (T) -> S): GraphProperty<T> =
GraphPropertyView(this, map, comap)
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform(transform, { it })", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <T> ObservableMutableProperty<T>.map(transform: (T) -> T) = transform(transform, { it })
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform({ it }, transform)", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <T> ObservableMutableProperty<T>.comap(transform: (T) -> T) = transform({ it }, transform)
@Deprecated("Use transformations from PropertyOperationUtil",
ReplaceWith("transform(map, comap)", "com.intellij.openapi.observable.util.transform"))
@ApiStatus.ScheduledForRemoval
fun <S, T> ObservableMutableProperty<S>.transform(map: (S) -> T, comap: (T) -> S): ObservableMutableProperty<T> =
ObservableMutablePropertyView(this, map, comap)
@Suppress("DEPRECATION")
private class GraphPropertyView<S, T>(
private val instance: GraphProperty<S>,
map: (S) -> T,
private val comap: (T) -> S
) : GraphProperty<T>, ObservableMutablePropertyView<S, T>(instance, map, comap) {
override fun dependsOn(parent: ObservableProperty<*>, update: () -> T) =
instance.dependsOn(parent) { comap(update()) }
override fun afterPropagation(listener: () -> Unit) =
instance.afterPropagation(listener)
override fun afterPropagation(parentDisposable: Disposable?, listener: () -> Unit) =
instance.afterPropagation(parentDisposable, listener)
override fun reset() =
instance.reset()
override fun afterReset(listener: () -> Unit) =
instance.afterReset(listener)
override fun afterReset(listener: () -> Unit, parentDisposable: Disposable) =
instance.afterReset(listener, parentDisposable)
}
private open class ObservableMutablePropertyView<S, T>(
private val instance: ObservableMutableProperty<S>,
private val map: (S) -> T,
private val comap: (T) -> S
) : ObservableMutableProperty<T> {
override fun get(): T =
map(instance.get())
override fun set(value: T) =
instance.set(comap(value))
override fun afterChange(listener: (T) -> Unit) =
instance.afterChange { listener(map(it)) }
override fun afterChange(listener: (T) -> Unit, parentDisposable: Disposable) =
instance.afterChange({ listener(map(it)) }, parentDisposable)
override fun equals(other: Any?): Boolean {
if (this === other) return true
return instance == other
}
override fun hashCode(): Int {
return instance.hashCode()
}
} | apache-2.0 | 1258c1294cc0c6fcff9b200647a46557 | 40.988764 | 140 | 0.725107 | 4.221469 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/ProductImagesRecyclerAdapter.kt | 1 | 2268 | package com.tungnui.dalatlaptop.ux.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.views.ResizableImageViewHeight
import com.tungnui.dalatlaptop.models.Image
import com.tungnui.dalatlaptop.utils.inflate
import com.tungnui.dalatlaptop.utils.loadImg
import kotlinx.android.synthetic.main.list_item_product_image.view.*
class ProductImagesRecyclerAdapter(val listener: (Int) -> Unit): RecyclerView.Adapter<ProductImagesRecyclerAdapter.ViewHolder>() {
private val productImages: MutableList<Image>
init {
productImages = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductImagesRecyclerAdapter.ViewHolder {
return ViewHolder(parent.inflate(R.layout.list_item_product_image))
}
override fun onBindViewHolder(holder: ProductImagesRecyclerAdapter.ViewHolder, position: Int) {
holder.blind(productImages[position],listener)
}
private fun getItem(position: Int): Image {
return productImages[position]
}
override fun getItemCount(): Int {
return productImages.size
}
fun add(position: Int, productImage: Image) {
productImages.add(position, productImage)
notifyItemInserted(position)
}
fun addAll(items:List<Image>){
productImages.addAll(items)
notifyDataSetChanged()
}
fun addLast(productImageUrl: Image) {
productImages.add(productImages.size, productImageUrl)
notifyItemInserted(productImages.size)
}
fun clearAll() {
val itemCount = productImages.size
if (itemCount > 0) {
productImages.clear()
notifyItemRangeRemoved(0, itemCount)
}
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
internal var position: Int = 0
fun blind(image:Image,listener: (Int) -> Unit)=with(itemView){
(list_item_product_images_view as ResizableImageViewHeight).loadImg(image.src)
setOnClickListener { listener(position) }
}
fun setPosition(position: Int) {
this.position = position
}
}
} | mit | 832f19b130c01d11917b67a1e69387bc | 30.082192 | 130 | 0.70194 | 4.56338 | false | false | false | false |
MarkusAmshove/Kluent | jvm/src/main/kotlin/org/amshove/kluent/BasicBacktick.kt | 1 | 3072 | package org.amshove.kluent
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.reflect.KClass
@Deprecated("Use `should be equal to`", ReplaceWith("this.`should be equal to`(expected)"))
infix fun <T> T.`should equal`(expected: T?): T = this.`should be equal to`(expected)
infix fun <T> T.`should be equal to`(expected: T?): T = this.shouldBeEqualTo(expected)
@Deprecated("Use `should not be equal to`", ReplaceWith("this.`should not be equal to`(expected)"))
infix fun <T> T.`should not equal`(expected: T?) = this.`should not be equal to`(expected)
infix fun <T> T.`should not be equal to`(expected: T?) = this.shouldNotBeEqualTo(expected)
infix fun <T> T.`should be`(expected: T?) = this.shouldBe(expected)
infix fun Any?.`should not be`(expected: Any?) = this.shouldNotBe(expected)
infix fun Any?.`should be instance of`(className: Class<*>) = this.shouldBeInstanceOf(className)
infix fun Any?.`should be instance of`(className: KClass<*>) = this.shouldBeInstanceOf(className)
inline fun <reified T : Any> Any?.`should be instance of`() = this.shouldBeInstanceOf<T>()
infix fun Any?.`should not be instance of`(className: Class<*>) = this.shouldNotBeInstanceOf(className)
infix fun Any?.`should not be instance of`(className: KClass<*>) = this.shouldNotBeInstanceOf(className)
inline fun <reified T : Any> Any?.`should not be instance of`() = this.shouldNotBeInstanceOf<T>()
fun Any?.`should be null`() = this.shouldBeNull()
@UseExperimental(ExperimentalContracts::class)
fun <T : Any> T?.`should not be null`(): T {
contract {
returns() implies (this@`should not be null` != null)
}
return this.shouldNotBeNull()
}
@UseExperimental(ExperimentalContracts::class)
fun Boolean.`should be true`(): Boolean {
contract {
returns() implies this@`should be true`
}
return this.shouldBeTrue()
}
@UseExperimental(ExperimentalContracts::class)
fun Boolean.`should be false`(): Boolean {
contract {
returns() implies !this@`should be false`
}
return this.shouldBeFalse()
}
@UseExperimental(ExperimentalContracts::class)
fun Boolean.`should not be true`(): Boolean {
contract {
returns() implies !this@`should not be true`
}
return this.shouldBeFalse()
}
@UseExperimental(ExperimentalContracts::class)
fun Boolean.`should not be false`(): Boolean {
contract {
returns() implies this@`should not be false`
}
return this.shouldBeTrue()
}
fun Char.`should be digit`(): Char = this.shouldBeDigit()
fun Char.`should not be digit`(): Char = this.shouldNotBeDigit()
@ExperimentalStdlibApi
infix fun <T : Any> T.`should be equivalent to`(expected: Pair<T, ((EquivalencyAssertionOptions) -> EquivalencyAssertionOptions)?>): T =
this.shouldBeEquivalentTo(expected.first, expected.second)
@ExperimentalStdlibApi
infix fun <T : Any> T.`should not be equivalent to`(expected: Pair<T, ((EquivalencyAssertionOptions) -> EquivalencyAssertionOptions)?>): T =
this.shouldNotBeEquivalentTo(expected.first, expected.second)
| mit | 2225da0826815a3266722ed15dd333d7 | 33.133333 | 140 | 0.716471 | 3.994798 | false | false | false | false |
zanata/zanata-platform | server/services/src/main/java/org/zanata/security/SamlAttributes.kt | 1 | 3574 | /*
* Copyright 2017, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.security
import io.undertow.security.idm.Account
import org.apache.deltaspike.core.api.common.DeltaSpike
import org.picketlink.common.constants.GeneralConstants.SESSION_ATTRIBUTE_MAP
import org.picketlink.identity.federation.bindings.wildfly.sp.SPFormAuthenticationMechanism.FORM_ACCOUNT_NOTE
import org.zanata.security.annotations.SAML
import org.zanata.security.annotations.SAMLAttribute
import org.zanata.security.annotations.SAMLAttribute.AttributeName.UID
import org.zanata.security.annotations.SAMLAttribute.AttributeName.CN
import org.zanata.security.annotations.SAMLAttribute.AttributeName.EMAIL
import java.security.Principal
import javax.enterprise.inject.Produces
import javax.inject.Inject
import javax.servlet.http.HttpSession
/**
* @author Patrick Huang [[email protected]](mailto:[email protected])
*/
open class SamlAttributes @Inject constructor(@DeltaSpike private val session: HttpSession) {
open val isAuthenticated get() = principalFromSAMLResponse() != null
@Suppress("UNCHECKED_CAST")
private val attributeMap: Map<String, List<String>> =
session.getAttribute(SESSION_ATTRIBUTE_MAP) as? Map<String, List<String>> ?: mapOf()
@Produces
@SAML
fun principalFromSAMLResponse(): Principal? {
val account = session.getAttribute(FORM_ACCOUNT_NOTE) as? Account
if (account != null && account.roles.contains("authenticated")) {
return account.principal
}
return null
}
@Produces
@SAMLAttribute(UID)
fun usernameFromSAMLResponse(@SAML principal: Principal?): String? {
if (principal == null) return null
val principalName = principal.name
// In some IDPs, this may be a more readable username than principal name.
return getValueFromSessionAttribute(attributeMap, UID.key, defaultVal = principalName)
}
@Produces
@SAMLAttribute(CN)
fun commonNameFromSAMLResponse(@SAML principal: Principal?): String? {
if (principal == null) return null
return getValueFromSessionAttribute(attributeMap, CN.key)
}
@Produces
@SAMLAttribute(EMAIL)
fun emailFromSAMLResponse(@SAML principal: Principal?): String? {
if (principal == null) return null
return getValueFromSessionAttribute(attributeMap, EMAIL.key)
}
companion object {
private fun getValueFromSessionAttribute(
map: Map<String, List<String>?>,
key: String,
defaultVal: String = "") =
map[key]?.elementAtOrNull(0) ?: defaultVal
}
}
| lgpl-2.1 | 293774a5f98de0414c4851484b9b592b | 39.157303 | 109 | 0.728036 | 4.219599 | false | false | false | false |
zanata/zanata-platform | server/services/src/main/java/org/zanata/rest/service/ExportRestService.kt | 1 | 3700 | /*
* Copyright 2018, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 2.1 of the License, or (at your option)
* any later version.
*
* This software 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 software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.rest.service
import javax.enterprise.context.RequestScoped
import javax.inject.Inject
import javax.ws.rs.Consumes
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import org.zanata.seam.security.CurrentUser
import org.zanata.service.GraphQLService
import org.zanata.util.toJson
import javax.ws.rs.GET
/**
* @author Alex Eng [[email protected]](mailto:[email protected]),
* Sean Flanigan [[email protected]](mailto:[email protected])
*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RequestScoped
@Path("/export")
class ExportRestService @Inject constructor(
private val currentUser: CurrentUser,
private val graphQLService: GraphQLService) {
@GET
@Path("/userData")
fun exportUserData(): Response {
if (!currentUser.isLoggedIn) {
return Response.status(Response.Status.UNAUTHORIZED).build()
}
val graphqlQuery = """
{
account (username: "${currentUser.username}") {
username
creationDate
lastChanged
enabled
roles { name }
person {
name
email
# global language teams
languageTeamMemberships {
locale { localeId }
isCoordinator
isReviewer
isTranslator
}
# project language teams
projectLocaleMemberships {
project {
slug
name
# no projectIterations
}
locale { localeId }
role
}
# project maintainer/owner or translation maintainer
projectMemberships {
project {
slug
name
projectIterations { slug }
}
role
}
}
}
}""".trimIndent()
// println(graphqlQuery)
val result = graphQLService.query(graphqlQuery)
if (!result.errors.isEmpty()) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(result.errors).build()
}
val data = result.toSpecification()["data"]!!
@Suppress("UNCHECKED_CAST")
val json = toJson(data as Map<String, Any>, pretty = true)
return Response.ok(json).build()
}
}
| lgpl-2.1 | 63ec3e98589bfad8e22a0962e381757a | 32.636364 | 81 | 0.581892 | 4.842932 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/attributes/CellStyle.kt | 1 | 1130 | package com.planbase.pdf.lm2.attributes
/**
* Holds the immutable style information for a cell.
* @param align the horizontal and vertical alignment
* @param boxStyle the padding, background-color, and border
* @param debuggingName this is an optional field that only affects the toString() representation, giving the style
* a name and suppressing the more detailed information (for briefer debugging).
*/
data class CellStyle
@JvmOverloads constructor(
val align: Align,
val boxStyle: BoxStyle,
val debuggingName: String? = null) {
/**
* Returns a new immutable CellStyle with the given Alignment and the current boxStyle (but not debuggingName).
*/
fun withAlign(a: Align) = CellStyle(a, boxStyle)
override fun toString() = debuggingName ?: "CellStyle($align, $boxStyle)"
companion object {
/**
* A CellStyle with [Align.TOP_LEFT], [BoxStyle.NO_PAD_NO_BORDER], and debuggingName="TOP_LEFT_BORDERLESS".
*/
@JvmField
val TOP_LEFT_BORDERLESS = CellStyle(Align.TOP_LEFT, BoxStyle.NO_PAD_NO_BORDER, "TOP_LEFT_BORDERLESS")
}
}
| agpl-3.0 | 1a55a663a30b8057002f0d725a5f4d3e | 36.666667 | 115 | 0.69292 | 4.23221 | false | false | false | false |
google/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/hierarchyOfEntities/after/gen/ChildEntityImpl.kt | 1 | 7263 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Open
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildEntityImpl(val dataSource: ChildEntityData) : ChildEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data1: String
get() = dataSource.data1
override val data2: String
get() = dataSource.data2
override val data3: String
get() = dataSource.data3
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildEntityData?) : ModifiableWorkspaceEntityBase<ChildEntity>(), ChildEntity.Builder {
constructor() : this(ChildEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isData1Initialized()) {
error("Field GrandParentEntity#data1 should be initialized")
}
if (!getEntityData().isData2Initialized()) {
error("Field ParentEntity#data2 should be initialized")
}
if (!getEntityData().isData3Initialized()) {
error("Field ChildEntity#data3 should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildEntity
this.entitySource = dataSource.entitySource
this.data1 = dataSource.data1
this.data2 = dataSource.data2
this.data3 = dataSource.data3
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data1: String
get() = getEntityData().data1
set(value) {
checkModificationAllowed()
getEntityData().data1 = value
changedProperty.add("data1")
}
override var data2: String
get() = getEntityData().data2
set(value) {
checkModificationAllowed()
getEntityData().data2 = value
changedProperty.add("data2")
}
override var data3: String
get() = getEntityData().data3
set(value) {
checkModificationAllowed()
getEntityData().data3 = value
changedProperty.add("data3")
}
override fun getEntityData(): ChildEntityData = result ?: super.getEntityData() as ChildEntityData
override fun getEntityClass(): Class<ChildEntity> = ChildEntity::class.java
}
}
class ChildEntityData : WorkspaceEntityData<ChildEntity>() {
lateinit var data1: String
lateinit var data2: String
lateinit var data3: String
fun isData1Initialized(): Boolean = ::data1.isInitialized
fun isData2Initialized(): Boolean = ::data2.isInitialized
fun isData3Initialized(): Boolean = ::data3.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildEntity> {
val modifiable = ChildEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildEntity {
return getCached(snapshot) {
val entity = ChildEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildEntity(data1, data2, data3, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildEntityData
if (this.entitySource != other.entitySource) return false
if (this.data1 != other.data1) return false
if (this.data2 != other.data2) return false
if (this.data3 != other.data3) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildEntityData
if (this.data1 != other.data1) return false
if (this.data2 != other.data2) return false
if (this.data3 != other.data3) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data1.hashCode()
result = 31 * result + data2.hashCode()
result = 31 * result + data3.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data1.hashCode()
result = 31 * result + data2.hashCode()
result = 31 * result + data3.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 179d05489ebb664dde8e32e5ebe2dc84 | 30.171674 | 115 | 0.707972 | 4.988324 | false | false | false | false |
google/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddModifierFix.kt | 2 | 6408 | // 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.FileModifier.SafeFieldForPreview
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.quickFixesPsiBasedFactory
import org.jetbrains.kotlin.idea.inspections.KotlinUniversalQuickFix
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
open class AddModifierFix(
element: KtModifierListOwner,
@SafeFieldForPreview
protected val modifier: KtModifierKeywordToken
) : KotlinCrossLanguageQuickFixAction<KtModifierListOwner>(element), KotlinUniversalQuickFix {
override fun getText(): String {
val element = element ?: return ""
if (modifier in modalityModifiers || modifier in KtTokens.VISIBILITY_MODIFIERS || modifier == KtTokens.CONST_KEYWORD) {
return KotlinBundle.message("fix.add.modifier.text", RemoveModifierFixBase.getElementName(element), modifier.value)
}
return KotlinBundle.message("fix.add.modifier.text.generic", modifier.value)
}
override fun getFamilyName() = KotlinBundle.message("fix.add.modifier.family")
protected fun invokeOnElement(element: KtModifierListOwner?) {
element?.addModifier(modifier)
if (modifier == KtTokens.ABSTRACT_KEYWORD && (element is KtProperty || element is KtNamedFunction)) {
element.containingClass()?.run {
if (!hasModifier(KtTokens.ABSTRACT_KEYWORD) && !hasModifier(KtTokens.SEALED_KEYWORD)) {
addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
if (modifier == KtTokens.NOINLINE_KEYWORD) {
element?.removeModifier(KtTokens.CROSSINLINE_KEYWORD)
}
}
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
val originalElement = element
invokeOnElement(originalElement)
}
// TODO: consider checking if this fix is available by testing if the [element] can be refactored by calling
// FIR version of [org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtilKt#canRefactor]
override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean = element != null
interface Factory<T : AddModifierFix> {
fun createFactory(modifier: KtModifierKeywordToken): QuickFixesPsiBasedFactory<PsiElement> {
return createFactory(modifier, KtModifierListOwner::class.java)
}
fun <T : KtModifierListOwner> createFactory(
modifier: KtModifierKeywordToken,
modifierOwnerClass: Class<T>
): QuickFixesPsiBasedFactory<PsiElement> {
return quickFixesPsiBasedFactory { e ->
val modifierListOwner =
PsiTreeUtil.getParentOfType(e, modifierOwnerClass, false) ?: return@quickFixesPsiBasedFactory emptyList()
listOfNotNull(createIfApplicable(modifierListOwner, modifier))
}
}
fun createIfApplicable(modifierListOwner: KtModifierListOwner, modifier: KtModifierKeywordToken): T? {
when (modifier) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD -> {
if (modifierListOwner is KtObjectDeclaration) return null
if (modifierListOwner is KtEnumEntry) return null
if (modifierListOwner is KtDeclaration && modifierListOwner !is KtClass) {
val parentClassOrObject = modifierListOwner.containingClassOrObject ?: return null
if (parentClassOrObject is KtObjectDeclaration) return null
if (parentClassOrObject is KtEnumEntry) return null
}
if (modifier == KtTokens.ABSTRACT_KEYWORD
&& modifierListOwner is KtClass
&& modifierListOwner.hasModifier(KtTokens.INLINE_KEYWORD)
) return null
}
KtTokens.INNER_KEYWORD -> {
if (modifierListOwner is KtObjectDeclaration) return null
if (modifierListOwner is KtClass) {
if (modifierListOwner.isInterface() ||
modifierListOwner.isSealed() ||
modifierListOwner.isEnum() ||
modifierListOwner.isData() ||
modifierListOwner.isAnnotation()
) return null
}
}
}
return createModifierFix(modifierListOwner, modifier)
}
fun createModifierFix(element: KtModifierListOwner, modifier: KtModifierKeywordToken): T
}
companion object : Factory<AddModifierFix> {
val addAbstractModifier = AddModifierFix.createFactory(KtTokens.ABSTRACT_KEYWORD)
val addAbstractToContainingClass = AddModifierFix.createFactory(KtTokens.ABSTRACT_KEYWORD, KtClassOrObject::class.java)
val addOpenToContainingClass = AddModifierFix.createFactory(KtTokens.OPEN_KEYWORD, KtClassOrObject::class.java)
val addFinalToProperty = AddModifierFix.createFactory(KtTokens.FINAL_KEYWORD, KtProperty::class.java)
val addInnerModifier = createFactory(KtTokens.INNER_KEYWORD)
val addOverrideModifier = createFactory(KtTokens.OVERRIDE_KEYWORD)
val modifiersWithWarning: Set<KtModifierKeywordToken> = setOf(KtTokens.ABSTRACT_KEYWORD, KtTokens.FINAL_KEYWORD)
private val modalityModifiers = modifiersWithWarning + KtTokens.OPEN_KEYWORD
override fun createModifierFix(element: KtModifierListOwner, modifier: KtModifierKeywordToken): AddModifierFix =
AddModifierFix(element, modifier)
}
}
| apache-2.0 | 1662407f215decc4db64b34ef390b5cf | 50.677419 | 158 | 0.687266 | 5.630931 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt | 5 | 4717 | // 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.codeInsight.generate
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.TestActionEvent
import junit.framework.ComparisonFailure
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.base.platforms.forcedTargetPlatform
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
abstract class AbstractCodeInsightActionTest : KotlinLightCodeInsightFixtureTestCase() {
protected open fun createAction(fileText: String): CodeInsightAction {
val actionClassName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// ACTION_CLASS: ")
return Class.forName(actionClassName).newInstance() as CodeInsightAction
}
protected open fun configure(mainFilePath: String, mainFileText: String) {
myFixture.configureByFile(mainFilePath) as KtFile
}
protected open fun checkExtra() {
}
protected open fun testAction(action: AnAction, forced: Boolean): Presentation {
val e = TestActionEvent(action)
if (ActionUtil.lastUpdateAndCheckDumb(action, e, true) || forced) {
ActionUtil.performActionDumbAwareWithCallbacks(action,e)
}
return e.presentation
}
protected open fun doTest(path: String) {
val fileText = FileUtil.loadFile(dataFile(), true)
val conflictFile = File("$path.messages")
val afterFile = File("$path.after")
var mainPsiFile: KtFile? = null
try {
ConfigLibraryUtil.configureLibrariesByDirective(module, fileText)
val mainFile = dataFile()
val mainFileName = mainFile.name
val fileNameBase = mainFile.nameWithoutExtension + "."
val rootDir = mainFile.parentFile
rootDir
.list { _, name ->
name.startsWith(fileNameBase) && name != mainFileName && (name.endsWith(".kt") || name.endsWith(".java"))
}
.forEach {
myFixture.configureByFile(it)
}
configure(fileName(), fileText)
mainPsiFile = myFixture.file as KtFile
val targetPlatformName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// PLATFORM: ")
if (targetPlatformName != null) {
val targetPlatform = when (targetPlatformName) {
"JVM" -> JvmPlatforms.unspecifiedJvmPlatform
"JavaScript" -> JsPlatforms.defaultJsPlatform
"Common" -> CommonPlatforms.defaultCommonPlatform
else -> error("Unexpected platform name: $targetPlatformName")
}
mainPsiFile.forcedTargetPlatform = targetPlatform
}
val action = createAction(fileText)
val isApplicableExpected = !InTextDirectivesUtils.isDirectiveDefined(fileText, "// NOT_APPLICABLE")
val isForced = InTextDirectivesUtils.isDirectiveDefined(fileText, "// FORCED")
val presentation = testAction(action, isForced)
if (!isForced) {
TestCase.assertEquals(isApplicableExpected, presentation.isEnabled)
}
assert(!conflictFile.exists()) { "Conflict file $conflictFile should not exist" }
if (isForced || isApplicableExpected) {
TestCase.assertTrue(afterFile.exists())
myFixture.checkResult(FileUtil.loadFile(afterFile, true))
checkExtra()
}
} catch (e: ComparisonFailure) {
KotlinTestUtils.assertEqualsToFile(afterFile, myFixture.editor)
} catch (e: CommonRefactoringUtil.RefactoringErrorHintException) {
KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!)
} finally {
mainPsiFile?.forcedTargetPlatform = null
ConfigLibraryUtil.unconfigureLibrariesByDirective(module, fileText)
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
| apache-2.0 | 719f50b1df2f4f59b007955dc5143586 | 41.881818 | 125 | 0.683061 | 5.57565 | false | true | false | false |
google/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/BundledRuntimeImpl.kt | 2 | 7736 | // 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.intellij.build.impl
import com.intellij.diagnostic.telemetry.use
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.NioFiles
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader
import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions
import org.jetbrains.intellij.build.dependencies.DependenciesProperties
import java.net.URI
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.DosFileAttributeView
import java.nio.file.attribute.PosixFilePermission.*
import java.util.*
import java.util.zip.GZIPInputStream
class BundledRuntimeImpl(
private val options: BuildOptions,
private val paths: BuildPaths,
private val dependenciesProperties: DependenciesProperties,
private val error: (String) -> Unit,
private val info: (String) -> Unit) : BundledRuntime {
companion object {
@JvmStatic
fun getProductPrefix(context: BuildContext): String {
return context.options.bundledRuntimePrefix ?: context.productProperties.runtimeDistribution.artifactPrefix
}
}
private val build by lazy {
options.bundledRuntimeBuild ?: dependenciesProperties.property("runtimeBuild")
}
override fun getHomeForCurrentOsAndArch(): Path {
var prefix = "jbr_jcef-"
val os = OsFamily.currentOs
val arch = JvmArchitecture.currentJvmArch
if (System.getProperty("intellij.build.jbr.setupSdk", "false").toBoolean()) {
// required as a runtime for debugger tests
prefix = "jbrsdk-"
}
else {
options.bundledRuntimePrefix?.let {
prefix = it
}
}
val path = extract(prefix, os, arch)
val home = if (os == OsFamily.MACOS) path.resolve("jbr/Contents/Home") else path.resolve("jbr")
val releaseFile = home.resolve("release")
if (!Files.exists(releaseFile)) {
throw IllegalStateException("Unable to find release file $releaseFile after extracting JBR at $path")
}
return home
}
// contract: returns a directory, where only one subdirectory is available: 'jbr', which contains specified JBR
override fun extract(prefix: String, os: OsFamily, arch: JvmArchitecture): Path {
val targetDir = paths.communityHomeDir.communityRoot.resolve("build/download/${prefix}${build}-${os.jbrArchiveSuffix}-$arch")
val jbrDir = targetDir.resolve("jbr")
val archive = findArchive(prefix, os, arch)
BuildDependenciesDownloader.extractFile(
archive, jbrDir,
paths.communityHomeDir,
BuildDependenciesExtractOptions.STRIP_ROOT,
)
fixPermissions(jbrDir, os == OsFamily.WINDOWS)
val releaseFile = if (os == OsFamily.MACOS) jbrDir.resolve("Contents/Home/release") else jbrDir.resolve("release")
if (!Files.exists(releaseFile)) {
throw IllegalStateException("Unable to find release file $releaseFile after extracting JBR at $archive")
}
return targetDir
}
override fun extractTo(prefix: String, os: OsFamily, destinationDir: Path, arch: JvmArchitecture) {
doExtract(findArchive(prefix, os, arch), destinationDir, os)
}
private fun findArchive(prefix: String, os: OsFamily, arch: JvmArchitecture): Path {
val archiveName = archiveName(prefix, arch, os)
val url = URI("https://cache-redirector.jetbrains.com/intellij-jbr/$archiveName")
return BuildDependenciesDownloader.downloadFileToCacheLocation(paths.communityHomeDir, url)
}
/**
* Update this method together with:
* [com.intellij.remoteDev.downloader.CodeWithMeClientDownloader.downloadClientAndJdk]
* [UploadingAndSigning.getMissingJbrs]
* [org.jetbrains.intellij.build.dependencies.JdkDownloader.getUrl]
*/
override fun archiveName(prefix: String, arch: JvmArchitecture, os: OsFamily, forceVersionWithUnderscores: Boolean): String {
val split = build.split('b')
if (split.size != 2) {
throw IllegalArgumentException("$build doesn't match '<update>b<build_number>' format (e.g.: 17.0.2b387.1)")
}
val version = if (forceVersionWithUnderscores) split[0].replace(".", "_") else split[0]
val buildNumber = "b${split[1]}"
val archSuffix = getArchSuffix(arch)
return "${prefix}${version}-${os.jbrArchiveSuffix}-${archSuffix}-${runtimeBuildPrefix()}${buildNumber}.tar.gz"
}
private fun runtimeBuildPrefix(): String {
if (!options.runtimeDebug) {
return ""
}
if (!options.isTestBuild && !options.isInDevelopmentMode) {
error("Either test or development mode is required to use fastdebug runtime build")
}
info("Fastdebug runtime build is requested")
return "fastdebug-"
}
/**
* When changing this list of patterns, also change patch_bin_file in launcher.sh (for remote dev)
*/
override fun executableFilesPatterns(os: OsFamily): List<String> {
val pathPrefix = if (os == OsFamily.MACOS) "jbr/Contents/Home/" else "jbr/"
@Suppress("SpellCheckingInspection")
val executableFilesPatterns = mutableListOf(
pathPrefix + "bin/*",
pathPrefix + "lib/jexec",
pathPrefix + "lib/jspawnhelper",
pathPrefix + "lib/chrome-sandbox"
)
if (os == OsFamily.LINUX) {
executableFilesPatterns += "jbr/lib/jcef_helper"
}
return executableFilesPatterns
}
}
private fun getArchSuffix(arch: JvmArchitecture): String {
return when (arch) {
JvmArchitecture.x64 -> "x64"
JvmArchitecture.aarch64 -> "aarch64"
}
}
private fun doExtract(archive: Path, destinationDir: Path, os: OsFamily) {
TraceManager.spanBuilder("extract JBR")
.setAttribute("archive", archive.toString())
.setAttribute("os", os.osName)
.setAttribute("destination", destinationDir.toString())
.use {
NioFiles.deleteRecursively(destinationDir)
unTar(archive, destinationDir)
fixPermissions(destinationDir, os == OsFamily.WINDOWS)
}
}
private fun unTar(archive: Path, destination: Path) {
// CompressorStreamFactory requires stream with mark support
val rootDir = createTarGzInputStream(archive).use {
it.nextTarEntry?.name
}
if (rootDir == null) {
throw IllegalStateException("Unable to detect root dir of $archive")
}
ArchiveUtils.unTar(archive, destination, if (rootDir.startsWith("jbr")) rootDir else null)
}
private fun createTarGzInputStream(archive: Path): TarArchiveInputStream {
return TarArchiveInputStream(GZIPInputStream(Files.newInputStream(archive), 64 * 1024))
}
private fun fixPermissions(destinationDir: Path, forWin: Boolean) {
val exeOrDir = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_EXECUTE, OTHERS_READ, OTHERS_EXECUTE)
val regular = EnumSet.of(OWNER_READ, OWNER_WRITE, GROUP_READ, OTHERS_READ)
Files.walkFileTree(destinationDir, object : SimpleFileVisitor<Path>() {
@Override
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
if (dir != destinationDir && SystemInfoRt.isUnix) {
Files.setPosixFilePermissions(dir, exeOrDir)
}
return FileVisitResult.CONTINUE
}
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (SystemInfoRt.isUnix) {
val noExec = forWin || OWNER_EXECUTE !in Files.getPosixFilePermissions(file)
Files.setPosixFilePermissions(file, if (noExec) regular else exeOrDir)
}
else {
Files.getFileAttributeView(file, DosFileAttributeView::class.java).setReadOnly(false)
}
return FileVisitResult.CONTINUE
}
})
} | apache-2.0 | 9264b886fc9c8d5ecc3591049f7d7123 | 37.879397 | 129 | 0.727378 | 4.353405 | false | false | false | false |
google/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/AbstractFeatureSuggester.kt | 5 | 3058 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.featuresSuggester.suggesters
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import org.jetbrains.annotations.Nls
import training.featuresSuggester.*
import training.featuresSuggester.settings.FeatureSuggesterSettings
import java.util.concurrent.TimeUnit
abstract class AbstractFeatureSuggester : FeatureSuggester {
protected open val suggestingTipFileName: String? = null
protected open val suggestingDocUrl: String? = null
protected abstract val message: String
protected abstract val suggestingActionId: String
/**
* There are following conditions that must be met to show suggestion:
* 1. The suggesting action must not have been used during the last [minSuggestingIntervalDays] working days
* 2. This suggestion must not have been shown during the last 24 hours
*/
override fun isSuggestionNeeded() = !isSuggestingActionUsedRecently() && !isSuggestionShownRecently()
private fun isSuggestingActionUsedRecently(): Boolean {
val summary = service<ActionsLocalSummary>().getActionStatsById(suggestingActionId) ?: return false
val lastTimeUsed = summary.lastUsedTimestamp
val oldestWorkingDayStart = FeatureSuggesterSettings.instance().getOldestWorkingDayStartMillis(minSuggestingIntervalDays)
return lastTimeUsed > oldestWorkingDayStart
}
private fun isSuggestionShownRecently(): Boolean {
val lastTimeShown = FeatureSuggesterSettings.instance().getSuggestionLastShownTime(id)
val delta = System.currentTimeMillis() - lastTimeShown
return delta < TimeUnit.DAYS.toMillis(1L)
}
protected fun createSuggestion(): Suggestion {
if (isRedoOrUndoRunning()) return NoSuggestion
val fullMessage = "$message ${getShortcutText(suggestingActionId)}"
return if (suggestingTipFileName != null) {
TipSuggestion(fullMessage, id, suggestingTipFileName!!)
}
else if (suggestingDocUrl != null) {
DocumentationSuggestion(fullMessage, id, suggestingDocUrl!!)
}
else error("Suggester must implement 'suggestingTipFileName' or 'suggestingDocLink' property.")
}
private fun isRedoOrUndoRunning(): Boolean {
val commandName = CommandProcessor.getInstance().currentCommandName
return commandName != null && (commandName.startsWith(ActionsBundle.message("action.redo.description", ""))
|| commandName.startsWith(ActionsBundle.message("action.undo.description", "")))
}
@Nls
fun getShortcutText(actionId: String): String {
val shortcut = KeymapUtil.getShortcutText(actionId)
return if (shortcut == "<no shortcut>") {
FeatureSuggesterBundle.message("shortcut.not.found.message")
}
else {
FeatureSuggesterBundle.message("shortcut", shortcut)
}
}
}
| apache-2.0 | 6aec7c08ecd8b91db199d77ebbfb8672 | 43.318841 | 125 | 0.768149 | 4.964286 | false | false | false | false |
vhromada/Catalog | web/src/test/kotlin/com/github/vhromada/catalog/web/mapper/MusicMapperTest.kt | 1 | 1341 | package com.github.vhromada.catalog.web.mapper
import com.github.vhromada.catalog.web.CatalogWebMapperTestConfiguration
import com.github.vhromada.catalog.web.utils.MusicUtils
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* A class represents test for mapper for music.
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [CatalogWebMapperTestConfiguration::class])
class MusicMapperTest {
/**
* Instance of [MusicMapper]
*/
@Autowired
private lateinit var mapper: MusicMapper
/**
* Test method for [MusicMapper.map].
*/
@Test
fun map() {
val music = MusicUtils.getMusic()
val result = mapper.map(source = music)
MusicUtils.assertMusicDeepEquals(expected = music, actual = result)
}
/**
* Test method for [MusicMapper.mapRequest].
*/
@Test
fun mapRequest() {
val musicFO = MusicUtils.getMusicFO()
val result = mapper.mapRequest(source = musicFO)
MusicUtils.assertRequestDeepEquals(expected = musicFO, actual = result)
}
}
| mit | 701f3b0dca2eaee12be6777c13e13a5d | 25.82 | 79 | 0.717375 | 4.257143 | false | true | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/EditActivity.kt | 1 | 33848 | package com.simplemobiletools.gallery.pro.activities
import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.Color
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.widget.RelativeLayout
import androidx.exifinterface.media.ExifInterface
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.simplemobiletools.commons.dialogs.ColorPickerDialog
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.pro.BuildConfig
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.adapters.FiltersAdapter
import com.simplemobiletools.gallery.pro.dialogs.OtherAspectRatioDialog
import com.simplemobiletools.gallery.pro.dialogs.ResizeDialog
import com.simplemobiletools.gallery.pro.dialogs.SaveAsDialog
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.copyNonDimensionAttributesTo
import com.simplemobiletools.gallery.pro.extensions.fixDateTaken
import com.simplemobiletools.gallery.pro.extensions.openEditor
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.FilterItem
import com.theartofdev.edmodo.cropper.CropImageView
import com.zomato.photofilters.FilterPack
import com.zomato.photofilters.imageprocessors.Filter
import kotlinx.android.synthetic.main.activity_edit.*
import kotlinx.android.synthetic.main.bottom_actions_aspect_ratio.*
import kotlinx.android.synthetic.main.bottom_editor_actions_filter.*
import kotlinx.android.synthetic.main.bottom_editor_crop_rotate_actions.*
import kotlinx.android.synthetic.main.bottom_editor_draw_actions.*
import kotlinx.android.synthetic.main.bottom_editor_primary_actions.*
import java.io.*
class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
companion object {
init {
System.loadLibrary("NativeImageProcessor")
}
}
private val TEMP_FOLDER_NAME = "images"
private val ASPECT_X = "aspectX"
private val ASPECT_Y = "aspectY"
private val CROP = "crop"
// constants for bottom primary action groups
private val PRIMARY_ACTION_NONE = 0
private val PRIMARY_ACTION_FILTER = 1
private val PRIMARY_ACTION_CROP_ROTATE = 2
private val PRIMARY_ACTION_DRAW = 3
private val CROP_ROTATE_NONE = 0
private val CROP_ROTATE_ASPECT_RATIO = 1
private lateinit var saveUri: Uri
private var uri: Uri? = null
private var resizeWidth = 0
private var resizeHeight = 0
private var drawColor = 0
private var lastOtherAspectRatio: Pair<Float, Float>? = null
private var currPrimaryAction = PRIMARY_ACTION_NONE
private var currCropRotateAction = CROP_ROTATE_ASPECT_RATIO
private var currAspectRatio = ASPECT_RATIO_FREE
private var isCropIntent = false
private var isEditingWithThirdParty = false
private var isSharingBitmap = false
private var wasDrawCanvasPositioned = false
private var oldExif: ExifInterface? = null
private var filterInitialBitmap: Bitmap? = null
private var originalUri: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit)
if (checkAppSideloading()) {
return
}
setupOptionsMenu()
handlePermission(getPermissionToRequest()) {
if (!it) {
toast(R.string.no_storage_permissions)
finish()
}
initEditActivity()
}
}
override fun onResume() {
super.onResume()
isEditingWithThirdParty = false
bottom_draw_width.setColors(getProperTextColor(), getProperPrimaryColor(), getProperBackgroundColor())
setupToolbar(editor_toolbar, NavigationIcon.Arrow)
}
override fun onStop() {
super.onStop()
if (isEditingWithThirdParty) {
finish()
}
}
private fun setupOptionsMenu() {
editor_toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.save_as -> saveImage()
R.id.edit -> editWith()
R.id.share -> shareImage()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
private fun initEditActivity() {
if (intent.data == null) {
toast(R.string.invalid_image_path)
finish()
return
}
uri = intent.data!!
originalUri = uri
if (uri!!.scheme != "file" && uri!!.scheme != "content") {
toast(R.string.unknown_file_location)
finish()
return
}
if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
val realPath = intent.extras!!.getString(REAL_FILE_PATH)
uri = when {
isPathOnOTG(realPath!!) -> uri
realPath.startsWith("file:/") -> Uri.parse(realPath)
else -> Uri.fromFile(File(realPath))
}
} else {
(getRealPathFromURI(uri!!))?.apply {
uri = Uri.fromFile(File(this))
}
}
saveUri = when {
intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true && intent.extras!!.get(MediaStore.EXTRA_OUTPUT) is Uri -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
else -> uri!!
}
isCropIntent = intent.extras?.get(CROP) == "true"
if (isCropIntent) {
bottom_editor_primary_actions.beGone()
(bottom_editor_crop_rotate_actions.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1)
}
loadDefaultImageView()
setupBottomActions()
if (config.lastEditorCropAspectRatio == ASPECT_RATIO_OTHER) {
if (config.lastEditorCropOtherAspectRatioX == 0f) {
config.lastEditorCropOtherAspectRatioX = 1f
}
if (config.lastEditorCropOtherAspectRatioY == 0f) {
config.lastEditorCropOtherAspectRatioY = 1f
}
lastOtherAspectRatio = Pair(config.lastEditorCropOtherAspectRatioX, config.lastEditorCropOtherAspectRatioY)
}
updateAspectRatio(config.lastEditorCropAspectRatio)
crop_image_view.guidelines = CropImageView.Guidelines.ON
bottom_aspect_ratios.beVisible()
}
private fun loadDefaultImageView() {
default_image_view.beVisible()
crop_image_view.beGone()
editor_draw_canvas.beGone()
val options = RequestOptions()
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
Glide.with(this)
.asBitmap()
.load(uri)
.apply(options)
.listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
if (uri != originalUri) {
uri = originalUri
Handler().post {
loadDefaultImageView()
}
}
return false
}
override fun onResourceReady(
bitmap: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
val currentFilter = getFiltersAdapter()?.getCurrentFilter()
if (filterInitialBitmap == null) {
loadCropImageView()
bottomCropRotateClicked()
}
if (filterInitialBitmap != null && currentFilter != null && currentFilter.filter.name != getString(R.string.none)) {
default_image_view.onGlobalLayout {
applyFilter(currentFilter)
}
} else {
filterInitialBitmap = bitmap
}
if (isCropIntent) {
bottom_primary_filter.beGone()
bottom_primary_draw.beGone()
}
return false
}
}).into(default_image_view)
}
private fun loadCropImageView() {
default_image_view.beGone()
editor_draw_canvas.beGone()
crop_image_view.apply {
beVisible()
setOnCropImageCompleteListener(this@EditActivity)
setImageUriAsync(uri)
guidelines = CropImageView.Guidelines.ON
if (isCropIntent && shouldCropSquare()) {
currAspectRatio = ASPECT_RATIO_ONE_ONE
setFixedAspectRatio(true)
bottom_aspect_ratio.beGone()
}
}
}
private fun loadDrawCanvas() {
default_image_view.beGone()
crop_image_view.beGone()
editor_draw_canvas.beVisible()
if (!wasDrawCanvasPositioned) {
wasDrawCanvasPositioned = true
editor_draw_canvas.onGlobalLayout {
ensureBackgroundThread {
fillCanvasBackground()
}
}
}
}
private fun fillCanvasBackground() {
val size = Point()
windowManager.defaultDisplay.getSize(size)
val options = RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.fitCenter()
try {
val builder = Glide.with(applicationContext)
.asBitmap()
.load(uri)
.apply(options)
.into(editor_draw_canvas.width, editor_draw_canvas.height)
val bitmap = builder.get()
runOnUiThread {
editor_draw_canvas.apply {
updateBackgroundBitmap(bitmap)
layoutParams.width = bitmap.width
layoutParams.height = bitmap.height
y = (height - bitmap.height) / 2f
requestLayout()
}
}
} catch (e: Exception) {
showErrorToast(e)
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun saveImage() {
setOldExif()
if (crop_image_view.isVisible()) {
crop_image_view.getCroppedImageAsync()
} else if (editor_draw_canvas.isVisible()) {
val bitmap = editor_draw_canvas.getBitmap()
if (saveUri.scheme == "file") {
SaveAsDialog(this, saveUri.path!!, true) {
saveBitmapToFile(bitmap, it, true)
}
} else if (saveUri.scheme == "content") {
val filePathGetter = getNewFilePath()
SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
saveBitmapToFile(bitmap, it, true)
}
}
} else {
val currentFilter = getFiltersAdapter()?.getCurrentFilter() ?: return
val filePathGetter = getNewFilePath()
SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
toast(R.string.saving)
// clean up everything to free as much memory as possible
default_image_view.setImageResource(0)
crop_image_view.setImageBitmap(null)
bottom_actions_filter_list.adapter = null
bottom_actions_filter_list.beGone()
ensureBackgroundThread {
try {
val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
currentFilter.filter.processFilter(originalBitmap)
saveBitmapToFile(originalBitmap, it, false)
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
}
}
}
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun setOldExif() {
var inputStream: InputStream? = null
try {
if (isNougatPlus()) {
inputStream = contentResolver.openInputStream(uri!!)
oldExif = ExifInterface(inputStream!!)
}
} catch (e: Exception) {
} finally {
inputStream?.close()
}
}
private fun shareImage() {
ensureBackgroundThread {
when {
default_image_view.isVisible() -> {
val currentFilter = getFiltersAdapter()?.getCurrentFilter()
if (currentFilter == null) {
toast(R.string.unknown_error_occurred)
return@ensureBackgroundThread
}
val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
currentFilter.filter.processFilter(originalBitmap)
shareBitmap(originalBitmap)
}
crop_image_view.isVisible() -> {
isSharingBitmap = true
runOnUiThread {
crop_image_view.getCroppedImageAsync()
}
}
editor_draw_canvas.isVisible() -> shareBitmap(editor_draw_canvas.getBitmap())
}
}
}
private fun getTempImagePath(bitmap: Bitmap, callback: (path: String?) -> Unit) {
val bytes = ByteArrayOutputStream()
bitmap.compress(CompressFormat.PNG, 0, bytes)
val folder = File(cacheDir, TEMP_FOLDER_NAME)
if (!folder.exists()) {
if (!folder.mkdir()) {
callback(null)
return
}
}
val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "tmp.jpg"
val newPath = "$folder/$filename"
val fileDirItem = FileDirItem(newPath, filename)
getFileOutputStream(fileDirItem, true) {
if (it != null) {
try {
it.write(bytes.toByteArray())
callback(newPath)
} catch (e: Exception) {
} finally {
it.close()
}
} else {
callback("")
}
}
}
private fun shareBitmap(bitmap: Bitmap) {
getTempImagePath(bitmap) {
if (it != null) {
sharePathIntent(it, BuildConfig.APPLICATION_ID)
} else {
toast(R.string.unknown_error_occurred)
}
}
}
private fun getFiltersAdapter() = bottom_actions_filter_list.adapter as? FiltersAdapter
private fun setupBottomActions() {
setupPrimaryActionButtons()
setupCropRotateActionButtons()
setupAspectRatioButtons()
setupDrawButtons()
}
private fun setupPrimaryActionButtons() {
bottom_primary_filter.setOnClickListener {
bottomFilterClicked()
}
bottom_primary_crop_rotate.setOnClickListener {
bottomCropRotateClicked()
}
bottom_primary_draw.setOnClickListener {
bottomDrawClicked()
}
}
private fun bottomFilterClicked() {
currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_FILTER) {
PRIMARY_ACTION_NONE
} else {
PRIMARY_ACTION_FILTER
}
updatePrimaryActionButtons()
}
private fun bottomCropRotateClicked() {
currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) {
PRIMARY_ACTION_NONE
} else {
PRIMARY_ACTION_CROP_ROTATE
}
updatePrimaryActionButtons()
}
private fun bottomDrawClicked() {
currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_DRAW) {
PRIMARY_ACTION_NONE
} else {
PRIMARY_ACTION_DRAW
}
updatePrimaryActionButtons()
}
private fun setupCropRotateActionButtons() {
bottom_rotate.setOnClickListener {
crop_image_view.rotateImage(90)
}
bottom_resize.beGoneIf(isCropIntent)
bottom_resize.setOnClickListener {
resizeImage()
}
bottom_flip_horizontally.setOnClickListener {
crop_image_view.flipImageHorizontally()
}
bottom_flip_vertically.setOnClickListener {
crop_image_view.flipImageVertically()
}
bottom_aspect_ratio.setOnClickListener {
currCropRotateAction = if (currCropRotateAction == CROP_ROTATE_ASPECT_RATIO) {
crop_image_view.guidelines = CropImageView.Guidelines.OFF
bottom_aspect_ratios.beGone()
CROP_ROTATE_NONE
} else {
crop_image_view.guidelines = CropImageView.Guidelines.ON
bottom_aspect_ratios.beVisible()
CROP_ROTATE_ASPECT_RATIO
}
updateCropRotateActionButtons()
}
}
private fun setupAspectRatioButtons() {
bottom_aspect_ratio_free.setOnClickListener {
updateAspectRatio(ASPECT_RATIO_FREE)
}
bottom_aspect_ratio_one_one.setOnClickListener {
updateAspectRatio(ASPECT_RATIO_ONE_ONE)
}
bottom_aspect_ratio_four_three.setOnClickListener {
updateAspectRatio(ASPECT_RATIO_FOUR_THREE)
}
bottom_aspect_ratio_sixteen_nine.setOnClickListener {
updateAspectRatio(ASPECT_RATIO_SIXTEEN_NINE)
}
bottom_aspect_ratio_other.setOnClickListener {
OtherAspectRatioDialog(this, lastOtherAspectRatio) {
lastOtherAspectRatio = it
config.lastEditorCropOtherAspectRatioX = it.first
config.lastEditorCropOtherAspectRatioY = it.second
updateAspectRatio(ASPECT_RATIO_OTHER)
}
}
updateAspectRatioButtons()
}
private fun setupDrawButtons() {
updateDrawColor(config.lastEditorDrawColor)
bottom_draw_width.progress = config.lastEditorBrushSize
updateBrushSize(config.lastEditorBrushSize)
bottom_draw_color_clickable.setOnClickListener {
ColorPickerDialog(this, drawColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
updateDrawColor(color)
}
}
}
bottom_draw_width.onSeekBarChangeListener {
config.lastEditorBrushSize = it
updateBrushSize(it)
}
bottom_draw_undo.setOnClickListener {
editor_draw_canvas.undo()
}
}
private fun updateBrushSize(percent: Int) {
editor_draw_canvas.updateBrushSize(percent)
val scale = Math.max(0.03f, percent / 100f)
bottom_draw_color.scaleX = scale
bottom_draw_color.scaleY = scale
}
private fun updatePrimaryActionButtons() {
if (crop_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) {
loadCropImageView()
} else if (default_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_FILTER) {
loadDefaultImageView()
} else if (editor_draw_canvas.isGone() && currPrimaryAction == PRIMARY_ACTION_DRAW) {
loadDrawCanvas()
}
arrayOf(bottom_primary_filter, bottom_primary_crop_rotate, bottom_primary_draw).forEach {
it.applyColorFilter(Color.WHITE)
}
val currentPrimaryActionButton = when (currPrimaryAction) {
PRIMARY_ACTION_FILTER -> bottom_primary_filter
PRIMARY_ACTION_CROP_ROTATE -> bottom_primary_crop_rotate
PRIMARY_ACTION_DRAW -> bottom_primary_draw
else -> null
}
currentPrimaryActionButton?.applyColorFilter(getProperPrimaryColor())
bottom_editor_filter_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_FILTER)
bottom_editor_crop_rotate_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE)
bottom_editor_draw_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_DRAW)
if (currPrimaryAction == PRIMARY_ACTION_FILTER && bottom_actions_filter_list.adapter == null) {
ensureBackgroundThread {
val thumbnailSize = resources.getDimension(R.dimen.bottom_filters_thumbnail_size).toInt()
val bitmap = try {
Glide.with(this)
.asBitmap()
.load(uri).listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
showErrorToast(e.toString())
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
) = false
})
.submit(thumbnailSize, thumbnailSize)
.get()
} catch (e: GlideException) {
showErrorToast(e)
finish()
return@ensureBackgroundThread
}
runOnUiThread {
val filterThumbnailsManager = FilterThumbnailsManager()
filterThumbnailsManager.clearThumbs()
val noFilter = Filter(getString(R.string.none))
filterThumbnailsManager.addThumb(FilterItem(bitmap, noFilter))
FilterPack.getFilterPack(this).forEach {
val filterItem = FilterItem(bitmap, it)
filterThumbnailsManager.addThumb(filterItem)
}
val filterItems = filterThumbnailsManager.processThumbs()
val adapter = FiltersAdapter(applicationContext, filterItems) {
val layoutManager = bottom_actions_filter_list.layoutManager as LinearLayoutManager
applyFilter(filterItems[it])
if (it == layoutManager.findLastCompletelyVisibleItemPosition() || it == layoutManager.findLastVisibleItemPosition()) {
bottom_actions_filter_list.smoothScrollBy(thumbnailSize, 0)
} else if (it == layoutManager.findFirstCompletelyVisibleItemPosition() || it == layoutManager.findFirstVisibleItemPosition()) {
bottom_actions_filter_list.smoothScrollBy(-thumbnailSize, 0)
}
}
bottom_actions_filter_list.adapter = adapter
adapter.notifyDataSetChanged()
}
}
}
if (currPrimaryAction != PRIMARY_ACTION_CROP_ROTATE) {
bottom_aspect_ratios.beGone()
currCropRotateAction = CROP_ROTATE_NONE
}
updateCropRotateActionButtons()
}
private fun applyFilter(filterItem: FilterItem) {
val newBitmap = Bitmap.createBitmap(filterInitialBitmap!!)
default_image_view.setImageBitmap(filterItem.filter.processFilter(newBitmap))
}
private fun updateAspectRatio(aspectRatio: Int) {
currAspectRatio = aspectRatio
config.lastEditorCropAspectRatio = aspectRatio
updateAspectRatioButtons()
crop_image_view.apply {
if (aspectRatio == ASPECT_RATIO_FREE) {
setFixedAspectRatio(false)
} else {
val newAspectRatio = when (aspectRatio) {
ASPECT_RATIO_ONE_ONE -> Pair(1f, 1f)
ASPECT_RATIO_FOUR_THREE -> Pair(4f, 3f)
ASPECT_RATIO_SIXTEEN_NINE -> Pair(16f, 9f)
else -> Pair(lastOtherAspectRatio!!.first, lastOtherAspectRatio!!.second)
}
setAspectRatio(newAspectRatio.first.toInt(), newAspectRatio.second.toInt())
}
}
}
private fun updateAspectRatioButtons() {
arrayOf(
bottom_aspect_ratio_free,
bottom_aspect_ratio_one_one,
bottom_aspect_ratio_four_three,
bottom_aspect_ratio_sixteen_nine,
bottom_aspect_ratio_other
).forEach {
it.setTextColor(Color.WHITE)
}
val currentAspectRatioButton = when (currAspectRatio) {
ASPECT_RATIO_FREE -> bottom_aspect_ratio_free
ASPECT_RATIO_ONE_ONE -> bottom_aspect_ratio_one_one
ASPECT_RATIO_FOUR_THREE -> bottom_aspect_ratio_four_three
ASPECT_RATIO_SIXTEEN_NINE -> bottom_aspect_ratio_sixteen_nine
else -> bottom_aspect_ratio_other
}
currentAspectRatioButton.setTextColor(getProperPrimaryColor())
}
private fun updateCropRotateActionButtons() {
arrayOf(bottom_aspect_ratio).forEach {
it.applyColorFilter(Color.WHITE)
}
val primaryActionView = when (currCropRotateAction) {
CROP_ROTATE_ASPECT_RATIO -> bottom_aspect_ratio
else -> null
}
primaryActionView?.applyColorFilter(getProperPrimaryColor())
}
private fun updateDrawColor(color: Int) {
drawColor = color
bottom_draw_color.applyColorFilter(color)
config.lastEditorDrawColor = color
editor_draw_canvas.updateColor(color)
}
private fun resizeImage() {
val point = getAreaSize()
if (point == null) {
toast(R.string.unknown_error_occurred)
return
}
ResizeDialog(this, point) {
resizeWidth = it.x
resizeHeight = it.y
crop_image_view.getCroppedImageAsync()
}
}
private fun shouldCropSquare(): Boolean {
val extras = intent.extras
return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) {
extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y)
} else {
false
}
}
private fun getAreaSize(): Point? {
val rect = crop_image_view.cropRect ?: return null
val rotation = crop_image_view.rotatedDegrees
return if (rotation == 0 || rotation == 180) {
Point(rect.width(), rect.height())
} else {
Point(rect.height(), rect.width())
}
}
override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) {
if (result.error == null) {
setOldExif()
val bitmap = result.bitmap
if (isSharingBitmap) {
isSharingBitmap = false
shareBitmap(bitmap)
return
}
if (isCropIntent) {
if (saveUri.scheme == "file") {
saveBitmapToFile(bitmap, saveUri.path!!, true)
} else {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val stream = ByteArrayOutputStream()
bitmap.compress(CompressFormat.JPEG, 100, stream)
inputStream = ByteArrayInputStream(stream.toByteArray())
outputStream = contentResolver.openOutputStream(saveUri)
inputStream.copyTo(outputStream!!)
} catch (e: Exception) {
showErrorToast(e)
return
} finally {
inputStream?.close()
outputStream?.close()
}
Intent().apply {
data = saveUri
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
setResult(RESULT_OK, this)
}
finish()
}
} else if (saveUri.scheme == "file") {
SaveAsDialog(this, saveUri.path!!, true) {
saveBitmapToFile(bitmap, it, true)
}
} else if (saveUri.scheme == "content") {
val filePathGetter = getNewFilePath()
SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
saveBitmapToFile(bitmap, it, true)
}
} else {
toast(R.string.unknown_file_location)
}
} else {
toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
}
}
private fun getNewFilePath(): Pair<String, Boolean> {
var newPath = applicationContext.getRealPathFromURI(saveUri) ?: ""
if (newPath.startsWith("/mnt/")) {
newPath = ""
}
var shouldAppendFilename = true
if (newPath.isEmpty()) {
val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: ""
if (filename.isNotEmpty()) {
val path =
if (intent.extras?.containsKey(REAL_FILE_PATH) == true) intent.getStringExtra(REAL_FILE_PATH)?.getParentPath() else internalStoragePath
newPath = "$path/$filename"
shouldAppendFilename = false
}
}
if (newPath.isEmpty()) {
newPath = "$internalStoragePath/${getCurrentFormattedDateTime()}.${saveUri.toString().getFilenameExtension()}"
shouldAppendFilename = false
}
return Pair(newPath, shouldAppendFilename)
}
private fun saveBitmapToFile(bitmap: Bitmap, path: String, showSavingToast: Boolean) {
if (!packageName.contains("slootelibomelpmis".reversed(), true)) {
if (baseConfig.appRunCount > 100) {
val label =
"sknahT .moc.slootelibomelpmis.www morf eno lanigiro eht daolnwod ytefas nwo ruoy roF .ppa eht fo noisrev ekaf a gnisu era uoY".reversed()
runOnUiThread {
ConfirmationDialog(this, label, positive = com.simplemobiletools.commons.R.string.ok, negative = 0) {
launchViewIntent("6629852208836920709=di?ved/sppa/erots/moc.elgoog.yalp//:sptth".reversed())
}
}
return
}
}
try {
ensureBackgroundThread {
val file = File(path)
val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
getFileOutputStream(fileDirItem, true) {
if (it != null) {
saveBitmap(file, bitmap, it, showSavingToast)
} else {
toast(R.string.image_editing_failed)
}
}
}
} catch (e: Exception) {
showErrorToast(e)
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream, showSavingToast: Boolean) {
if (showSavingToast) {
toast(R.string.saving)
}
if (resizeWidth > 0 && resizeHeight > 0) {
val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false)
resized.compress(file.absolutePath.getCompressionFormat(), 90, out)
} else {
bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out)
}
try {
if (isNougatPlus()) {
val newExif = ExifInterface(file.absolutePath)
oldExif?.copyNonDimensionAttributesTo(newExif)
}
} catch (e: Exception) {
}
setResult(Activity.RESULT_OK, intent)
scanFinalPath(file.absolutePath)
out.close()
}
private fun editWith() {
openEditor(uri.toString(), true)
isEditingWithThirdParty = true
}
private fun scanFinalPath(path: String) {
val paths = arrayListOf(path)
rescanPaths(paths) {
fixDateTaken(paths, false)
setResult(Activity.RESULT_OK, intent)
toast(R.string.file_saved)
finish()
}
}
}
| gpl-3.0 | f7cc5f35faeb19a0061f734d6d45b6d1 | 35.791304 | 181 | 0.575573 | 5.051186 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineNamedDeclarationProcessor.kt | 1 | 6798 | // 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.refactoring.inline
import com.intellij.lang.Language
import com.intellij.lang.refactoring.InlineHandler
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.refactoring.OverrideMethodsProcessor
import com.intellij.refactoring.inline.GenericInlineHandler
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.replaceUsages
import org.jetbrains.kotlin.idea.base.searching.usages.ReferencesSearchScopeHelper
import org.jetbrains.kotlin.idea.refactoring.pullUp.deleteWithCompanion
import org.jetbrains.kotlin.idea.search.declarationsSearch.findSuperMethodsNoWrapping
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingElement
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtReferenceExpression
abstract class AbstractKotlinInlineNamedDeclarationProcessor<TDeclaration : KtNamedDeclaration>(
declaration: TDeclaration,
private val reference: PsiReference?,
private val inlineThisOnly: Boolean,
private val deleteAfter: Boolean,
editor: Editor?,
project: Project,
) : AbstractKotlinDeclarationInlineProcessor<TDeclaration>(declaration, editor, project) {
private lateinit var inliners: Map<Language, InlineHandler.Inliner>
abstract fun createReplacementStrategy(): UsageReplacementStrategy?
open fun postAction() = Unit
open fun postDeleteAction() = Unit
final override fun findUsages(): Array<UsageInfo> {
if (inlineThisOnly && reference != null) return arrayOf(UsageInfo(reference))
val usages = hashSetOf<UsageInfo>()
for (usage in ReferencesSearchScopeHelper.search(declaration, myRefactoringScope)) {
usages += UsageInfo(usage)
}
if (shouldDeleteAfter) {
declaration.forEachOverridingElement(scope = myRefactoringScope) { _, overridingMember ->
val superMethods = findSuperMethodsNoWrapping(overridingMember)
if (superMethods.singleOrNull()?.unwrapped == declaration) {
usages += OverrideUsageInfo(overridingMember)
return@forEachOverridingElement true
}
true
}
}
return usages.toArray(UsageInfo.EMPTY_ARRAY)
}
open fun additionalPreprocessUsages(usages: Array<out UsageInfo>, conflicts: MultiMap<PsiElement, String>) = Unit
final override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
val usagesInfo = refUsages.get()
if (inlineThisOnly) {
val element = usagesInfo.singleOrNull()?.element
if (element != null && !CommonRefactoringUtil.checkReadOnlyStatus(myProject, element)) return false
}
val conflicts = MultiMap<PsiElement, String>()
additionalPreprocessUsages(usagesInfo, conflicts)
for (usage in usagesInfo) {
val element = usage.element ?: continue
val callableConflict = findCallableConflictForUsage(element) ?: continue
conflicts.putValue(element, callableConflict)
}
if (shouldDeleteAfter) {
for (superDeclaration in findSuperMethodsNoWrapping(declaration)) {
val fqName = superDeclaration.kotlinFqName?.asString() ?: KotlinBundle.message("fix.change.signature.error")
val message = KotlinBundle.message("text.inlined.0.overrides.0.1", kind, fqName)
conflicts.putValue(superDeclaration, message)
}
}
inliners = GenericInlineHandler.initInliners(
declaration,
usagesInfo,
InlineHandler.Settings { inlineThisOnly },
conflicts,
KotlinLanguage.INSTANCE
)
return showConflicts(conflicts, usagesInfo)
}
private val shouldDeleteAfter: Boolean get() = deleteAfter && isWritable
private fun postActions() {
if (shouldDeleteAfter) {
declaration.deleteWithCompanion()
postDeleteAction()
}
postAction()
}
override fun performRefactoring(usages: Array<out UsageInfo>) {
if (usages.isEmpty()) {
if (!shouldDeleteAfter) {
val message = KotlinBundle.message("0.1.is.never.used", kind.capitalize(), declaration.name.toString())
CommonRefactoringUtil.showErrorHint(myProject, editor, message, commandName, null)
} else {
postActions()
}
return
}
val replacementStrategy = createReplacementStrategy() ?: return
val (kotlinReferenceUsages, nonKotlinReferenceUsages) = usages.partition { it !is OverrideUsageInfo && it.element is KtReferenceExpression }
for (usage in nonKotlinReferenceUsages) {
val element = usage.element ?: continue
when {
usage is OverrideUsageInfo -> for (processor in OverrideMethodsProcessor.EP_NAME.extensionList) {
if (processor.removeOverrideAttribute(element)) break
}
element.language == KotlinLanguage.INSTANCE -> LOG.error("Found unexpected Kotlin usage $element")
else -> GenericInlineHandler.inlineReference(usage, declaration, inliners)
}
}
replacementStrategy.replaceUsages(
usages = kotlinReferenceUsages.mapNotNull { it.element as? KtReferenceExpression }
)
postActions()
}
private val isWritable: Boolean
get() = declaration.isWritable
override fun getElementsToWrite(descriptor: UsageViewDescriptor): Collection<PsiElement?> = when {
inlineThisOnly -> listOfNotNull(reference?.element)
isWritable -> listOfNotNull(reference?.element, declaration)
else -> emptyList()
}
companion object {
private val LOG = Logger.getInstance(AbstractKotlinInlineNamedDeclarationProcessor::class.java)
}
}
private class OverrideUsageInfo(element: PsiElement) : UsageInfo(element)
| apache-2.0 | 9766df1466140c3c2b8624d9196740df | 40.45122 | 148 | 0.704178 | 5.217191 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/entity/Picture.kt | 1 | 655 | package com.github.vhromada.catalog.entity
import java.util.Objects
/**
* A class represents picture.
*
* @author Vladimir Hromada
*/
data class Picture(
/**
* UUID
*/
val uuid: String,
/**
* Content
*/
val content: ByteArray,
) {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return if (other !is Picture) {
false
} else {
uuid == other.uuid && content.contentEquals(other.content)
}
}
override fun hashCode(): Int {
return Objects.hash(uuid, content.contentHashCode())
}
}
| mit | be94d67af9ac04fd39c402ad8a48ee77 | 16.702703 | 70 | 0.541985 | 4.198718 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/volumes/BufferedVolume.kt | 1 | 10923 | package graphics.scenery.volumes
import bdv.tools.transformation.TransformedSource
import graphics.scenery.Hub
import graphics.scenery.OrientedBoundingBox
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.plus
import graphics.scenery.utils.extensions.times
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.DoubleType
import net.imglib2.type.numeric.real.FloatType
import org.joml.Vector3f
import org.joml.Vector3i
import org.lwjgl.system.MemoryUtil
import tpietzsch.example2.VolumeViewerOptions
import java.nio.ByteBuffer
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Convenience class to handle buffer-based volumes. Data descriptor is stored in [ds], similar
* to [Volume.VolumeDataSource.RAISource], with [options] and a required [hub].
*/
class BufferedVolume(val ds: VolumeDataSource.RAISource<*>, options: VolumeViewerOptions, hub: Hub): Volume(
ds,
options,
hub
) {
init {
name = "Volume (Buffer source)"
logger.debug("Data source is $ds")
boundingBox = generateBoundingBox()
}
override fun generateBoundingBox(): OrientedBoundingBox {
val source = (ds.sources[0].spimSource as TransformedSource).wrappedSource as? BufferSource<*>
val sizes = if(source != null) {
val min = Vector3f(0.0f)
val max = Vector3f(source.width.toFloat(), source.height.toFloat(), source.depth.toFloat())
max - min
} else {
Vector3f(1.0f, 1.0f, 1.0f)
}
return OrientedBoundingBox(this,
Vector3f(-0.0f, -0.0f, -0.0f),
sizes)
}
data class Timepoint(val name: String, val contents: ByteBuffer)
/**
* Access all the timepoints this volume has attached.
*/
@Suppress("UNNECESSARY_SAFE_CALL", "UNUSED_PARAMETER")
val timepoints: CopyOnWriteArrayList<Timepoint>?
get() = ((ds?.sources?.firstOrNull()?.spimSource as? TransformedSource)?.wrappedSource as? BufferSource)?.timepoints
/**
* Adds a new timepoint with a given [name], with data stored in [buffer].
*/
fun addTimepoint(name: String, buffer: ByteBuffer) {
timepoints?.removeIf { it.name == name }
timepoints?.add(Timepoint(name, buffer))
timepointCount = timepoints?.size ?: 0
viewerState.numTimepoints = timepointCount
volumeManager.notifyUpdate(this)
}
/**
* Removes the timepoint with the given [name].
*/
@JvmOverloads fun removeTimepoint(name: String, deallocate: Boolean = false): Boolean {
val tp = timepoints?.find { it.name == name }
val result = timepoints?.removeIf { it.name == name }
if(deallocate) {
tp?.contents?.let { MemoryUtil.memFree(it) }
}
timepointCount = timepoints?.size ?: 0
viewerState.numTimepoints = timepointCount
volumeManager.notifyUpdate(this)
return result != null
}
/**
* Purges the first [count] timepoints, while always leaving [leave] timepoints
* in the list.
*/
@JvmOverloads fun purgeFirst(count: Int, leave: Int = 0, deallocate: Boolean = false) {
val elements = if(timepoints?.size ?: 0 - count < leave) {
0
} else {
max(1, count - leave)
}
repeat(elements) {
val tp = timepoints?.removeAt(0)
if(deallocate && tp != null) {
MemoryUtil.memFree(tp.contents)
}
}
timepointCount = timepoints?.size ?: 0
viewerState.numTimepoints = timepointCount
}
/**
* Purges the last [count] timepoints, while always leaving [leave] timepoints
* in the list.
*/
@JvmOverloads fun purgeLast(count: Int, leave: Int = 0, deallocate: Boolean = false) {
val elements = if(timepoints?.size ?: 0 - count < leave) {
0
} else {
max(1, count - leave)
}
val n = timepoints?.size ?: 0 - elements
repeat(n) {
val tp = timepoints?.removeLast()
if(deallocate && tp != null) {
MemoryUtil.memFree(tp.contents)
}
}
timepointCount = timepoints?.size ?: 0
viewerState.numTimepoints = timepointCount
}
/**
* Samples a point from the currently used volume, [uv] is the texture coordinate of the volume, [0.0, 1.0] for
* all of the components.
*
* Returns the sampled value as a [Float], or null in case nothing could be sampled.
*/
@OptIn(ExperimentalUnsignedTypes::class)
override fun sample(uv: Vector3f, interpolate: Boolean): Float? {
val texture = timepoints?.lastOrNull() ?: throw IllegalStateException("Could not find timepoint")
val dimensions = getDimensions()
val bpp = when(ds.type) {
is UnsignedByteType, is ByteType -> 1
is UnsignedShortType, is ShortType -> 2
is UnsignedIntType, is IntType ->4
is FloatType -> 4
is DoubleType -> 8
else -> throw IllegalStateException("Data type ${ds.type.javaClass.simpleName} is not supported for sampling")
}
if(uv.x() < 0.0f || uv.x() > 1.0f || uv.y() < 0.0f || uv.y() > 1.0f || uv.z() < 0.0f || uv.z() > 1.0f) {
logger.debug("Invalid UV coords for volume access: $uv")
return null
}
val absoluteCoords = Vector3f(uv.x() * dimensions.x(), uv.y() * dimensions.y(), uv.z() * dimensions.z())
// val index: Int = (floor(gt.dimensions.x() * gt.dimensions.y() * absoluteCoords.z()).toInt()
// + floor(gt.dimensions.x() * absoluteCoords.y()).toInt()
// + floor(absoluteCoords.x()).toInt())
val absoluteCoordsD = Vector3f(floor(absoluteCoords.x()), floor(absoluteCoords.y()), floor(absoluteCoords.z()))
val diff = absoluteCoords - absoluteCoordsD
fun toIndex(absoluteCoords: Vector3f): Int = (
absoluteCoords.x().roundToInt().dec()
+ (dimensions.x() * absoluteCoords.y()).roundToInt().dec()
+ (dimensions.x() * dimensions.y() * absoluteCoords.z()).roundToInt().dec()
)
val index = toIndex(absoluteCoordsD)
val contents = texture.contents
if(contents.limit() < index*bpp) {
logger.debug("Absolute index ${index*bpp} for data type ${ds.type.javaClass.simpleName} from $uv exceeds data buffer limit of ${contents.limit()} (capacity=${contents.capacity()}), coords=$absoluteCoords/${dimensions}")
return 0.0f
}
fun density(index:Int): Float {
if(index*bpp >= contents.limit()) {
return 0.0f
}
val s = when(ds.type) {
is ByteType -> contents.get(index).toFloat()
is UnsignedByteType -> contents.get(index).toUByte().toFloat()
is ShortType -> contents.asShortBuffer().get(index).toFloat()
is UnsignedShortType -> contents.asShortBuffer().get(index).toUShort().toFloat()
is IntType -> contents.asIntBuffer().get(index).toFloat()
is UnsignedIntType -> contents.asIntBuffer().get(index).toUInt().toFloat()
is FloatType -> contents.asFloatBuffer().get(index)
is DoubleType -> contents.asDoubleBuffer().get(index).toFloat()
else -> throw java.lang.IllegalStateException("Can't determine density for ${ds.type.javaClass.simpleName} data")
}
// TODO: Correctly query transfer range
val trangemax = 65536.0f
return transferFunction.evaluate(s/trangemax)
}
return if(interpolate) {
val offset = 1.0f
val d00 = lerp(diff.x(), density(index), density(toIndex(absoluteCoordsD + Vector3f(offset, 0.0f, 0.0f))))
val d10 = lerp(diff.x(), density(toIndex(absoluteCoordsD + Vector3f(0.0f, offset, 0.0f))), density(toIndex(absoluteCoordsD + Vector3f(offset, offset, 0.0f))))
val d01 = lerp(diff.x(), density(toIndex(absoluteCoordsD + Vector3f(0.0f, 0.0f, offset))), density(toIndex(absoluteCoordsD + Vector3f(offset, 0.0f, offset))))
val d11 = lerp(diff.x(), density(toIndex(absoluteCoordsD + Vector3f(0.0f, offset, offset))), density(toIndex(absoluteCoordsD + Vector3f(offset, offset, offset))))
val d0 = lerp(diff.y(), d00, d10)
val d1 = lerp(diff.y(), d01, d11)
lerp(diff.z(), d0, d1)
} else {
density(index)
}
}
private fun lerp(t: Float, v0: Float, v1: Float): Float {
return (1.0f - t) * v0 + t * v1
}
/**
* Takes samples along the ray from [start] to [end] from the currently active volume.
* Values beyond [0.0, 1.0] for [start] and [end] will be clamped to that interval.
*
* Returns the list of samples (which might include `null` values in case a sample failed),
* as well as the delta used along the ray, or null if the start/end coordinates are invalid.
*/
override fun sampleRay(start: Vector3f, end: Vector3f): Pair<List<Float?>, Vector3f>? {
val dimensions = Vector3f(getDimensions())
if (start.x() < 0.0f || start.x() > 1.0f || start.y() < 0.0f || start.y() > 1.0f || start.z() < 0.0f || start.z() > 1.0f) {
logger.debug("Invalid UV coords for ray start: {} -- will clamp values to [0.0, 1.0].", start)
}
if (end.x() < 0.0f || end.x() > 1.0f || end.y() < 0.0f || end.y() > 1.0f || end.z() < 0.0f || end.z() > 1.0f) {
logger.debug("Invalid UV coords for ray end: {} -- will clamp values to [0.0, 1.0].", end)
}
val startClamped = Vector3f(
min(max(start.x(), 0.0f), 1.0f),
min(max(start.y(), 0.0f), 1.0f),
min(max(start.z(), 0.0f), 1.0f)
)
val endClamped = Vector3f(
min(max(end.x(), 0.0f), 1.0f),
min(max(end.y(), 0.0f), 1.0f),
min(max(end.z(), 0.0f), 1.0f)
)
val direction = (endClamped - startClamped).normalize()
val maxSteps = (Vector3f(direction).mul(dimensions).length() * 2.0f).roundToInt()
val delta = direction * (1.0f / maxSteps.toFloat())
return (0 until maxSteps).map {
sample(startClamped + (delta * it.toFloat()))
} to delta
}
/**
* Returns the volume's physical (voxel) dimensions.
*/
override fun getDimensions(): Vector3i {
val source = ((ds.sources.first().spimSource as? TransformedSource)?.wrappedSource as? BufferSource) ?: throw IllegalStateException("No source found")
return Vector3i(source.width, source.height, source.depth)
}
}
| lgpl-3.0 | 9ff30abfd0849d324fd1bf071dc2ced3 | 39.158088 | 231 | 0.601117 | 3.842068 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ChangesViewCommitWorkflowHandler.kt | 2 | 10493 | // 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.application.subscribe
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.util.EventDispatcher
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet
import java.util.*
import kotlin.properties.Delegates.observable
private fun Collection<Change>.toPartialAwareSet() = ObjectOpenCustomHashSet(this, ChangeListChange.HASHING_STRATEGY)
internal class ChangesViewCommitWorkflowHandler(
override val workflow: ChangesViewCommitWorkflow,
override val ui: ChangesViewCommitWorkflowUi
) : NonModalCommitWorkflowHandler<ChangesViewCommitWorkflow, ChangesViewCommitWorkflowUi>(),
CommitAuthorTracker by ui,
CommitAuthorListener,
ProjectManagerListener {
override val commitPanel: CheckinProjectPanel = CommitProjectPanelAdapter(this)
override val amendCommitHandler: NonModalAmendCommitHandler = NonModalAmendCommitHandler(this)
private fun getCommitState(): ChangeListCommitState {
val changes = getIncludedChanges()
val changeList = workflow.getAffectedChangeList(changes)
return ChangeListCommitState(changeList, changes, getCommitMessage())
}
private val activityEventDispatcher = EventDispatcher.create(ActivityListener::class.java)
private val changeListManager = ChangeListManagerEx.getInstanceEx(project)
private var knownActiveChanges: Collection<Change> = emptyList()
private val inclusionModel = PartialCommitInclusionModel(project)
private val commitMessagePolicy = ChangesViewCommitMessagePolicy(project)
private var currentChangeList by observable<LocalChangeList?>(null) { _, oldValue, newValue ->
if (oldValue?.id != newValue?.id) {
changeListChanged(oldValue, newValue)
changeListDataChanged()
}
else if (oldValue?.data != newValue?.data) {
changeListDataChanged()
}
}
init {
Disposer.register(this, inclusionModel)
Disposer.register(ui, this)
workflow.addListener(this, this)
workflow.addCommitListener(GitCommitStateCleaner(), this)
addCommitAuthorListener(this, this)
ui.addExecutorListener(this, this)
ui.addDataProvider(createDataProvider())
ui.addInclusionListener(this, this)
ui.inclusionModel = inclusionModel
Disposer.register(inclusionModel, Disposable { ui.inclusionModel = null })
ui.setCompletionContext(changeListManager.changeLists)
setupDumbModeTracking()
ProjectManager.TOPIC.subscribe(this, this)
setupCommitHandlersTracking()
setupCommitChecksResultTracking()
vcsesChanged() // as currently vcses are set before handler subscribes to corresponding event
currentChangeList = workflow.getAffectedChangeList(emptySet())
if (isToggleMode()) deactivate(false)
project.messageBus.connect(this).subscribe(CommitModeManager.COMMIT_MODE_TOPIC, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
if (isToggleMode()) {
deactivate(false)
}
else {
activate()
}
}
})
DelayedCommitMessageProvider.init(project, ui, ::getCommitMessageFromPolicy)
}
override fun createDataProvider(): DataProvider = object : DataProvider {
private val superProvider = [email protected]()
override fun getData(dataId: String): Any? =
if (COMMIT_WORKFLOW_HANDLER.`is`(dataId)) [email protected] { it.isActive }
else superProvider.getData(dataId)
}
override fun commitOptionsCreated() {
currentChangeList?.let { commitOptions.changeListChanged(it) }
}
override fun executionEnded() {
super.executionEnded()
ui.endExecution()
}
fun synchronizeInclusion(changeLists: List<LocalChangeList>, unversionedFiles: List<FilePath>) {
if (!inclusionModel.isInclusionEmpty()) {
val possibleInclusion: MutableSet<Any> = changeLists.flatMapTo(ObjectOpenCustomHashSet(ChangeListChange.HASHING_STRATEGY)) { it.changes }
possibleInclusion.addAll(unversionedFiles)
inclusionModel.retainInclusion(possibleInclusion)
}
if (knownActiveChanges.isNotEmpty()) {
val activeChanges = changeListManager.defaultChangeList.changes
knownActiveChanges = knownActiveChanges.intersect(activeChanges)
}
inclusionModel.changeLists = changeLists
ui.setCompletionContext(changeLists)
}
fun setCommitState(changeList: LocalChangeList, items: Collection<Any>, force: Boolean) {
setInclusion(items, force)
setSelection(changeList)
}
private fun setInclusion(items: Collection<Any>, force: Boolean) {
val activeChanges = changeListManager.defaultChangeList.changes
if (!isActive || force) {
inclusionModel.clearInclusion()
ui.includeIntoCommit(items)
knownActiveChanges = if (!isActive) activeChanges else emptyList()
}
else {
// skip if we have inclusion from not active change lists
if ((inclusionModel.getInclusion() - activeChanges.toPartialAwareSet()).filterIsInstance<Change>().isNotEmpty()) return
// we have inclusion in active change list and/or unversioned files => include new active changes if any
val newChanges = activeChanges - knownActiveChanges
ui.includeIntoCommit(newChanges)
// include all active changes if nothing is included
if (inclusionModel.isInclusionEmpty()) ui.includeIntoCommit(activeChanges)
}
}
private fun setSelection(changeList: LocalChangeList) {
val inclusion = inclusionModel.getInclusion()
val isChangeListFullyIncluded = changeList.changes.run { isNotEmpty() && all { it in inclusion } }
if (isChangeListFullyIncluded) {
ui.select(changeList)
ui.expand(changeList)
}
else {
ui.selectFirst(inclusion)
}
}
val isActive: Boolean get() = ui.isActive
fun activate(): Boolean = fireActivityStateChanged { ui.activate() }
fun deactivate(isRestoreState: Boolean) = fireActivityStateChanged { ui.deactivate(isRestoreState) }
fun addActivityListener(listener: ActivityListener, parent: Disposable) = activityEventDispatcher.addListener(listener, parent)
private fun <T> fireActivityStateChanged(block: () -> T): T {
val oldValue = isActive
return block().also { if (oldValue != isActive) activityEventDispatcher.multicaster.activityStateChanged() }
}
private fun changeListChanged(oldChangeList: LocalChangeList?, newChangeList: LocalChangeList?) {
oldChangeList?.let { commitMessagePolicy.save(it, getCommitMessage(), false) }
val newCommitMessage = newChangeList?.let(::getCommitMessageFromPolicy)
setCommitMessage(newCommitMessage)
newChangeList?.let { commitOptions.changeListChanged(it) }
}
private fun getCommitMessageFromPolicy(changeList: LocalChangeList? = currentChangeList): String? {
if (changeList == null) return null
return commitMessagePolicy.getCommitMessage(changeList) { getIncludedChanges() }
}
private fun changeListDataChanged() {
commitAuthor = currentChangeList?.author
}
override fun commitAuthorChanged() {
val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return
if (commitAuthor == changeList.author) return
changeListManager.editChangeListData(changeList.name, ChangeListData.of(commitAuthor, changeList.authorDate))
}
override fun inclusionChanged() {
val inclusion = inclusionModel.getInclusion()
val activeChanges = changeListManager.defaultChangeList.changes
val includedActiveChanges = activeChanges.filter { it in inclusion }
// ensure all included active changes are known => if user explicitly checks and unchecks some change, we know it is unchecked
knownActiveChanges = knownActiveChanges.union(includedActiveChanges)
currentChangeList = workflow.getAffectedChangeList(inclusion.filterIsInstance<Change>())
super.inclusionChanged()
}
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) {
super.beforeCommitChecksEnded(isDefaultCommit, result)
if (result == CheckinHandler.ReturnResult.COMMIT) {
// commit message could be changed during before-commit checks - ensure updated commit message is used for commit
workflow.commitState = workflow.commitState.copy(getCommitMessage())
if (isToggleMode()) deactivate(true)
}
}
private fun isToggleMode(): Boolean {
val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode()
return commitMode is CommitMode.NonModalCommitMode && commitMode.isToggleMode
}
override fun updateWorkflow() {
workflow.commitState = getCommitState()
}
override fun addUnversionedFiles(): Boolean = addUnversionedFiles(workflow.getAffectedChangeList(getIncludedChanges()))
override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(currentChangeList, getCommitMessage(), success)
// save state on project close
// using this method ensures change list comment and commit options are updated before project state persisting
override fun projectClosingBeforeSave(project: Project) {
saveStateBeforeDispose()
disposeCommitOptions()
currentChangeList = null
}
// save state on other events - like "settings changed to use commit dialog"
override fun dispose() {
saveStateBeforeDispose()
disposeCommitOptions()
super.dispose()
}
private fun saveStateBeforeDispose() {
saveCommitOptions(false)
saveCommitMessage(false)
}
interface ActivityListener : EventListener {
fun activityStateChanged()
}
private inner class GitCommitStateCleaner : CommitStateCleaner() {
private fun initCommitMessage() = setCommitMessage(getCommitMessageFromPolicy())
override fun onSuccess(commitMessage: String) {
initCommitMessage()
super.onSuccess(commitMessage)
}
}
}
| apache-2.0 | 40ff25bfc293d98a8e67dc8484fcfb91 | 36.744604 | 143 | 0.764128 | 5.015774 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/proteins/RibbonDiagram.kt | 1 | 26467 | package graphics.scenery.proteins
import graphics.scenery.geometry.Curve
import graphics.scenery.geometry.DummySpline
import graphics.scenery.geometry.Spline
import graphics.scenery.geometry.UniformBSpline
import org.joml.*
import graphics.scenery.numerics.Random
import graphics.scenery.Mesh
import org.biojava.nbio.structure.Atom
import org.biojava.nbio.structure.Group
import org.biojava.nbio.structure.secstruc.SecStrucCalc
import org.biojava.nbio.structure.secstruc.SecStrucElement
import org.biojava.nbio.structure.secstruc.SecStrucTools
import org.biojava.nbio.structure.secstruc.SecStrucType
import kotlin.math.min
/**
* A Ribbon Diagram for Proteins. Ribbon models are currently the most common representations of proteins.
* They draw a Spline approximately along the Backbone and highlight secondary structures like alpha helices
* with a wider curve along the helix, beta sheets are represented with arrows pointing from the N-terminal
* to the C-terminal. If you want to know more about the Ribbon diagrams, see the Wikipedia article:
* https://en.wikipedia.org/wiki/Ribbon_diagram
* In case you want to dig deeper here is an article of Jane D. Richardson, who developed the Ribbon:
* https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3535681/ (Studying and Polishing the PDB's Macromolecules)
*
* In the code below, we use a Uniform B-Spline to draw the C-alpha trace of the protein. The controlpoints
* are created via the algorithm of Carlson and Bugg (Algorithm for ribbon models of proteins, Carson et. al)
* The algorithm roughly works like this:
* Take a list of coordinates of C-alpha-atoms (Ca) and the coordinates
* of the Oxygen-atoms (O) of their carbonyl groups. Form the vectors:
*
* A(i) = Ca(i)-Ca(i+1) (i is the index)
* B(i) = O(i) - Ca(i)
* C = A X B (X is the cross product)
* D = A X C
*
* After normalizing C and D, we now form the midpoints between two consecutive C-alpha atoms:
* P = [Ca(i)-Ca(i+1)]/2
*
* Then we scale D by the desired Ribbon width. Finally, we calculate the guide points:
* P1 = P - D
* P2 = P + D
*
* For the implementation we have consulted KiNG, a visualization software by David C. Richardson et al:
* https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2788294/
* (KING (Kinemage, Next Generation): A versatile interactive molecular and scientific visualization program,
* by Richardson et al.)
*
* @author Justin Buerger <[email protected]>
* @param [protein] the polypeptide you wish to visualize, stored in the class Protein
*/
class RibbonDiagram(val protein: Protein, private val displaySS: Boolean = false): Mesh("ribbon") {
/*
*[structure] the structure of the protein stored in the class Structure of BioJava
*[chains] all the chains of the protein (C-alpha trace and sidechains)
*[groups] atomGroups within the chains
*[widthAlpha] specifies how wide outside the C-alpha trace the controlpoints
* of the alpha helices will be
*[widthBeta] specifies how wide outside the C-alpha trace the controlpoints
* of the beta sheets will be
*[widthCoil] specifies how wide outside the C-alpha trace the controlpoints
* of the coil will be. The value 1 corresponds to the point laying approximately on
* the trace.
*[aminoList] List of all the amino acids in the protein
*[sectionVerticesCount] Specifies how fine grained the geometry along the backbone
* will be. Please note that the calculation could take much longer if this parameter is too
* big, especially for large proteins.
* [chainList} filtered list of the chains to be used
*/
private val structure = protein.structure
private val chains = structure.chains
val groups = chains.flatMap { it.atomGroups }
private val widthAlpha = 2.0f
private val widthBeta = 2.2f
private val widthCoil = 1.0f
private val chainList = ArrayList<List<Group>>(groups.size)
private val sectionVerticesCount = 10
private val secStruc = dssp()
//calculate the centroid of the protein
private val centroid = Axis.getCentroid(groups.flatMap { it.atoms }.filter{it.name == "CA"}.map{it.getVector()})
/**
* Returns the final Ribbon Diagram
*/
init {
chains.forEach{ chain ->
if(chain.isProtein) {
val aminoList = ArrayList<Group>(chain.atomGroups.size)
chain.atomGroups.forEach { group ->
if (group.hasAminoAtoms()) {
aminoList.add(group)
}
}
chainList.add(aminoList)
}
}
chainList.forEach { aminoList ->
val guidePointList = calculateGuidePoints(aminoList, secStruc)
val spline = ribbonSpline(guidePointList)
val subProtein = subShapes(guidePointList, spline)
if(!displaySS) {
val rainbow = Rainbow()
rainbow.colorVector(subProtein)
}
this.addChild(subProtein)
}
}
/**
* The baseShape for the Spline, the coil is represented with an octagon,
* the helices with rectangles, and the sheets with arrows.
*/
private fun subShapes(guidePointList: ArrayList<GuidePoint>, spline: Spline): Mesh {
val subParent = Mesh("SubProtein")
val splinePoints = spline.splinePoints().map{ it.sub(centroid) }
val rectangle = ArrayList<Vector3f>(4)
rectangle.add(Vector3f(0.9f, 0f, 0f))
rectangle.add(Vector3f(0f, 0.1f, 0f))
rectangle.add(Vector3f(-0.9f, 0f, 0f))
rectangle.add(Vector3f(0f, -0.1f, 0f))
val octagon = ArrayList<Vector3f>(8)
val sin45 = kotlin.math.sqrt(2f) / 40f
octagon.add(Vector3f(0.05f, 0f, 0f))
octagon.add(Vector3f(sin45, sin45, 0f))
octagon.add(Vector3f(0f, 0.05f, 0f))
octagon.add(Vector3f(-sin45, sin45, 0f))
octagon.add(Vector3f(-0.05f, 0f, 0f))
octagon.add(Vector3f(-sin45, -sin45, 0f))
octagon.add(Vector3f(0f, -0.05f, 0f))
octagon.add(Vector3f(sin45, -sin45, 0f))
val reversedRectangle = ArrayList<Vector3f>(4)
reversedRectangle.add(Vector3f(0.1f, 0.8f, 0f))
reversedRectangle.add(Vector3f(-0.1f, 0.8f, 0f))
reversedRectangle.add(Vector3f(-0.1f, -0.8f, 0f))
reversedRectangle.add(Vector3f(0.1f, -0.8f, 0f))
var guidePointsOffset = 1
//offset to divide the spline into partial splines for the secondary structures
var splineOffset = 0
/*
In the following lines of code(144-211), we build a curve for each secondary structure. How does this work, step
by step? First, we iterate through the guide points. A guide point represents a residue, therefore, it can be
assigned a secondary structure or none, respectively. Each secondary structure is of a certain length and has a
certain type (or none). With the type we adapt the curve base shapes: rectangles for the helices, small octagons
for loops, and flat rectangles for the sheets. What is missing are the spline points. Fortunately, we already
have a spline for the whole backbone. We take the points belonging to this section and put them into a new
spline ("subSpline"). Now, an instance of the curve class is created, with the base shapes and the subSpline as
properties. When displaySS is true this curve gets its parent, depending of course on its secondary structure
type. In the end, it would satisfy this tree structure:
PDB (protein)
| | ... |
/ | ... \
/ | ... \
/ | ... \
/ | ... \
subUnit 1 subUnit 2 ...subUnit n
| | | | | | ....
/ | \ / | \
/ | \ / | \
alphas coils betas alphas coils betas
*/
val alphas = Mesh("alpha")
val betas = Mesh("beta")
val coils = Mesh("coil")
while (guidePointsOffset < guidePointList.lastIndex - 1) {
val guideIndex = guidePointsOffset
val guide = guidePointList[guidePointsOffset]
val count = getCount(guidePointList.drop(guidePointsOffset))
//one subSpline for each secondary structure
val subSpline = ArrayList<Vector3f>(sectionVerticesCount * count)
val ssSubList = ArrayList<List<Vector3f>>(sectionVerticesCount * count)
val helpSpline = splinePoints.drop(splineOffset)
guidePointsOffset++
when {
(guide.type == SecStrucType.helix4 && count >= 3) -> {
guidePointsOffset += count
val caList = ArrayList<Vector3f?>(count)
for(k in 0 .. count) {
caList.add(guidePointList[guideIndex+k].nextResidue?.getAtom("CA")?.getVector())
}
val axis = Axis(caList)
for (j in 0..count) {
for (i in 0..sectionVerticesCount) {
if (i + (sectionVerticesCount + 1) * j <= helpSpline.lastIndex) {
splineOffset++
subSpline.add(helpSpline[i + (sectionVerticesCount + 1) * j])
ssSubList.add(rectangle)
}
}
}
val axisLine = MathLine(axis.direction, axis.position)
val helixCurve = Helix(axisLine, DummySpline(subSpline, sectionVerticesCount)) { rectangle }
if(displaySS) { alphas.addChild(helixCurve) }
else { subParent.addChild(helixCurve) }
}
//the beta sheets are visualized with arrows
(guide.type.isBetaStrand) -> {
val sheetSize = (count + 1) * (sectionVerticesCount + 1)
for (i in 0 until (count + 1) * (sectionVerticesCount + 1)) {
splineOffset++
subSpline.add(helpSpline[i])
}
guidePointsOffset += count
val seventyPercent = (sheetSize * 0.70).toInt()
for (j in 0 until seventyPercent) {
ssSubList.add(reversedRectangle)
}
val thirtyPercent = sheetSize - seventyPercent
for (j in thirtyPercent downTo 1) {
val y = 1.65f * j / thirtyPercent
val x = 0.1f
ssSubList.add(arrayListOf(Vector3f(x, y, 0f),
Vector3f(-x, y, 0f),
Vector3f(-x, -y, 0f),
Vector3f(x, -y, 0f)))
}
val betaCurve = Curve(DummySpline(subSpline, sectionVerticesCount)) { baseShape(ssSubList) }
if(displaySS) { betas.addChild(betaCurve) }
else { subParent.addChild(betaCurve) }
}
else -> {
guidePointsOffset += count
for (j in 0..count) {
for (i in 0..sectionVerticesCount) {
if (i + (sectionVerticesCount + 1) * j <= helpSpline.lastIndex) {
splineOffset++
subSpline.add(helpSpline[i + (sectionVerticesCount+1) * j])
ssSubList.add(octagon)
}
}
}
val coilCurve = Curve(DummySpline(subSpline, sectionVerticesCount)) { baseShape(ssSubList) }
if(displaySS) { coils.addChild(coilCurve) }
else { subParent.addChild(coilCurve) }
}
}
}
if(displaySS) {
subParent.addChild(alphas)
subParent.addChild(betas)
subParent.addChild(coils)
}
return subParent
}
/**
* Returns the secondary structures of a protein, calculated with the dssp algorithm. For additional
* information about the algorithm see https://swift.cmbi.umcn.nl/gv/dssp/
*/
private fun dssp(): List<SecStrucElement> {
//see: https://github.com/biojava/biojava-tutorial/blob/master/structure/secstruc.md
val ssc = SecStrucCalc()
ssc.calculate(structure, true)
return SecStrucTools.getSecStrucElements(structure)
}
/**
* data class containing two B-Splines, which will be melted into one.
*/
data class SplineSkeleton(
val splineSkeleton1: ArrayList<Vector3f>,
val splineSkeleton2: ArrayList<Vector3f>)
/**
* Calculates the splineSkeleton out of the GuidePoints
*/
private fun splineSkeleton(guidePoints: ArrayList<GuidePoint>): SplineSkeleton {
val pts1 = ArrayList<Vector3f>(guidePoints.size)
val pts2 = ArrayList<Vector3f>(guidePoints.size)
guidePoints.forEach{
val ribWith = if(it.offset > 0f){widthAlpha} else {widthBeta}
val halfwidth = 0.5f*(widthCoil + it.widthFactor*(ribWith-widthCoil))
val dVecPlus = Vector3f()
it.finalPoint.add(it.dVec.mul(halfwidth, dVecPlus), dVecPlus)
val dVecMinus = Vector3f()
it.finalPoint.add(it.dVec.mul(-halfwidth, dVecMinus), dVecMinus)
pts1.add(dVecPlus)
pts2.add(dVecMinus)
}
return SplineSkeleton(pts1, pts2)
}
/**
* Melts the two B-Splines of the SplineSkeleton into one Dummy-Spline
* (a spline which list of controlPoints is equal to its guidePoints)
*/
private fun ribbonSpline(guidePoints: ArrayList<GuidePoint>): Spline {
val finalSpline = ArrayList<Vector3f>(guidePoints.size * sectionVerticesCount)
val skeleton = splineSkeleton(guidePoints)
val spline1 = UniformBSpline(skeleton.splineSkeleton1, sectionVerticesCount).splinePoints()
val spline2 = UniformBSpline(skeleton.splineSkeleton2, sectionVerticesCount).splinePoints()
spline1.forEachIndexed { i, _ ->
val splinePoint = Vector3f()
spline1[i].add(spline2[i], splinePoint)
splinePoint.mul(0.5f)
finalSpline.add(splinePoint)
}
return DummySpline(finalSpline, sectionVerticesCount)
}
companion object GuidePointCalculation {
/**
* Calculates the GuidePoints from the list of amino acids.
*/
fun calculateGuidePoints(aminoList: List<Group>, ssList: List<SecStrucElement>): ArrayList<GuidePoint> {
//To include all points in the visualization, dummy points need to be made.
//First, a list without these dummy points is calculated.
val guidePointsWithoutDummy = ArrayList<GuidePoint>(aminoList.size - 1)
val guidePoints = ArrayList<GuidePoint>(aminoList.size + 4 - 1)
val maxOffSet = 1.5f
aminoList.dropLast(1).forEachIndexed { i, _ ->
val ca1 = aminoList[i].getAtom("CA")
val ca2 = aminoList[i + 1].getAtom("CA")
val ca1Vec = ca1.getVector()
val ca2Vec = ca2.getVector()
val aVec = Vector3f()
ca1Vec.sub(ca2Vec, aVec)
val o = aminoList[i].getAtom("O")
val bVec = o.getVector()
val finalPoint = Vector3f()
ca1Vec.add(ca2Vec, finalPoint)
finalPoint.mul(0.5f)
//See Carlson et. al
val cVec = Vector3f()
aVec.cross(bVec, cVec)
cVec.normalize()
val dVec = Vector3f()
cVec.cross(aVec, dVec)
cVec.normalize()
val widthFactor: Float
val offset: Float
/*
Ribbons widen in areas of high curvature, respectively helices, and
low curvature, respectively beta sheets. The factors are listed in
the table* below:
CA-CA DIST WIDTH FACTOR OFFSET FACTOR NOTE
========== ============ ============= ====
5.0 1 1 ~limit for curled-up protein
5.5 1 1 } linear interpolation
7.0 0 0 } from 1.0 to 0.0
9.0 0 0 } linear interpolation
10.5 1 0 } from 1.0 to 0.0
11.0 1 0 ~limit for extended protein
*Copyright (C) 2002-2007 Ian W. Davis & Vincent B. Chen. All rights reserved
*/
when {
(i >= 1 && i < aminoList.size - 3) -> {
val ca0 = aminoList[i - 1].getAtom("CA").getVector()
val ca3 = aminoList[i + 2].getAtom("CA").getVector()
val ca0Ca3 = Vector3f()
ca0.sub(ca3, ca0Ca3)
val ca0Ca3Distance = ca0.distance(ca3)
when {
(ca0Ca3Distance < 7f) -> {
widthFactor = java.lang.Float.min(1.5f, 7f - ca0Ca3Distance) / 1.5f
offset = widthFactor
val ca0Ca3Midpoint = Vector3f()
ca0Ca3.mul(0.5f, ca0Ca3Midpoint)
val offsetVec = Vector3f()
finalPoint.sub(ca0Ca3Midpoint, offsetVec)
offsetVec.normalize().mul(offset * maxOffSet)
finalPoint.add(offsetVec)
}
(ca0Ca3Distance > 9f) -> {
widthFactor = min(1.5f, ca0Ca3Distance - 9f) / 1.5f
offset = 0f
}
else -> {
widthFactor = 0f
offset = 0f
}
}
}
else -> {
widthFactor = 0f
offset = 0f
}
}
guidePointsWithoutDummy.add(i, GuidePoint(finalPoint, cVec, dVec, offset, widthFactor,
aminoList[i], aminoList[i + 1], SecStrucType.bend, 0)
)
}
guidePointsWithoutDummy.forEachIndexed { index, guide ->
ssList.forEach { ss ->
if (ss.range.start == guide.nextResidue!!.residueNumber) {
for (i in 0 until ss.range.length) {
if(ss.type == SecStrucType.helix4 && ss.range.length < 4) {
guidePointsWithoutDummy[index + i].type = SecStrucType.bend
}
else {
guidePointsWithoutDummy[index + i].type = ss.type
}
guidePointsWithoutDummy[index + i].ssLength = ss.range.length - 1
}
}
}
}
//only assign widthFactor if there are three guide points with one in a row
guidePointsWithoutDummy.windowed(5, 1) { window ->
when {
(window[0].widthFactor == 0f && window[4].widthFactor == 0f) -> {
if (window[1].widthFactor == 0f || window[2].widthFactor == 0f || window[3].widthFactor == 0f) {
window[1].widthFactor = 0f
window[2].widthFactor = 0f
window[3].widthFactor = 0f
}
}
}
}
if(guidePointsWithoutDummy.isEmpty()) {
return guidePointsWithoutDummy
}
//if there is a width factor is still assigned at the beginning, also assign it to the first point
if (guidePointsWithoutDummy[1].widthFactor != 0f && guidePointsWithoutDummy[2].widthFactor != 0f &&
guidePointsWithoutDummy[3].widthFactor != 0f) {
guidePointsWithoutDummy[0].widthFactor = guidePointsWithoutDummy[1].widthFactor
}
//if there is a width factor is still assigned at the and, also assign it to the last point
if (guidePointsWithoutDummy.dropLast(1).last().widthFactor != 0f &&
guidePointsWithoutDummy.dropLast(2).last().widthFactor != 0f &&
guidePointsWithoutDummy.dropLast(3).last().widthFactor != 0f) {
guidePointsWithoutDummy.last().widthFactor = guidePointsWithoutDummy.dropLast(1).last().widthFactor
}
//dummy points at the beginning
val caBegin = aminoList[0].getAtom("CA").getVector()
//increase the count of the first section because we add one more point
val count = guidePointsWithoutDummy[0].ssLength
for (i in 0..count) {
guidePointsWithoutDummy[i].ssLength++
}
val dummyVecBeg = caBegin.randomFromVector()
guidePoints.add(
GuidePoint(dummyVecBeg, guidePointsWithoutDummy[0].cVec, guidePointsWithoutDummy[0].dVec,
guidePointsWithoutDummy[0].offset, guidePointsWithoutDummy[0].widthFactor, aminoList[0], aminoList[0],
SecStrucType.bend, 0)
)
guidePoints.add(
GuidePoint(caBegin, guidePointsWithoutDummy[0].cVec, guidePointsWithoutDummy[0].dVec,
guidePointsWithoutDummy[0].offset, guidePointsWithoutDummy[0].widthFactor, aminoList[0], aminoList[0],
SecStrucType.bend, 0)
)
//add all guide points from the previous calculation
guidePoints.addAll(guidePointsWithoutDummy)
//add dummy points at the end
val caEnd = aminoList.last().getAtom("CA").getVector()
guidePoints.add(
GuidePoint(caEnd,
guidePointsWithoutDummy.last().cVec, guidePointsWithoutDummy.last().dVec,
guidePointsWithoutDummy.last().offset, guidePointsWithoutDummy.last().widthFactor,
aminoList.last(), aminoList.last(), SecStrucType.bend,
guidePointsWithoutDummy.last().ssLength)
)
val dummyVecEnd = caEnd.randomFromVector()
guidePoints.add(
GuidePoint(dummyVecEnd,
guidePointsWithoutDummy.last().cVec, guidePointsWithoutDummy.last().dVec,
guidePointsWithoutDummy.last().offset, guidePointsWithoutDummy.last().widthFactor,
aminoList.last(), aminoList.last(), SecStrucType.bend,
0)
)
return untwistRibbon(guidePoints)
}
/**
* The calculation of the helices results in twists of the curve. This function
* takes a list of GuidePoints and untwists them.
*/
private fun untwistRibbon(guidePoints: ArrayList<GuidePoint>): ArrayList<GuidePoint> {
guidePoints.forEachIndexed { i, _ ->
if (i > 0) {
if (guidePoints[i].dVec.dot(guidePoints[i - 1].dVec) < 0f) {
guidePoints[i].dVec.mul(-1f)
}
}
}
return guidePoints
}
/**
* Dummy lambda function for the curve
*/
private fun baseShape(baseShapes: List<List<Vector3f>>): List<List<Vector3f>> {
return baseShapes
}
/**
* Extension function to make a Vector out of an atom position. We do not
* need any information about an atom besides its name and its position.
*/
fun Atom.getVector(): Vector3f {
return Vector3f(this.x.toFloat(), this.y.toFloat(), this.z.toFloat())
}
/**
* Extension Function to make Dummy Points not too far away from the original points - the spline
* doesn't include the first and the last controlpoint, which in our case would mean to lose the first
* and the last residue, hence, this function.
*/
private fun Vector3f.randomFromVector(): Vector3f {
return Vector3f(Random.randomFromRange(this.x() - 0.1f, this.x() + 0.1f),
Random.randomFromRange(this.y() - 0.1f, this.y() + 0.1f),
Random.randomFromRange(this.z() - 0.1f, this.z() + 0.1f))
}
}
/**
* Counts the secondary structure length.
*/
private fun getCount(guidePointList: List<GuidePoint>): Int {
var count = 0
guidePointList.forEachIndexed { index, guide ->
if (index < guidePointList.lastIndex) {
val nextGuide = guidePointList[index + 1]
//Secondary structures which are not sheets or helices are summarized
if (guide.type == SecStrucType.helix4 && nextGuide.type == SecStrucType.helix4 ||
guide.type.isBetaStrand && nextGuide.type.isBetaStrand ||
(guide.type != SecStrucType.helix4 && nextGuide.type != SecStrucType.helix4
&& !guide.type.isBetaStrand && !nextGuide.type.isBetaStrand)){
count++
} else {
return count
}
}
}
return count
}
}
| lgpl-3.0 | c84917812df881fec53fc6add4eb667c | 47.474359 | 122 | 0.547134 | 4.35886 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ui/mouse/MouseWheelSmoothScrollOptions.kt | 4 | 5947 | // 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.ui.mouse
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.geom.CubicCurve2D
import java.awt.geom.Point2D
import javax.swing.JComponent
internal class MouseWheelSmoothScrollOptionsAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val settings = UISettings.instance.state
val points = settings.animatedScrollingCurvePoints
val myBezierPainter = BezierPainter(
(points shr 24 and 0xFF) / 200.0,
(points shr 16 and 0xFF) / 200.0,
(points shr 8 and 0xFF) / 200.0,
(points and 0xFF) / 200.0
)
myBezierPainter.minimumSize = Dimension(300, 200)
dialog(
title = IdeBundle.message("title.smooth.scrolling.options"),
panel = panel {
lateinit var c: CellBuilder<JBCheckBox>
row {
c = checkBox(IdeBundle.message("checkbox.smooth.scrolling.animated"), settings::animatedScrolling)
}
row {
row(IdeBundle.message("label.smooth.scrolling.duration")) {
cell {
spinner(settings::animatedScrollingDuration, 0, 2000, 50).enableIf(c.selected)
label(IdeBundle.message("label.milliseconds"))
}
}
}
row {
myBezierPainter(CCFlags.grow).enableIf(c.selected)
}
}
).showAndGet().let {
if (it) {
val (x1, y1) = myBezierPainter.firstControlPoint
val (x2, y2) = myBezierPainter.secondControlPoint
var targetValue = 0
targetValue += (x1 * 200).toInt() shl 24 and 0xFF000000.toInt()
targetValue += (y1 * 200).toInt() shl 16 and 0xFF0000
targetValue += (x2 * 200).toInt() shl 8 and 0xFF00
targetValue += (y2 * 200).toInt() and 0xFF
settings.animatedScrollingCurvePoints = targetValue
}
}
}
}
private class BezierPainter(x1: Double, y1: Double, x2: Double, y2: Double) : JComponent() {
private val controlSize = 10
private val gridColor = JBColor(Color(0xF0F0F0), Color(0x313335))
var firstControlPoint: Point2D.Double = Point2D.Double(x1, y1)
var secondControlPoint: Point2D.Double = Point2D.Double(x2, y2)
init {
val value = object : MouseAdapter() {
var i = 0
override fun mouseDragged(e: MouseEvent) {
val point = e.point
when (i) {
1 -> firstControlPoint = fromScreenXY(point)
2 -> secondControlPoint = fromScreenXY(point)
}
repaint()
}
override fun mouseMoved(e: MouseEvent) = with (e.point ) {
i = when {
this intersects firstControlPoint -> 1
this intersects secondControlPoint -> 2
else -> 0
}
if (i != 0) {
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
} else {
cursor = Cursor.getDefaultCursor()
}
}
private infix fun Point.intersects(point: Point2D.Double) : Boolean {
val xy = toScreenXY(point)
return xy.x - controlSize / 2 <= x && x <= xy.x + controlSize / 2 &&
xy.y - controlSize / 2 <= y && y <= xy.y + controlSize / 2
}
}
addMouseMotionListener(value)
addMouseListener(value)
}
private fun toScreenXY(point: Point2D) : Point = bounds.let { b ->
return Point((point.x * b.width).toInt(), b.height - (point.y * b.height).toInt())
}
private fun fromScreenXY(point: Point) : Point2D.Double = bounds.let { b ->
val x = minOf(maxOf(0, point.x), bounds.width).toDouble() / bounds.width
val y = minOf(maxOf(0, point.y), bounds.height).toDouble() / bounds.height
return Point2D.Double(x, 1.0 - y)
}
override fun paintComponent(g: Graphics) {
val bounds = bounds
val g2d = g.create() as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED)
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE)
g2d.color = JBColor.background()
g2d.fillRect(0, 0, bounds.width, bounds.height)
g2d.color = gridColor
for (i in 0..4) {
g2d.drawLine(bounds.width * i / 4, 0, bounds.width * i / 4, bounds.height)
g2d.drawLine(0,bounds.height * i / 4, bounds.width, bounds.height * i / 4)
}
val x0 = 0.0
val y0 = bounds.height.toDouble()
val (x1, y1) = toScreenXY(firstControlPoint)
val (x2, y2) = toScreenXY(secondControlPoint)
val x3 = bounds.width.toDouble()
val y3 = 0.0
val bez = CubicCurve2D.Double(x0, y0, x1, y1, x2, y2, x3, y3)
g2d.color = JBColor.foreground()
g2d.stroke = BasicStroke(2f)
g2d.draw(bez)
g2d.stroke = BasicStroke(1f)
g2d.color = when {
isEnabled -> Color(151, 118, 169)
JBColor.isBright() -> JBColor.LIGHT_GRAY
else -> JBColor.GRAY
}
g2d.fillOval(x1.toInt() - controlSize / 2, y1.toInt() - controlSize / 2, controlSize, controlSize)
g2d.drawLine(x0.toInt(), y0.toInt(), x1.toInt(), y1.toInt())
g2d.color = when {
isEnabled -> Color(208, 167, 8)
JBColor.isBright() -> JBColor.LIGHT_GRAY
else -> JBColor.GRAY
}
g2d.fillOval(x2.toInt() - controlSize / 2, y2.toInt() - controlSize / 2, controlSize, controlSize)
g2d.drawLine(x2.toInt(), y2.toInt(), x3.toInt(), y3.toInt())
}
}
private operator fun Point2D.component1() = x
private operator fun Point2D.component2() = y | apache-2.0 | 5b94b64a4c93ae718eb4d3756d4f59b8 | 34.195266 | 140 | 0.649571 | 3.580373 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/filter/adapter/StrengthAdapterTest.kt | 1 | 3535 | /*
* 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.filter.adapter
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.wifi.model.Strength
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
class StrengthAdapterTest {
private val settings: Settings = mock()
private val fixture = StrengthAdapter(Strength.values().toSet())
@After
fun tearDown() {
verifyNoMoreInteractions(settings)
}
@Test
fun testIsActive() {
assertFalse(fixture.isActive())
}
@Test
fun testIsActiveWithChanges() {
// setup
fixture.toggle(Strength.TWO)
// execute & validate
assertTrue(fixture.isActive())
}
@Test
fun testGetValues() {
// setup
val expected = Strength.values()
// execute
val actual = fixture.selections
// validate
assertTrue(actual.containsAll(expected.toList()))
}
@Test
fun testGetValuesDefault() {
// setup
val expected = Strength.values()
// execute
val actual = fixture.defaults
// validate
assertArrayEquals(expected, actual)
}
@Test
fun testToggleRemoves() {
// execute
val actual = fixture.toggle(Strength.TWO)
// validate
assertTrue(actual)
assertFalse(fixture.contains(Strength.TWO))
}
@Test
fun testToggleAdds() {
// setup
fixture.toggle(Strength.THREE)
// execute
val actual = fixture.toggle(Strength.THREE)
// validate
assertTrue(actual)
assertTrue(fixture.contains(Strength.THREE))
}
@Test
fun testRemovingAllWillNotRemoveLast() {
// setup
val values: Set<Strength> = Strength.values().toSet()
// execute
values.forEach { fixture.toggle(it) }
// validate
values.toList().subList(0, values.size - 1).forEach { assertFalse(fixture.contains(it)) }
assertTrue(fixture.contains(values.last()))
}
@Test
fun testGetColorWithExisting() {
// execute & validate
assertEquals(Strength.TWO.colorResource, fixture.color(Strength.TWO))
}
@Test
fun testGetColorWithNonExisting() {
// setup
fixture.toggle(Strength.TWO)
// execute & validate
assertEquals(Strength.colorResourceDefault, fixture.color(Strength.TWO))
}
@Test
fun testSave() {
// setup
val expected = fixture.selections
// execute
fixture.save(settings)
// execute
verify(settings).saveStrengths(expected)
}
}
| gpl-3.0 | bc36b8eef3882e472a2b102c83e2b3d1 | 27.055556 | 97 | 0.652334 | 4.532051 | false | true | false | false |
SmokSmog/smoksmog-android | app/src/main/kotlin/com/antyzero/smoksmog/ui/screen/history/HistoryActivity.kt | 1 | 3955 | package com.antyzero.smoksmog.ui.screen.history
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.support.annotation.IntRange
import android.support.annotation.VisibleForTesting
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.widget.Toast
import com.antyzero.smoksmog.R
import com.antyzero.smoksmog.SmokSmogApplication
import com.antyzero.smoksmog.error.ErrorReporter
import com.antyzero.smoksmog.ui.BaseDragonActivity
import com.antyzero.smoksmog.ui.screen.ActivityModule
import kotlinx.android.synthetic.main.activity_history.*
import pl.malopolska.smoksmog.Api
import pl.malopolska.smoksmog.model.Station
import rx.android.schedulers.AndroidSchedulers
import smoksmog.logger.Logger
import javax.inject.Inject
/**
* Shows history chart
*/
class HistoryActivity : BaseDragonActivity() {
@Inject lateinit var api: Api
@Inject lateinit var errorReporter: ErrorReporter
@Inject lateinit var logger: Logger
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SmokSmogApplication[this].appComponent.plus(ActivityModule(this)).inject(this)
val stationId = getStationIdExtra(intent)
setContentView(R.layout.activity_history)
setSupportActionBar(toolbar)
if (supportActionBar != null) {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
api.stationHistory(stationId)
.compose(bindToLifecycle<Any>())
.observeOn(AndroidSchedulers.mainThread())
.cast(Station::class.java)
.subscribe(
{ station -> showHistory(station) }
) { throwable ->
val message = getString(R.string.error_unable_to_load_station_history)
errorReporter.report(message)
logger.i(TAG, message, throwable)
}
}
private fun showHistory(station: Station?) {
if (station == null) {
return
}
val spanCount = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) 1 else 2
val adapter = HistoryAdapter(station.particulates)
recyclerViewCharts!!.layoutManager = GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false)
recyclerViewCharts!!.adapter = adapter
}
/**
* @return Station ID if available or throws a [IllegalArgumentException]
*/
private fun getStationIdExtra(intent: Intent?): Long {
if (intent == null || !intent.hasExtra(STATION_ID_KEY)) {
// TODO com.antyzero.smoksmog.dsl.toast text should be in resources and tranlsted
Toast.makeText(this, "Pokazanie historii było niemożliwe", Toast.LENGTH_SHORT).show()
logger.e(TAG, "Unable to display History screen, missing start data")
finish()
return -1
}
return intent.getLongExtra(STATION_ID_KEY, -1)
}
companion object {
private val STATION_ID_KEY = "station_id_key"
private val TAG = "HistoryActivity"
fun start(context: Context, @IntRange(from = 1) stationId: Long) {
context.startActivity(intent(context, stationId))
}
fun intent(context: Context, station: Station): Intent {
return intent(context, station.id)
}
fun intent(context: Context, @IntRange(from = 1) stationId: Long): Intent {
val intent = Intent(context, HistoryActivity::class.java)
fillIntent(intent, stationId)
return intent
}
@VisibleForTesting
fun fillIntent(intent: Intent, @IntRange(from = 1) stationId: Long): Intent {
intent.putExtra(STATION_ID_KEY, stationId)
return intent
}
}
} | gpl-3.0 | 67b990d8a4d6977f5497cc2e36dfdc2a | 35.611111 | 116 | 0.672654 | 4.564665 | false | false | false | false |
cartland/android-UniversalMusicPlayer | app/src/main/java/com/example/android/uamp/fragments/MediaItemFragment.kt | 2 | 3910 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.android.uamp.MediaItemAdapter
import com.example.android.uamp.MediaItemData
import com.example.android.uamp.R
import com.example.android.uamp.utils.InjectorUtils
import com.example.android.uamp.viewmodels.MainActivityViewModel
import com.example.android.uamp.viewmodels.MediaItemFragmentViewModel
import kotlinx.android.synthetic.main.fragment_mediaitem_list.list
import kotlinx.android.synthetic.main.fragment_mediaitem_list.loadingSpinner
import kotlinx.android.synthetic.main.fragment_mediaitem_list.networkError
/**
* A fragment representing a list of MediaItems.
*/
class MediaItemFragment : Fragment() {
private lateinit var mediaId: String
private lateinit var mainActivityViewModel: MainActivityViewModel
private lateinit var mediaItemFragmentViewModel: MediaItemFragmentViewModel
private val listAdapter = MediaItemAdapter { clickedItem ->
mainActivityViewModel.mediaItemClicked(clickedItem)
}
companion object {
fun newInstance(mediaId: String): MediaItemFragment {
return MediaItemFragment().apply {
arguments = Bundle().apply {
putString(MEDIA_ID_ARG, mediaId)
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_mediaitem_list, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Always true, but lets lint know that as well.
val context = activity ?: return
mediaId = arguments?.getString(MEDIA_ID_ARG) ?: return
mainActivityViewModel = ViewModelProviders
.of(context, InjectorUtils.provideMainActivityViewModel(context))
.get(MainActivityViewModel::class.java)
mediaItemFragmentViewModel = ViewModelProviders
.of(this, InjectorUtils.provideMediaItemFragmentViewModel(context, mediaId))
.get(MediaItemFragmentViewModel::class.java)
mediaItemFragmentViewModel.mediaItems.observe(this,
Observer<List<MediaItemData>> { list ->
loadingSpinner.visibility =
if (list?.isNotEmpty() == true) View.GONE else View.VISIBLE
listAdapter.submitList(list)
})
mediaItemFragmentViewModel.networkError.observe(this,
Observer<Boolean> { error ->
networkError.visibility = if (error) View.VISIBLE else View.GONE
})
// Set the adapter
if (list is RecyclerView) {
list.layoutManager = LinearLayoutManager(list.context)
list.adapter = listAdapter
}
}
}
private const val MEDIA_ID_ARG = "com.example.android.uamp.fragments.MediaItemFragment.MEDIA_ID"
| apache-2.0 | c3dc1500904b5b71dac7ae6e76988e47 | 37.712871 | 96 | 0.718926 | 5.006402 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/synchronized/exceptionInMonitorExpression.kt | 2 | 480 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
fun box(): String {
val obj = "" as java.lang.Object
val e = IllegalArgumentException()
fun m(): Nothing = throw e
try {
synchronized (m()) {
throw AssertionError("Should not have reached this point")
}
}
catch (caught: Throwable) {
if (caught !== e) return "Fail: $caught"
}
return "OK"
}
| apache-2.0 | 55eed4ce0426a328df36086e2a045af6 | 23 | 72 | 0.591667 | 4.067797 | false | false | false | false |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/util/MarketingImpl.kt | 1 | 3126 | package com.antonio.samir.meteoritelandingsspots.util
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.LifecycleCoroutineScope
import com.vanniktech.rxpermission.Permission
import com.vanniktech.rxpermission.RealRxPermission
import io.nodle.sdk.INodle
import io.nodle.sdk.NodleBluetoothScanRecord
import io.nodle.sdk.NodleEvent
import io.nodle.sdk.NodleEventType
import io.nodle.sdk.android.Nodle
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class MarketingImpl(val context: Context, val nodleKey: String) : MarketingInterface {
private lateinit var nodle: INodle
override fun init() {
Nodle.init(context)
}
@RequiresApi(Build.VERSION_CODES.S)
@SuppressLint("CheckResult")
override fun start(lifecycleScope: LifecycleCoroutineScope) {
RealRxPermission.getInstance(context)
.requestEach(
Manifest.permission.INTERNET,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
.reduce(true) { c, p -> c && p.state() === Permission.State.GRANTED }
.subscribe { granted ->
if (granted) {
Log.d(TAG, "all the permissions was granted by user")
nodle.start("ss58:4mbWpKrrmE6DY78J6sCFbER2qHiLWtL4UZ7EdTpf6hyimpr7")
Log.d(TAG,"Is started ${nodle.isStarted()} ")
Log.d(TAG,"Is scanning ${nodle.isScanning()} ")
} else {
Log.d(TAG, "some permission was denied by user")
}
}
collectEvents(lifecycleScope = lifecycleScope)
}
override fun setNodle(nodle: INodle) {
this.nodle = nodle
}
fun collectEvents(lifecycleScope: LifecycleCoroutineScope) {
lifecycleScope.launch {
val events: SharedFlow<NodleEvent> = nodle.getEvents()
events.collect { event ->
// collect the NodleEvents events here by chosing a type
when (event.type) {
NodleEventType.BlePayloadEvent -> handlePayload(event)
NodleEventType.BleStartSearching -> Log.d(TAG,"Bluetooth started searching")
NodleEventType.BleStopSearching -> Log.d(TAG,"Bluetooth stopped searching")
}
}
}
}
fun handlePayload(payload: NodleEvent) {
val data = payload as NodleBluetoothScanRecord
Log.d(TAG,"Bluetooth payload available ${data.device} ")
}
companion object {
private val TAG = MarketingImpl::class.java.simpleName
}
} | mit | 0355d914baec081c84a59c1869d94753 | 34.134831 | 96 | 0.646193 | 4.465714 | false | false | false | false |
exponent/exponent | packages/expo-manifests/android/src/main/java/expo/modules/manifests/core/LegacyManifest.kt | 2 | 721 | package expo.modules.manifests.core
import expo.modules.jsonutils.getNullable
import expo.modules.jsonutils.require
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
open class LegacyManifest(json: JSONObject) : BaseLegacyManifest(json) {
@Throws(JSONException::class)
fun getBundleKey(): String? = json.getNullable("bundleKey")
@Throws(JSONException::class)
fun getReleaseId(): String = json.require("releaseId")
fun getRuntimeVersion(): String? = json.getNullable("runtimeVersion")
@Throws(JSONException::class)
fun getBundledAssets(): JSONArray? = json.getNullable("bundledAssets")
open fun getAssetUrlOverride(): String? = json.getNullable("assetUrlOverride")
}
| bsd-3-clause | 169bfb0a0812e996e28fe57888b4ba9e | 31.772727 | 80 | 0.78086 | 4.19186 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/data/local/db/FilmContract.kt | 1 | 7196 | /*
package tech.salroid.filmy.data.local.database
import android.content.ContentResolver
import android.content.ContentUris
import android.net.Uri
import android.provider.BaseColumns
import android.provider.BaseColumns._ID
object FilmContract {
// The "Content authority" is a name for the entire content provider, similar to the
// relationship between a domain name and its website. A convenient string to use for the
// content authority is the package name for the app, which is guaranteed to be unique on the
// device
const val CONTENT_AUTHORITY = "tech.salroid.filmy"
// Use CONTENT_AUTHORITY to create the base of all URI' FilmyAuthenticator which apps will use to contact
// the content provider.
private val BASE_CONTENT_URI = Uri.parse("content://$CONTENT_AUTHORITY")
const val TRENDING_PATH_MOVIE = "trending_movie"
const val INTHEATERS_PATH_MOVIE = "intheaters_movie"
const val UPCOMING_PATH_MOVIE = "upcoming_movie"
const val PATH_CAST = "cast"
const val PATH_SAVE = "save"
object MoviesEntry : BaseColumns {
const val TABLE_NAME = "trending"
const val MOVIE_ID = "movie_id"
const val MOVIE_YEAR = "movie_year"
const val MOVIE_POSTER_LINK = "movie_poster"
const val MOVIE_TITLE = "movie_title"
const val MOVIE_BANNER = "movie_banner"
const val MOVIE_DESCRIPTION = "movie_description"
const val MOVIE_TAGLINE = "movie_tagline"
const val MOVIE_TRAILER = "movie_trailer"
const val MOVIE_RATING = "movie_rating"
const val MOVIE_RUNTIME = "movie_runtime"
const val MOVIE_RELEASED = "movie_release"
const val MOVIE_CERTIFICATION = "movie_certification"
const val MOVIE_LANGUAGE = "movie_language"
@JvmField
val CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(TRENDING_PATH_MOVIE).build()
const val CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TRENDING_PATH_MOVIE
const val CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TRENDING_PATH_MOVIE
fun buildMovieUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildMovieByTag(movieTag: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieTag).build()
}
fun buildMovieUriWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendQueryParameter(MOVIE_ID, movieId).build()
}
@JvmStatic
fun buildMovieWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieId).build()
}
fun getMovieIdFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getID() = _ID
}
object InTheatersMoviesEntry : BaseColumns {
const val TABLE_NAME = "intheaters"
val CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(INTHEATERS_PATH_MOVIE).build()
fun buildMovieUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildMovieByTag(movieTag: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieTag).build()
}
fun buildMovieWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieId).build()
}
fun getMovieIdFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getID() = _ID
}
object UpComingMoviesEntry : BaseColumns {
const val TABLE_NAME = "upcoming"
val CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(UPCOMING_PATH_MOVIE).build()
fun buildMovieUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildMovieByTag(movieTag: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieTag).build()
}
fun buildMovieWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieId).build()
}
fun getMovieIdFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getID() = _ID
}
object CastEntry : BaseColumns {
const val TABLE_NAME = "cast"
const val CAST_MOVIE_ID = "cast_movie_id"
const val CAST_ID = "cast_id"
const val CAST_ROLE = "cast_role"
const val CAST_POSTER_LINK = "cast_poster"
const val CAST_NAME = "cast_name"
@JvmField
val CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CAST).build()
const val CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CAST
const val CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CAST
fun buildCastUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
@JvmStatic
fun buildCastUriByMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendQueryParameter(CAST_MOVIE_ID, movieId).build()
}
fun getMovieIdFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getID() = _ID
}
object SaveEntry : BaseColumns {
const val TABLE_NAME = "save"
const val SAVE_ID = "save_id"
const val SAVE_YEAR = "save_year"
const val SAVE_POSTER_LINK = "save_poster"
const val SAVE_TITLE = "save_title"
const val SAVE_BANNER = "save_banner"
const val SAVE_DESCRIPTION = "save_description"
const val SAVE_TAGLINE = "save_tagline"
const val SAVE_TRAILER = "save_trailer"
const val SAVE_RATING = "save_rating"
const val SAVE_RUNTIME = "save_runtime"
const val SAVE_RELEASED = "save_release"
const val SAVE_CERTIFICATION = "save_certification"
const val SAVE_LANGUAGE = "save_language"
const val SAVE_FLAG = "save_flag"
val CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SAVE).build()
const val CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_SAVE
const val CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_SAVE
fun buildMovieUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildMovieByTag(movieTag: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieTag).build()
}
fun buildMovieUriWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendQueryParameter(SAVE_ID, movieId).build()
}
fun buildMovieWithMovieId(movieId: String?): Uri {
return CONTENT_URI.buildUpon().appendPath(movieId).build()
}
fun getMovieIdFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getID() = _ID
}
}*/
| apache-2.0 | dadd8470cd997ddd57a417032872b561 | 34.800995 | 109 | 0.627571 | 4.235433 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/Cell.kt | 1 | 5841 | // 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.ui.dsl.builder
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.dsl.gridLayout.*
import com.intellij.ui.layout.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import javax.swing.JLabel
internal const val DSL_INT_TEXT_RANGE_PROPERTY = "dsl.intText.range"
enum class LabelPosition {
LEFT,
TOP
}
interface Cell<out T : JComponent> : CellBase<Cell<T>> {
override fun horizontalAlign(horizontalAlign: HorizontalAlign): Cell<T>
override fun verticalAlign(verticalAlign: VerticalAlign): Cell<T>
override fun resizableColumn(): Cell<T>
override fun gap(rightGap: RightGap): Cell<T>
override fun customize(customGaps: Gaps): Cell<T>
/**
* Component that occupies the cell
*/
val component: T
fun focused(): Cell<T>
fun applyToComponent(task: T.() -> Unit): Cell<T>
override fun enabled(isEnabled: Boolean): Cell<T>
override fun enabledIf(predicate: ComponentPredicate): Cell<T>
override fun visible(isVisible: Boolean): Cell<T>
override fun visibleIf(predicate: ComponentPredicate): Cell<T>
/**
* Changes [component] font to bold
*/
fun bold(): Cell<T>
@Deprecated("Use overloaded comment(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun comment(@NlsContexts.DetailedDescription comment: String?,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH): Cell<T>
/**
* Adds comment under the cell aligned by left edge with appropriate color and font size (macOS uses smaller font).
* [comment] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
* The comment occupies the available width before the next comment (if present) or
* whole remaining width. Visibility and enabled state of the cell affects comment as well.
*
* For layout [RowLayout.LABEL_ALIGNED] comment after second columns is placed in second column (there are technical problems,
* can be implemented later)
*
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun comment(@NlsContexts.DetailedDescription comment: String?,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<T>
@Deprecated("Use comment(...) instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun commentHtml(@NlsContexts.DetailedDescription comment: String?,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<T>
/**
* See doc for overloaded method
*/
fun label(@NlsContexts.Label label: String, position: LabelPosition = LabelPosition.LEFT): Cell<T>
/**
* Adds label at specified [position]. [LabelPosition.TOP] labels occupy available width before the next top label (if present) or
* whole remaining width. Visibility and enabled state of the cell affects the label as well.
*
* For layout [RowLayout.LABEL_ALIGNED] labels for two first columns are supported only (there are technical problems,
* can be implemented later)
*/
fun label(label: JLabel, position: LabelPosition = LabelPosition.LEFT): Cell<T>
/**
* If this method is called, the value of the component will be stored to the backing property only if the component is enabled
*/
fun applyIfEnabled(): Cell<T>
fun accessibleName(@Nls name: String): Cell<T>
fun accessibleDescription(@Nls description: String): Cell<T>
/**
* Binds component value that is provided by [componentGet] and [componentSet] methods to specified [binding] property.
* The property is applied only when [DialogPanel.apply] is invoked. Methods [DialogPanel.isModified] and [DialogPanel.reset]
* are also supported automatically for bound properties.
* This method is rarely used directly, see [Cell] extension methods named like "bindXXX" for specific components
*/
fun <V> bind(componentGet: (T) -> V, componentSet: (T, V) -> Unit, binding: PropertyBinding<V>): Cell<T>
/**
* Binds [component] value changing to [property]. The property is updated when value is changed and is not related to [DialogPanel.apply].
* This method is rarely used directly, see [Cell] extension methods named like "bindXXX" for specific components
*/
fun graphProperty(property: GraphProperty<*>): Cell<T>
/**
* Adds [component] validation
*/
fun validationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): Cell<T>
/**
* Shows error [message] if [condition] is true. Short version for particular case of [validationOnApply]
*/
fun errorOnApply(@NlsContexts.DialogMessage message: String, condition: (T) -> Boolean): Cell<T>
/**
* Adds [component] validation
*/
fun validationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): Cell<T>
/**
* Registers [callback] that will be called for [component] from [DialogPanel.apply] method
*/
fun onApply(callback: () -> Unit): Cell<T>
/**
* Registers [callback] that will be called for [component] from [DialogPanel.reset] method
*/
fun onReset(callback: () -> Unit): Cell<T>
/**
* Registers [callback] that will be called for [component] from [DialogPanel.isModified] method
*/
fun onIsModified(callback: () -> Boolean): Cell<T>
}
| apache-2.0 | 64f7f710a92f675627f86052f41aaacd | 37.427632 | 158 | 0.725389 | 4.329874 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/slicer/inflow/secondaryConstructorParameterWithDefault.kt | 9 | 326 | // FLOW: IN
// WITH_STDLIB
open class A {
@JvmOverloads constructor(n: Int, <caret>s: String = "???")
}
class B1: A(1)
class B2: A(1, "2")
class B3: A(1, s = "2")
class B4: A(n = 1, s = "2")
class B5: A(s = "2", n = 1)
fun test() {
A(1)
A(1, "2")
A(1, s = "2")
A(n = 1, s = "2")
A(s = "2", n = 1)
}
| apache-2.0 | 6478dbc5522b6596288c727f52752925 | 15.3 | 63 | 0.444785 | 2.063291 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/Utils.kt | 10 | 781 | // 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.tooling.proxy
import java.io.File
fun <T> List<T>?.nullize() = if (isNullOrEmpty()) null else this
/**
* Duplicates code in [com.intellij.openapi.util.io.FileUtil#findSequentFile] which can not be used to avoid the proxy app classpath pollution.
*/
fun File.findSequentChild(filePrefix: String, extension: String, condition: (File) -> Boolean): File {
var postfix = 0
val ext = if (extension.isEmpty()) "" else ".$extension"
var candidate = File(this, filePrefix + ext)
while (!condition.invoke(candidate)) {
candidate = File(this, filePrefix + ++postfix + ext)
}
return candidate
} | apache-2.0 | 7f61becd752944780495b56900c89b04 | 40.157895 | 143 | 0.725992 | 3.791262 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/runMarkers/testNGTestClassWithSubclasses.kt | 5 | 659 | // CONFIGURE_LIBRARY: TestNG
package testing
import org.testng.annotations.Test
abstract class <lineMarker descr="*"><lineMarker descr="Run Test">KBase</lineMarker></lineMarker> {// LIGHT_CLASS_FALLBACK
@Test
fun <lineMarker descr="*">testFoo</lineMarker>() {// LIGHT_CLASS_FALLBACK
}
}
class <lineMarker descr="*">KTest</lineMarker> : KBase() {// LIGHT_CLASS_FALLBACK
@Test
fun <lineMarker descr="*">testBar</lineMarker>() {// LIGHT_CLASS_FALLBACK
}
}
class <lineMarker descr="*">KTest2</lineMarker> : KBase() {// LIGHT_CLASS_FALLBACK
@Test
fun <lineMarker descr="*">testBaz</lineMarker>() {// LIGHT_CLASS_FALLBACK
}
} | apache-2.0 | a1aa39abee95faba9368292625a510ef | 29 | 122 | 0.6783 | 3.922619 | false | true | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/DynamoDB.kt | 1 | 2834 | package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement
import com.amazonaws.services.dynamodbv2.model.Projection
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.DynamoDB
class DynamoDBTableResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateTableRequest> {
override val requestClazz = CreateTableRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateTableRequest).let {
DynamoDB.Table(
AttributeDefinitions = request.attributeDefinitions.map {
DynamoDB.Table.AttributeDefinitionProperty(
AttributeName = it.attributeName,
AttributeType = it.attributeType
)
},
KeySchema = request.keySchema.toCfKeySchema(),
// TableName = request.tableName,
ProvisionedThroughput = request.provisionedThroughput.toCfProvisionedThroughput(),
GlobalSecondaryIndexes = request.globalSecondaryIndexes?.map {
DynamoDB.Table.GlobalSecondaryIndexProperty(
IndexName = it.indexName,
KeySchema = it.keySchema.toCfKeySchema(),
Projection = it.projection.toCfProjection(),
ProvisionedThroughput = it.provisionedThroughput.toCfProvisionedThroughput()
)
},
LocalSecondaryIndexes = request.localSecondaryIndexes?.map {
DynamoDB.Table.LocalSecondaryIndexProperty(
IndexName = it.indexName,
KeySchema = it.keySchema.toCfKeySchema(),
Projection = it.projection.toCfProjection()
)
}
)
}
}
fun Projection.toCfProjection() = DynamoDB.Table.ProjectionProperty(
NonKeyAttributes = this.nonKeyAttributes,
ProjectionType = this.projectionType
)
fun ProvisionedThroughput.toCfProvisionedThroughput() = DynamoDB.Table.ProvisionedThroughputProperty(
ReadCapacityUnits = this.readCapacityUnits.toString(),
WriteCapacityUnits = this.writeCapacityUnits.toString()
)
fun List<KeySchemaElement>.toCfKeySchema() = map {
DynamoDB.Table.KeySchemaProperty(
AttributeName = it.attributeName,
KeyType = it.keyType
)
}
| mit | 4b4db4bba5e6405c4a551217d8b1f357 | 45.459016 | 101 | 0.65067 | 5.56778 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/extensions/HexByteArrayConversion.kt | 1 | 896 | package info.nightscout.androidaps.utils.extensions
import java.util.*
private val HEX_CHARS = "0123456789abcdef".toCharArray()
fun ByteArray.toHex() : String{
val result = StringBuffer()
forEach {
val octet = it.toInt()
val firstIndex = (octet and 0xF0).ushr(4)
val secondIndex = octet and 0x0F
result.append(HEX_CHARS[firstIndex])
result.append(HEX_CHARS[secondIndex])
}
return result.toString()
}
fun String.hexStringToByteArray() : ByteArray {
val result = ByteArray(length / 2)
val lowerCased = this.toLowerCase(Locale.getDefault())
for (i in 0 until length step 2) {
val firstIndex = HEX_CHARS.indexOf(lowerCased[i])
val secondIndex = HEX_CHARS.indexOf(lowerCased[i + 1])
val octet = firstIndex.shl(4).or(secondIndex)
result.set(i.shr(1), octet.toByte())
}
return result
} | agpl-3.0 | a9375e0641519f09437eff0c7f4b56ba | 24.628571 | 62 | 0.658482 | 3.878788 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/leguicomp/AnimationPanel.kt | 1 | 7112 | package com.cout970.modeler.gui.leguicomp
import com.cout970.modeler.api.animation.IAnimation
import com.cout970.modeler.core.animation.ref
import com.cout970.modeler.render.tool.Animator
import com.cout970.modeler.util.toIVector
import com.cout970.modeler.util.toJoml4f
import com.cout970.reactive.dsl.sizeX
import com.cout970.vector.extensions.times
import com.cout970.vector.extensions.vec4Of
import org.joml.Vector2f
import org.joml.Vector4f
import org.liquidengine.legui.component.optional.align.HorizontalAlign
import org.liquidengine.legui.component.optional.align.VerticalAlign
import org.liquidengine.legui.style.color.ColorConstants.*
import org.liquidengine.legui.style.font.FontRegistry
import org.liquidengine.legui.system.context.Context
import org.liquidengine.legui.system.renderer.nvg.NvgComponentRenderer
import org.liquidengine.legui.system.renderer.nvg.util.NvgRenderUtils.createScissorByParent
import org.liquidengine.legui.system.renderer.nvg.util.NvgRenderUtils.resetScissor
import org.liquidengine.legui.system.renderer.nvg.util.NvgShapes
import org.liquidengine.legui.system.renderer.nvg.util.NvgText
import kotlin.math.*
private fun baseForZoom(zoom: Float): Int {
return if (zoom < 2f) 1 else {
val log2 = log(zoom.toDouble(), 2.0)
max(1, 1 shl floor(log2 - 1f).toInt())
}
}
private const val FRAMES_BETWEEN_MARKS = 5f
class AnimationPanel(val animator: Animator, val animation: IAnimation) : Panel() {
object Renderer : NvgComponentRenderer<AnimationPanel>() {
override fun renderComponent(comp: AnimationPanel, context: Context, nanovg: Long) {
createScissorByParent(nanovg, comp)
val style = comp.style
NvgShapes.drawRect(nanovg, comp.absolutePosition, comp.size, style.background.color, 0f)
comp.render(nanovg)
resetScissor(nanovg)
}
fun AnimationPanel.render(nanovg: Long) {
val absPos = absolutePosition
val time = animator.animationTime
val zoom = animator.zoom
val timeToPixel = size.x / zoom
val pixelOffset = animator.offset * timeToPixel
val frameSize = 1.0 / 60.0 * timeToPixel
// channels background
val color = (style.background.color.toIVector() * vec4Of(1.3, 1.3, 1.3, 1.0)).toJoml4f()
val channelLength = animation.timeLength * timeToPixel
// Channel background
repeat(animation.channels.size) { index ->
NvgShapes.drawRect(nanovg,
Vector2f(absPos.x + pixelOffset, absPos.y + index * 24f),
Vector2f(channelLength, 24f),
color, 0f)
}
// Channel separation line
repeat(animation.channels.size) { index ->
NvgShapes.drawRect(nanovg,
Vector2f(absPos.x, 24f + absPos.y + index * 24f),
Vector2f(size.x, 1f),
black(), 0f)
}
// time lines
val start = -animator.offset * 60f
val markSize = frameSize.toFloat() * FRAMES_BETWEEN_MARKS
val filterOdds = baseForZoom(zoom * 10f / FRAMES_BETWEEN_MARKS)
var barIndex = ceil(start / FRAMES_BETWEEN_MARKS).toInt()
var current = (barIndex * FRAMES_BETWEEN_MARKS / 60f) * timeToPixel + pixelOffset
while (current < size.x) {
if (barIndex % filterOdds == 0) {
NvgShapes.drawRect(nanovg,
Vector2f(absPos.x + current, absPos.y),
Vector2f(2f, size.y),
black(), 0f)
}
current += markSize
barIndex++
}
// keyframes
animation.channels.values.forEachIndexed { index, c ->
val selected = animator.selectedChannel == c.ref
c.keyframes.forEachIndexed { i, keyframe ->
val pos = keyframe.time * timeToPixel + pixelOffset
val innerColor = if (selected && animator.selectedKeyframe == i) lightGreen() else lightRed()
NvgShapes.drawRect(nanovg,
Vector2f(absPos.x + pos - 12f + 2f, absPos.y + 2f + index * 24f),
Vector2f(20f, 20f),
lightBlack(), 0f)
NvgShapes.drawRect(nanovg,
Vector2f(absPos.x + pos - 7f, absPos.y + 5f + index * 24f),
Vector2f(14f, 14f),
innerColor, 0f)
}
}
// Pointer
val pointerPos = timeToPixel * time + pixelOffset
val absPointerPos = Vector2f(absPos.x + pointerPos, absPos.y)
NvgShapes.drawRect(nanovg, absPointerPos, Vector2f(2f, size.y), lightBlue(), 0f)
}
}
}
class AnimationPanelHead(val animator: Animator, val animation: IAnimation) : Panel() {
object Renderer : NvgComponentRenderer<AnimationPanelHead>() {
override fun renderComponent(comp: AnimationPanelHead, context: Context, nanovg: Long) {
createScissorByParent(nanovg, comp)
val style = comp.style
NvgShapes.drawRect(nanovg, comp.absolutePosition, comp.size, style.background.color, 0f)
comp.render(nanovg)
resetScissor(nanovg)
}
fun AnimationPanelHead.render(nanovg: Long) {
val absPos = absolutePosition
val zoom = animator.zoom
val width = parent.sizeX - 16f - 200f
val timeToPixel = width / zoom
val pixelOffset = animator.offset * timeToPixel
val frameSize = 1.0 / 60.0 * timeToPixel
// time lines
val start = -animator.offset * 60f
val markSize = frameSize.toFloat() * FRAMES_BETWEEN_MARKS
val filterOdds = baseForZoom(zoom * 10f / FRAMES_BETWEEN_MARKS)
var barIndex = ceil(start / FRAMES_BETWEEN_MARKS).toInt()
var current = (barIndex * FRAMES_BETWEEN_MARKS / 60f) * timeToPixel + pixelOffset
while (current < size.x) {
if (barIndex % filterOdds == 0) {
val frame = (barIndex * markSize / frameSize).roundToInt()
val offsetX = markSize * barIndex + pixelOffset
if (offsetX >= 0) {
renderMark(nanovg, absPos.x + offsetX, absPos.y, frame)
}
}
current += markSize
barIndex++
}
}
fun renderMark(nanovg: Long, posX: Float, posY: Float, frame: Int) {
NvgText.drawTextLineToRect(
nanovg,
Vector4f(posX - 30f, posY, 60f, 20f),
false,
HorizontalAlign.CENTER,
VerticalAlign.MIDDLE,
18f,
FontRegistry.getDefaultFont(),
frame.toString(),
white()
)
}
}
} | gpl-3.0 | 7029c2452fffc70128318fbf12f62d2a | 37.657609 | 113 | 0.584083 | 4.215768 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/folding/checkCollapse/collectionFactoryFunctions.kt | 4 | 254 | val array = arrayOf<fold text='(...)' expand='true'>(
11 to 0,
12 to 1,
13 to 3,
)</fold>
val set = setOf<fold text='(...)' expand='true'>(
1,
2
)</fold>
val list = listOf<fold text='(...)' expand='true'>(
1,
2
)</fold>
// WITH_RUNTIME | apache-2.0 | 39c4825db8e71725c74cbba52d65a3ec | 14 | 53 | 0.531496 | 2.76087 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/CodeVisionProvidersWatcher.kt | 4 | 1137 | // 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.codeInsight.codeVision
import java.util.concurrent.TimeUnit
class CodeVisionProvidersWatcher {
companion object {
const val Threshold = 30
const val MinThreshold = 10
}
private val providersWaitingTime = mutableMapOf<String, Long>()
fun reportProvider(groupId: String, time: Long) {
val timeInSeconds = TimeUnit.SECONDS.convert(time, TimeUnit.NANOSECONDS)
if (timeInSeconds >= Threshold) {
providersWaitingTime[groupId] = if (providersWaitingTime.containsKey(groupId)) {
(timeInSeconds + time) / 2
}
else {
time
}
}
val providerTime = providersWaitingTime[groupId]
if (providerTime != null && providerTime < MinThreshold) {
providersWaitingTime.remove(groupId)
}
}
fun shouldConsiderProvider(groupId: String): Boolean {
val time = providersWaitingTime[groupId]
return time == null || time < Threshold
}
fun dropProvider(groupId: String) {
providersWaitingTime.remove(groupId)
}
} | apache-2.0 | 83473d94ef6f5e6d317ff796e8602c08 | 27.45 | 120 | 0.706245 | 4.339695 | false | false | false | false |
jwren/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/AssertBetweenInconvertibleTypesInspection.kt | 1 | 6960 | // 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.codeInspection
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiType
import com.intellij.uast.UastHintedVisitorAdapter
import com.siyeh.ig.callMatcher.CallMatcher
import com.siyeh.ig.psiutils.InconvertibleTypesChecker
import com.siyeh.ig.psiutils.InconvertibleTypesChecker.Convertible
import com.siyeh.ig.psiutils.InconvertibleTypesChecker.LookForMutualSubclass
import com.siyeh.ig.psiutils.TypeUtils
import com.siyeh.ig.testFrameworks.UAssertHint
import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertEqualsUHint
import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertNotEqualsUHint
import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertNotSameUHint
import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertSameUHint
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.NotNull
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
import java.util.*
class AssertBetweenInconvertibleTypesInspection : AbstractBaseUastLocalInspectionTool() {
private val ASSERTJ_IS_EQUAL: CallMatcher = CallMatcher.instanceCall(
"org.assertj.core.api.Assert", "isEqualTo", "isSameAs", "isNotEqualTo", "isNotSameAs")
.parameterTypes(CommonClassNames.JAVA_LANG_OBJECT)
private val ASSERTJ_DESCRIBED: CallMatcher = CallMatcher.instanceCall(
"org.assertj.core.api.Descriptable", "describedAs", "as")
private val ASSERTJ_ASSERT_THAT: CallMatcher = CallMatcher.staticCall(
"org.assertj.core.api.Assertions", "assertThat").parameterCount(1)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = UastHintedVisitorAdapter.create(
holder.file.language, AssertEqualsBetweenInconvertibleTypesVisitor(holder), arrayOf(UCallExpression::class.java), true)
override fun getID(): String = "AssertBetweenInconvertibleTypes"
inner class AssertEqualsBetweenInconvertibleTypesVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
processAssertHint(createAssertEqualsUHint(node), node, holder)
processAssertHint(createAssertNotEqualsUHint(node), node, holder)
processAssertHint(createAssertSameUHint(node), node, holder)
processAssertHint(createAssertNotSameUHint(node), node, holder)
processAssertJ(node)
return true
}
private fun processAssertHint(assertHint: UAssertHint?, expression: UCallExpression, holder : ProblemsHolder ) {
if (assertHint == null) return
val firstArgument = assertHint.firstArgument
val secondArgument = assertHint.secondArgument
val firstParameter = expression.getParameterForArgument(firstArgument)
if (firstParameter == null || !TypeUtils.isJavaLangObject(firstParameter.type)) return
val secondParameter = expression.getParameterForArgument(secondArgument)
if (secondParameter == null || !TypeUtils.isJavaLangObject(secondParameter.type)) return
checkConvertibleTypes(expression, firstArgument, secondArgument, holder)
}
private fun checkConvertibleTypes(expression: UCallExpression, firstArgument: UExpression, secondArgument: UExpression,
holder : ProblemsHolder) {
val type1 = firstArgument.getExpressionType() ?: return
val type2 = secondArgument.getExpressionType() ?: return
val mismatch = InconvertibleTypesChecker.checkTypes(type1, type2, LookForMutualSubclass.IF_CHEAP)
if (mismatch != null) {
val name = expression.methodIdentifier?.sourcePsi ?: return
val convertible = mismatch.isConvertible
if (convertible == Convertible.CONVERTIBLE_MUTUAL_SUBCLASS_UNKNOWN) {
holder.registerPossibleProblem(name)
}
else {
val methodName = expression.methodName ?: return
val highlightType = if (isAssertNotEqualsMethod(methodName)) ProblemHighlightType.WEAK_WARNING
else ProblemHighlightType.GENERIC_ERROR_OR_WARNING
val errorString = buildErrorString(methodName, mismatch.left, mismatch.right)
holder.registerProblem(name, errorString, highlightType)
}
}
}
private fun getQualifier(call: UCallExpression) : UCallExpression? {
val receiver = call.getParentOfType<UQualifiedReferenceExpression>()?.receiver
if (receiver is UCallExpression) return receiver
if (receiver is UQualifiedReferenceExpression) {
val selector = receiver.selector
if (selector is UCallExpression) return selector
}
return null
}
private fun processAssertJ(call: UCallExpression) {
if (!ASSERTJ_IS_EQUAL.uCallMatches(call)) return
var qualifier = getQualifier(call)
if (qualifier == null) return
val chain = qualifier.getOutermostQualified().getQualifiedChain()
val lastDescribed = chain.lastOrNull { expr ->
expr is UCallExpression && ASSERTJ_DESCRIBED.uCallMatches(expr)
}
if (lastDescribed != null) {
qualifier = getQualifier(lastDescribed as UCallExpression)
}
if (qualifier == null || !ASSERTJ_ASSERT_THAT.uCallMatches(qualifier)) return
checkConvertibleTypes(call, call.valueArguments[0], qualifier.valueArguments[0], holder)
}
}
@Nls
fun buildErrorString(methodName: @NotNull String, left: @NotNull PsiType, right: @NotNull PsiType): String {
val comparedTypeText = left.presentableText
val comparisonTypeText = right.presentableText
if (isAssertNotEqualsMethod(methodName)) {
return JvmAnalysisBundle.message("jvm.inspections.assertnotequals.between.inconvertible.types.problem.descriptor", comparedTypeText,
comparisonTypeText)
}
return if (isAssertNotSameMethod(methodName)) {
JvmAnalysisBundle.message("jvm.inspections.assertnotsame.between.inconvertible.types.problem.descriptor", comparedTypeText, comparisonTypeText)
}
else JvmAnalysisBundle.message("jvm.inspections.assertequals.between.inconvertible.types.problem.descriptor",
StringUtil.escapeXmlEntities(comparedTypeText),
StringUtil.escapeXmlEntities(comparisonTypeText))
}
private fun isAssertNotEqualsMethod(methodName: @NonNls String): Boolean {
return "assertNotEquals".equals(methodName) || "isNotEqualTo".equals(methodName)
}
private fun isAssertNotSameMethod(methodName: @NonNls String): Boolean {
return "assertNotSame".equals(methodName) || "isNotSameAs".equals(methodName)
}
}
| apache-2.0 | 8471e36a190a8512cdb522df5d4fb167 | 51.330827 | 149 | 0.756753 | 5.054466 | false | false | false | false |
jwren/intellij-community | platform/util/src/com/intellij/concurrency/threadContext.kt | 1 | 2199 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("ThreadContext")
@file:Experimental
package com.intellij.concurrency
import com.intellij.openapi.application.AccessToken
import org.jetbrains.annotations.ApiStatus.Experimental
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
private val tlCoroutineContext: ThreadLocal<CoroutineContext?> = ThreadLocal()
internal fun checkUninitializedThreadContext() {
check(tlCoroutineContext.get() == null) {
"Thread context was already set"
}
}
/**
* @return current thread context
*/
fun currentThreadContext(): CoroutineContext {
return tlCoroutineContext.get() ?: EmptyCoroutineContext
}
/**
* Replaces the current thread context with [coroutineContext].
*
* @return handle to restore the previous thread context
*/
fun resetThreadContext(coroutineContext: CoroutineContext): AccessToken {
return updateThreadContext {
coroutineContext
}
}
/**
* Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus],
* and runs the [action].
*
* @return result of [action] invocation
*/
fun <X> withThreadContext(coroutineContext: CoroutineContext, action: () -> X): X {
return withThreadContext(coroutineContext).use {
action()
}
}
/**
* Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus].
*
* @return handle to restore the previous thread context
*/
fun withThreadContext(coroutineContext: CoroutineContext): AccessToken {
return updateThreadContext { current ->
current + coroutineContext
}
}
private fun updateThreadContext(
update: (CoroutineContext) -> CoroutineContext
): AccessToken {
val previousContext = tlCoroutineContext.get()
val newContext = update(previousContext ?: EmptyCoroutineContext)
tlCoroutineContext.set(newContext)
return object : AccessToken() {
override fun finish() {
val currentContext = tlCoroutineContext.get()
tlCoroutineContext.set(previousContext)
check(currentContext === newContext) {
"Context was not reset correctly"
}
}
}
}
| apache-2.0 | 64823be19050027c72b8a1c1274f977b | 27.934211 | 120 | 0.753979 | 4.89755 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt | 1 | 7641 | // 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.references
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.FunctionImportedFromObject
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedTypeAliasDescriptor
import org.jetbrains.kotlin.util.OperatorNameConventions
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtSimpleNameExpression.mainReferenceCompat: KtSimpleNameReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtReferenceExpression.mainReferenceCompat: KtReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KDocName.mainReferenceCompat: KDocReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtElement.mainReferenceCompat: KtReference?
get() = mainReference
fun DeclarationDescriptor.findPsiDeclarations(project: Project, resolveScope: GlobalSearchScope): Collection<PsiElement> {
val fqName = importableFqName ?: return emptyList()
fun Collection<KtNamedDeclaration>.fqNameFilter() = filter { it.fqName == fqName }
return when (this) {
is DeserializedClassDescriptor ->
KotlinFullClassNameIndex.get(fqName.asString(), project, resolveScope)
is DeserializedTypeAliasDescriptor ->
KotlinTypeAliasShortNameIndex.get(fqName.shortName().asString(), project, resolveScope).fqNameFilter()
is DeserializedSimpleFunctionDescriptor,
is FunctionImportedFromObject ->
KotlinFunctionShortNameIndex.get(fqName.shortName().asString(), project, resolveScope).fqNameFilter()
is DeserializedPropertyDescriptor,
is PropertyImportedFromObject ->
KotlinPropertyShortNameIndex.get(fqName.shortName().asString(), project, resolveScope).fqNameFilter()
is DeclarationDescriptorWithSource -> listOfNotNull(source.getPsi())
else -> emptyList()
}
}
fun AbstractKtReference<out KtExpression>.renameImplicitConventionalCall(newName: String?): KtExpression {
if (newName == null) return expression
val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(expression)
if (OperatorNameConventions.INVOKE.asString() == newName && newExpression is KtDotQualifiedExpression) {
val canMoveLambda = newExpression.getPossiblyQualifiedCallExpression()?.canMoveLambdaOutsideParentheses() == true
OperatorToFunctionIntention.replaceExplicitInvokeCallWithImplicit(newExpression)?.let { newQualifiedExpression ->
newQualifiedExpression.getPossiblyQualifiedCallExpression()
?.takeIf { canMoveLambda }
?.let(KtCallExpression::moveFunctionLiteralOutsideParentheses)
return newQualifiedExpression
}
}
newNameElement.mainReference.handleElementRename(newName)
return newExpression
}
fun KtElement.resolveMainReferenceToDescriptors(): Collection<DeclarationDescriptor> {
val bindingContext = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
return mainReference?.resolveToDescriptors(bindingContext) ?: emptyList()
}
fun PsiReference.getImportAlias(): KtImportAlias? {
return (this as? KtSimpleNameReference)?.getImportAlias()
}
// ----------- Read/write access -----------------------------------------------------------------------------------------------------------------------
fun KtReference.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean {
if (this is KDocReference) {
val qualifier = element.getQualifier() ?: return true
return if (target.isExtension) {
val elementHasFunctionDescriptor = element.resolveMainReferenceToDescriptors().any { it is FunctionDescriptor }
val qualifierHasClassDescriptor = qualifier.resolveMainReferenceToDescriptors().any { it is ClassDescriptor }
elementHasFunctionDescriptor && qualifierHasClassDescriptor
} else {
false
}
}
return element.canBeResolvedViaImport(target, bindingContext)
}
fun KtElement.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean {
if (!target.canBeReferencedViaImport()) return false
if (target.isExtension) return true // assume that any type of reference can use imports when resolved to extension
if (this !is KtNameReferenceExpression) return false
val callTypeAndReceiver = CallTypeAndReceiver.detect(this)
if (callTypeAndReceiver.receiver != null) {
if (target !is PropertyDescriptor || !target.type.isExtensionFunctionType) return false
if (callTypeAndReceiver !is CallTypeAndReceiver.DOT && callTypeAndReceiver !is CallTypeAndReceiver.SAFE) return false
val resolvedCall = bindingContext[BindingContext.CALL, this].getResolvedCall(bindingContext)
as? VariableAsFunctionResolvedCall ?: return false
if (resolvedCall.variableCall.explicitReceiverKind.isDispatchReceiver) return false
}
if (parent is KtThisExpression || parent is KtSuperExpression) return false // TODO: it's a bad design of PSI tree, we should change it
return true
}
| apache-2.0 | 151bcecadb0f051666008ec2c8ffa5e9 | 50.979592 | 152 | 0.782882 | 5.626657 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.