content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.iyanuadelekan.kanary.app.router
import com.iyanuadelekan.kanary.app.RouteList
import com.iyanuadelekan.kanary.app.RouterAction
import com.iyanuadelekan.kanary.app.adapter.component.middleware.MiddlewareAdapter
import com.iyanuadelekan.kanary.app.constant.RouteType
import com.iyanuadelekan.kanary.exceptions.InvalidRouteException
/**
* @author Iyanu Adelekan on 18/11/2018.
*/
/**
* Class managing the creation and addition of routes to respective route trees.
*/
internal class RouteManager : com.iyanuadelekan.kanary.app.framework.router.RouteManager {
private val getRoutes by lazy { RouteList() }
private val postRoutes by lazy { RouteList() }
private val putRoutes by lazy { RouteList() }
private val deleteRoutes by lazy { RouteList() }
private val optionsRoutes by lazy { RouteList() }
private val headRoutes by lazy { RouteList() }
private val patchRoutes by lazy { RouteList() }
private val linkRoutes by lazy { RouteList() }
private val unlinkRoutes by lazy { RouteList() }
/**
* Invoked to register a new route to the router.
*
* @param routeType - type of route to be added. See [RouteType].
* @param path - URL path.
* @param action - router action.
*
* @return [RouteManager] - current [RouteManager] instance.
*/
@Throws(InvalidRouteException::class)
override fun addRoute(
routeType: RouteType,
path: String,
action: RouterAction,
middleware: List<MiddlewareAdapter>?): RouteManager {
val routeList: RouteList = getRouteList(routeType)
val subPaths: List<String> = path.split("/")
if (!subPaths.isEmpty()) {
var node = getMatchingNode(routeList, subPaths[0])
if (node == null) {
node = RouteNode(subPaths[0], action)
routeList.add(node)
}
if (subPaths.size > 1) {
for (i in 1 until subPaths.size) {
node = node as RouteNode
val pathSegment = subPaths[i]
if (!node.hasChild(pathSegment)) {
val childNode = RouteNode(pathSegment)
if (i == subPaths.size - 1) {
childNode.action = action
}
if (middleware != null) {
childNode.addMiddleware(middleware)
}
node.addChild(childNode)
} else {
if (i == subPaths.size - 1) {
throw InvalidRouteException(
"The path '$path' with method '${routeType.name}' has already been defined.")
}
node = node.getChild(pathSegment)
}
}
}
return this
}
throw InvalidRouteException("The path '$path' is an invalid route path")
}
/**
* Invoked to resolve a corresponding RouteNode to a given URL target - if any.
*
* @param path - URL path (target).
* @return [RouteNode] - Returns corresponding instance of [RouteNode], if one exists. Else returns null.
*/
override fun getRouteNode(path: String, method: RouteType): RouteNode? {
val queue: ArrayList<RouteNode> = ArrayList()
val urlPathSegments = path.split('/')
val iterator = urlPathSegments.iterator()
var currentSegment = iterator.next()
getRouteList(method).forEach {
if (it.path == currentSegment || it.path[0] == ':') {
queue.add(it)
}
}
while (!queue.isEmpty()) {
val currentNode = queue[0]
if (currentNode.path == currentSegment || currentNode.path[0] == ':') {
if (!iterator.hasNext()) {
return currentNode
}
currentSegment = iterator.next()
}
currentNode.getChildren().forEach {
if (it.path == currentSegment || it.path[0] == ':') {
queue.add(it)
}
}
queue.removeAt(0)
}
return null
}
/**
* Invoked to get a matching route node - within a given route list - for a given sub path.
*
* @param routeList - list of routes.
* @param subPath - sub path to match.
* @return [RouteNode] - returns a [RouteNode] is one exists and null otherwise.
*/
override fun getMatchingNode(routeList: RouteList, subPath: String): RouteNode? {
var node: RouteNode? = null
routeList.forEach {
if (it.path == subPath) {
node = it
}
}
return node
}
/**
* Invoked to resolve the required route list for a given route type.
*
* @param method - Specified [RouteType].
* @return [RouteList] - Corresponding route list.
*/
private fun getRouteList(method: RouteType): RouteList {
return when (method) {
RouteType.GET -> getRoutes
RouteType.POST -> postRoutes
RouteType.PUT -> putRoutes
RouteType.DELETE -> deleteRoutes
RouteType.OPTIONS -> optionsRoutes
RouteType.HEAD -> headRoutes
RouteType.PATCH -> patchRoutes
RouteType.LINK -> linkRoutes
RouteType.UNLINK -> unlinkRoutes
}
}
} | src/main/com/iyanuadelekan/kanary/app/router/RouteManager.kt | 3867265444 |
package net.nemerosa.ontrack.extension.notifications.subscriptions
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.model.annotations.APIDescription
import net.nemerosa.ontrack.model.structure.ProjectEntity
/**
* Subscrition to an event.
*
* @property projectEntity Project entity to subscribe to (`null` for global events)
* @property events List of events types to subscribe to
* @property keywords Optional space-separated list of tokens to look for in the events
* @property channel Type of channel to send the event to
* @property channelConfig Specific configuration of the channel
* @property disabled If the subscription is disabled
* @property origin Origin of the subscription (used for filtering)
*/
data class EventSubscription(
val projectEntity: ProjectEntity?,
@APIDescription("List of events types to subscribe to")
val events: Set<String>,
@APIDescription("Optional space-separated list of tokens to look for in the events")
val keywords: String?,
@APIDescription("Type of channel to send the event to")
val channel: String,
val channelConfig: JsonNode,
@APIDescription("If the subscription is disabled")
val disabled: Boolean,
@APIDescription("Origin of the subscription (used for filtering)")
val origin: String,
) {
fun disabled(disabled: Boolean) = EventSubscription(
projectEntity = projectEntity,
events = events,
keywords = keywords,
channel = channel,
channelConfig = channelConfig,
disabled = disabled,
origin = origin
)
} | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/subscriptions/EventSubscription.kt | 651760932 |
package com.xiaojinzi.component.compiler.kt
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.KSAnnotated
class TestProcessor : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
TODO()
}
} | ComponentCompilerKotlin/src/main/java/com/xiaojinzi/component/compiler/kt/TestProcessor.kt | 1368513741 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp
import com.demonwav.mcdev.util.SemanticVersion
data class McpVersionPair(val mcpVersion: String, val mcVersion: SemanticVersion) : Comparable<McpVersionPair> {
override fun compareTo(other: McpVersionPair): Int {
val mcRes = mcVersion.compareTo(other.mcVersion)
if (mcRes != 0) {
return mcRes
}
val thisStable = mcpVersion.startsWith("stable")
val thatStable = other.mcpVersion.startsWith("stable")
return if (thisStable && !thatStable) {
-1
} else if (!thisStable && thatStable) {
1
} else {
val thisNum = mcpVersion.substringAfter('_')
val thatNum = other.mcpVersion.substringAfter('_')
thisNum.toInt().compareTo(thatNum.toInt())
}
}
}
| src/main/kotlin/platform/mcp/McpVersionPair.kt | 615638917 |
package com.natpryce.hamkrest
import kotlin.reflect.KFunction1
/**
* Matches an [Iterable] if any element is matched by [elementMatcher].
*/
fun <T> anyElement(elementMatcher: Matcher<T>) = object : Matcher.Primitive<Iterable<T>>() {
override fun invoke(actual: Iterable<T>): MatchResult =
match(actual.any(elementMatcher.asPredicate())) { "was ${describe(actual)}" }
override val description: String get() = "in which any element ${describe(elementMatcher)}"
override val negatedDescription: String get() = "in which no element ${describe(elementMatcher)}"
}
/**
* Matches an [Iterable] if any element is matched by [elementPredicate].
*/
fun <T> anyElement(elementPredicate: KFunction1<T, Boolean>) = anyElement(Matcher(elementPredicate))
/**
* Matches an [Iterable] if all elements are matched by [elementMatcher].
*/
fun <T> allElements(elementMatcher: Matcher<T>) = object : Matcher.Primitive<Iterable<T>>() {
override fun invoke(actual: Iterable<T>): MatchResult =
match(actual.all(elementMatcher.asPredicate())) { "was ${describe(actual)}" }
override val description: String get() = "in which all elements ${describe(elementMatcher)}"
override val negatedDescription: String get() = "in which not all elements ${describe(elementMatcher)}"
}
/**
* Matches an [Iterable] if all elements are matched by [elementPredicate].
*/
fun <T> allElements(elementPredicate: KFunction1<T, Boolean>) = allElements(Matcher(elementPredicate))
/**
* Matches an empty collection.
*/
val isEmpty = Matcher(Collection<Any>::isEmpty)
/**
* Matches a collection with a size that matches [sizeMatcher].
*/
fun hasSize(sizeMatcher: Matcher<Int>) = has(Collection<Any>::size, sizeMatcher)
/**
* Matches a collection that contains [element]
*
* See [Collection::contains]
*/
fun <T> hasElement(element: T): Matcher<Collection<T>> = object : Matcher.Primitive<Collection<T>>() {
override fun invoke(actual: Collection<T>): MatchResult =
match(element in actual) { "was ${describe(actual)}" }
override val description: String get() = "contains ${describe(element)}"
override val negatedDescription: String get() = "does not contain ${describe(element)}"
}
fun <T> isIn(i: Iterable<T>) : Matcher<T> = object : Matcher.Primitive<T>() {
override fun invoke(actual: T) = match(actual in i) {"was not in ${describe(i)}"}
override val description: String get() = "is in ${describe(i)}"
override val negatedDescription: String get() = "is not in ${describe(i)}"
}
fun <T> isIn(vararg elements: T) = isIn(elements.toList())
| src/main/kotlin/com/natpryce/hamkrest/collection_matchers.kt | 172704632 |
package runtimemodels.chazm.api.entity
import runtimemodels.chazm.api.id.UniqueId
/**
* The [AttributeId] interface defines a [UniqueId] for [Attribute].
*
* @author Christopher Zhong
* @since 7.0
*/
interface AttributeId : UniqueId<Attribute>
| chazm-api/src/main/kotlin/runtimemodels/chazm/api/entity/AttributeId.kt | 2124549709 |
package me.lazmaid.kraph.test
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import me.lazmaid.kraph.lang.Argument
import me.lazmaid.kraph.lang.Field
import me.lazmaid.kraph.lang.SelectionSet
import me.lazmaid.kraph.lang.PrintFormat
import me.lazmaid.kraph.lang.relay.CursorConnection
import me.lazmaid.kraph.lang.relay.Edges
import me.lazmaid.kraph.lang.relay.InputArgument
import me.lazmaid.kraph.lang.relay.PageInfo
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
/**
* Created by VerachadW on 10/3/2016 AD.
*/
class RelayPrintSpek : Spek({
data class Expectation(val normal: String, val pretty: String, val json: String)
describe("Relay InputArgument") {
val tests = listOf(
Triple(
mapOf("id" to 1),
"one number argument",
Expectation("(input: { id: 1 })", "(input: { id: 1 })", "(input: { id: 1 })")
),
Triple(
mapOf("name" to "John Doe"),
"name string argument",
Expectation(
"(input: { name: \"John Doe\" })",
"(input: { name: \"John Doe\" })",
"(input: { name: \\\"John Doe\\\" })"
)
)
)
for((args, title, expectation) in tests) {
val arguments = InputArgument(args)
given(title) {
it("should print correctly in NORMAL mode") {
assertThat(arguments.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal))
}
it("should print correctly in PRETTY mode") {
assertThat(arguments.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty))
}
it("should print correctly in JSON mode") {
assertThat(arguments.print(PrintFormat.JSON, 0), equalTo(expectation.json))
}
}
}
}
describe("Relay Edges") {
val tests = listOf(
Triple(
Edges(SelectionSet(listOf(Field("title"))), additionalField = listOf(Field("id"))),
"edges with addtional field id",
Expectation(
"edges { node { title } id }",
"edges {\n node {\n title\n }\n id\n}",
"edges { node { title } id }"
)
),
Triple(
Edges(SelectionSet(listOf(Field("id"), Field("title")))),
"edges with id and title inside node object",
Expectation(
"edges { node { id title } }",
"edges {\n node {\n id\n title\n }\n}",
"edges { node { id title } }"
)
)
)
for((edge, title, expectation) in tests) {
given(title) {
it("should print correctly in NORMAL mode") {
assertThat(edge.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal))
}
it("should print correctly in PRETTY mode") {
assertThat(edge.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty))
}
it("should print correctly in JSON mode") {
assertThat(edge.print(PrintFormat.JSON, 0), equalTo(expectation.json))
}
}
}
}
describe("Relay PageInfo") {
given("default pageInfo with hasNextPage and hasPreviousPage") {
val node = PageInfo(SelectionSet(listOf(Field("hasNextPage"),Field("hasPreviousPage"))))
it("should print correctly in NORMAL mode") {
assertThat(node.print(PrintFormat.NORMAL, 0), equalTo("pageInfo { hasNextPage hasPreviousPage }"))
}
it("should print correctly in PRETTY mode") {
assertThat(node.print(PrintFormat.PRETTY, 0), equalTo("pageInfo {\n hasNextPage\n hasPreviousPage\n}"))
}
it("should print correctly in JSON mode") {
assertThat(node.print(PrintFormat.JSON, 0), equalTo("pageInfo { hasNextPage hasPreviousPage }"))
}
}
}
describe("Relay Cursor Connection") {
val tests = listOf(
Triple(
CursorConnection(
"notes",
Argument(mapOf("first" to 10)),
SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title"))))))
),
"name notes, title in node object, and only 10 items",
Expectation(
"notes (first: 10) { edges { node { title } } }",
"notes (first: 10) {\n edges {\n node {\n title\n }\n }\n}",
"notes (first: 10) { edges { node { title } } }"
)
),
Triple(
CursorConnection(
"notes",
Argument(mapOf("first" to 10, "after" to "abcd1234")),
SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title"))))))
),
"name notes, title in node object, and only next 10 items after 'abcd1234'",
Expectation(
"notes (first: 10, after: \"abcd1234\") { edges { node { title } } }",
"notes (first: 10, after: \"abcd1234\") {\n edges {\n node {\n title\n }\n }\n}",
"notes (first: 10, after: \\\"abcd1234\\\") { edges { node { title } } }"
)
),
Triple(
CursorConnection(
"notes",
Argument(mapOf("last" to 10)),
SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title"))))))
),
"name notes, title in node object, and only last 10 items",
Expectation(
"notes (last: 10) { edges { node { title } } }",
"notes (last: 10) {\n edges {\n node {\n title\n }\n }\n}",
"notes (last: 10) { edges { node { title } } }"
)
),
Triple(
CursorConnection(
"notes",
Argument(mapOf("last" to 10, "before" to "abcd1234")),
SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title"))))))
),
"name notes with title in node object and only last 10 items before 'abcd1234'",
Expectation(
"notes (last: 10, before: \"abcd1234\") { edges { node { title } } }",
"notes (last: 10, before: \"abcd1234\") {\n edges {\n node {\n title\n }\n }\n}",
"notes (last: 10, before: \\\"abcd1234\\\") { edges { node { title } } }"
)
),
Triple(
CursorConnection(
"notes",
Argument(mapOf("first" to 10)),
SelectionSet(
listOf(
Edges(SelectionSet(listOf(Field("title")))),
PageInfo(SelectionSet(listOf(
Field("hasNextPage"),
Field("hasPreviousPage")
)))
)
)
),
"name notes and a PageInfo object",
Expectation(
"notes (first: 10) { edges { node { title } } pageInfo { hasNextPage hasPreviousPage } }",
"notes (first: 10) {\n edges {\n node {\n title\n }\n }\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n}",
"notes (first: 10) { edges { node { title } } pageInfo { hasNextPage hasPreviousPage } }"
)
)
)
for((cursor, title, expectation) in tests) {
given(title) {
it("should print correctly in NORMAL mode") {
assertThat(cursor.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal))
}
it("should print correctly in PRETTY mode") {
assertThat(cursor.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty))
}
it("should print correctly in JSON mode") {
assertThat(cursor.print(PrintFormat.JSON, 0), equalTo(expectation.json))
}
}
}
}
})
| core/src/test/kotlin/me/lazmaid/kraph/test/RelayPrintSpek.kt | 4114520841 |
package com.sksamuel.rxhive.parquet
import com.sksamuel.rxhive.ArrayType
import com.sksamuel.rxhive.BinaryType
import com.sksamuel.rxhive.BooleanType
import com.sksamuel.rxhive.DateType
import com.sksamuel.rxhive.DecimalType
import com.sksamuel.rxhive.EnumType
import com.sksamuel.rxhive.Float32Type
import com.sksamuel.rxhive.Float64Type
import com.sksamuel.rxhive.Int16Type
import com.sksamuel.rxhive.Int32Type
import com.sksamuel.rxhive.Int64Type
import com.sksamuel.rxhive.Int8Type
import com.sksamuel.rxhive.Precision
import com.sksamuel.rxhive.Scale
import com.sksamuel.rxhive.StringType
import com.sksamuel.rxhive.StructField
import com.sksamuel.rxhive.StructType
import com.sksamuel.rxhive.TimeMillisType
import com.sksamuel.rxhive.TimestampMillisType
import com.sksamuel.rxhive.Type
import org.apache.parquet.schema.GroupType
import org.apache.parquet.schema.MessageType
import org.apache.parquet.schema.OriginalType
import org.apache.parquet.schema.PrimitiveType
/**
* Conversion functions from parquet types to rxhive types.
*
* Parquet types are defined at the parquet repo:
* https://github.com/apache/parquet-format/blob/c6d306daad4910d21927b8b4447dc6e9fae6c714/LogicalTypes.md
*/
object FromParquetSchema {
fun fromParquet(type: org.apache.parquet.schema.Type): Type {
return when (type) {
is PrimitiveType -> fromPrimitiveType(type)
is MessageType -> fromGroupType(type)
is GroupType -> fromGroupType(type)
else -> throw UnsupportedOperationException()
}
}
fun fromGroupType(groupType: GroupType): StructType {
val fields = groupType.fields.map {
val fieldType = fromParquet(it)
StructField(
it.name,
fieldType,
it.repetition.isNullable()
)
}
return StructType(fields)
}
fun fromPrimitiveType(type: PrimitiveType): Type {
fun int32(original: OriginalType?): Type = when (original) {
OriginalType.UINT_32 -> Int32Type
OriginalType.INT_32 -> Int32Type
OriginalType.UINT_16 -> Int16Type
OriginalType.INT_16 -> Int16Type
OriginalType.UINT_8 -> Int8Type
OriginalType.INT_8 -> Int8Type
OriginalType.DATE -> DateType
OriginalType.TIME_MILLIS -> TimeMillisType
else -> Int32Type
}
fun int64(original: OriginalType?): Type = when (original) {
OriginalType.UINT_64 -> Int64Type
OriginalType.INT_64 -> Int64Type
OriginalType.TIMESTAMP_MILLIS -> TimestampMillisType
else -> Int64Type
}
fun binary(type: PrimitiveType, original: OriginalType?, length: Int): Type = when (original) {
OriginalType.ENUM -> EnumType(emptyList())
OriginalType.UTF8 -> StringType
OriginalType.DECIMAL -> {
val meta = type.decimalMetadata
DecimalType(Precision(meta.precision), Scale(meta.scale))
}
else -> BinaryType
}
val elementType = when (type.primitiveTypeName) {
PrimitiveType.PrimitiveTypeName.BINARY -> binary(type, type.originalType, type.typeLength)
PrimitiveType.PrimitiveTypeName.BOOLEAN -> BooleanType
PrimitiveType.PrimitiveTypeName.DOUBLE -> Float64Type
PrimitiveType.PrimitiveTypeName.FLOAT -> Float32Type
PrimitiveType.PrimitiveTypeName.INT32 -> int32(type.originalType)
PrimitiveType.PrimitiveTypeName.INT64 -> int64(type.originalType)
// INT96 is deprecated, but it's commonly used (wrongly) for timestamp millis
// Spark does this, so we must do too
// https://issues.apache.org/jira/browse/PARQUET-323
PrimitiveType.PrimitiveTypeName.INT96 -> TimestampMillisType
PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY -> binary(type, type.originalType, type.typeLength)
}
return if (type.isRepeated()) ArrayType(elementType) else elementType
}
}
private fun org.apache.parquet.schema.Type.Repetition.isNullable(): Boolean =
this == org.apache.parquet.schema.Type.Repetition.OPTIONAL
private fun PrimitiveType.isRepeated(): Boolean {
return repetition == org.apache.parquet.schema.Type.Repetition.REPEATED
} | rxhive-parquet/src/main/kotlin/com/sksamuel/rxhive/parquet/FromParquetSchema.kt | 4145726745 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.samplepay
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.RadioButton
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import com.example.android.samplepay.databinding.PaymentActivityBinding
import com.example.android.samplepay.model.PaymentDetailsUpdate
import com.example.android.samplepay.model.PaymentParams
import org.chromium.components.payments.IPaymentDetailsUpdateService
import org.chromium.components.payments.IPaymentDetailsUpdateServiceCallback
import org.json.JSONObject
import java.util.*
import kotlin.math.roundToInt
private const val TAG = "PaymentActivity"
/**
* This activity handles the PAY action from Chrome.
*
* It [returns][setResult] [#RESULT_OK] when the user clicks on the "Pay" button. The "Pay" button
* is disabled unless the calling app is Chrome.
*/
class PaymentActivity : AppCompatActivity(R.layout.payment_activity) {
private val viewModel: PaymentViewModel by viewModels()
private val binding by viewBindings(PaymentActivityBinding::bind)
private var paymentDetailsUpdateService: IPaymentDetailsUpdateService? = null
private var shippingOptionsListenerEnabled = false
private var shippingAddressListenerEnabled = false
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder?) {
Log.d(TAG, "IPaymentDetailsUpdateService connected")
paymentDetailsUpdateService = IPaymentDetailsUpdateService.Stub.asInterface(service)
}
override fun onServiceDisconnected(className: ComponentName?) {
Log.d(TAG, "IPaymentDetailsUpdateService disconnected")
paymentDetailsUpdateService = null
}
}
private val callback = object : IPaymentDetailsUpdateServiceCallback.Stub() {
override fun paymentDetailsNotUpdated() {
Log.d("TAG", "Payment details did not change.")
}
override fun updateWith(newPaymentDetails: Bundle) {
val update = PaymentDetailsUpdate.from(newPaymentDetails)
runOnUiThread {
update.shippingOptions?.let { viewModel.updateShippingOptions(it) }
update.total?.let { viewModel.updateTotal(it) }
viewModel.updateError(update.error ?: "")
update.addressErrors?.let { viewModel.updateAddressErrors(it) }
viewModel.updatePromotionError(update.stringifiedPaymentMethodErrors ?: "")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.payment.layoutParams.width =
(resources.displayMetrics.widthPixels * 0.90).roundToInt()
setSupportActionBar(findViewById(R.id.toolbar))
// Bind values from ViewModel to views.
viewModel.merchantName.observe(this) { merchantName ->
binding.merchantName.isVisible = merchantName != null
binding.merchantName.text = merchantName
}
viewModel.origin.observe(this) { origin ->
binding.origin.isVisible = origin != null
binding.origin.text = origin
}
viewModel.error.observe(this) { error ->
if (error.isEmpty()) { // No error
binding.error.isVisible = false
binding.error.text = null
binding.pay.isEnabled = true
} else {
binding.error.isVisible = true
binding.error.text = error
binding.pay.isEnabled = false
}
}
viewModel.promotionError.observe(this) { promotionError ->
if (promotionError.isEmpty()) { // No promotion error
binding.promotionError.isVisible = false
binding.promotionError.text = null
} else {
binding.promotionError.isVisible = true
binding.promotionError.text = promotionError
}
}
viewModel.total.observe(this) { total ->
binding.total.isVisible = total != null
binding.total.text = if (total != null) {
getString(R.string.total_format, total.currency, total.value)
} else {
null
}
}
viewModel.paymentOptions.observe(this) { paymentOptions ->
binding.payerName.isVisible = paymentOptions.requestPayerName
binding.payerPhone.isVisible = paymentOptions.requestPayerPhone
binding.payerEmail.isVisible = paymentOptions.requestPayerEmail
binding.contactTitle.isVisible = paymentOptions.requireContact
binding.shippingOptions.isVisible = paymentOptions.requestShipping
binding.shippingAddresses.isVisible = paymentOptions.requestShipping
binding.optionTitle.text = formatTitle(
R.string.option_title_format,
paymentOptions.shippingType
)
binding.addressTitle.text = formatTitle(
R.string.address_title_format,
paymentOptions.shippingType
)
}
viewModel.shippingOptions.observe(this) { shippingOptions ->
shippingOptionsListenerEnabled = false
binding.shippingOptions.removeAllViews()
var selectedId = 0
for (option in shippingOptions) {
binding.shippingOptions.addView(
AppCompatRadioButton(this).apply {
text = getString(
R.string.option_format,
option.label,
option.amountCurrency,
option.amountValue
)
tag = option.id
id = ViewCompat.generateViewId()
if (option.selected) {
selectedId = id
}
}
)
}
if (selectedId != 0) {
binding.shippingOptions.check(selectedId)
}
shippingOptionsListenerEnabled = true
}
viewModel.paymentAddresses.observe(this) { addresses ->
shippingAddressListenerEnabled = false
binding.canadaAddress.text = addresses[R.id.canada_address].toString()
binding.usAddress.text = addresses[R.id.us_address].toString()
binding.ukAddress.text = addresses[R.id.uk_address].toString()
shippingAddressListenerEnabled = true
}
// Handle UI events.
binding.promotionButton.setOnClickListener {
val promotionCode = binding.promotionCode.text.toString()
paymentDetailsUpdateService?.changePaymentMethod(
Bundle().apply {
putString("methodName", BuildConfig.SAMPLE_PAY_METHOD_NAME)
putString("details", JSONObject().apply {
put("promotionCode", promotionCode)
}.toString())
},
callback
)
}
binding.shippingOptions.setOnCheckedChangeListener { group, checkedId ->
if (shippingOptionsListenerEnabled) {
group.findViewById<RadioButton>(checkedId)?.let { button ->
val shippingOptionId = button.tag as String
paymentDetailsUpdateService?.changeShippingOption(shippingOptionId, callback)
}
}
}
binding.shippingAddresses.setOnCheckedChangeListener { _, checkedId ->
if (shippingAddressListenerEnabled) {
viewModel.paymentAddresses.value?.get(checkedId)?.let { address ->
paymentDetailsUpdateService?.changeShippingAddress(address.asBundle(), callback)
}
}
}
binding.pay.setOnClickListener { pay() }
if (savedInstanceState == null) {
val result = handleIntent()
if (!result) cancel()
}
}
private fun handleIntent(): Boolean {
val intent = intent ?: return false
if (intent.action != "org.chromium.intent.action.PAY") {
return false
}
val extras = intent.extras ?: return false
viewModel.initialize(PaymentParams.from(extras), callingPackage)
return true
}
override fun onStart() {
super.onStart()
bindPaymentDetailsUpdateService()
}
override fun onStop() {
super.onStop()
unbindService(serviceConnection)
}
private fun bindPaymentDetailsUpdateService() {
val callingBrowserPackage = callingPackage ?: return
val intent = Intent("org.chromium.intent.action.UPDATE_PAYMENT_DETAILS")
.setPackage(callingBrowserPackage)
if (packageManager.resolveServiceByFilter(intent) == null) {
// Fallback to Chrome-only approach.
intent.setClassName(
callingBrowserPackage,
"org.chromium.components.payments.PaymentDetailsUpdateService"
)
intent.action = IPaymentDetailsUpdateService::class.java.name
}
bindService(intent, serviceConnection, BIND_AUTO_CREATE)
}
private fun cancel() {
setResult(RESULT_CANCELED)
finish()
}
private fun pay() {
setResult(RESULT_OK, Intent().apply {
putExtra("methodName", BuildConfig.SAMPLE_PAY_METHOD_NAME)
putExtra("details", "{\"token\": \"put-some-data-here\"}")
val paymentOptions = viewModel.paymentOptions.value
if (paymentOptions == null) {
cancel()
return
}
if (paymentOptions.requestPayerName) {
putExtra("payerName", binding.payerName.text.toString())
}
if (paymentOptions.requestPayerPhone) {
putExtra("payerPhone", binding.payerPhone.text.toString())
}
if (paymentOptions.requestPayerEmail) {
putExtra("payerEmail", binding.payerEmail.text.toString())
}
if (paymentOptions.requestShipping) {
val addresses = viewModel.paymentAddresses.value!!
putExtra(
"shippingAddress",
addresses[binding.shippingAddresses.checkedRadioButtonId]?.asBundle()
)
val optionId = binding.shippingOptions.findViewById<RadioButton>(
binding.shippingOptions.checkedRadioButtonId
).tag as String
putExtra("shippingOptionId", optionId)
}
if (BuildConfig.DEBUG) {
Log.d(getString(R.string.payment_response), "${this.extras}")
}
})
finish()
}
private fun formatTitle(@StringRes id: Int, label: String): String {
return getString(
id,
label.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
}
)
}
}
| SamplePay/app/src/main/java/com/example/android/samplepay/PaymentActivity.kt | 3948546586 |
package com.github.dynamicextensionsalfresco.web
import com.github.dynamicextensionsalfresco.webscripts.DummyStore
import com.github.dynamicextensionsalfresco.webscripts.support.AbstractBundleResourceHandler
import org.osgi.framework.BundleContext
import org.springframework.extensions.webscripts.*
import java.util.ResourceBundle
import javax.servlet.http.HttpServletResponse
/**
* Webscript to serve static web resources found in an extension
* When requests are prefixed with symbolic-name/web, no cache headers are set,
* with the /web-cached/$version prefix, cache is set to expire now + 1 year
*
* @author Laurent Van der Linden
*/
public class ResourceWebscript(private val bundleContext: BundleContext) : WebScript, AbstractBundleResourceHandler() {
private val module = "alfresco-dynamic-extensions-repo-control-panel";
init {
initContentTypes()
}
private val descriptionImpl = run {
val uris = arrayOf("/$module/web/{path}", "/$module/web-cached/{version}/{path}")
val id = "${module}-web"
val descriptionImpl = DescriptionImpl(
id,
"staticWebResource$module",
"static web resources for extension $module",
uris.first()
)
descriptionImpl.method = "GET"
descriptionImpl.formatStyle = Description.FormatStyle.argument
descriptionImpl.defaultFormat = "html"
descriptionImpl.setUris(uris)
descriptionImpl.familys = setOf("static-web")
descriptionImpl.store = DummyStore()
descriptionImpl.requiredAuthentication = Description.RequiredAuthentication.none
descriptionImpl.requiredTransactionParameters = with(TransactionParameters()) {
required = Description.RequiredTransaction.none
this
}
descriptionImpl
}
override fun getBundleContext(): BundleContext? {
return bundleContext
}
override fun setURLModelFactory(urlModelFactory: URLModelFactory?) {}
override fun init(container: Container?, description: Description?) {}
override fun execute(req: WebScriptRequest, res: WebScriptResponse) {
val path = req.serviceMatch.templateVars.get("path")
if (path != null) {
if (req.serviceMatch.path.startsWith("/$module/web-cached/") && !shouldNotCache(path)) {
setInfinateCache(res)
}
handleResource(path, req, res)
} else {
res.setStatus(HttpServletResponse.SC_BAD_REQUEST)
}
}
private fun shouldNotCache(path: String) = path.endsWith(".map")
override fun getBundleEntryPath(path: String?): String? {
return "/META-INF/alfresco/web/$path"
}
override fun getDescription(): Description? {
return descriptionImpl
}
override fun getResources(): ResourceBundle? {
return null
}
} | annotations-runtime/src/main/kotlin/com/github/dynamicextensionsalfresco/web/ResourceWebscript.kt | 2808437095 |
package org.jackJew.biz.engine.test
import org.jackJew.biz.engine.JsEngine
import org.jackJew.biz.engine.JsEngineNashorn
import org.jackJew.biz.engine.JsEngineRhino
import org.jackJew.biz.engine.util.IOUtils
import org.junit.Test
import com.google.gson.JsonObject
/**
* when MAX is below 50, Rhino is better than Nashorn;
* <br></br>
* when MAX is 100, Nashorn is better than Rhino.
* @author Jack
*/
const val MAX = 200
class JsEngineTest {
@Test
fun testNashornJS() {
val cl = Thread.currentThread().contextClassLoader
cl.getResourceAsStream("site_source.html").use {
val content = IOUtils.toString(it, JsEngine.DEFAULT_CHARSET)
val config = JsonObject().also {
it.addProperty("content", content)
}
val script = cl.getResourceAsStream("org/jackJew/biz/engine/test/config/test.js").use {
IOUtils.toString(it, JsEngine.DEFAULT_CHARSET)
}
val startTime = System.currentTimeMillis()
var i = 0
while (i < MAX) {
val result = JsEngineNashorn.INSTANCE.runScript2JSON(
"(function(args){$script})($config);")
if (i++ == 0) {
println(result)
}
}
println("testNashornJS time cost: " + (System.currentTimeMillis() - startTime) + " ms.")
}
}
@Test
fun testRhinoJS() {
val cl = Thread.currentThread().contextClassLoader
cl.getResourceAsStream("site_source.html").use {
val content = IOUtils.toString(it, JsEngine.DEFAULT_CHARSET)
val config = JsonObject().also{ it.addProperty("content", content)}
val script = cl.getResourceAsStream("org/jackJew/biz/engine/test/config/test.js").use {
IOUtils.toString(it, JsEngine.DEFAULT_CHARSET)
}
val startTime = System.currentTimeMillis()
var i = 0
while (i < MAX) {
val result = JsEngineRhino.INSTANCE.runScript2JSON(
"(function(args){$script})($config);")
if (i++ == 0) {
println(result)
}
}
println("testRhinoJS time cost: " + (System.currentTimeMillis() - startTime) + " ms.")
}
}
}
| src/test/java/org/jackJew/biz/engine/test/JsEngineTest.kt | 903444955 |
package com.stripe.android.payments.core.injection
import android.content.Context
import com.stripe.android.core.injection.CoreCommonModule
import com.stripe.android.core.injection.CoroutineContextModule
import com.stripe.android.core.injection.ENABLE_LOGGING
import com.stripe.android.core.injection.PUBLISHABLE_KEY
import com.stripe.android.payments.core.authentication.threeds2.Stripe3ds2TransactionViewModelFactory
import dagger.BindsInstance
import dagger.Component
import javax.inject.Named
import javax.inject.Singleton
/**
* Component to inject [Stripe3ds2TransactionViewModelFactory] when the app process is killed and
* there is no [Injector] available.
*/
@Singleton
@Component(
modules = [
StripeRepositoryModule::class,
Stripe3ds2TransactionModule::class,
CoroutineContextModule::class,
CoreCommonModule::class
]
)
internal interface Stripe3ds2TransactionViewModelFactoryComponent {
fun inject(stripe3ds2TransactionViewModelFactory: Stripe3ds2TransactionViewModelFactory)
@Component.Builder
interface Builder {
@BindsInstance
fun context(context: Context): Builder
@BindsInstance
fun enableLogging(@Named(ENABLE_LOGGING) enableLogging: Boolean): Builder
@BindsInstance
fun publishableKeyProvider(
@Named(PUBLISHABLE_KEY) publishableKeyProvider: () -> String
): Builder
@BindsInstance
fun productUsage(@Named(PRODUCT_USAGE) productUsage: Set<String>): Builder
@BindsInstance
fun isInstantApp(@Named(IS_INSTANT_APP) isInstantApp: Boolean): Builder
fun build(): Stripe3ds2TransactionViewModelFactoryComponent
}
}
| payments-core/src/main/java/com/stripe/android/payments/core/injection/Stripe3ds2TransactionViewModelFactoryComponent.kt | 4230003104 |
package com.vimeo.networking2.params
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Encapsulates publishing data for each of the supported social media platforms.
*
* @param facebook Optional publishing data for Facebook.
* @param youTube Optional publishing data for YouTube.
* @param twitter Optional publishing data for Twitter.
* @param linkedIn Optional publishing data for LinkedIn.
*/
@JsonClass(generateAdapter = true)
data class BatchPublishToSocialMedia(
@Json(name = "facebook")
val facebook: PublishToFacebookPost? = null,
@Json(name = "youtube")
val youTube: PublishToYouTubePost? = null,
@Json(name = "twitter")
val twitter: PublishToTwitterPost? = null,
@Json(name = "linkedin")
val linkedIn: PublishToLinkedInPost? = null
)
| models/src/main/java/com/vimeo/networking2/params/BatchPublishToSocialMedia.kt | 584058085 |
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics
import kotlin.test.Test
import kotlin.test.assertEquals
class StampedPathEffectStyleTest {
@Test
fun testToString() {
assertEquals("Translate", StampedPathEffectStyle.Translate.toString())
assertEquals("Rotate", StampedPathEffectStyle.Rotate.toString())
assertEquals("Morph", StampedPathEffectStyle.Morph.toString())
}
}
| compose/ui/ui-graphics/src/commonTest/kotlin/androidx/compose/ui/graphics/StampedPathEffectStyleTest.kt | 2506085159 |
package com.vimeo.modelgenerator.extensions
import com.squareup.kotlinpoet.*
import org.jetbrains.kotlin.psi.ValueArgument
/**
* Adds a list of Types to the given [FileSpec], good for when building a single
* file that contains multiple classes or objects.
*
* @param types a list of [TypeSpec].
*/
internal fun FileSpec.Builder.addTypes(types: List<TypeSpec>): FileSpec.Builder = apply {
types.forEach { addType(it) }
}
/**
* Adds a list of functions to the given [FileSpec], good for when building a single
* file that contains multiple classes or objects.
*
* @param functions a list of [FunSpec].
*/
internal fun FileSpec.Builder.addFunctions(functions: List<FunSpec>): FileSpec.Builder = apply {
functions.forEach { addFunction(it) }
}
/**
* Adds a list of properties to the given [FileSpec], good for when building a single
* file that contains multiple classes or objects.
*
* @param properties a list of [FunSpec].
*/
internal fun FileSpec.Builder.addProperties(properties: List<PropertySpec>): FileSpec.Builder =
apply {
properties.forEach { addProperty(it) }
}
/**
* Add a list of imports to the given [FileSpec].
*
* @param imports a list of Imports.
*/
internal fun FileSpec.Builder.addImports(imports: List<Pair<String, String>>): FileSpec.Builder =
apply {
imports.forEach { addImport(it.second, it.first) }
}
/**
* Adds a list of [AnnotationSpec] to the given [FileSpec].
*
* @param annotations a list of [AnnotationSpec].
*/
internal fun FileSpec.Builder.addAnnotations(annotations: List<AnnotationSpec>): FileSpec.Builder =
apply {
annotations.forEach { addAnnotation(it) }
}
/**
* Conditionally add a block of code to a [Taggable.Builder].
*
* This can be applied to [FileSpec.Builder], [PropertySpec.Builder], [ParameterSpec.Builder] or any class that has
* [Taggable.Builder] as a super.
*
* @param condition a condition if met will add the [addition] to the given [Taggable.Builder].
* @param addition a block of code that can be applied to the [Taggable.Builder] if the [condition] is met.
*/
internal fun <T : Taggable.Builder<T>> T.addIfConditionMet(
condition: Boolean,
addition: T.() -> Unit
): T = apply {
if (condition) addition()
}
/**
* Parses [valArgs] to create parameters for AnnotationSpec.Builders [AnnotationSpec.Builder].
*
* @param valArgs a list of [ValueArgument].
*/
internal fun AnnotationSpec.Builder.addMembers(valArgs: List<ValueArgument>): AnnotationSpec.Builder =
apply { valArgs.toParams.forEach { addMember(it) } }
/**
* Adds a list of enums to a given [TypeSpec].
*
* @param enums takes a list of [Pairs][Pair] with the first type being the enum name, and the second being the class body.
*/
internal fun TypeSpec.Builder.addEnumConstants(enums: List<Pair<String, TypeSpec>>): TypeSpec.Builder =
apply {
enums.forEach {
addEnumConstant(it.first, it.second)
}
}
/**
* Adds all the given params to a superclass constructor.
*
* @param params a list of pairs representing params for a superclass constructor.
*/
internal fun TypeSpec.Builder.addSuperclassConstructorParameters(params: List<Pair<String, Any>>): TypeSpec.Builder =
apply {
params.forEach {
addSuperclassConstructorParameter(it.first, it.second)
}
}
/**
* Adds a list of KDocs to the [TypeSpec.Builder].
*
* @param docs a list of KDocs
*/
internal fun TypeSpec.Builder.addKdocs(docs: List<String>): TypeSpec.Builder =
apply { docs.forEach { addKdoc(it) } }
/**
* Adds a list of KDocs to the [FunSpec.Builder].
*
* @param docs a list of KDocs
*/
internal fun FunSpec.Builder.addKdocs(docs: List<String>): FunSpec.Builder =
apply { docs.forEach { addKdoc(it) } }
/**
* Adds a list of KDocs to the [PropertySpec.Builder].
*
* @param docs a list of KDocs
*/
internal fun PropertySpec.Builder.addKdocs(docs: List<String>): PropertySpec.Builder =
apply { docs.forEach { addKdoc(it) } }
| model-generator/plugin/src/main/java/com/vimeo/modelgenerator/extensions/KotlinPoetExtensions.kt | 425936112 |
package com.peterlaurence.trekme.core.providers.urltilebuilder
class UrlTileBuilderIgnSpain : UrlTileBuilder {
override fun build(level: Int, row: Int, col: Int): String {
return "http://www.ign.es/wmts/mapa-raster?Layer=MTN&Style=normal&Tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix=$level&TileCol=$col&TileRow=$row"
}
} | app/src/main/java/com/peterlaurence/trekme/core/providers/urltilebuilder/UrlTileBuilderIgnSpain.kt | 3081576626 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.utils
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class TemplatingUtilTest {
@Test
fun testOpsStringRand() {
val randTemplateString = "rand 2-4"
val randOpsString = TemplatingUtil.opsString(randTemplateString)
assertThat(randOpsString.operation).isEqualTo("rand")
assertThat(randOpsString.arguments).isEqualTo("2-4")
}
@Test
fun testOpsStringRandSign() {
val randSignTemplateString = "randsign"
val randOpsString = TemplatingUtil.opsString(randSignTemplateString)
assertThat(randOpsString.operation).isEqualTo("randsign")
assertThat(randOpsString.arguments).isEqualTo("")
}
@Test
fun doesRandTemplateReturnAccurateValue() {
val randTemplateString = "+%rand 2-4% Memes"
val actual = TemplatingUtil.template(randTemplateString)
assertThat(actual).isIn("+2 Memes", "+3 Memes", "+4 Memes")
}
@Test
fun doesRandsignTemplateReturnAccurateValue() {
val randsignTemplateString = "%randsign%3 Memes"
val actual = TemplatingUtil.template(randsignTemplateString)
assertThat(actual).isIn("-3 Memes", "+3 Memes")
}
@Test
fun doesRandAndRandsignWorkTogether() {
val randsignTemplateString = "%randsign%%rand 2-4% Memes"
val actual = TemplatingUtil.template(randsignTemplateString)
assertThat(actual).isIn(
"+2 Memes", "+3 Memes", "+4 Memes",
"-2 Memes", "-3 Memes", "-4 Memes"
)
}
@Test
fun doMultipleRandsWork() {
val randTemplateString = "%rand 1-4%%rand 1-4%"
val actual = TemplatingUtil.template(randTemplateString)
assertThat(actual).isIn(
"11", "12", "13", "14", "21", "22", "23", "24", "31", "32", "33", "34", "41", "42", "43",
"44"
)
}
}
| src/test/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/TemplatingUtilTest.kt | 3853061945 |
package com.vimeo.networking2.enums
/**
* Video transcoding states.
*/
enum class VideoStateType(override val value: String?) : StringValue {
ACTIVE("active"),
BLOCKED("blocked"),
EXCEEDS_QUOTA("exceeds_quota"),
EXCEEDS_TOTAL_CAP("exceeds_total_cap"),
FAILED("failed"),
FINISHING("finishing"),
INTERNAL_ERROR("internal_error"),
INVALID_FILE("invalid_file"),
PENDING("pending"),
READY("ready"),
RETRIEVED("retrieved"),
STANDBY("standby"),
STARTING("starting"),
UPLOAD_COMPLETE("upload_complete"),
UPLOAD_INCOMPLETE("upload_incomplete"),
UNKNOWN("unknown")
}
| models/src/main/java/com/vimeo/networking2/enums/VideoStateType.kt | 74898320 |
/*
* Copyright (c) 2017-2019 Yui
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package moe.kyubey.akatsuki.commands
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.annotations.Load
import javax.script.ScriptEngineManager
@Load
@Argument("code", "string")
class JS : Command() {
override val desc = "Evaluate (js) code"
override val ownerOnly = true
override fun run(ctx: Context) {
val engine = ScriptEngineManager().getEngineByName("nashorn")
engine.put("ctx", ctx)
try {
val res = engine.eval(ctx.rawArgs.joinToString(" "))
ctx.sendCode("js", res ?: "null")
} catch (e: Throwable) {
ctx.sendCode("diff", "- $e")
}
}
} | src/main/kotlin/moe/kyubey/akatsuki/commands/JS.kt | 326449359 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsEnumVariant
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.psi.RsTupleFieldDecl
import org.rust.lang.core.stubs.RsPlaceholderStub
import javax.swing.Icon
val RsTupleFieldDecl.position: Int?
get() = owner?.positionalFields?.withIndex()?.firstOrNull { it.value === this }?.index
abstract class RsTupleFieldDeclImplMixin : RsStubbedElementImpl<RsPlaceholderStub<*>>, RsTupleFieldDecl {
constructor(node: ASTNode) : super(node)
constructor(stub: RsPlaceholderStub<*>, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon =
if (owner is RsEnumVariant) RsIcons.FIELD else iconWithVisibility(flags, RsIcons.FIELD)
override fun getName(): String? = position?.toString()
override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope()
}
| src/main/kotlin/org/rust/lang/core/psi/ext/RsTupleFieldDecl.kt | 2246817419 |
/*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.currency
import com.mvcoding.expensius.extensions.toSystemCurrency
import com.mvcoding.expensius.model.Currency
import com.mvcoding.expensius.model.CurrencyFormat
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*
class SystemCurrencyFormatsProvider : CurrencyFormatsProvider {
override fun getCurrencyFormat(currency: Currency): CurrencyFormat = currency.toSystemCurrency()?.toCurrencyFormat() ?: currency.getDefaultCurrencyFormat()
private fun Currency.getDefaultCurrencyFormat(): CurrencyFormat {
return NumberFormat.getCurrencyInstance(Locale.getDefault())
.let {
CurrencyFormat(
code,
it.symbolPosition(),
symbolDistance(),
it.decimalSeparator(),
it.groupSeparator(),
it.minFractionDigits(),
it.maxFractionDigits())
}
}
private fun java.util.Currency.toCurrencyFormat(): CurrencyFormat {
return NumberFormat.getCurrencyInstance(Locale.getDefault())
.apply { currency = this@toCurrencyFormat }
.let {
CurrencyFormat(
symbol,
it.symbolPosition(),
symbolDistance(),
it.decimalSeparator(),
it.groupSeparator(),
it.minFractionDigits(),
it.maxFractionDigits())
}
}
private fun NumberFormat.symbolPosition(): CurrencyFormat.SymbolPosition = if (this is DecimalFormat) {
toLocalizedPattern().indexOf('\u00A4').let { if (it == 0) CurrencyFormat.SymbolPosition.START else CurrencyFormat.SymbolPosition.END }
} else {
CurrencyFormat.SymbolPosition.START
}
private fun NumberFormat.decimalSeparator(): CurrencyFormat.DecimalSeparator = if (this is DecimalFormat) {
decimalFormatSymbols.decimalSeparator.let {
when (it) {
',' -> CurrencyFormat.DecimalSeparator.COMMA
' ' -> CurrencyFormat.DecimalSeparator.SPACE
else -> CurrencyFormat.DecimalSeparator.DOT
}
}
} else {
CurrencyFormat.DecimalSeparator.DOT
}
private fun NumberFormat.groupSeparator(): CurrencyFormat.GroupSeparator = if (this is DecimalFormat) {
decimalFormatSymbols.groupingSeparator.let {
when (it) {
'.' -> CurrencyFormat.GroupSeparator.DOT
',' -> CurrencyFormat.GroupSeparator.COMMA
' ' -> CurrencyFormat.GroupSeparator.SPACE
else -> CurrencyFormat.GroupSeparator.NONE
}
}
} else {
CurrencyFormat.GroupSeparator.NONE
}
private fun symbolDistance() = CurrencyFormat.SymbolDistance.FAR
private fun NumberFormat.minFractionDigits() = minimumFractionDigits
private fun NumberFormat.maxFractionDigits() = maximumFractionDigits
} | app-core/src/main/kotlin/com/mvcoding/expensius/feature/currency/SystemCurrencyFormatsProvider.kt | 1119727978 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class ChopParameterListIntentionTest : RsIntentionTestBase(ChopParameterListIntention::class) {
fun `test one parameter`() = doUnavailableTest("""
fn foo(/*caret*/p1: i32) {}
""")
fun `test two parameter`() = doAvailableTest("""
fn foo(/*caret*/p1: i32, p2: i32) {}
""", """
fn foo(
p1: i32,
p2: i32
) {}
""")
fun `test has all line breaks`() = doUnavailableTest("""
fn foo(
/*caret*/p1: i32,
p2: i32,
p3: i32
) {}
""")
fun `test has some line breaks`() = doAvailableTest("""
fn foo(p1: i32, /*caret*/p2: i32,
p3: i32
) {}
""", """
fn foo(
p1: i32,
p2: i32,
p3: i32
) {}
""")
fun `test has some line breaks 2`() = doAvailableTest("""
fn foo(
p1: i32, p2: i32, p3: i32/*caret*/
) {}
""", """
fn foo(
p1: i32,
p2: i32,
p3: i32
) {}
""")
fun `test has comment`() = doUnavailableTest("""
fn foo(
/*caret*/p1: i32, /* comment */
p2: i32,
p3: i32
) {}
""")
fun `test has comment 2`() = doAvailableTest("""
fn foo(
/*caret*/p1: i32, /*
comment
*/p2: i32,
p3: i32
) {}
""", """
fn foo(
p1: i32, /*
comment
*/
p2: i32,
p3: i32
) {}
""")
fun `test has single line comment`() = doAvailableTest("""
fn foo(/*caret*/p1: i32, // comment p1
p2: i32, p3: i32 // comment p3
) {}
""", """
fn foo(
p1: i32, // comment p1
p2: i32,
p3: i32 // comment p3
) {}
""")
fun `test trailing comma`() = doAvailableTest("""
fn foo(/*caret*/p1: i32, p2: i32, p3: i32,) {}
""", """
fn foo(
p1: i32,
p2: i32,
p3: i32,
) {}
""")
fun `test trailing comma with comments`() = doAvailableTest("""
fn foo(/*caret*/p1: i32 /* comment 1 */, p2: i32, p3: i32 /* comment 2 */,) {}
""", """
fn foo(
p1: i32 /* comment 1 */,
p2: i32,
p3: i32 /* comment 2 */,
) {}
""")
}
| src/test/kotlin/org/rust/ide/intentions/ChopParameterListIntentionTest.kt | 715103782 |
package com.habitrpg.android.habitica.ui.fragments.support
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.os.bundleOf
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.FAQRepository
import com.habitrpg.android.habitica.databinding.FragmentFaqOverviewBinding
import com.habitrpg.android.habitica.databinding.SupportFaqItemBinding
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.setMarkdown
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import io.reactivex.rxjava3.functions.Consumer
import javax.inject.Inject
class FAQOverviewFragment : BaseMainFragment<FragmentFaqOverviewBinding>() {
override var binding: FragmentFaqOverviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentFaqOverviewBinding {
return FragmentFaqOverviewBinding.inflate(inflater, container, false)
}
@Inject
lateinit var faqRepository: FAQRepository
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
hidesToolbar = true
showsBackButton = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.healthSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfHeartLarge())
binding?.experienceSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfExperienceReward())
binding?.manaSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfMagicLarge())
binding?.goldSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfGoldReward())
binding?.gemsSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
binding?.hourglassesSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfHourglassLarge())
binding?.statsSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfStats())
binding?.moreHelpTextView?.setMarkdown(context?.getString(R.string.need_help_header_description, "[Habitica Help Guild](https://habitica.com/groups/guild/5481ccf3-5d2d-48a9-a871-70a7380cee5a)"))
binding?.moreHelpTextView?.setOnClickListener { MainNavigationController.navigate(R.id.guildFragment, bundleOf("groupID" to "5481ccf3-5d2d-48a9-a871-70a7380cee5a")) }
binding?.moreHelpTextView?.movementMethod = LinkMovementMethod.getInstance()
this.loadArticles()
}
override fun onDestroy() {
faqRepository.close()
super.onDestroy()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun loadArticles() {
compositeSubscription.add(
faqRepository.getArticles().subscribe(
Consumer {
val context = context ?: return@Consumer
for (article in it) {
val binding = SupportFaqItemBinding.inflate(context.layoutInflater, binding?.faqLinearLayout, true)
binding.textView.text = article.question
binding.root.setOnClickListener {
val direction = FAQOverviewFragmentDirections.openFAQDetail(null, null)
direction.position = article.position ?: 0
MainNavigationController.navigate(direction)
}
}
},
RxErrorHandler.handleEmptyError()
)
)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/FAQOverviewFragment.kt | 3446150164 |
/*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.execution.model.stages
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.docker.client.DockerContainerType
import batect.execution.ContainerDependencyGraph
import batect.execution.ContainerDependencyGraphNode
import batect.execution.model.rules.TaskStepRule
import batect.execution.model.rules.run.BuildImageStepRule
import batect.execution.model.rules.run.CreateContainerStepRule
import batect.execution.model.rules.run.CreateTaskNetworkStepRule
import batect.execution.model.rules.run.PullImageStepRule
import batect.execution.model.rules.run.RunContainerSetupCommandsStepRule
import batect.execution.model.rules.run.RunContainerStepRule
import batect.execution.model.rules.run.WaitForContainerToBecomeHealthyStepRule
import batect.logging.Logger
import batect.utils.flatMapToSet
import batect.utils.mapToSet
class RunStagePlanner(private val logger: Logger) {
fun createStage(graph: ContainerDependencyGraph, containerType: DockerContainerType): RunStage {
val allContainersInNetwork = graph.allNodes.mapToSet { it.container }
val rules = imageCreationRulesFor(graph) +
graph.allNodes.flatMapToSet { executionStepsFor(it, allContainersInNetwork) } +
CreateTaskNetworkStepRule(containerType)
logger.info {
message("Created run plan.")
data("rules", rules.map { it.toString() })
}
return RunStage(rules, graph.taskContainerNode.container)
}
private fun executionStepsFor(node: ContainerDependencyGraphNode, allContainersInNetwork: Set<Container>) = setOf(
CreateContainerStepRule(node.container, node.config, allContainersInNetwork),
RunContainerStepRule(node.container, node.dependsOnContainers),
WaitForContainerToBecomeHealthyStepRule(node.container),
RunContainerSetupCommandsStepRule(node.container, node.config, allContainersInNetwork)
)
private fun imageCreationRulesFor(graph: ContainerDependencyGraph): Set<TaskStepRule> {
return graph.allNodes.map { it.container }
.groupBy { it.imageSource }
.mapToSet { (imageSource, containers) ->
when (imageSource) {
is PullImage -> PullImageStepRule(imageSource)
is BuildImage -> BuildImageStepRule(imageSource, imageTagsFor(graph.config.projectName, containers))
}
}
}
private fun imageTagsFor(projectName: String, containers: List<Container>): Set<String> =
containers.mapToSet { "$projectName-${it.name}" }
}
| app/src/main/kotlin/batect/execution/model/stages/RunStagePlanner.kt | 2782747895 |
/*
* Copyright 2002-2022 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
*
* 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 org.springframework.security.config.annotation.web
import org.assertj.core.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.UnsatisfiedDependencyException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.authorization.AuthorizationDecision
import org.springframework.security.authorization.AuthorizationManager
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.core.Authentication
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.access.intercept.RequestAuthorizationContext
import org.springframework.security.web.util.matcher.RegexRequestMatcher
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.put
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import org.springframework.web.util.WebUtils
import java.util.function.Supplier
import jakarta.servlet.DispatcherType
/**
* Tests for [AuthorizeHttpRequestsDsl]
*
* @author Yuriy Savchenko
*/
@ExtendWith(SpringTestContextExtension::class)
class AuthorizeHttpRequestsDslTests {
@JvmField
val spring = SpringTestContext(this)
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `request when secured by regex matcher then responds with forbidden`() {
this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by regex matcher then responds with ok`() {
this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
}
@Test
fun `request when allowed by regex matcher with http method then responds based on method`() {
this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire()
this.mockMvc.post("/onlyPostPermitted") { with(csrf()) }
.andExpect {
status { isOk() }
}
this.mockMvc.get("/onlyPostPermitted")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
open class AuthorizeHttpRequestsByRegexConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize(RegexRequestMatcher("/path", null), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "POST"), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "GET"), denyAll)
authorize(RegexRequestMatcher(".*", null), authenticated)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
@RequestMapping("/onlyPostPermitted")
fun onlyPostPermitted() {
}
}
}
@Test
fun `request when secured by mvc then responds with forbidden`() {
this.spring.register(AuthorizeHttpRequestsByMvcConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by mvc then responds with OK`() {
this.spring.register(AuthorizeHttpRequestsByMvcConfig::class.java, LegacyMvcMatchingConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path.html")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path/")
.andExpect {
status { isOk() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeHttpRequestsByMvcConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/path", permitAll)
authorize("/**", authenticated)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Configuration
open class LegacyMvcMatchingConfig : WebMvcConfigurer {
override fun configurePathMatch(configurer: PathMatchConfigurer) {
configurer.setUseSuffixPatternMatch(true)
}
}
@Test
fun `request when secured by mvc path variables then responds based on path variable value`() {
this.spring.register(MvcMatcherPathVariablesConfig::class.java).autowire()
this.mockMvc.get("/user/user")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/user/deny")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherPathVariablesConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
val access = AuthorizationManager { _: Supplier<Authentication>, context: RequestAuthorizationContext ->
AuthorizationDecision(context.variables["userName"] == "user")
}
http {
authorizeHttpRequests {
authorize("/user/{userName}", access)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/user/{user}")
fun path(@PathVariable user: String) {
}
}
}
@Test
fun `request when user has allowed role then responds with OK`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have allowed role then responds with forbidden`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasRoleConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/**", hasRole("ADMIN"))
}
httpBasic { }
}
return http.build()
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
open fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val adminDetails = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
return InMemoryUserDetailsManager(userDetails, adminDetails)
}
}
@Test
fun `request when user has some allowed roles then responds with OK`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed roles then responds with forbidden`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyRoleConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/**", hasAnyRole("ADMIN", "USER"))
}
httpBasic { }
}
return http.build()
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
open fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.roles("OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when user has allowed authority then responds with OK`() {
this.spring.register(HasAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have allowed authority then responds with forbidden`() {
this.spring.register(HasAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAuthorityConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/**", hasAuthority("ROLE_ADMIN"))
}
httpBasic { }
}
return http.build()
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
open fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val adminDetails = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
return InMemoryUserDetailsManager(userDetails, adminDetails)
}
}
@Test
fun `request when user has some allowed authorities then responds with OK`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed authorities then responds with forbidden`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyAuthorityConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/**", hasAnyAuthority("ROLE_ADMIN", "ROLE_USER"))
}
httpBasic { }
}
return http.build()
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
open fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.authorities("ROLE_USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.authorities("ROLE_ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.authorities("ROLE_OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when secured by mvc with servlet path then responds based on servlet path`() {
this.spring.register(MvcMatcherServletPathConfig::class.java).autowire()
this.mockMvc.perform(get("/spring/path")
.with { request ->
request.servletPath = "/spring"
request
})
.andExpect(status().isForbidden)
this.mockMvc.perform(get("/other/path")
.with { request ->
request.servletPath = "/other"
request
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/path", "/spring", denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with http method then responds based on http method`() {
this.spring.register(AuthorizeRequestsByMvcConfigWithHttpMethod::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.put("/path") { with(csrf()) }
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeRequestsByMvcConfigWithHttpMethod {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize(HttpMethod.GET, "/path", permitAll)
authorize(HttpMethod.PUT, "/path", denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with servlet path and http method then responds based on path and method`() {
this.spring.register(MvcMatcherServletPathHttpMethodConfig::class.java).autowire()
this.mockMvc.perform(get("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(put("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
csrf()
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(get("/other/path")
.with { request ->
request.apply {
servletPath = "/other"
}
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathHttpMethodConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize(HttpMethod.GET, "/path", "/spring", denyAll)
authorize(HttpMethod.PUT, "/path", "/spring", denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when both authorizeRequests and authorizeHttpRequests configured then exception`() {
assertThatThrownBy { this.spring.register(BothAuthorizeRequestsConfig::class.java).autowire() }
.isInstanceOf(UnsatisfiedDependencyException::class.java)
.hasRootCauseInstanceOf(IllegalStateException::class.java)
.hasMessageContaining(
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one."
)
}
@EnableWebSecurity
@EnableWebMvc
open class BothAuthorizeRequestsConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, permitAll)
}
authorizeHttpRequests {
authorize(anyRequest, denyAll)
}
}
return http.build()
}
}
@Test
fun `request when shouldFilterAllDispatcherTypes and denyAll and ERROR then responds with forbidden`() {
this.spring.register(ShouldFilterAllDispatcherTypesTrueDenyAllConfig::class.java).autowire()
this.mockMvc.perform(get("/path")
.with { request ->
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error")
request.apply {
dispatcherType = DispatcherType.ERROR
}
})
.andExpect(status().isForbidden)
}
@EnableWebSecurity
@EnableWebMvc
open class ShouldFilterAllDispatcherTypesTrueDenyAllConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
shouldFilterAllDispatcherTypes = true
authorize(anyRequest, denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when shouldFilterAllDispatcherTypes and permitAll and ERROR then responds with ok`() {
this.spring.register(ShouldFilterAllDispatcherTypesTruePermitAllConfig::class.java).autowire()
this.mockMvc.perform(get("/path")
.with { request ->
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error")
request.apply {
dispatcherType = DispatcherType.ERROR
}
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class ShouldFilterAllDispatcherTypesTruePermitAllConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
shouldFilterAllDispatcherTypes = true
authorize(anyRequest, permitAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when shouldFilterAllDispatcherTypes false and ERROR dispatcher then responds with ok`() {
this.spring.register(ShouldFilterAllDispatcherTypesFalseAndDenyAllConfig::class.java).autowire()
this.mockMvc.perform(get("/path")
.with { request ->
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error")
request.apply {
dispatcherType = DispatcherType.ERROR
}
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class ShouldFilterAllDispatcherTypesFalseAndDenyAllConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
shouldFilterAllDispatcherTypes = false
authorize(anyRequest, denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when shouldFilterAllDispatcherTypes omitted and ERROR dispatcher then responds with forbidden`() {
this.spring.register(ShouldFilterAllDispatcherTypesOmittedAndDenyAllConfig::class.java).autowire()
this.mockMvc.perform(get("/path")
.with { request ->
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error")
request.apply {
dispatcherType = DispatcherType.ERROR
}
})
.andExpect(status().isForbidden)
}
@EnableWebSecurity
@EnableWebMvc
open class ShouldFilterAllDispatcherTypesOmittedAndDenyAllConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize(anyRequest, denyAll)
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
}
| config/src/test/kotlin/org/springframework/security/config/annotation/web/AuthorizeHttpRequestsDslTests.kt | 1512627490 |
package com.devbrackets.android.exomedia.core.renderer
import android.content.Context
import android.os.Handler
import com.devbrackets.android.exomedia.core.renderer.provider.AudioRenderProvider
import com.devbrackets.android.exomedia.core.renderer.provider.CaptionRenderProvider
import com.devbrackets.android.exomedia.core.renderer.provider.MetadataRenderProvider
import com.devbrackets.android.exomedia.core.renderer.provider.VideoRenderProvider
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.RenderersFactory
import androidx.media3.exoplayer.audio.AudioRendererEventListener
import androidx.media3.exoplayer.metadata.MetadataOutput
import androidx.media3.exoplayer.text.TextOutput
import androidx.media3.exoplayer.video.VideoRendererEventListener
class PlayerRendererFactory(
private val context: Context
): RenderersFactory {
override fun createRenderers(
eventHandler: Handler,
videoRendererEventListener: VideoRendererEventListener,
audioRendererEventListener: AudioRendererEventListener,
textRendererOutput: TextOutput,
metadataRendererOutput: MetadataOutput
): Array<Renderer> {
return mutableListOf<Renderer>().apply {
addAll(AudioRenderProvider().buildRenderers(context, eventHandler, audioRendererEventListener))
addAll(VideoRenderProvider().buildRenderers(context, eventHandler, videoRendererEventListener))
addAll(CaptionRenderProvider().buildRenderers(eventHandler, textRendererOutput))
addAll(MetadataRenderProvider().buildRenderers(eventHandler, metadataRendererOutput))
}.toTypedArray()
}
} | library/src/main/kotlin/com/devbrackets/android/exomedia/core/renderer/PlayerRendererFactory.kt | 2482537831 |
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.config
import com.netflix.spinnaker.q.Activator
import com.netflix.spinnaker.q.DeadMessageCallback
import com.netflix.spinnaker.q.EnabledActivator
import com.netflix.spinnaker.q.MessageHandler
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.q.QueueExecutor
import com.netflix.spinnaker.q.QueueProcessor
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.QueueEvent
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationEventPublisher
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.time.Clock
import java.time.Duration
@Configuration
@EnableConfigurationProperties(QueueProperties::class, ObjectMapperSubtypeProperties::class)
@ComponentScan(basePackages = ["com.netflix.spinnaker.q"])
@EnableScheduling
class QueueConfiguration {
@Bean
@ConditionalOnMissingBean(Clock::class)
fun systemClock(): Clock = Clock.systemDefaultZone()
@Bean
fun messageHandlerPool(queueProperties: QueueProperties) =
ThreadPoolTaskExecutor().apply {
threadNamePrefix = queueProperties.handlerThreadNamePrefix
corePoolSize = queueProperties.handlerCorePoolSize
maxPoolSize = queueProperties.handlerMaxPoolSize
setQueueCapacity(0)
}
@Bean
@ConditionalOnMissingBean(QueueExecutor::class)
fun queueExecutor(messageHandlerPool: ThreadPoolTaskExecutor) =
object : QueueExecutor<ThreadPoolTaskExecutor>(messageHandlerPool) {
override fun hasCapacity() =
executor.threadPoolExecutor.run {
activeCount < maximumPoolSize
}
override fun availableCapacity() =
executor.threadPoolExecutor.run {
maximumPoolSize - activeCount
}
}
@Bean
fun queueProcessor(
queue: Queue,
executor: QueueExecutor<*>,
handlers: Collection<MessageHandler<*>>,
activators: List<Activator>,
publisher: EventPublisher,
queueProperties: QueueProperties,
deadMessageHandler: DeadMessageCallback
) = QueueProcessor(
queue,
executor,
handlers,
activators,
publisher,
deadMessageHandler,
queueProperties.fillExecutorEachCycle,
Duration.ofSeconds(queueProperties.requeueDelaySeconds),
Duration.ofSeconds(queueProperties.requeueMaxJitterSeconds)
)
@Bean
fun enabledActivator(queueProperties: QueueProperties) = EnabledActivator(queueProperties.enabled)
@Bean
fun queueEventPublisher(
applicationEventPublisher: ApplicationEventPublisher
) = object : EventPublisher {
override fun publishEvent(event: QueueEvent) {
applicationEventPublisher.publishEvent(event)
}
}
}
| keiko-spring/src/main/kotlin/com/netflix/spinnaker/config/QueueConfiguration.kt | 3922968599 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.node
import androidx.compose.testutils.TestViewConfiguration
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.Autofill
import androidx.compose.ui.autofill.AutofillTree
import androidx.compose.ui.draw.DrawModifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.geometry.MutableRect
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.RenderEffect
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerIconService
import androidx.compose.ui.input.pointer.PointerInputFilter
import androidx.compose.ui.input.pointer.PointerInputModifier
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.RootMeasurePolicy.measure
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.modifier.ModifierLocalManager
import androidx.compose.ui.platform.AccessibilityManager
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.platform.TextToolbar
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.platform.WindowInfo
import androidx.compose.ui.platform.invertTo
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsModifier
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toOffset
import androidx.compose.ui.zIndex
import com.google.common.truth.Truth.assertThat
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
@OptIn(ExperimentalComposeUiApi::class)
class LayoutNodeTest {
// Ensure that attach and detach work properly
@Test
fun layoutNodeAttachDetach() {
val node = LayoutNode()
assertNull(node.owner)
val owner = MockOwner()
node.attach(owner)
assertEquals(owner, node.owner)
assertTrue(node.isAttached)
assertEquals(1, owner.onAttachParams.count { it === node })
node.detach()
assertNull(node.owner)
assertFalse(node.isAttached)
assertEquals(1, owner.onDetachParams.count { it === node })
}
// Ensure that LayoutNode's children are ordered properly through add, remove, move
@Test
fun layoutNodeChildrenOrder() {
val (node, child1, child2) = createSimpleLayout()
assertEquals(2, node.children.size)
assertEquals(child1, node.children[0])
assertEquals(child2, node.children[1])
assertEquals(0, child1.children.size)
assertEquals(0, child2.children.size)
node.removeAt(index = 0, count = 1)
assertEquals(1, node.children.size)
assertEquals(child2, node.children[0])
node.insertAt(index = 0, instance = child1)
assertEquals(2, node.children.size)
assertEquals(child1, node.children[0])
assertEquals(child2, node.children[1])
node.removeAt(index = 0, count = 2)
assertEquals(0, node.children.size)
val child3 = LayoutNode()
val child4 = LayoutNode()
node.insertAt(0, child1)
node.insertAt(1, child2)
node.insertAt(2, child3)
node.insertAt(3, child4)
assertEquals(4, node.children.size)
assertEquals(child1, node.children[0])
assertEquals(child2, node.children[1])
assertEquals(child3, node.children[2])
assertEquals(child4, node.children[3])
node.move(from = 3, count = 1, to = 0)
assertEquals(4, node.children.size)
assertEquals(child4, node.children[0])
assertEquals(child1, node.children[1])
assertEquals(child2, node.children[2])
assertEquals(child3, node.children[3])
node.move(from = 0, count = 2, to = 3)
assertEquals(4, node.children.size)
assertEquals(child2, node.children[0])
assertEquals(child3, node.children[1])
assertEquals(child4, node.children[2])
assertEquals(child1, node.children[3])
}
// Ensure that attach of a LayoutNode connects all children
@Test
fun layoutNodeAttach() {
val (node, child1, child2) = createSimpleLayout()
val owner = MockOwner()
node.attach(owner)
assertEquals(owner, node.owner)
assertEquals(owner, child1.owner)
assertEquals(owner, child2.owner)
assertEquals(1, owner.onAttachParams.count { it === node })
assertEquals(1, owner.onAttachParams.count { it === child1 })
assertEquals(1, owner.onAttachParams.count { it === child2 })
}
// Ensure that detach of a LayoutNode detaches all children
@Test
fun layoutNodeDetach() {
val (node, child1, child2) = createSimpleLayout()
val owner = MockOwner()
node.attach(owner)
owner.onAttachParams.clear()
node.detach()
assertEquals(node, child1.parent)
assertEquals(node, child2.parent)
assertNull(node.owner)
assertNull(child1.owner)
assertNull(child2.owner)
assertEquals(1, owner.onDetachParams.count { it === node })
assertEquals(1, owner.onDetachParams.count { it === child1 })
assertEquals(1, owner.onDetachParams.count { it === child2 })
}
// Ensure that dropping a child also detaches it
@Test
fun layoutNodeDropDetaches() {
val (node, child1, child2) = createSimpleLayout()
val owner = MockOwner()
node.attach(owner)
node.removeAt(0, 1)
assertEquals(owner, node.owner)
assertNull(child1.owner)
assertEquals(owner, child2.owner)
assertEquals(0, owner.onDetachParams.count { it === node })
assertEquals(1, owner.onDetachParams.count { it === child1 })
assertEquals(0, owner.onDetachParams.count { it === child2 })
}
// Ensure that adopting a child also attaches it
@Test
fun layoutNodeAdoptAttaches() {
val (node, child1, child2) = createSimpleLayout()
val owner = MockOwner()
node.attach(owner)
node.removeAt(0, 1)
node.insertAt(1, child1)
assertEquals(owner, node.owner)
assertEquals(owner, child1.owner)
assertEquals(owner, child2.owner)
assertEquals(1, owner.onAttachParams.count { it === node })
assertEquals(2, owner.onAttachParams.count { it === child1 })
assertEquals(1, owner.onAttachParams.count { it === child2 })
}
@Test
fun childAdd() {
val node = LayoutNode()
val owner = MockOwner()
node.attach(owner)
assertEquals(1, owner.onAttachParams.count { it === node })
val child = LayoutNode()
node.insertAt(0, child)
assertEquals(1, owner.onAttachParams.count { it === child })
assertEquals(1, node.children.size)
assertEquals(node, child.parent)
assertEquals(owner, child.owner)
}
@Test
fun childCount() {
val node = LayoutNode()
assertEquals(0, node.children.size)
node.insertAt(0, LayoutNode())
assertEquals(1, node.children.size)
}
@Test
fun childGet() {
val node = LayoutNode()
val child = LayoutNode()
node.insertAt(0, child)
assertEquals(child, node.children[0])
}
@Test
fun noMove() {
val (layout, child1, child2) = createSimpleLayout()
layout.move(0, 0, 1)
assertEquals(child1, layout.children[0])
assertEquals(child2, layout.children[1])
}
@Test
fun childRemove() {
val node = LayoutNode()
val owner = MockOwner()
node.attach(owner)
val child = LayoutNode()
node.insertAt(0, child)
node.removeAt(index = 0, count = 1)
assertEquals(1, owner.onDetachParams.count { it === child })
assertEquals(0, node.children.size)
assertEquals(null, child.parent)
assertNull(child.owner)
}
// Ensure that depth is as expected
@Test
fun depth() {
val root = LayoutNode()
val (child, grand1, grand2) = createSimpleLayout()
root.insertAt(0, child)
val owner = MockOwner()
root.attach(owner)
assertEquals(0, root.depth)
assertEquals(1, child.depth)
assertEquals(2, grand1.depth)
assertEquals(2, grand2.depth)
}
// layoutNode hierarchy should be set properly when a LayoutNode is a child of a LayoutNode
@Test
fun directLayoutNodeHierarchy() {
val layoutNode = LayoutNode()
val childLayoutNode = LayoutNode()
layoutNode.insertAt(0, childLayoutNode)
assertNull(layoutNode.parent)
assertEquals(layoutNode, childLayoutNode.parent)
val layoutNodeChildren = layoutNode.children
assertEquals(1, layoutNodeChildren.size)
assertEquals(childLayoutNode, layoutNodeChildren[0])
layoutNode.removeAt(index = 0, count = 1)
assertNull(childLayoutNode.parent)
}
@Test
fun testLayoutNodeAdd() {
val (layout, child1, child2) = createSimpleLayout()
val inserted = LayoutNode()
layout.insertAt(0, inserted)
val children = layout.children
assertEquals(3, children.size)
assertEquals(inserted, children[0])
assertEquals(child1, children[1])
assertEquals(child2, children[2])
}
@Test
fun testLayoutNodeRemove() {
val (layout, child1, _) = createSimpleLayout()
val child3 = LayoutNode()
val child4 = LayoutNode()
layout.insertAt(2, child3)
layout.insertAt(3, child4)
layout.removeAt(index = 1, count = 2)
val children = layout.children
assertEquals(2, children.size)
assertEquals(child1, children[0])
assertEquals(child4, children[1])
}
@Test
fun testMoveChildren() {
val (layout, child1, child2) = createSimpleLayout()
val child3 = LayoutNode()
val child4 = LayoutNode()
layout.insertAt(2, child3)
layout.insertAt(3, child4)
layout.move(from = 2, to = 1, count = 2)
val children = layout.children
assertEquals(4, children.size)
assertEquals(child1, children[0])
assertEquals(child3, children[1])
assertEquals(child4, children[2])
assertEquals(child2, children[3])
layout.move(from = 1, to = 3, count = 2)
assertEquals(4, children.size)
assertEquals(child1, children[0])
assertEquals(child2, children[1])
assertEquals(child3, children[2])
assertEquals(child4, children[3])
}
@Test
fun testPxGlobalToLocal() {
val node0 = ZeroSizedLayoutNode()
node0.attach(MockOwner())
val node1 = ZeroSizedLayoutNode()
node0.insertAt(0, node1)
val x0 = 100
val y0 = 10
val x1 = 50
val y1 = 80
node0.place(x0, y0)
node1.place(x1, y1)
val globalPosition = Offset(250f, 300f)
val expectedX = globalPosition.x - x0.toFloat() - x1.toFloat()
val expectedY = globalPosition.y - y0.toFloat() - y1.toFloat()
val expectedPosition = Offset(expectedX, expectedY)
val result = node1.coordinates.windowToLocal(globalPosition)
assertEquals(expectedPosition, result)
}
@Test
fun testIntPxGlobalToLocal() {
val node0 = ZeroSizedLayoutNode()
node0.attach(MockOwner())
val node1 = ZeroSizedLayoutNode()
node0.insertAt(0, node1)
val x0 = 100
val y0 = 10
val x1 = 50
val y1 = 80
node0.place(x0, y0)
node1.place(x1, y1)
val globalPosition = Offset(250f, 300f)
val expectedX = globalPosition.x - x0.toFloat() - x1.toFloat()
val expectedY = globalPosition.y - y0.toFloat() - y1.toFloat()
val expectedPosition = Offset(expectedX, expectedY)
val result = node1.coordinates.windowToLocal(globalPosition)
assertEquals(expectedPosition, result)
}
@Test
fun testPxLocalToGlobal() {
val node0 = ZeroSizedLayoutNode()
node0.attach(MockOwner())
val node1 = ZeroSizedLayoutNode()
node0.insertAt(0, node1)
val x0 = 100
val y0 = 10
val x1 = 50
val y1 = 80
node0.place(x0, y0)
node1.place(x1, y1)
val localPosition = Offset(5f, 15f)
val expectedX = localPosition.x + x0.toFloat() + x1.toFloat()
val expectedY = localPosition.y + y0.toFloat() + y1.toFloat()
val expectedPosition = Offset(expectedX, expectedY)
val result = node1.coordinates.localToWindow(localPosition)
assertEquals(expectedPosition, result)
}
@Test
fun testIntPxLocalToGlobal() {
val node0 = ZeroSizedLayoutNode()
node0.attach(MockOwner())
val node1 = ZeroSizedLayoutNode()
node0.insertAt(0, node1)
val x0 = 100
val y0 = 10
val x1 = 50
val y1 = 80
node0.place(x0, y0)
node1.place(x1, y1)
val localPosition = Offset(5f, 15f)
val expectedX = localPosition.x + x0.toFloat() + x1.toFloat()
val expectedY = localPosition.y + y0.toFloat() + y1.toFloat()
val expectedPosition = Offset(expectedX, expectedY)
val result = node1.coordinates.localToWindow(localPosition)
assertEquals(expectedPosition, result)
}
@Test
fun testPxLocalToGlobalUsesOwnerPosition() {
val node = ZeroSizedLayoutNode()
node.attach(MockOwner(IntOffset(20, 20)))
node.place(100, 10)
val result = node.coordinates.localToWindow(Offset.Zero)
assertEquals(Offset(120f, 30f), result)
}
@Test
fun testIntPxLocalToGlobalUsesOwnerPosition() {
val node = ZeroSizedLayoutNode()
node.attach(MockOwner(IntOffset(20, 20)))
node.place(100, 10)
val result = node.coordinates.localToWindow(Offset.Zero)
assertEquals(Offset(120f, 30f), result)
}
@Test
fun testChildToLocal() {
val node0 = ZeroSizedLayoutNode()
node0.attach(MockOwner())
val node1 = ZeroSizedLayoutNode()
node0.insertAt(0, node1)
val x1 = 50
val y1 = 80
node0.place(100, 10)
node1.place(x1, y1)
val localPosition = Offset(5f, 15f)
val expectedX = localPosition.x + x1.toFloat()
val expectedY = localPosition.y + y1.toFloat()
val expectedPosition = Offset(expectedX, expectedY)
val result = node0.coordinates.localPositionOf(node1.coordinates, localPosition)
assertEquals(expectedPosition, result)
}
@Test
fun testLocalPositionOfWithSiblings() {
val node0 = LayoutNode()
node0.attach(MockOwner())
val node1 = LayoutNode()
val node2 = LayoutNode()
node0.insertAt(0, node1)
node0.insertAt(1, node2)
node1.place(10, 20)
node2.place(100, 200)
val offset = node2.coordinates.localPositionOf(node1.coordinates, Offset(5f, 15f))
assertEquals(Offset(-85f, -165f), offset)
}
@Test
fun testChildToLocalFailedWhenNotAncestorNoParent() {
val owner = MockOwner()
val node0 = LayoutNode()
node0.attach(owner)
val node1 = LayoutNode()
node1.attach(owner)
Assert.assertThrows(IllegalArgumentException::class.java) {
node1.coordinates.localPositionOf(node0.coordinates, Offset(5f, 15f))
}
}
@Test
fun testChildToLocalTheSameNode() {
val node = LayoutNode()
node.attach(MockOwner())
val position = Offset(5f, 15f)
val result = node.coordinates.localPositionOf(node.coordinates, position)
assertEquals(position, result)
}
@Test
fun testPositionRelativeToRoot() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
parent.place(-100, 10)
child.place(50, 80)
val actual = child.coordinates.positionInRoot()
assertEquals(Offset(-50f, 90f), actual)
}
@Test
fun testPositionRelativeToRootIsNotAffectedByOwnerPosition() {
val parent = LayoutNode()
parent.attach(MockOwner(IntOffset(20, 20)))
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
child.place(50, 80)
val actual = child.coordinates.positionInRoot()
assertEquals(Offset(50f, 80f), actual)
}
@Test
fun testPositionRelativeToAncestorWithParent() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
parent.place(-100, 10)
child.place(50, 80)
val actual = parent.coordinates.localPositionOf(child.coordinates, Offset.Zero)
assertEquals(Offset(50f, 80f), actual)
}
@Test
fun testPositionRelativeToAncestorWithGrandParent() {
val grandParent = ZeroSizedLayoutNode()
grandParent.attach(MockOwner())
val parent = ZeroSizedLayoutNode()
val child = ZeroSizedLayoutNode()
grandParent.insertAt(0, parent)
parent.insertAt(0, child)
grandParent.place(-7, 17)
parent.place(23, -13)
child.place(-3, 11)
val actual = grandParent.coordinates.localPositionOf(child.coordinates, Offset.Zero)
assertEquals(Offset(20f, -2f), actual)
}
// LayoutNode shouldn't allow adding beyond the count
@Test
fun testAddBeyondCurrent() {
val node = LayoutNode()
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.insertAt(1, LayoutNode())
}
}
// LayoutNode shouldn't allow adding below 0
@Test
fun testAddBelowZero() {
val node = LayoutNode()
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.insertAt(-1, LayoutNode())
}
}
// LayoutNode should error when removing at index < 0
@Test
fun testRemoveNegativeIndex() {
val node = LayoutNode()
node.insertAt(0, LayoutNode())
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.removeAt(-1, 1)
}
}
// LayoutNode should error when removing at index > count
@Test
fun testRemoveBeyondIndex() {
val node = LayoutNode()
node.insertAt(0, LayoutNode())
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.removeAt(1, 1)
}
}
// LayoutNode should error when removing at count < 0
@Test
fun testRemoveNegativeCount() {
val node = LayoutNode()
node.insertAt(0, LayoutNode())
Assert.assertThrows(IllegalArgumentException::class.java) {
node.removeAt(0, -1)
}
}
// LayoutNode should error when removing at count > entry count
@Test
fun testRemoveWithIndexBeyondSize() {
val node = LayoutNode()
node.insertAt(0, LayoutNode())
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.removeAt(0, 2)
}
}
// LayoutNode should error when there aren't enough items
@Test
fun testRemoveWithIndexEqualToSize() {
val node = LayoutNode()
Assert.assertThrows(IndexOutOfBoundsException::class.java) {
node.removeAt(0, 1)
}
}
// LayoutNode should allow removing two items
@Test
fun testRemoveTwoItems() {
val node = LayoutNode()
node.insertAt(0, LayoutNode())
node.insertAt(0, LayoutNode())
node.removeAt(0, 2)
assertEquals(0, node.children.size)
}
// The layout coordinates of a LayoutNode should be attached when
// the layout node is attached.
@Test
fun coordinatesAttachedWhenLayoutNodeAttached() {
val layoutNode = LayoutNode()
val layoutModifier = Modifier.graphicsLayer { }
layoutNode.modifier = layoutModifier
assertFalse(layoutNode.coordinates.isAttached)
assertFalse(layoutNode.coordinates.isAttached)
layoutNode.attach(MockOwner())
assertTrue(layoutNode.coordinates.isAttached)
assertTrue(layoutNode.coordinates.isAttached)
layoutNode.detach()
assertFalse(layoutNode.coordinates.isAttached)
assertFalse(layoutNode.coordinates.isAttached)
}
// The NodeCoordinator should be reused when it has been replaced with the same type
@Test
fun nodeCoordinatorSameWithReplacementModifier() {
val layoutNode = LayoutNode()
val layoutModifier = Modifier.graphicsLayer { }
layoutNode.modifier = layoutModifier
val oldNodeCoordinator = layoutNode.outerCoordinator
assertFalse(oldNodeCoordinator.isAttached)
layoutNode.attach(MockOwner())
assertTrue(oldNodeCoordinator.isAttached)
layoutNode.modifier = Modifier.graphicsLayer { }
val newNodeCoordinator = layoutNode.outerCoordinator
assertSame(newNodeCoordinator, oldNodeCoordinator)
}
// The NodeCoordinator should be reused when it has been replaced with the same type,
// even with multiple NodeCoordinators for one modifier.
@Test
fun nodeCoordinatorSameWithReplacementMultiModifier() {
class TestModifier : DrawModifier, LayoutModifier {
override fun ContentDrawScope.draw() {
drawContent()
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
) = layout(0, 0) {}
}
val layoutNode = LayoutNode()
layoutNode.modifier = TestModifier()
val oldNodeCoordinator = layoutNode.outerCoordinator
val oldNodeCoordinator2 = oldNodeCoordinator.wrapped
layoutNode.modifier = TestModifier()
val newNodeCoordinator = layoutNode.outerCoordinator
val newNodeCoordinator2 = newNodeCoordinator.wrapped
assertSame(newNodeCoordinator, oldNodeCoordinator)
assertSame(newNodeCoordinator2, oldNodeCoordinator2)
}
// The NodeCoordinator should be detached when it has been replaced.
@Test
fun nodeCoordinatorAttachedWhenLayoutNodeAttached() {
val layoutNode = LayoutNode()
// 2 modifiers at the start
val layoutModifier = Modifier.graphicsLayer { }.graphicsLayer { }
layoutNode.modifier = layoutModifier
val oldNodeCoordinator = layoutNode.outerCoordinator
val oldInnerNodeCoordinator = oldNodeCoordinator.wrapped
assertFalse(oldNodeCoordinator.isAttached)
assertNotNull(oldInnerNodeCoordinator)
assertFalse(oldInnerNodeCoordinator!!.isAttached)
layoutNode.attach(MockOwner())
assertTrue(oldNodeCoordinator.isAttached)
// only 1 modifier now, so one should be detached and the other can be reused
layoutNode.modifier = Modifier.graphicsLayer()
val newNodeCoordinator = layoutNode.outerCoordinator
// one can be reused, but we don't care which one
val notReused = if (newNodeCoordinator == oldNodeCoordinator) {
oldInnerNodeCoordinator
} else {
oldNodeCoordinator
}
assertTrue(newNodeCoordinator.isAttached)
assertFalse(notReused.isAttached)
}
@Test
fun nodeCoordinatorParentLayoutCoordinates() {
val layoutNode = LayoutNode()
val layoutNode2 = LayoutNode()
val layoutModifier = Modifier.graphicsLayer { }
layoutNode.modifier = layoutModifier
layoutNode2.insertAt(0, layoutNode)
layoutNode2.attach(MockOwner())
assertEquals(
layoutNode2.innerCoordinator,
layoutNode.innerCoordinator.parentLayoutCoordinates
)
assertEquals(
layoutNode2.innerCoordinator,
layoutNode.outerCoordinator.parentLayoutCoordinates
)
}
@Test
fun nodeCoordinatorParentCoordinates() {
val layoutNode = LayoutNode()
val layoutNode2 = LayoutNode()
val layoutModifier = object : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
TODO("Not yet implemented")
}
}
val drawModifier = Modifier.drawBehind { }
layoutNode.modifier = layoutModifier.then(drawModifier)
layoutNode2.insertAt(0, layoutNode)
layoutNode2.attach(MockOwner())
val layoutModifierWrapper = layoutNode.outerCoordinator
assertEquals(
layoutModifierWrapper,
layoutNode.innerCoordinator.parentCoordinates
)
assertEquals(
layoutNode2.innerCoordinator,
layoutModifierWrapper.parentCoordinates
)
}
@Test
fun nodeCoordinator_transformFrom_offsets() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
parent.place(-100, 10)
child.place(50, 80)
val matrix = Matrix()
child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix)
assertEquals(Offset(-50f, -80f), matrix.map(Offset.Zero))
parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix)
assertEquals(Offset(50f, 80f), matrix.map(Offset.Zero))
}
@Test
fun nodeCoordinator_transformFrom_translation() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
child.modifier = Modifier.graphicsLayer {
translationX = 5f
translationY = 2f
}
parent.outerCoordinator
.measure(listOf(parent.outerCoordinator), Constraints())
child.outerCoordinator
.measure(listOf(child.outerCoordinator), Constraints())
parent.place(0, 0)
child.place(0, 0)
val matrix = Matrix()
child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix)
assertEquals(-5f, matrix.map(Offset.Zero).x, 0.001f)
assertEquals(-2f, matrix.map(Offset.Zero).y, 0.001f)
parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix)
assertEquals(5f, matrix.map(Offset.Zero).x, 0.001f)
assertEquals(2f, matrix.map(Offset.Zero).y, 0.001f)
}
@Test
fun nodeCoordinator_transformFrom_rotation() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
child.modifier = Modifier.graphicsLayer {
rotationZ = 90f
}
parent.outerCoordinator
.measure(listOf(parent.outerCoordinator), Constraints())
child.outerCoordinator
.measure(listOf(child.outerCoordinator), Constraints())
parent.place(0, 0)
child.place(0, 0)
val matrix = Matrix()
child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix)
assertEquals(0f, matrix.map(Offset(1f, 0f)).x, 0.001f)
assertEquals(-1f, matrix.map(Offset(1f, 0f)).y, 0.001f)
parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix)
assertEquals(0f, matrix.map(Offset(1f, 0f)).x, 0.001f)
assertEquals(1f, matrix.map(Offset(1f, 0f)).y, 0.001f)
}
@Test
fun nodeCoordinator_transformFrom_scale() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child = ZeroSizedLayoutNode()
parent.insertAt(0, child)
child.modifier = Modifier.graphicsLayer {
scaleX = 0f
}
parent.outerCoordinator
.measure(listOf(parent.outerCoordinator), Constraints())
child.outerCoordinator
.measure(listOf(child.outerCoordinator), Constraints())
parent.place(0, 0)
child.place(0, 0)
val matrix = Matrix()
child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix)
// The X coordinate is somewhat nonsensical since it is scaled to 0
// We've chosen to make it not transform when there's a nonsensical inverse.
assertEquals(1f, matrix.map(Offset(1f, 1f)).x, 0.001f)
assertEquals(1f, matrix.map(Offset(1f, 1f)).y, 0.001f)
parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix)
// This direction works, so we can expect the normal scaling
assertEquals(0f, matrix.map(Offset(1f, 1f)).x, 0.001f)
assertEquals(1f, matrix.map(Offset(1f, 1f)).y, 0.001f)
child.innerCoordinator.onLayerBlockUpdated {
scaleX = 0.5f
scaleY = 0.25f
}
child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix)
assertEquals(2f, matrix.map(Offset(1f, 1f)).x, 0.001f)
assertEquals(4f, matrix.map(Offset(1f, 1f)).y, 0.001f)
parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix)
assertEquals(0.5f, matrix.map(Offset(1f, 1f)).x, 0.001f)
assertEquals(0.25f, matrix.map(Offset(1f, 1f)).y, 0.001f)
}
@Test
fun nodeCoordinator_transformFrom_siblings() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child1 = ZeroSizedLayoutNode()
parent.insertAt(0, child1)
child1.modifier = Modifier.graphicsLayer {
scaleX = 0.5f
scaleY = 0.25f
transformOrigin = TransformOrigin(0f, 0f)
}
val child2 = ZeroSizedLayoutNode()
parent.insertAt(0, child2)
child2.modifier = Modifier.graphicsLayer {
scaleX = 5f
scaleY = 2f
transformOrigin = TransformOrigin(0f, 0f)
}
parent.outerCoordinator
.measure(listOf(parent.outerCoordinator), Constraints())
child1.outerCoordinator
.measure(listOf(child1.outerCoordinator), Constraints())
child2.outerCoordinator
.measure(listOf(child2.outerCoordinator), Constraints())
parent.place(0, 0)
child1.place(100, 200)
child2.place(5, 11)
val matrix = Matrix()
child2.innerCoordinator.transformFrom(child1.innerCoordinator, matrix)
// (20, 36) should be (10, 9) in real coordinates due to scaling
// Translate to (110, 209) in the parent
// Translate to (105, 198) in child2's coordinates, discounting scale
// Scaled to (21, 99)
val offset = matrix.map(Offset(20f, 36f))
assertEquals(21f, offset.x, 0.001f)
assertEquals(99f, offset.y, 0.001f)
child1.innerCoordinator.transformFrom(child2.innerCoordinator, matrix)
val offset2 = matrix.map(Offset(21f, 99f))
assertEquals(20f, offset2.x, 0.001f)
assertEquals(36f, offset2.y, 0.001f)
}
@Test
fun nodeCoordinator_transformFrom_cousins() {
val parent = ZeroSizedLayoutNode()
parent.attach(MockOwner())
val child1 = ZeroSizedLayoutNode()
parent.insertAt(0, child1)
val child2 = ZeroSizedLayoutNode()
parent.insertAt(1, child2)
val grandChild1 = ZeroSizedLayoutNode()
child1.insertAt(0, grandChild1)
val grandChild2 = ZeroSizedLayoutNode()
child2.insertAt(0, grandChild2)
parent.place(-100, 10)
child1.place(10, 11)
child2.place(22, 33)
grandChild1.place(45, 27)
grandChild2.place(17, 59)
val matrix = Matrix()
grandChild1.innerCoordinator.transformFrom(grandChild2.innerCoordinator, matrix)
// (17, 59) + (22, 33) - (10, 11) - (45, 27) = (-16, 54)
assertEquals(Offset(-16f, 54f), matrix.map(Offset.Zero))
grandChild2.innerCoordinator.transformFrom(grandChild1.innerCoordinator, matrix)
assertEquals(Offset(16f, -54f), matrix.map(Offset.Zero))
}
@Test
fun hitTest_pointerInBounds_pointerInputFilterHit() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl(pointerInputFilter)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(0f, 0f), hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl(pointerInputFilter),
DpSize(48.dp, 48.dp)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(-3f, 3f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_horizontal() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1000, 1,
PointerInputModifierImpl(pointerInputFilter),
DpSize(48.dp, 48.dp)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(0f, 3f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_vertical() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1, 1000,
PointerInputModifierImpl(pointerInputFilter),
DpSize(48.dp, 48.dp)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(3f, 0f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_nestedNodes() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val outerNode = LayoutNode(0, 0, 1, 1).apply { attach(MockOwner()) }
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl(pointerInputFilter),
DpSize(48.dp, 48.dp)
)
outerNode.add(layoutNode)
layoutNode.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
outerNode.hitTest(Offset(-3f, 3f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInputFilterHit_outsideParent() {
val outerPointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val outerNode = LayoutNode(
0, 0, 10, 10,
PointerInputModifierImpl(outerPointerInputFilter)
).apply { attach(MockOwner()) }
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode = LayoutNode(
20, 20, 30, 30,
PointerInputModifierImpl(pointerInputFilter)
)
outerNode.add(layoutNode)
layoutNode.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
outerNode.hitTest(Offset(25f, 25f), hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerInputFilterHit_outsideParent_interceptOutOfBoundsChildEvents() {
val outerPointerInputFilter: PointerInputFilter = mockPointerInputFilter(
interceptChildEvents = true
)
val outerNode = LayoutNode(
0, 0, 10, 10,
PointerInputModifierImpl(outerPointerInputFilter)
).apply { attach(MockOwner()) }
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode = LayoutNode(
20, 20, 30, 30,
PointerInputModifierImpl(pointerInputFilter)
)
outerNode.add(layoutNode)
layoutNode.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
outerNode.hitTest(Offset(25f, 25f), hit)
assertThat(hit.toFilters()).isEqualTo(listOf(outerPointerInputFilter, pointerInputFilter))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_closestHit() {
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
0, 0, 5, 5,
PointerInputModifierImpl(pointerInputFilter1),
DpSize(48.dp, 48.dp)
)
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val layoutNode2 = LayoutNode(
6, 6, 11, 11,
PointerInputModifierImpl(pointerInputFilter2),
DpSize(48.dp, 48.dp)
)
val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) }
outerNode.add(layoutNode1)
outerNode.add(layoutNode2)
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
// Hit closer to layoutNode1
outerNode.hitTest(Offset(5.1f, 5.5f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
hit.clear()
// Hit closer to layoutNode2
outerNode.hitTest(Offset(5.9f, 5.5f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
hit.clear()
// Hit closer to layoutNode1
outerNode.hitTest(Offset(5.5f, 5.1f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
hit.clear()
// Hit closer to layoutNode2
outerNode.hitTest(Offset(5.5f, 5.9f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
hit.clear()
// Hit inside layoutNode1
outerNode.hitTest(Offset(4.9f, 4.9f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
hit.clear()
// Hit inside layoutNode2
outerNode.hitTest(Offset(6.1f, 6.1f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
}
/**
* When a child is in the minimum touch target area, but the parent is big enough to not
* worry about minimum touch target, the child should still be able to be hit outside the
* parent's bounds.
*/
@Test
fun hitTest_pointerInMinimumTouchTarget_inChild_closestHit() {
test_pointerInMinimumTouchTarget_inChild_closestHit { outerNode, nodeWithChild, soloNode ->
outerNode.add(nodeWithChild)
outerNode.add(soloNode)
}
}
/**
* When a child is in the minimum touch target area, but the parent is big enough to not
* worry about minimum touch target, the child should still be able to be hit outside the
* parent's bounds. This is different from
* [hitTest_pointerInMinimumTouchTarget_inChild_closestHit] because the node with the nested
* child is after the other node.
*/
@Test
fun hitTest_pointerInMinimumTouchTarget_inChildOver_closestHit() {
test_pointerInMinimumTouchTarget_inChild_closestHit { outerNode, nodeWithChild, soloNode ->
outerNode.add(soloNode)
outerNode.add(nodeWithChild)
}
}
private fun test_pointerInMinimumTouchTarget_inChild_closestHit(
block: (outerNode: LayoutNode, nodeWithChild: LayoutNode, soloNode: LayoutNode) -> Unit
) {
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
5, 5, 10, 10,
PointerInputModifierImpl(pointerInputFilter1),
DpSize(48.dp, 48.dp)
)
val pointerInputFilter2: PointerInputFilter =
mockPointerInputFilter(interceptChildEvents = true)
val layoutNode2 = LayoutNode(
0, 0, 10, 10,
PointerInputModifierImpl(pointerInputFilter2),
DpSize(48.dp, 48.dp)
)
layoutNode2.add(layoutNode1)
val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter()
val layoutNode3 = LayoutNode(
12, 12, 17, 17,
PointerInputModifierImpl(pointerInputFilter3),
DpSize(48.dp, 48.dp)
)
val outerNode = LayoutNode(0, 0, 20, 20).apply { attach(MockOwner()) }
block(outerNode, layoutNode2, layoutNode3)
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
layoutNode3.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
// Hit outside of layoutNode2, but near layoutNode1
outerNode.hitTest(Offset(10.1f, 10.1f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2, pointerInputFilter1))
hit.clear()
// Hit closer to layoutNode3
outerNode.hitTest(Offset(11.9f, 11.9f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter3))
}
@Test
fun hitTest_pointerInMinimumTouchTarget_closestHitWithOverlap() {
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
0, 0, 5, 5, PointerInputModifierImpl(pointerInputFilter1),
DpSize(48.dp, 48.dp)
)
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val layoutNode2 = LayoutNode(
4, 4, 9, 9,
PointerInputModifierImpl(pointerInputFilter2),
DpSize(48.dp, 48.dp)
)
val outerNode = LayoutNode(0, 0, 9, 9).apply { attach(MockOwner()) }
outerNode.add(layoutNode1)
outerNode.add(layoutNode2)
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
val hit = mutableListOf<PointerInputModifierNode>()
// Hit layoutNode1
outerNode.hitTest(Offset(3.95f, 3.95f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
hit.clear()
// Hit layoutNode2
outerNode.hitTest(Offset(4.05f, 4.05f), hit, true)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
}
@Test
fun hitTestSemantics_pointerInMinimumTouchTarget_pointerInputFilterHit() {
val semanticsConfiguration = SemanticsConfiguration()
val semanticsModifier = object : SemanticsModifier {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val layoutNode =
LayoutNode(
0, 0, 1, 1,
semanticsModifier,
DpSize(48.dp, 48.dp)
).apply {
attach(MockOwner())
}
val hit = HitTestResult<SemanticsModifierNode>()
layoutNode.hitTestSemantics(Offset(-3f, 3f), hit)
assertThat(hit).hasSize(1)
// assertThat(hit[0].modifier).isEqualTo(semanticsModifier)
}
@Test
fun hitTestSemantics_pointerInMinimumTouchTarget_pointerInputFilterHit_nestedNodes() {
val semanticsConfiguration = SemanticsConfiguration()
val semanticsModifier = object : SemanticsModifier {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val outerNode = LayoutNode(0, 0, 1, 1).apply { attach(MockOwner()) }
val layoutNode = LayoutNode(0, 0, 1, 1, semanticsModifier, DpSize(48.dp, 48.dp))
outerNode.add(layoutNode)
layoutNode.onNodePlaced()
val hit = HitTestResult<SemanticsModifierNode>()
layoutNode.hitTestSemantics(Offset(-3f, 3f), hit)
assertThat(hit).hasSize(1)
assertThat(hit[0].toModifier()).isEqualTo(semanticsModifier)
}
@Test
fun hitTestSemantics_pointerInMinimumTouchTarget_closestHit() {
val semanticsConfiguration = SemanticsConfiguration()
val semanticsModifier1 = object : SemanticsModifierNode, Modifier.Node() {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val semanticsModifier2 = object : SemanticsModifierNode, Modifier.Node() {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val semanticsModifierElement1 = modifierElementOf(null, { semanticsModifier1 }, { }, { })
val semanticsModifierElement2 = modifierElementOf(null, { semanticsModifier2 }, { }, { })
val layoutNode1 = LayoutNode(0, 0, 5, 5, semanticsModifierElement1, DpSize(48.dp, 48.dp))
val layoutNode2 = LayoutNode(6, 6, 11, 11, semanticsModifierElement2, DpSize(48.dp, 48.dp))
val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) }
outerNode.add(layoutNode1)
outerNode.add(layoutNode2)
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
// Hit closer to layoutNode1
val hit1 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(5.1f, 5.5f), hit1, true)
assertThat(hit1).hasSize(1)
assertThat(hit1[0]).isEqualTo(semanticsModifier1)
// Hit closer to layoutNode2
val hit2 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(5.9f, 5.5f), hit2, true)
assertThat(hit2).hasSize(1)
assertThat(hit2[0]).isEqualTo(semanticsModifier2)
// Hit closer to layoutNode1
val hit3 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(5.5f, 5.1f), hit3, true)
assertThat(hit3).hasSize(1)
assertThat(hit3[0]).isEqualTo(semanticsModifier1)
// Hit closer to layoutNode2
val hit4 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(5.5f, 5.9f), hit4, true)
assertThat(hit4).hasSize(1)
assertThat(hit4[0]).isEqualTo(semanticsModifier2)
// Hit inside layoutNode1
val hit5 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(4.9f, 4.9f), hit5, true)
assertThat(hit5).hasSize(1)
assertThat(hit5[0]).isEqualTo(semanticsModifier1)
// Hit inside layoutNode2
val hit6 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(6.1f, 6.1f), hit6, true)
assertThat(hit6).hasSize(1)
assertThat(hit6[0]).isEqualTo(semanticsModifier2)
}
@Test
fun hitTestSemantics_pointerInMinimumTouchTarget_closestHitWithOverlap() {
val semanticsConfiguration = SemanticsConfiguration()
val semanticsModifier1 = object : SemanticsModifier {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val semanticsModifier2 = object : SemanticsModifier {
override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration
}
val layoutNode1 = LayoutNode(0, 0, 5, 5, semanticsModifier1, DpSize(48.dp, 48.dp))
val layoutNode2 = LayoutNode(4, 4, 9, 9, semanticsModifier2, DpSize(48.dp, 48.dp))
val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) }
outerNode.add(layoutNode1)
outerNode.add(layoutNode2)
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
// Hit layoutNode1
val hit1 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(3.95f, 3.95f), hit1, true)
assertThat(hit1).hasSize(1)
assertThat(hit1[0].toModifier()).isEqualTo(semanticsModifier1)
// Hit layoutNode2
val hit2 = HitTestResult<SemanticsModifierNode>()
outerNode.hitTestSemantics(Offset(4.05f, 4.05f), hit2, true)
assertThat(hit2).hasSize(1)
assertThat(hit2[0].toModifier()).isEqualTo(semanticsModifier2)
}
@Test
fun hitTest_pointerOutOfBounds_nothingHit() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl(pointerInputFilter)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(-1f, -1f), hit)
layoutNode.hitTest(Offset(0f, -1f), hit)
layoutNode.hitTest(Offset(1f, -1f), hit)
layoutNode.hitTest(Offset(-1f, 0f), hit)
// 0, 0 would hit
layoutNode.hitTest(Offset(1f, 0f), hit)
layoutNode.hitTest(Offset(-1f, 1f), hit)
layoutNode.hitTest(Offset(0f, 1f), hit)
layoutNode.hitTest(Offset(1f, 1f), hit)
assertThat(hit).isEmpty()
}
@Test
fun hitTest_pointerOutOfBounds_nothingHit_extendedBounds() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode =
LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl(pointerInputFilter),
minimumTouchTargetSize = DpSize(4.dp, 8.dp)
).apply {
attach(MockOwner())
}
val hit = mutableListOf<PointerInputModifierNode>()
layoutNode.hitTest(Offset(-3f, -5f), hit)
layoutNode.hitTest(Offset(0f, -5f), hit)
layoutNode.hitTest(Offset(3f, -5f), hit)
layoutNode.hitTest(Offset(-3f, 0f), hit)
// 0, 0 would hit
layoutNode.hitTest(Offset(3f, 0f), hit)
layoutNode.hitTest(Offset(-3f, 5f), hit)
layoutNode.hitTest(Offset(0f, 5f), hit)
layoutNode.hitTest(Offset(-3f, 5f), hit)
assertThat(hit).isEmpty()
}
@Test
fun hitTest_nestedOffsetNodesHits3_allHitInCorrectOrder() {
hitTest_nestedOffsetNodes_allHitInCorrectOrder(3)
}
@Test
fun hitTest_nestedOffsetNodesHits2_allHitInCorrectOrder() {
hitTest_nestedOffsetNodes_allHitInCorrectOrder(2)
}
@Test
fun hitTest_nestedOffsetNodesHits1_allHitInCorrectOrder() {
hitTest_nestedOffsetNodes_allHitInCorrectOrder(1)
}
private fun hitTest_nestedOffsetNodes_allHitInCorrectOrder(numberOfChildrenHit: Int) {
// Arrange
val childPointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val middlePointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val parentPointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val childLayoutNode =
LayoutNode(
100, 100, 200, 200,
PointerInputModifierImpl(
childPointerInputFilter
)
)
val middleLayoutNode: LayoutNode =
LayoutNode(
100, 100, 400, 400,
PointerInputModifierImpl(
middlePointerInputFilter
)
).apply {
insertAt(0, childLayoutNode)
}
val parentLayoutNode: LayoutNode =
LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl(
parentPointerInputFilter
)
).apply {
insertAt(0, middleLayoutNode)
attach(MockOwner())
}
middleLayoutNode.onNodePlaced()
childLayoutNode.onNodePlaced()
val offset = when (numberOfChildrenHit) {
3 -> Offset(250f, 250f)
2 -> Offset(150f, 150f)
1 -> Offset(50f, 50f)
else -> throw IllegalStateException()
}
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
parentLayoutNode.hitTest(offset, hit)
// Assert.
when (numberOfChildrenHit) {
3 ->
assertThat(hit.toFilters())
.isEqualTo(
listOf(
parentPointerInputFilter,
middlePointerInputFilter,
childPointerInputFilter
)
)
2 ->
assertThat(hit.toFilters())
.isEqualTo(
listOf(
parentPointerInputFilter,
middlePointerInputFilter
)
)
1 ->
assertThat(hit.toFilters())
.isEqualTo(
listOf(
parentPointerInputFilter
)
)
else -> throw IllegalStateException()
}
}
/**
* This test creates a layout of this shape:
*
* -------------
* | | |
* | t | |
* | | |
* |-----| |
* | |
* | |-----|
* | | |
* | | t |
* | | |
* -------------
*
* Where there is one child in the top right and one in the bottom left, and 2 pointers where
* one in the top left and one in the bottom right.
*/
@Test
fun hitTest_2PointersOver2DifferentPointerInputModifiers_resultIsCorrect() {
// Arrange
val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val childLayoutNode1 =
LayoutNode(
0, 0, 50, 50,
PointerInputModifierImpl(
childPointerInputFilter1
)
)
val childLayoutNode2 =
LayoutNode(
50, 50, 100, 100,
PointerInputModifierImpl(
childPointerInputFilter2
)
)
val parentLayoutNode = LayoutNode(0, 0, 100, 100).apply {
insertAt(0, childLayoutNode1)
insertAt(1, childLayoutNode2)
attach(MockOwner())
}
childLayoutNode1.onNodePlaced()
childLayoutNode2.onNodePlaced()
val offset1 = Offset(25f, 25f)
val offset2 = Offset(75f, 75f)
val hit1 = mutableListOf<PointerInputModifierNode>()
val hit2 = mutableListOf<PointerInputModifierNode>()
// Act
parentLayoutNode.hitTest(offset1, hit1)
parentLayoutNode.hitTest(offset2, hit2)
// Assert
assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2))
}
/**
* This test creates a layout of this shape:
*
* ---------------
* | t | |
* | | |
* | |-------| |
* | | t | |
* | | | |
* | | | |
* |--| |-------|
* | | | t |
* | | | |
* | | | |
* | |--| |
* | | |
* ---------------
*
* There are 3 staggered children and 3 pointers, the first is on child 1, the second is on
* child 2 in a space that overlaps child 1, and the third is in a space in child 3 that
* overlaps child 2.
*/
@Test
fun hitTest_3DownOnOverlappingPointerInputModifiers_resultIsCorrect() {
val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val childPointerInputFilter3: PointerInputFilter = mockPointerInputFilter()
val childLayoutNode1 =
LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl(
childPointerInputFilter1
)
)
val childLayoutNode2 =
LayoutNode(
50, 50, 150, 150,
PointerInputModifierImpl(
childPointerInputFilter2
)
)
val childLayoutNode3 =
LayoutNode(
100, 100, 200, 200,
PointerInputModifierImpl(
childPointerInputFilter3
)
)
val parentLayoutNode = LayoutNode(0, 0, 200, 200).apply {
insertAt(0, childLayoutNode1)
insertAt(1, childLayoutNode2)
insertAt(2, childLayoutNode3)
attach(MockOwner())
}
childLayoutNode1.onNodePlaced()
childLayoutNode2.onNodePlaced()
childLayoutNode3.onNodePlaced()
val offset1 = Offset(25f, 25f)
val offset2 = Offset(75f, 75f)
val offset3 = Offset(125f, 125f)
val hit1 = mutableListOf<PointerInputModifierNode>()
val hit2 = mutableListOf<PointerInputModifierNode>()
val hit3 = mutableListOf<PointerInputModifierNode>()
parentLayoutNode.hitTest(offset1, hit1)
parentLayoutNode.hitTest(offset2, hit2)
parentLayoutNode.hitTest(offset3, hit3)
assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2))
assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter3))
}
/**
* This test creates a layout of this shape:
*
* ---------------
* | |
* | t |
* | |
* | |-------| |
* | | | |
* | | t | |
* | | | |
* | |-------| |
* | |
* | t |
* | |
* ---------------
*
* There are 2 children with one over the other and 3 pointers: the first is on background
* child, the second is on the foreground child, and the third is again on the background child.
*/
@Test
fun hitTest_3DownOnFloatingPointerInputModifierV_resultIsCorrect() {
val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val childLayoutNode1 = LayoutNode(
0, 0, 100, 150,
PointerInputModifierImpl(
childPointerInputFilter1
)
)
val childLayoutNode2 = LayoutNode(
25, 50, 75, 100,
PointerInputModifierImpl(
childPointerInputFilter2
)
)
val parentLayoutNode = LayoutNode(0, 0, 150, 150).apply {
insertAt(0, childLayoutNode1)
insertAt(1, childLayoutNode2)
attach(MockOwner())
}
childLayoutNode1.onNodePlaced()
childLayoutNode2.onNodePlaced()
val offset1 = Offset(50f, 25f)
val offset2 = Offset(50f, 75f)
val offset3 = Offset(50f, 125f)
val hit1 = mutableListOf<PointerInputModifierNode>()
val hit2 = mutableListOf<PointerInputModifierNode>()
val hit3 = mutableListOf<PointerInputModifierNode>()
// Act
parentLayoutNode.hitTest(offset1, hit1)
parentLayoutNode.hitTest(offset2, hit2)
parentLayoutNode.hitTest(offset3, hit3)
// Assert
assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2))
assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
}
/**
* This test creates a layout of this shape:
*
* -----------------
* | |
* | |-------| |
* | | | |
* | t | t | t |
* | | | |
* | |-------| |
* | |
* -----------------
*
* There are 2 children with one over the other and 3 pointers: the first is on background
* child, the second is on the foreground child, and the third is again on the background child.
*/
@Test
fun hitTest_3DownOnFloatingPointerInputModifierH_resultIsCorrect() {
val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val childLayoutNode1 = LayoutNode(
0, 0, 150, 100,
PointerInputModifierImpl(
childPointerInputFilter1
)
)
val childLayoutNode2 = LayoutNode(
50, 25, 100, 75,
PointerInputModifierImpl(
childPointerInputFilter2
)
)
val parentLayoutNode = LayoutNode(0, 0, 150, 150).apply {
insertAt(0, childLayoutNode1)
insertAt(1, childLayoutNode2)
attach(MockOwner())
}
childLayoutNode2.onNodePlaced()
childLayoutNode1.onNodePlaced()
val offset1 = Offset(25f, 50f)
val offset2 = Offset(75f, 50f)
val offset3 = Offset(125f, 50f)
val hit1 = mutableListOf<PointerInputModifierNode>()
val hit2 = mutableListOf<PointerInputModifierNode>()
val hit3 = mutableListOf<PointerInputModifierNode>()
// Act
parentLayoutNode.hitTest(offset1, hit1)
parentLayoutNode.hitTest(offset2, hit2)
parentLayoutNode.hitTest(offset3, hit3)
// Assert
assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2))
assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter1))
}
/**
* This test creates a layout of this shape:
* 0 1 2 3 4
* ......... .........
* 0 . t . . t .
* . |---|---|---| .
* 1 . t | t | | t | t .
* ....|---| |---|....
* 2 | |
* ....|---| |---|....
* 3 . t | t | | t | t .
* . |---|---|---| .
* 4 . t . . t .
* ......... .........
*
* 4 LayoutNodes with PointerInputModifiers that are clipped by their parent LayoutNode. 4
* touches touch just inside the parent LayoutNode and inside the child LayoutNodes. 8
* touches touch just outside the parent LayoutNode but inside the child LayoutNodes.
*
* Because layout node bounds are not used to clip pointer input hit testing, all pointers
* should hit.
*/
@Test
fun hitTest_4DownInClippedAreaOfLnsWithPims_resultIsCorrect() {
// Arrange
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter4: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
-1, -1, 1, 1,
PointerInputModifierImpl(
pointerInputFilter1
)
)
val layoutNode2 = LayoutNode(
2, -1, 4, 1,
PointerInputModifierImpl(
pointerInputFilter2
)
)
val layoutNode3 = LayoutNode(
-1, 2, 1, 4,
PointerInputModifierImpl(
pointerInputFilter3
)
)
val layoutNode4 = LayoutNode(
2, 2, 4, 4,
PointerInputModifierImpl(
pointerInputFilter4
)
)
val parentLayoutNode = LayoutNode(1, 1, 4, 4).apply {
insertAt(0, layoutNode1)
insertAt(1, layoutNode2)
insertAt(2, layoutNode3)
insertAt(3, layoutNode4)
attach(MockOwner())
}
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
layoutNode3.onNodePlaced()
layoutNode4.onNodePlaced()
val offsetsThatHit1 =
listOf(
Offset(0f, 1f),
Offset(1f, 0f),
Offset(1f, 1f)
)
val offsetsThatHit2 =
listOf(
Offset(3f, 0f),
Offset(3f, 1f),
Offset(4f, 1f)
)
val offsetsThatHit3 =
listOf(
Offset(0f, 3f),
Offset(1f, 3f),
Offset(1f, 4f)
)
val offsetsThatHit4 =
listOf(
Offset(3f, 3f),
Offset(3f, 4f),
Offset(4f, 3f)
)
val hit = mutableListOf<PointerInputModifierNode>()
// Act and Assert
offsetsThatHit1.forEach {
hit.clear()
parentLayoutNode.hitTest(it, hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
}
offsetsThatHit2.forEach {
hit.clear()
parentLayoutNode.hitTest(it, hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
}
offsetsThatHit3.forEach {
hit.clear()
parentLayoutNode.hitTest(it, hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter3))
}
offsetsThatHit4.forEach {
hit.clear()
parentLayoutNode.hitTest(it, hit)
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter4))
}
}
@Test
fun hitTest_pointerOn3NestedPointerInputModifiers_allPimsHitInCorrectOrder() {
// Arrange.
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter()
val modifier =
PointerInputModifierImpl(
pointerInputFilter1
) then PointerInputModifierImpl(
pointerInputFilter2
) then PointerInputModifierImpl(
pointerInputFilter3
)
val layoutNode = LayoutNode(
25, 50, 75, 100,
modifier
).apply {
attach(MockOwner())
}
val offset1 = Offset(50f, 75f)
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
layoutNode.hitTest(offset1, hit)
// Assert.
assertThat(hit.toFilters()).isEqualTo(
listOf(
pointerInputFilter1,
pointerInputFilter2,
pointerInputFilter3
)
)
}
@Test
fun hitTest_pointerOnDeeplyNestedPointerInputModifier_pimIsHit() {
// Arrange.
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 =
LayoutNode(
1, 5, 500, 500,
PointerInputModifierImpl(
pointerInputFilter
)
)
val layoutNode2: LayoutNode = LayoutNode(2, 6, 500, 500).apply {
insertAt(0, layoutNode1)
}
val layoutNode3: LayoutNode = LayoutNode(3, 7, 500, 500).apply {
insertAt(0, layoutNode2)
}
val layoutNode4: LayoutNode = LayoutNode(4, 8, 500, 500).apply {
insertAt(0, layoutNode3)
}.apply {
attach(MockOwner())
}
layoutNode3.onNodePlaced()
layoutNode2.onNodePlaced()
layoutNode1.onNodePlaced()
val offset1 = Offset(499f, 499f)
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
layoutNode4.hitTest(offset1, hit)
// Assert.
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter))
}
@Test
fun hitTest_pointerOnComplexPointerAndLayoutNodePath_pimsHitInCorrectOrder() {
// Arrange.
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter4: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
1, 6, 500, 500,
PointerInputModifierImpl(
pointerInputFilter1
) then PointerInputModifierImpl(
pointerInputFilter2
)
)
val layoutNode2: LayoutNode = LayoutNode(2, 7, 500, 500).apply {
insertAt(0, layoutNode1)
}
val layoutNode3 =
LayoutNode(
3, 8, 500, 500,
PointerInputModifierImpl(
pointerInputFilter3
) then PointerInputModifierImpl(
pointerInputFilter4
)
).apply {
insertAt(0, layoutNode2)
}
val layoutNode4: LayoutNode = LayoutNode(4, 9, 500, 500).apply {
insertAt(0, layoutNode3)
}
val layoutNode5: LayoutNode = LayoutNode(5, 10, 500, 500).apply {
insertAt(0, layoutNode4)
}.apply {
attach(MockOwner())
}
layoutNode4.onNodePlaced()
layoutNode3.onNodePlaced()
layoutNode2.onNodePlaced()
layoutNode1.onNodePlaced()
val offset1 = Offset(499f, 499f)
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
layoutNode5.hitTest(offset1, hit)
// Assert.
assertThat(hit.toFilters()).isEqualTo(
listOf(
pointerInputFilter3,
pointerInputFilter4,
pointerInputFilter1,
pointerInputFilter2
)
)
}
@Test
fun hitTest_pointerOnFullyOverlappingPointerInputModifiers_onlyTopPimIsHit() {
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val layoutNode1 = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl(
pointerInputFilter1
)
)
val layoutNode2 = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl(
pointerInputFilter2
)
)
val parentLayoutNode = LayoutNode(0, 0, 100, 100).apply {
insertAt(0, layoutNode1)
insertAt(1, layoutNode2)
attach(MockOwner())
}
layoutNode1.onNodePlaced()
layoutNode2.onNodePlaced()
val offset = Offset(50f, 50f)
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
parentLayoutNode.hitTest(offset, hit)
// Assert.
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2))
}
@Test
fun hitTest_pointerOnPointerInputModifierInLayoutNodeWithNoSize_nothingHit() {
val pointerInputFilter: PointerInputFilter = mockPointerInputFilter()
val layoutNode = LayoutNode(
0, 0, 0, 0,
PointerInputModifierImpl(
pointerInputFilter
)
).apply {
attach(MockOwner())
}
val offset = Offset.Zero
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
layoutNode.hitTest(offset, hit)
// Assert.
assertThat(hit.toFilters()).isEmpty()
}
@Test
fun hitTest_zIndexIsAccounted() {
val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter()
val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter()
val parent = LayoutNode(
0, 0, 2, 2
).apply {
attach(
MockOwner().apply {
measureIteration = 1L
}
)
}
parent.insertAt(
0,
LayoutNode(
0, 0, 2, 2,
PointerInputModifierImpl(
pointerInputFilter1
).zIndex(1f)
)
)
parent.insertAt(
1,
LayoutNode(
0, 0, 2, 2,
PointerInputModifierImpl(
pointerInputFilter2
)
)
)
parent.remeasure()
parent.replace()
val hit = mutableListOf<PointerInputModifierNode>()
// Act.
parent.hitTest(Offset(1f, 1f), hit)
// Assert.
assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1))
}
@Test
fun onRequestMeasureIsNotCalledOnDetachedNodes() {
val root = LayoutNode()
val node1 = LayoutNode()
root.add(node1)
val node2 = LayoutNode()
node1.add(node2)
val owner = MockOwner()
root.attach(owner)
owner.onAttachParams.clear()
owner.onRequestMeasureParams.clear()
// Dispose
root.removeAt(0, 1)
assertFalse(node1.isAttached)
assertFalse(node2.isAttached)
assertEquals(0, owner.onRequestMeasureParams.count { it === node1 })
assertEquals(0, owner.onRequestMeasureParams.count { it === node2 })
}
@Test
fun modifierMatchesWrapperWithIdentity() {
val modifier1 = Modifier.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
val modifier2 = Modifier.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(1, 1)
}
}
val root = LayoutNode()
root.modifier = modifier1.then(modifier2)
val wrapper1 = root.outerCoordinator
val wrapper2 = root.outerCoordinator.wrapped
assertEquals(
modifier1,
(wrapper1 as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier()
)
assertEquals(
modifier2,
(wrapper2 as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier()
)
root.modifier = modifier2.then(modifier1)
assertEquals(
modifier1,
(root.outerCoordinator.wrapped as LayoutModifierNodeCoordinator)
.layoutModifierNode
.toModifier()
)
assertEquals(
modifier2,
(root.outerCoordinator as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier()
)
}
@Test
fun measureResultAndPositionChangesCallOnLayoutChange() {
val node = LayoutNode(20, 20, 100, 100)
val owner = MockOwner()
node.attach(owner)
node.innerCoordinator.measureResult = object : MeasureResult {
override val width = 50
override val height = 50
override val alignmentLines: Map<AlignmentLine, Int> get() = mapOf()
override fun placeChildren() {}
}
assertEquals(1, owner.layoutChangeCount)
node.place(0, 0)
assertEquals(2, owner.layoutChangeCount)
}
@Test
fun layerParamChangeCallsOnLayoutChange() {
val node = LayoutNode(20, 20, 100, 100, Modifier.graphicsLayer())
val owner = MockOwner()
node.attach(owner)
assertEquals(0, owner.layoutChangeCount)
node.innerCoordinator.onLayerBlockUpdated { scaleX = 0.5f }
assertEquals(1, owner.layoutChangeCount)
repeat(2) {
node.innerCoordinator.onLayerBlockUpdated { scaleX = 1f }
}
assertEquals(2, owner.layoutChangeCount)
node.innerCoordinator.onLayerBlockUpdated(null)
assertEquals(3, owner.layoutChangeCount)
}
@Test
fun reuseModifiersThatImplementMultipleModifierInterfaces() {
val drawAndLayoutModifier: Modifier = object : DrawModifier, LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
return layout(placeable.width, placeable.height) {
placeable.placeRelative(IntOffset.Zero)
}
}
override fun ContentDrawScope.draw() {
drawContent()
}
}
val a = Modifier.then(EmptyLayoutModifier()).then(drawAndLayoutModifier)
val b = Modifier.then(EmptyLayoutModifier()).then(drawAndLayoutModifier)
val node = LayoutNode(20, 20, 100, 100)
val owner = MockOwner()
node.attach(owner)
node.modifier = a
assertEquals(2, node.getModifierInfo().size)
node.modifier = b
assertEquals(2, node.getModifierInfo().size)
}
@Test
fun nodeCoordinator_alpha() {
val root = LayoutNode().apply { this.modifier = Modifier.drawBehind {} }
val layoutNode1 = LayoutNode().apply {
this.modifier = Modifier.graphicsLayer { }.graphicsLayer { }.drawBehind {}
}
val layoutNode2 = LayoutNode().apply { this.modifier = Modifier.drawBehind {} }
val owner = MockOwner()
root.insertAt(0, layoutNode1)
layoutNode1.insertAt(0, layoutNode2)
root.attach(owner)
// provide alpha to the graphics layer
layoutNode1.outerCoordinator.wrapped!!.onLayerBlockUpdated {
alpha = 0f
}
layoutNode1.outerCoordinator.wrapped!!.wrapped!!.onLayerBlockUpdated {
alpha = 0.5f
}
assertFalse(layoutNode1.outerCoordinator.isTransparent())
assertTrue(layoutNode1.innerCoordinator.isTransparent())
assertTrue(layoutNode2.outerCoordinator.isTransparent())
assertTrue(layoutNode2.innerCoordinator.isTransparent())
}
private fun createSimpleLayout(): Triple<LayoutNode, LayoutNode, LayoutNode> {
val layoutNode = ZeroSizedLayoutNode()
val child1 = ZeroSizedLayoutNode()
val child2 = ZeroSizedLayoutNode()
layoutNode.insertAt(0, child1)
layoutNode.insertAt(1, child2)
return Triple(layoutNode, child1, child2)
}
private fun ZeroSizedLayoutNode() = LayoutNode(0, 0, 0, 0)
private class PointerInputModifierImpl(override val pointerInputFilter: PointerInputFilter) :
PointerInputModifier
}
private class EmptyLayoutModifier : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
return layout(placeable.width, placeable.height) {
placeable.placeRelative(IntOffset.Zero)
}
}
}
@OptIn(InternalCoreApi::class)
internal class MockOwner(
val position: IntOffset = IntOffset.Zero,
override val root: LayoutNode = LayoutNode()
) : Owner {
val onRequestMeasureParams = mutableListOf<LayoutNode>()
val onAttachParams = mutableListOf<LayoutNode>()
val onDetachParams = mutableListOf<LayoutNode>()
var layoutChangeCount = 0
override val rootForTest: RootForTest
get() = TODO("Not yet implemented")
override val hapticFeedBack: HapticFeedback
get() = TODO("Not yet implemented")
override val inputModeManager: InputModeManager
get() = TODO("Not yet implemented")
override val clipboardManager: ClipboardManager
get() = TODO("Not yet implemented")
override val accessibilityManager: AccessibilityManager
get() = TODO("Not yet implemented")
override val textToolbar: TextToolbar
get() = TODO("Not yet implemented")
@OptIn(ExperimentalComposeUiApi::class)
override val autofillTree: AutofillTree
get() = TODO("Not yet implemented")
@OptIn(ExperimentalComposeUiApi::class)
override val autofill: Autofill?
get() = TODO("Not yet implemented")
override val density: Density
get() = Density(1f)
override val textInputService: TextInputService
get() = TODO("Not yet implemented")
override val pointerIconService: PointerIconService
get() = TODO("Not yet implemented")
override val focusManager: FocusManager
get() = TODO("Not yet implemented")
override val windowInfo: WindowInfo
get() = TODO("Not yet implemented")
@Deprecated(
"fontLoader is deprecated, use fontFamilyResolver",
replaceWith = ReplaceWith("fontFamilyResolver")
)
@Suppress("DEPRECATION")
override val fontLoader: Font.ResourceLoader
get() = TODO("Not yet implemented")
override val fontFamilyResolver: FontFamily.Resolver
get() = TODO("Not yet implemented")
override val layoutDirection: LayoutDirection
get() = LayoutDirection.Ltr
override var showLayoutBounds: Boolean = false
override val snapshotObserver = OwnerSnapshotObserver { it.invoke() }
override val modifierLocalManager: ModifierLocalManager = ModifierLocalManager(this)
override fun onRequestMeasure(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean
) {
onRequestMeasureParams += layoutNode
if (affectsLookahead) {
layoutNode.markLookaheadMeasurePending()
}
layoutNode.markMeasurePending()
}
override fun onRequestRelayout(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean
) {
if (affectsLookahead) {
layoutNode.markLookaheadLayoutPending()
}
layoutNode.markLayoutPending()
}
override fun requestOnPositionedCallback(layoutNode: LayoutNode) {
}
override fun onAttach(node: LayoutNode) {
onAttachParams += node
}
override fun onDetach(node: LayoutNode) {
onDetachParams += node
}
override fun calculatePositionInWindow(localPosition: Offset): Offset =
localPosition + position.toOffset()
override fun calculateLocalPosition(positionInWindow: Offset): Offset =
positionInWindow - position.toOffset()
override fun requestFocus(): Boolean = false
override fun measureAndLayout(sendPointerUpdate: Boolean) {
}
override fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) {
}
override fun forceMeasureTheSubtree(layoutNode: LayoutNode) {
}
override fun registerOnEndApplyChangesListener(listener: () -> Unit) {
listener()
}
override fun onEndApplyChanges() {
}
override fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) {
TODO("Not yet implemented")
}
override fun createLayer(
drawBlock: (Canvas) -> Unit,
invalidateParentLayer: () -> Unit
): OwnedLayer {
val transform = Matrix()
val inverseTransform = Matrix()
return object : OwnedLayer {
override fun updateLayerProperties(
scaleX: Float,
scaleY: Float,
alpha: Float,
translationX: Float,
translationY: Float,
shadowElevation: Float,
rotationX: Float,
rotationY: Float,
rotationZ: Float,
cameraDistance: Float,
transformOrigin: TransformOrigin,
shape: Shape,
clip: Boolean,
renderEffect: RenderEffect?,
ambientShadowColor: Color,
spotShadowColor: Color,
compositingStrategy: CompositingStrategy,
layoutDirection: LayoutDirection,
density: Density
) {
transform.reset()
// This is not expected to be 100% accurate
transform.scale(scaleX, scaleY)
transform.rotateZ(rotationZ)
transform.translate(translationX, translationY)
transform.invertTo(inverseTransform)
}
override fun isInLayer(position: Offset) = true
override fun move(position: IntOffset) {
}
override fun resize(size: IntSize) {
}
override fun drawLayer(canvas: Canvas) {
drawBlock(canvas)
}
override fun updateDisplayList() {
}
override fun invalidate() {
}
override fun destroy() {
}
override fun mapBounds(rect: MutableRect, inverse: Boolean) {
}
override fun reuseLayer(
drawBlock: (Canvas) -> Unit,
invalidateParentLayer: () -> Unit
) {
}
override fun transform(matrix: Matrix) {
matrix.timesAssign(transform)
}
override fun inverseTransform(matrix: Matrix) {
matrix.timesAssign(inverseTransform)
}
override fun mapOffset(point: Offset, inverse: Boolean) = point
}
}
override fun onSemanticsChange() {
}
override fun onLayoutChange(layoutNode: LayoutNode) {
layoutChangeCount++
}
override fun getFocusDirection(keyEvent: KeyEvent): FocusDirection? {
TODO("Not yet implemented")
}
override var measureIteration: Long = 0
override val viewConfiguration: ViewConfiguration
get() = TODO("Not yet implemented")
override val sharedDrawScope = LayoutNodeDrawScope()
}
@OptIn(ExperimentalComposeUiApi::class)
private fun LayoutNode.hitTest(
pointerPosition: Offset,
hitPointerInputFilters: MutableList<PointerInputModifierNode>,
isTouchEvent: Boolean = false
) {
val hitTestResult = HitTestResult<PointerInputModifierNode>()
hitTest(pointerPosition, hitTestResult, isTouchEvent)
hitPointerInputFilters.addAll(hitTestResult)
}
internal fun LayoutNode(
x: Int,
y: Int,
x2: Int,
y2: Int,
modifier: Modifier = Modifier,
minimumTouchTargetSize: DpSize = DpSize.Zero
) = LayoutNode().apply {
this.viewConfiguration = TestViewConfiguration(minimumTouchTargetSize = minimumTouchTargetSize)
this.modifier = modifier
measurePolicy = object : LayoutNode.NoIntrinsicsMeasurePolicy("not supported") {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
): MeasureResult =
layout(x2 - x, y2 - y) {
measurables.forEach { it.measure(constraints).place(0, 0) }
}
}
attach(MockOwner())
markMeasurePending()
remeasure(Constraints())
var wrapper: NodeCoordinator? = outerCoordinator
while (wrapper != null) {
wrapper.measureResult = innerCoordinator.measureResult
wrapper = (wrapper as? NodeCoordinator)?.wrapped
}
place(x, y)
detach()
}
private fun mockPointerInputFilter(
interceptChildEvents: Boolean = false
): PointerInputFilter = object : PointerInputFilter() {
override fun onPointerEvent(
pointerEvent: PointerEvent,
pass: PointerEventPass,
bounds: IntSize
) {
}
override fun onCancel() {
}
override val interceptOutOfBoundsChildEvents: Boolean
get() = interceptChildEvents
}
// This returns the corresponding modifier that produced the PointerInputNode. This is only
// possible for PointerInputNodes that are BackwardsCompatNodes and once we refactor the
// pointerInput modifier to use Modifier.Nodes directly, the tests that use this should be rewritten
@OptIn(ExperimentalComposeUiApi::class)
fun PointerInputModifierNode.toFilter(): PointerInputFilter {
val node = this as? BackwardsCompatNode
?: error("Incorrectly assumed PointerInputNode was a BackwardsCompatNode")
val modifier = node.element as? PointerInputModifier
?: error("Incorrectly assumed Modifier.Element was a PointerInputModifier")
return modifier.pointerInputFilter
}
@OptIn(ExperimentalComposeUiApi::class)
fun List<PointerInputModifierNode>.toFilters(): List<PointerInputFilter> = map { it.toFilter() }
// This returns the corresponding modifier that produced the Node. This is only possible for
// Nodes that are BackwardsCompatNodes and once we refactor semantics / pointer input to use
// Modifier.Nodes directly, the tests that use this should be rewritten
@OptIn(ExperimentalComposeUiApi::class)
fun DelegatableNode.toModifier(): Modifier.Element {
val node = node as? BackwardsCompatNode
?: error("Incorrectly assumed Modifier.Node was a BackwardsCompatNode")
return node.element
} | compose/ui/ui/src/test/kotlin/androidx/compose/ui/node/LayoutNodeTest.kt | 1235152785 |
/*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.refactorings.extract
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds
import org.eclipse.jdt.ui.actions.SelectionDispatchAction
import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper
import org.eclipse.jface.text.ITextSelection
import org.eclipse.ui.PlatformUI
import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor
public class KotlinExtractVariableAction(val editor: KotlinCommonEditor) : SelectionDispatchAction(editor.getSite()) {
init {
setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_LOCAL_VARIABLE)
setText(RefactoringMessages.ExtractTempAction_label)
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTRACT_TEMP_ACTION)
}
companion object {
val ACTION_ID = "ExtractLocalVariable"
}
override fun run(selection: ITextSelection) {
RefactoringStarter().activate(
KotlinExtractVariableWizard(KotlinExtractVariableRefactoring(selection, editor)),
getShell(),
RefactoringMessages.ExtractTempAction_extract_temp,
RefactoringSaveHelper.SAVE_NOTHING)
}
} | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/refactorings/extract/KotlinExtractVariableAction.kt | 1357319847 |
package com.baeldung.jvmannotations
import java.util.*
class TextDocument : Document {
override fun getType() = "text"
fun transformList(list : List<Number>) : List<Number> {
return list.filter { n -> n.toInt() > 1 }
}
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
return list.filter { n -> n.toInt() > 1 }
}
var list : List<@JvmWildcard Any> = ArrayList()
}
| projects/tutorials-master/tutorials-master/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt | 922339166 |
package antlr
import antlr.KongParser.ExpressionContext
import org.antlr.v4.runtime.tree.ParseTree
import org.antlr.v4.runtime.tree.TerminalNode
class Function(val id: String, val params: List<TerminalNode>, val block: ParseTree) {
fun invoke(params: List<ExpressionContext>, functions: Map<String, Function>, outerScope: Scope?): NodeValue {
if (params.size != this.params.size) {
throw RuntimeException("Illegal Function call")
}
var functionScope = Scope(outerScope) // create function functionScope
val evalVisitor = EvalVisitor(functionScope, functions)
for (i in this.params.indices) {
val value = evalVisitor.visit(params[i])
functionScope.assignParam(this.params[i].text, value)
}
var ret: NodeValue?
try {
ret = evalVisitor.visit(this.block)
} catch (returnValue: ReturnValue) {
ret = returnValue.value
}
return ret ?: NodeValue.VOID
}
}
| src/main/kotlin/antlr/Function.kt | 1538170743 |
package br.com.vitorsalgado.example.features
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
abstract class AbstractViewModel : ViewModel() {
private val mCompositeSubscription = CompositeDisposable()
protected fun addSubscription(disposable: Disposable) {
mCompositeSubscription.add(disposable)
}
override fun onCleared() {
mCompositeSubscription.clear()
super.onCleared()
}
}
| app/src/main/kotlin/br/com/vitorsalgado/example/features/AbstractViewModel.kt | 4213831035 |
package com.hewking.widget
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.support.v4.content.ContextCompat.getColor
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.hewking.dp2px
import com.hewking.getColor
import hewking.github.customviewdemo.BuildConfig
import hewking.github.customviewdemo.R
import java.util.concurrent.CopyOnWriteArrayList
/**
* 项目名称:FlowChat
* 类的描述:xfermode 的使用采用canvas.drawBitmap 的方式实现
* 创建人员:hewking
* 创建时间:2018/12/11 0011
* 修改人员:hewking
* 修改时间:2018/12/11 0011
* 修改备注:
* Version: 1.0.0
*/
class TanTanRippleView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) {
private var radiuls: Int = 0
private val rippleCircles = CopyOnWriteArrayList<RippleCircle>()
init {
}
private val ripplePaint by lazy {
Paint().apply {
style = Paint.Style.STROKE
strokeWidth = dp2px(0.5f).toFloat()
color = getColor(R.color.color_FF434343)
isAntiAlias = true
}
}
private val backPaint by lazy {
Paint().apply {
style = Paint.Style.FILL
isAntiAlias = true
strokeWidth = dp2px(0.5f).toFloat()
}
}
private var sweepProgress = 0
set(value) {
if (value >= 360) {
field = 0
} else {
field = value
}
}
private var fps: Int = 0
private var fpsPaint = Paint().apply {
isAntiAlias = true
style = Paint.Style.STROKE
color = Color.GREEN
textSize = dp2px(20f).toFloat()
strokeWidth = dp2px(1f).toFloat()
}
private val renderAnimator by lazy {
ValueAnimator.ofInt(0, 60)
.apply {
interpolator = LinearInterpolator()
duration = 1000
repeatMode = ValueAnimator.RESTART
repeatCount = ValueAnimator.INFINITE
addUpdateListener {
postInvalidateOnAnimation()
fps++
sweepProgress++
}
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationRepeat(animation: Animator?) {
super.onAnimationRepeat(animation)
fps = 0
}
})
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val wMode = MeasureSpec.getMode(widthMeasureSpec)
val wSize = MeasureSpec.getSize(widthMeasureSpec)
val hMode = MeasureSpec.getMode(heightMeasureSpec)
val hSize = MeasureSpec.getSize(heightMeasureSpec)
val size = Math.min(wSize, hSize)
if (wMode == MeasureSpec.AT_MOST || hMode == MeasureSpec.AT_MOST) {
radiuls = size.div(2)
}
}
var backCanvas: Canvas? = null
var backBitmap: Bitmap? = null
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
backBitmap?.recycle()
if (w != 0 && h != 0) {
backBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
backCanvas = Canvas(backBitmap)
}
}
override fun onDraw(canvas: Canvas?) {
canvas ?: return
val maxRadius = Math.min(width, height).div(2).toFloat()
val radius = maxRadius
canvas.save()
canvas.rotate(sweepProgress.toFloat(), width.div(2f), height.div(2f))
val colors = intArrayOf(getColor(R.color.pink_fa758a), getColor(R.color.pink_f5b8c2), getColor(R.color.top_background_color), getColor(R.color.white))
backPaint.setShader(SweepGradient(width.div(2).toFloat(), height.div(2).toFloat(), colors, floatArrayOf(0f, 0.001f, 0.9f, 1f)))
val rectF = RectF(width.div(2f) - radius
, height.div(2f) - radius
, width.div(2f) + radius
, height.div(2f) + radius)
val sc = canvas.saveLayer(rectF, backPaint, Canvas.ALL_SAVE_FLAG)
// canvas.drawBitmap(makeDst(), null,rectF, backPaint)
canvas.drawCircle(width.div(2).toFloat(), height.div(2).toFloat(), radius, backPaint)
backPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OUT))
// canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint)
/* rectF.apply {
left = width.div(2f) - radius * 1f.div(3)
top = height.div(2f) - radius * 1f.div(3)
right = width.div(2f) + radius * 1f.div(3)
bottom = height.div(2f) + radius * 1f.div(3)
}
canvas.drawBitmap(makeSrc(),null,rectF,backPaint)*/
canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint)
backPaint.setXfermode(null)
backPaint.setShader(null)
canvas.restoreToCount(sc)
canvas.restore()
for (i in 0 until rippleCircles.size) {
rippleCircles[i].draw(canvas)
}
if (BuildConfig.DEBUG) {
canvas.drawText(fps.toString(), paddingStart.toFloat()
, height - dp2px(10f).toFloat() - paddingBottom, fpsPaint)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
// start anim
// startRipple()
renderAnimator.start()
}
open fun startRipple() {
val runnable = Runnable {
rippleCircles.add(RippleCircle().apply {
cx = width.div(2).toFloat()
cy = height.div(2).toFloat()
val maxRadius = Math.min(width, height).div(2).toFloat()
startRadius = maxRadius.div(3)
endRadius = maxRadius
})
// startRipple()
}
postOnAnimation(runnable)
// postOnAnimationDelayed(runnable, 2000)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
// end anim
renderAnimator.end()
backBitmap?.recycle()
}
inner class RippleCircle {
// 4s * 60 frms = 240
private val slice = 150
var startRadius = 0f
var endRadius = 0f
var cx = 0f
var cy = 0f
private var progress = 0
fun draw(canvas: Canvas) {
if (progress >= slice) {
// remove
post {
rippleCircles.remove(this)
}
return
}
progress++
ripplePaint.alpha = (1 - progress.div(slice * 1.0f)).times(255).toInt()
val radis = startRadius + (endRadius - startRadius).div(slice).times(progress)
canvas.drawCircle(cx, cy, radis, ripplePaint)
}
}
} | app/src/main/java/com/hewking/widget/TanTanRippleView.kt | 3785921998 |
package org.ccci.gto.android.common.androidx.lifecycle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
fun Lifecycle.onStart(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onStart = block).also { addObserver(it) }
fun Lifecycle.onResume(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onResume = block).also { addObserver(it) }
fun Lifecycle.onPause(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onPause = block).also { addObserver(it) }
fun Lifecycle.onStop(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onStop = block).also { addObserver(it) }
fun Lifecycle.onDestroy(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onDestroy = block).also { addObserver(it) }
internal class LambdaLifecycleObserver(
private val onStart: ((owner: LifecycleOwner) -> Unit)? = null,
private val onResume: ((owner: LifecycleOwner) -> Unit)? = null,
private val onPause: ((owner: LifecycleOwner) -> Unit)? = null,
private val onStop: ((owner: LifecycleOwner) -> Unit)? = null,
private val onDestroy: ((owner: LifecycleOwner) -> Unit)? = null
) : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
onStart?.invoke(owner)
}
override fun onResume(owner: LifecycleOwner) {
onResume?.invoke(owner)
}
override fun onPause(owner: LifecycleOwner) {
onPause?.invoke(owner)
}
override fun onStop(owner: LifecycleOwner) {
onStop?.invoke(owner)
}
override fun onDestroy(owner: LifecycleOwner) {
onDestroy?.invoke(owner)
}
}
| gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/Lifecycle.kt | 1400287295 |
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.base.extensions.collections
/**
* Created by Kasper Tvede on 09-07-2017.
*/
/**
* Toggles whenever a set contains the given item;
* if the set contains the item it will be removed.
* if it does not contain the item, the item will be inserted.
*/
inline fun <T> MutableSet<T>.toggleExistence(item: T) {
setExistence(item, !contains(item))
}
/**
* like toggle, except you control the action by the "shouldExists";
* if that is true, then the element is added, if false the element is removed.
*/
inline fun <T> MutableSet<T>.setExistence(item: T, shouldExists: Boolean) {
if (shouldExists) {
add(item)
} else {
remove(item)
}
} | base/src/main/kotlin/com/commonsense/android/kotlin/base/extensions/collections/SetExtensions.kt | 567878196 |
// 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.panelmatch.common.storage.testing
import org.wfanet.measurement.common.crypto.PrivateKeyStore as CryptoPrivateKeyStore
import org.wfanet.measurement.common.crypto.tink.TinkKeyId
import org.wfanet.measurement.common.crypto.tink.TinkPrivateKeyHandle
internal class FakePrivateKeyStore : CryptoPrivateKeyStore<TinkKeyId, TinkPrivateKeyHandle> {
override suspend fun read(keyId: TinkKeyId): TinkPrivateKeyHandle? {
TODO("Not yet implemented")
}
override suspend fun write(privateKey: TinkPrivateKeyHandle): String {
TODO("Not yet implemented")
}
}
| src/main/kotlin/org/wfanet/panelmatch/common/storage/testing/FakePrivateKeyStore.kt | 2674629318 |
/**
* 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.video.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.groups.dto.GroupsGroupFull
import com.vk.sdk.api.users.dto.UsersUser
import kotlin.Int
import kotlin.collections.List
/**
* @param count - Total number
* @param items
* @param profiles
* @param groups
*/
data class VideoSearchExtendedResponse(
@SerializedName("count")
val count: Int,
@SerializedName("items")
val items: List<VideoVideoFull>,
@SerializedName("profiles")
val profiles: List<UsersUser>,
@SerializedName("groups")
val groups: List<GroupsGroupFull>
)
| api/src/main/java/com/vk/sdk/api/video/dto/VideoSearchExtendedResponse.kt | 2901066406 |
package org.jetbrains.bio.big
import com.google.common.collect.Iterators
import gnu.trove.TCollections
import gnu.trove.map.TIntObjectMap
import gnu.trove.map.hash.TIntObjectHashMap
import org.apache.commons.math3.util.Precision
import org.jetbrains.annotations.TestOnly
import org.jetbrains.bio.*
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.io.IOException
import java.nio.ByteOrder
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.atomic.AtomicLong
import kotlin.LazyThreadSafetyMode.NONE
typealias RomBufferFactoryProvider = (String, ByteOrder) -> RomBufferFactory
/**
* A common superclass for Big files.
*
* Supported format versions
*
* 3 full support
* 4 partial support, specifically, extra indices aren't supported
* 5 custom version, requires Snappy instead of DEFLATE for
* compressed data blocks
*/
abstract class BigFile<out T> internal constructor(
val source: String,
internal val buffFactory: RomBufferFactory,
magic: Int,
prefetch: Int,
cancelledChecker: (() -> Unit)?
) : Closeable {
internal lateinit var header: Header
internal lateinit var zoomLevels: List<ZoomLevel>
internal lateinit var bPlusTree: BPlusTree
internal lateinit var rTree: RTreeIndex
// Kotlin doesn't allow do this val and init in constructor
private var prefetechedTotalSummary: BigSummary? = null
/** Whole-file summary. */
val totalSummary: BigSummary by lazy(NONE) {
prefetechedTotalSummary ?: buffFactory.create().use {
BigSummary.read(it, header.totalSummaryOffset)
}
}
private var prefetchedChromosomes: TIntObjectMap<String>? = null
/**
* An in-memory mapping of chromosome IDs to chromosome names.
*
* Because sometimes (always) you don't need a B+ tree for that.
*/
val chromosomes: TIntObjectMap<String> by lazy(NONE) {
prefetchedChromosomes ?: with(bPlusTree) {
val res = TIntObjectHashMap<String>(header.itemCount)
// returns sequence, but process here => resource could be closed
buffFactory.create().use {
for ((key, id) in traverse(it)) {
res.put(id, key)
}
}
TCollections.unmodifiableMap(res)
}
}
internal var prefetchedLevel2RTreeIndex: Map<ZoomLevel, RTreeIndex>? = null
internal var prefetchedChr2Leaf: Map<String, BPlusLeaf?>? = null
init {
try {
buffFactory.create().use { input ->
cancelledChecker?.invoke()
header = Header.read(input, magic)
zoomLevels = (0 until header.zoomLevelCount).map { ZoomLevel.read(input) }
bPlusTree = BPlusTree.read(input, header.chromTreeOffset)
// if do prefetch input and file not empty:
if (prefetch >= BigFile.PREFETCH_LEVEL_FAST) {
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetechedTotalSummary = BigSummary.read(input, header.totalSummaryOffset)
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetchedChromosomes = with(bPlusTree) {
val res = TIntObjectHashMap<String>(this.header.itemCount)
// returns sequence, but process here => resource could be closed
for ((key, id) in traverse(input)) {
res.put(id, key)
}
TCollections.unmodifiableMap(res)
}
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetchedChr2Leaf = prefetchedChromosomes!!.valueCollection().map {
it to bPlusTree.find(input, it)
}.toMap()
// stored not in the beginning of file
prefetchedLevel2RTreeIndex = zoomLevels.mapNotNull {
if (it.reduction == 0) {
null
} else {
require(it.indexOffset != 0L) {
"Zoom index offset expected to be not zero."
}
require(it.dataOffset != 0L) {
"Zoom data offset expected to be not zero."
}
val zRTree = RTreeIndex.read(input, it.indexOffset)
zRTree.prefetchBlocksIndex(
input, true, false, header.uncompressBufSize,
cancelledChecker
)
it to zRTree
}
}.toMap()
}
// this point not to the beginning of file => read it here using new buffer
// in buffered stream
cancelledChecker?.invoke()
rTree = RTreeIndex.read(input, header.unzoomedIndexOffset)
if (prefetch >= BigFile.PREFETCH_LEVEL_DETAILED) {
rTree.prefetchBlocksIndex(
input, false, true, header.uncompressBufSize, cancelledChecker
)
}
}
} catch (e: Exception) {
buffFactory.close()
throw e
}
}
/**
* File compression type.
*
* @since 0.2.6
*/
val compression: CompressionType get() = with(header) {
when {
// Compression was introduced in version 3 of the format. See
// bbiFile.h in UCSC sources.
version < 3 || uncompressBufSize == 0 -> CompressionType.NO_COMPRESSION
version <= 4 -> CompressionType.DEFLATE
version == 5 -> CompressionType.SNAPPY
else -> error("unsupported version: $version")
}
}
/**
* Internal caching Statistics: Counter for case when cached decompressed block
* differs from desired
*/
private val blockCacheMisses = AtomicLong()
/**
* Internal caching Statistics: Counter for case when cached decompressed block
* matches desired
*/
private val blockCacheIns = AtomicLong()
/**
* Splits the interval `[startOffset, endOffset)` into `numBins`
* non-intersecting sub-intervals (aka bins) and computes a summary
* of the data values for each bin.
*
* @param name human-readable chromosome name, e.g. `"chr9"`.
* @param startOffset 0-based start offset (inclusive).
* @param endOffset 0-based end offset (exclusive), if 0 than the whole
* chromosome is used.
* @param numBins number of summaries to compute. Defaults to `1`.
* @param index if `true` pre-computed is index is used if possible.
* @param cancelledChecker Throw cancelled exception to abort operation
* @return a list of summaries.
*/
@Throws(IOException::class)
fun summarize(name: String, startOffset: Int = 0, endOffset: Int = 0,
numBins: Int = 1, index: Boolean = true,
cancelledChecker: (() -> Unit)? = null): List<BigSummary> {
var list: List<BigSummary> = emptyList()
buffFactory.create().use { input ->
val chromosome = when {
prefetchedChr2Leaf != null -> prefetchedChr2Leaf!![name]
else -> bPlusTree.find(input, name)
} ?: throw NoSuchElementException(name)
val properEndOffset = if (endOffset == 0) chromosome.size else endOffset
val query = Interval(chromosome.id, startOffset, properEndOffset)
require(numBins <= query.length()) {
"number of bins must not exceed interval length, got " +
"$numBins > ${query.length()}, source $source"
}
// The 2-factor guarantees that we get at least two data points
// per bin. Otherwise we might not be able to estimate SD.
val zoomLevel = zoomLevels.pick(query.length() / (2 * numBins))
val sparseSummaries = if (zoomLevel == null || !index) {
LOG.trace("Summarizing $query from raw data")
summarizeInternal(input, query, numBins, cancelledChecker)
} else {
LOG.trace("Summarizing $query from ${zoomLevel.reduction}x zoom")
summarizeFromZoom(input, query, zoomLevel, numBins, cancelledChecker)
}
val emptySummary = BigSummary()
val summaries = Array(numBins) { emptySummary }
for ((i, summary) in sparseSummaries) {
summaries[i] = summary
}
list = summaries.asList()
}
return list
}
@Throws(IOException::class)
internal abstract fun summarizeInternal(
input: RomBuffer,
query: ChromosomeInterval,
numBins: Int,
cancelledChecker: (() -> Unit)?
): Sequence<IndexedValue<BigSummary>>
private fun summarizeFromZoom(input: RomBuffer,
query: ChromosomeInterval, zoomLevel: ZoomLevel,
numBins: Int,
cancelledChecker: (() -> Unit)?): Sequence<IndexedValue<BigSummary>> {
val zRTree = when {
prefetchedLevel2RTreeIndex != null -> prefetchedLevel2RTreeIndex!![zoomLevel]!!
else -> RTreeIndex.read(input, zoomLevel.indexOffset)
}
val zoomData = zRTree.findOverlappingBlocks(input, query, header.uncompressBufSize, cancelledChecker)
.flatMap { (_ /* interval */, offset, size) ->
assert(!compression.absent || size % ZoomData.SIZE == 0L)
val chrom = chromosomes[query.chromIx]
with(decompressAndCacheBlock(input, chrom, offset, size)) {
val res = ArrayList<ZoomData>()
do {
val zoomData = ZoomData.read(this)
if (zoomData.interval intersects query) {
res.add(zoomData)
}
} while (hasRemaining())
res.asSequence()
}
// XXX we can avoid explicit '#toList' call here, but the
// worst-case space complexity will still be O(n).
}.toList()
var edge = 0 // yay! map with a side effect.
return query.slice(numBins).mapIndexed { i, bin ->
val summary = BigSummary()
for (j in edge until zoomData.size) {
val interval = zoomData[j].interval
if (interval.endOffset <= bin.startOffset) {
edge = j + 1
continue
} else if (interval.startOffset > bin.endOffset) {
break
}
if (interval intersects bin) {
summary.update(zoomData[j],
interval.intersectionLength(bin),
interval.length())
}
}
if (summary.isEmpty()) null else IndexedValue(i, summary)
}.filterNotNull()
}
/**
* Queries an R+-tree.
*
* @param name human-readable chromosome name, e.g. `"chr9"`.
* @param startOffset 0-based start offset (inclusive).
* @param endOffset 0-based end offset (exclusive), if 0 than the whole
* chromosome is used.
* @param overlaps if `false` the resulting list contains only the
* items completely contained within the query,
* otherwise it also includes the items overlapping
* the query.
* @param cancelledChecker Throw cancelled exception to abort operation
* @return a list of items.
* @throws IOException if the underlying [RomBuffer] does so.
*/
@Throws(IOException::class)
@JvmOverloads fun query(name: String, startOffset: Int = 0, endOffset: Int = 0,
overlaps: Boolean = false,
cancelledChecker: (() -> Unit)? = null): List<T> {
buffFactory.create().use { input ->
val res = when {
prefetchedChr2Leaf != null -> prefetchedChr2Leaf!![name]
else -> bPlusTree.find(input, name)
}
return if (res == null) {
emptyList()
} else {
val (_/* key */, chromIx, size) = res
val properEndOffset = if (endOffset == 0) size else endOffset
query(input, Interval(chromIx, startOffset, properEndOffset), overlaps, cancelledChecker).toList()
}
}
}
internal fun query(
input: RomBuffer,
query: ChromosomeInterval,
overlaps: Boolean,
cancelledChecker: (() -> Unit)?
): Sequence<T> {
val chrom = chromosomes[query.chromIx]
return rTree.findOverlappingBlocks(input, query, header.uncompressBufSize, cancelledChecker)
.flatMap { (_, dataOffset, dataSize) ->
cancelledChecker?.invoke()
decompressAndCacheBlock(input, chrom, dataOffset, dataSize).use { decompressedInput ->
queryInternal(decompressedInput, query, overlaps)
}
}
}
internal fun decompressAndCacheBlock(input: RomBuffer,
chrom: String,
dataOffset: Long, dataSize: Long): RomBuffer {
var stateAndBlock = lastCachedBlockInfo.get()
// LOG.trace("Decompress $chrom $dataOffset, size=$dataSize")
val newState = RomBufferState(buffFactory, dataOffset, dataSize, chrom)
val decompressedBlock: RomBuffer
if (stateAndBlock.first != newState) {
val newDecompressedInput = input.decompress(dataOffset, dataSize, compression, header.uncompressBufSize)
stateAndBlock = newState to newDecompressedInput
// We cannot cache block if it is resource which is supposed to be closed
decompressedBlock = when (newDecompressedInput) {
is BBRomBuffer, is MMBRomBuffer -> {
lastCachedBlockInfo.set(stateAndBlock)
blockCacheMisses.incrementAndGet()
// we will reuse block, so let's path duplicate to reader
// in order not to affect buffer state
newDecompressedInput.duplicate(newDecompressedInput.position, newDecompressedInput.limit)
}
else -> newDecompressedInput // no buffer re-use => pass as is
}
} else {
// if decompressed input was supposed to be close => it hasn't been cached => won't be here
blockCacheIns.incrementAndGet()
// we reuse block, so let's path duplicate to reader
// in order not to affect buffer state
val block = stateAndBlock.second!!
decompressedBlock = block.duplicate(block.position, block.limit)
}
return decompressedBlock
}
@Throws(IOException::class)
internal abstract fun queryInternal(decompressedBlock: RomBuffer,
query: ChromosomeInterval,
overlaps: Boolean): Sequence<T>
override fun close() {
lastCachedBlockInfo.remove()
val m = blockCacheMisses.get()
val n = m + blockCacheIns.get()
LOG.trace("BigFile closed: Cache misses ${Precision.round(100.0 * m / n, 1)}% ($m of $n), " +
"source: : $source ")
buffFactory.close()
}
internal data class Header(
val order: ByteOrder,
val magic: Int,
val version: Int = 5,
val zoomLevelCount: Int = 0,
val chromTreeOffset: Long,
val unzoomedDataOffset: Long,
val unzoomedIndexOffset: Long,
val fieldCount: Int,
val definedFieldCount: Int,
val asOffset: Long = 0,
val totalSummaryOffset: Long = 0,
val uncompressBufSize: Int,
val extendedHeaderOffset: Long = 0
) {
internal fun write(output: OrderedDataOutput) = with(output) {
check(output.tell() == 0L) // a header is always first.
writeInt(magic)
writeShort(version)
writeShort(zoomLevelCount)
writeLong(chromTreeOffset)
writeLong(unzoomedDataOffset)
writeLong(unzoomedIndexOffset)
writeShort(fieldCount)
writeShort(definedFieldCount)
writeLong(asOffset)
writeLong(totalSummaryOffset)
writeInt(uncompressBufSize)
writeLong(extendedHeaderOffset)
}
companion object {
/** Number of bytes used for this header. */
internal const val BYTES = 64
internal fun read(input: RomBuffer, magic: Int) = with(input) {
checkHeader(magic)
val version = readUnsignedShort()
val zoomLevelCount = readUnsignedShort()
val chromTreeOffset = readLong()
val unzoomedDataOffset = readLong()
val unzoomedIndexOffset = readLong()
val fieldCount = readUnsignedShort()
val definedFieldCount = readUnsignedShort()
val asOffset = readLong()
val totalSummaryOffset = readLong()
val uncompressBufSize = readInt()
val extendedHeaderOffset = readLong()
when {
// asOffset > 0 -> LOG.trace("AutoSQL queries are unsupported")
extendedHeaderOffset > 0 -> LOG.debug("Header extensions are unsupported")
}
Header(order, magic, version, zoomLevelCount, chromTreeOffset,
unzoomedDataOffset, unzoomedIndexOffset,
fieldCount, definedFieldCount, asOffset,
totalSummaryOffset, uncompressBufSize,
extendedHeaderOffset)
}
}
}
internal data class RomBufferState(private val buffFactory: RomBufferFactory?,
val offset: Long, val size: Long,
val chrom: String)
companion object {
private val LOG = LoggerFactory.getLogger(BigFile::class.java)
const val PREFETCH_LEVEL_OFF = 0
const val PREFETCH_LEVEL_FAST = 1
const val PREFETCH_LEVEL_DETAILED = 2
private val lastCachedBlockInfo: ThreadLocal<Pair<RomBufferState, RomBuffer?>> = ThreadLocal.withInitial {
RomBufferState(null, 0L, 0L, "") to null
}
@TestOnly
internal fun lastCachedBlockInfoValue() = lastCachedBlockInfo.get()
/**
* Magic specifies file format and bytes order. Let's read magic as little endian.
*/
private fun readLEMagic(buffFactory: RomBufferFactory) =
buffFactory.create().use {
it.readInt()
}
/**
* Determines byte order using expected magic field value
*/
internal fun getByteOrder(path: String, magic: Int, bufferFactory: RomBufferFactory): ByteOrder {
val leMagic = readLEMagic(bufferFactory)
val (valid, byteOrder) = guess(magic, leMagic)
check(valid) {
val bigMagic = java.lang.Integer.reverseBytes(magic)
"Unexpected header leMagic: Actual $leMagic doesn't match expected LE=$magic and BE=$bigMagic}," +
" file: $path"
}
return byteOrder
}
private fun guess(expectedMagic: Int, littleEndianMagic: Int): Pair<Boolean, ByteOrder> {
if (littleEndianMagic != expectedMagic) {
val bigEndianMagic = java.lang.Integer.reverseBytes(littleEndianMagic)
if (bigEndianMagic != expectedMagic) {
return false to ByteOrder.BIG_ENDIAN
}
return (true to ByteOrder.BIG_ENDIAN)
}
return true to ByteOrder.LITTLE_ENDIAN
}
/**
* @since 0.7.0
*/
fun defaultFactory(): RomBufferFactoryProvider = { p, byteOrder ->
EndianSynchronizedBufferFactory.create(p, byteOrder)
}
@Throws(IOException::class)
@JvmStatic
fun read(path: Path, cancelledChecker: (() -> Unit)? = null): BigFile<Comparable<*>> = read(path.toString(), cancelledChecker = cancelledChecker)
@Throws(IOException::class)
@JvmStatic
fun read(src: String, prefetch: Int = BigFile.PREFETCH_LEVEL_DETAILED,
cancelledChecker: (() -> Unit)? = null,
factoryProvider: RomBufferFactoryProvider = defaultFactory()
): BigFile<Comparable<*>> = factoryProvider(src, ByteOrder.LITTLE_ENDIAN).use { factory ->
val magic = readLEMagic(factory)
when (guessFileType(magic)) {
Type.BIGBED -> BigBedFile.read(src, prefetch, cancelledChecker, factoryProvider)
Type.BIGWIG -> BigWigFile.read(src, prefetch, cancelledChecker, factoryProvider)
else -> throw IllegalStateException("Unsupported file header magic: $magic")
}
}
/**
* Determines file type by reading first byte
*
* @since 0.8.0
*/
fun determineFileType(
src: String,
factoryProvider: RomBufferFactoryProvider = defaultFactory()
) = factoryProvider(src, ByteOrder.LITTLE_ENDIAN).use { factory ->
guessFileType(readLEMagic(factory))
}
private fun guessFileType(magic: Int) = when {
guess(BigBedFile.MAGIC, magic).first -> BigFile.Type.BIGBED
guess(BigWigFile.MAGIC, magic).first -> BigFile.Type.BIGWIG
else -> null
}
}
/** Ad hoc post-processing for [BigFile]. */
protected object Post {
private val LOG = LoggerFactory.getLogger(javaClass)
private inline fun <T> modify(
path: Path, offset: Long = 0L,
block: (BigFile<*>, OrderedDataOutput) -> T): T = read(path).use { bf ->
OrderedDataOutput(path, bf.header.order, offset, create = false).use {
block(bf, it)
}
}
/**
* Fills in zoom levels for a [BigFile] located at [path].
*
* Note that the number of zoom levels to compute must be
* specified in the file [Header]. Additionally the file must
* contain `ZoomData.BYTES * header.zoomLevelCount` zero
* bytes right after the header.
*
* @param path to [BigFile].
* @param itemsPerSlot number of summaries to aggregate prior to
* building an R+ tree. Lower values allow
* for better granularity when loading zoom
* levels, but may degrade the performance
* of [BigFile.summarizeFromZoom]. See
* [RTreeIndex] for details
* @param initial initial reduction.
* @param step reduction step to use, i.e. the first zoom level
* will be `initial`, next `initial * step` etc.
*/
internal fun zoom(
path: Path,
itemsPerSlot: Int = 512,
initial: Int = 8,
step: Int = 4,
cancelledChecker: (() -> Unit)?
) {
LOG.time("Computing zoom levels with step $step for $path") {
val zoomLevels = ArrayList<ZoomLevel>()
modify(path, offset = Files.size(path)) { bf, output ->
var reduction = initial
for (level in bf.zoomLevels.indices) {
val zoomLevel = reduction.zoomAt(
bf, output, itemsPerSlot,
reduction / step,
cancelledChecker
)
if (zoomLevel == null) {
LOG.trace("${reduction}x reduction rejected")
break
} else {
LOG.trace("${reduction}x reduction accepted")
zoomLevels.add(zoomLevel)
}
reduction *= step
if (reduction < 0) {
LOG.trace("Reduction overflow ($reduction) at level $level, next levels ignored")
break
}
}
}
modify(path, offset = Header.BYTES.toLong()) { _/* bf */, output ->
for (zoomLevel in zoomLevels) {
val zoomHeaderOffset = output.tell()
zoomLevel.write(output)
assert((output.tell() - zoomHeaderOffset).toInt() == ZoomLevel.BYTES)
}
}
}
}
private fun Int.zoomAt(
bf: BigFile<*>,
output: OrderedDataOutput,
itemsPerSlot: Int,
prevLevelReduction: Int,
cancelledChecker: (() -> Unit)?
): ZoomLevel? {
val reduction = this
val zoomedDataOffset = output.tell()
val leaves = ArrayList<RTreeIndexLeaf>()
bf.buffFactory.create().use { input ->
for ((_/* name */, chromIx, size) in bf.bPlusTree.traverse(input)) {
val query = Interval(chromIx, 0, size)
if (prevLevelReduction > size) {
// chromosome already covered by 1 bin at prev level
continue
}
// We can re-use pre-computed zooms, but preliminary
// results suggest this doesn't give a noticeable speedup.
val summaries = bf.summarizeInternal(
input, query,
numBins = size divCeiling reduction,
cancelledChecker = cancelledChecker
)
for (slot in Iterators.partition(summaries.iterator(), itemsPerSlot)) {
val dataOffset = output.tell()
output.with(bf.compression) {
for ((i, summary) in slot) {
val startOffset = i * reduction
val endOffset = (i + 1) * reduction
val (count, minValue, maxValue, sum, sumSquares) = summary
ZoomData(chromIx, startOffset, endOffset,
count.toInt(),
minValue.toFloat(), maxValue.toFloat(),
sum.toFloat(), sumSquares.toFloat()).write(this)
}
}
// Compute the bounding interval.
val interval = Interval(chromIx, slot.first().index * reduction,
(slot.last().index + 1) * reduction)
leaves.add(RTreeIndexLeaf(interval, dataOffset, output.tell() - dataOffset))
}
}
}
return if (leaves.size > 1) {
val zoomedIndexOffset = output.tell()
RTreeIndex.write(output, leaves, itemsPerSlot = itemsPerSlot)
ZoomLevel(reduction, zoomedDataOffset, zoomedIndexOffset)
} else {
null // no need for trivial zoom levels.
}
}
/**
* Fills in whole-file [BigSummary] for a [BigFile] located at [path].
*
* The file must contain `BigSummary.BYTES` zero bytes right after
* the zoom levels block.
*/
internal fun totalSummary(path: Path) {
val totalSummaryOffset = BigFile.read(path).use {
it.header.totalSummaryOffset
}
LOG.time("Computing total summary block for $path") {
modify(path, offset = totalSummaryOffset) { bf, output ->
bf.chromosomes.valueCollection()
.flatMap { bf.summarize(it, 0, 0, numBins = 1) }
.fold(BigSummary(), BigSummary::plus)
.write(output)
assert((output.tell() - totalSummaryOffset).toInt() == BigSummary.BYTES)
}
}
}
}
enum class Type {
BIGWIG, BIGBED
}
}
| src/main/kotlin/org/jetbrains/bio/big/BigFile.kt | 1632012250 |
/**
* 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.stories.dto
import com.google.gson.annotations.SerializedName
import kotlin.Int
import kotlin.collections.List
/**
* @param clickableStickers
* @param originalHeight
* @param originalWidth
*/
data class StoriesClickableStickers(
@SerializedName("clickable_stickers")
val clickableStickers: List<StoriesClickableSticker>,
@SerializedName("original_height")
val originalHeight: Int,
@SerializedName("original_width")
val originalWidth: Int
)
| api/src/main/java/com/vk/sdk/api/stories/dto/StoriesClickableStickers.kt | 2547311989 |
package com.vimeo.dummy.sample_kotlin
import org.junit.Test
import verification.Utils
/**
* Unit tests for [KotlinSamples].
*
* Created by restainoa on 5/8/17.
*/
class KotlinSamplesTest {
@Test
fun verifyTypeAdapterGenerated() {
Utils.verifyTypeAdapterGeneration(KotlinSamples::class)
}
@Test
fun verifyTypeAdapterCorrectness() {
Utils.verifyTypeAdapterCorrectness(KotlinSamples::class)
}
}
| integration-test-kotlin/src/test/kotlin/com/vimeo/dummy/sample_kotlin/KotlinSamplesTest.kt | 3149413689 |
package ktx.tiled
import com.badlogic.gdx.maps.MapObject
import com.badlogic.gdx.maps.MapObjects
import com.badlogic.gdx.maps.MapProperties
import com.badlogic.gdx.maps.objects.CircleMapObject
import com.badlogic.gdx.maps.objects.EllipseMapObject
import com.badlogic.gdx.maps.objects.PolygonMapObject
import com.badlogic.gdx.maps.objects.PolylineMapObject
import com.badlogic.gdx.maps.objects.RectangleMapObject
import com.badlogic.gdx.maps.objects.TextureMapObject
import com.badlogic.gdx.math.Circle
import com.badlogic.gdx.math.Ellipse
import com.badlogic.gdx.math.Polygon
import com.badlogic.gdx.math.Polyline
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Shape2D
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. If the property
* is not defined then this method throws a [MissingPropertyException].
* @param key property name.
* @return value of the property.
* @throws MissingPropertyException If the property is not defined.
*/
inline fun <reified T> MapObject.property(key: String): T = properties[key, T::class.java]
?: throw MissingPropertyException("Property $key does not exist for object $name")
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. The type is automatically
* derived from the type of the given default value. If the property is not defined the [defaultValue]
* will be returned.
* @param key property name.
* @param defaultValue default value in case the property is missing.
* @return value of the property or defaultValue if property is missing.
*/
inline fun <reified T> MapObject.property(key: String, defaultValue: T): T = properties[key, defaultValue, T::class.java]
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. If the property
* is not defined then this method returns null.
* @param key property name.
* @return value of the property or null if the property is missing.
*/
inline fun <reified T> MapObject.propertyOrNull(key: String): T? = properties[key, T::class.java]
/**
* Extension method to directly access the [MapProperties] of a [MapObject] and its
* [containsKey][MapProperties.containsKey] method.
* @param key property name.
* @return true if the property exists. Otherwise false.
*/
fun MapObject.containsProperty(key: String) = properties.containsKey(key)
/**
* Extension property to retrieve the x-coordinate of the [MapObject].
* @throws MissingPropertyException if property x does not exist.
*/
val MapObject.x: Float
get() = property("x")
/**
* Extension property to retrieve the y-coordinate of the [MapObject].
* @throws MissingPropertyException if property y does not exist.
*/
val MapObject.y: Float
get() = property("y")
/**
* Extension property to retrieve the width of the [MapObject].
* @throws MissingPropertyException if property width does not exist.
*/
val MapObject.width: Float
get() = property("width")
/**
* Extension property to retrieve the height of the [MapObject].
* @throws MissingPropertyException if property height does not exist.
*/
val MapObject.height: Float
get() = property("height")
/**
* Extension property to retrieve the unique ID of the [MapObject].
* @throws MissingPropertyException if property id does not exist.
*/
val MapObject.id: Int
get() = property("id")
/**
* Extension property to retrieve the rotation of the [MapObject]. Null if the property is unset.
*/
val MapObject.rotation: Float?
get() = propertyOrNull("rotation")
/**
* Extension property to retrieve the type of the [MapObject]. Null if the property is unset.
*/
val MapObject.type: String?
get() = propertyOrNull("type")
/**
* Extension method to retrieve the [Shape2D] instance of a [MapObject].
* Depending on the type of the object a different shape will be returned:
*
* - [CircleMapObject] -> [Circle]
* - [EllipseMapObject] -> [Ellipse]
* - [PolylineMapObject] -> [Polyline]
* - [PolygonMapObject] -> [Polygon]
* - [RectangleMapObject] -> [Rectangle]
*
* Note that objects that do not have any shape like [TextureMapObject] will throw a [MissingShapeException]
* @throws MissingShapeException If the object does not have any shape
*/
val MapObject.shape: Shape2D
get() = when (this) {
is CircleMapObject -> circle
is EllipseMapObject -> ellipse
is PolylineMapObject -> polyline
is PolygonMapObject -> polygon
is RectangleMapObject -> rectangle
else -> throw MissingShapeException("MapObject of type ${this::class.java} does not have a shape.")
}
/**
* Returns **true** if and only if the [MapObjects] collection is empty.
*/
fun MapObjects.isEmpty() = this.count <= 0
/**
* Returns **true** if and only if the [MapObjects] collection is not empty.
*/
fun MapObjects.isNotEmpty() = this.count > 0
| tiled/src/main/kotlin/ktx/tiled/mapObjects.kt | 3863797852 |
/*
* Copyright 2016-2022 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
*
* 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 examples.kotlin.mybatis3.column.comparison
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
object ColumnComparisonDynamicSqlSupport {
val columnComparison = ColumnComparison()
val number1 = columnComparison.number1
val number2 = columnComparison.number2
val columnList = listOf(number1, number2)
class ColumnComparison : SqlTable("ColumnComparison") {
val number1 = column<Int>(name = "number1", jdbcType = JDBCType.INTEGER)
val number2 = column<Int>(name = "number2", jdbcType = JDBCType.INTEGER)
}
}
| src/test/kotlin/examples/kotlin/mybatis3/column/comparison/ColumnComparisonDynamicSqlSupport.kt | 608872643 |
package com.themovielist.moviedetail.review
import com.themovielist.base.BasePresenter
import com.themovielist.model.MovieReviewModel
object MovieReviewListDialogContract {
interface View {
fun addReviewsToList(movieReviewList: List<MovieReviewModel>)
fun enableLoadMoreListener()
fun disableLoadMoreListener()
fun showLoadingIndicator()
fun showErrorLoadingReviews()
}
internal interface Presenter : BasePresenter<View> {
fun start(movieReviewList: List<MovieReviewModel>, movieId: Int, hasMore: Boolean)
fun onListEndReached()
fun tryLoadReviewsAgain()
}
}
| app/src/main/java/com/themovielist/moviedetail/review/MovieReviewListDialogContract.kt | 752390309 |
package com.habitrpg.android.habitica.ui.views.social
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.habitrpg.android.habitica.databinding.ViewInvitationBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.invitations.GenericInvitation
class InvitationsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var acceptCall: ((String) -> Unit)? = null
var rejectCall: ((String) -> Unit)? = null
var setLeader: ((String) -> Unit)? = null
var leaderID: String? = null
var groupName: String? = null
init {
orientation = VERTICAL
}
fun setInvitations(invitations: List<GenericInvitation>) {
removeAllViews()
for (invitation in invitations) {
leaderID = invitation.inviter
groupName = invitation.name
val binding = ViewInvitationBinding.inflate(context.layoutInflater, this, true)
leaderID?.let {
setLeader?.invoke(it)
invalidate()
}
binding.acceptButton.setOnClickListener {
invitation.id?.let { it1 -> acceptCall?.invoke(it1) }
}
binding.rejectButton.setOnClickListener {
invitation.id?.let { it1 -> rejectCall?.invoke(it1) }
}
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/social/InvitationsView.kt | 3633027464 |
package org.stepik.android.view.user_reviews.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_user_review_potential.*
import org.stepic.droid.R
import org.stepik.android.domain.user_reviews.model.UserCourseReviewItem
import org.stepik.android.model.Course
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class UserReviewsPotentialAdapterDelegate(
private val onCourseTitleClicked: (Course) -> Unit,
private val onWriteReviewClicked: (Long, String, Float) -> Unit
) : AdapterDelegate<UserCourseReviewItem, DelegateViewHolder<UserCourseReviewItem>>() {
companion object {
private const val RATING_RESET_DELAY_MS = 750L
}
override fun isForViewType(position: Int, data: UserCourseReviewItem): Boolean =
data is UserCourseReviewItem.PotentialReviewItem
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<UserCourseReviewItem> =
ViewHolder(createView(parent, R.layout.item_user_review_potential))
private inner class ViewHolder(override val containerView: View) : DelegateViewHolder<UserCourseReviewItem>(containerView), LayoutContainer {
init {
userReviewIcon.setOnClickListener { (itemData as? UserCourseReviewItem.PotentialReviewItem)?.course?.let(onCourseTitleClicked) }
userReviewCourseTitle.setOnClickListener { (itemData as? UserCourseReviewItem.PotentialReviewItem)?.course?.let(onCourseTitleClicked) }
userReviewRating.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
val potentialReview = (itemData as? UserCourseReviewItem.PotentialReviewItem) ?: return@setOnRatingBarChangeListener
if (fromUser) {
onWriteReviewClicked(potentialReview.course.id, potentialReview.course.title.toString(), rating)
// TODO .postDelayed is not safe, it would be a good idea to replace this
ratingBar.postDelayed({ ratingBar.rating = 0f }, RATING_RESET_DELAY_MS)
}
}
userReviewWriteAction.setOnClickListener {
val potentialReview = (itemData as? UserCourseReviewItem.PotentialReviewItem) ?: return@setOnClickListener
onWriteReviewClicked(potentialReview.course.id, potentialReview.course.title.toString(), -1f)
}
}
override fun onBind(data: UserCourseReviewItem) {
data as UserCourseReviewItem.PotentialReviewItem
userReviewCourseTitle.text = data.course.title
Glide
.with(context)
.asBitmap()
.load(data.course.cover)
.placeholder(R.drawable.general_placeholder)
.fitCenter()
.into(userReviewIcon)
userReviewRating.max = 5
}
}
} | app/src/main/java/org/stepik/android/view/user_reviews/ui/adapter/delegate/UserReviewsPotentialAdapterDelegate.kt | 2301037082 |
package org.stepik.android.domain.personal_deadlines.model
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import org.stepic.droid.R
import org.stepic.droid.util.AppConstants
enum class LearningRate(
@StringRes val title: Int,
@DrawableRes val icon: Int,
val millisPerWeek: Long
) : Parcelable {
HOBBY(
R.string.deadlines_learning_rate_hobby,
R.drawable.ic_deadlines_learning_rate_hobby,
AppConstants.MILLIS_IN_1HOUR * 3
),
STANDARD(
R.string.deadlines_learning_rate_standard,
R.drawable.ic_deadlines_learning_rate_standard,
AppConstants.MILLIS_IN_1HOUR * 7
),
EXTREME(
R.string.deadlines_learning_rate_extreme,
R.drawable.ic_deadlines_learning_rate_extreme,
AppConstants.MILLIS_IN_1HOUR * 15
);
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(ordinal)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<LearningRate> {
override fun createFromParcel(parcel: Parcel): LearningRate =
LearningRate.values()[parcel.readInt()]
override fun newArray(size: Int): Array<LearningRate?> =
arrayOfNulls(size)
}
} | app/src/main/java/org/stepik/android/domain/personal_deadlines/model/LearningRate.kt | 2664894962 |
package org.stepic.droid.di
import dagger.Binds
import dagger.Module
import org.stepic.droid.core.GoogleApiChecker
import org.stepic.droid.core.GoogleApiCheckerImpl
@Module
interface GoogleModule {
@Binds
fun bindGoogleChecker(googleApiCheckerImpl: GoogleApiCheckerImpl): GoogleApiChecker
}
| app/src/main/java/org/stepic/droid/di/GoogleModule.kt | 2960659877 |
/**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.control.view
import com.savvasdalkitsis.gameframe.infra.base.BaseView
import com.savvasdalkitsis.gameframe.feature.networking.model.IpAddress
interface ControlView: BaseView {
fun operationSuccess()
fun operationFailure(e: Throwable)
fun ipAddressLoaded(ipAddress: IpAddress)
fun ipCouldNotBeFound(throwable: Throwable)
fun wifiNotEnabledError(e: Throwable)
}
| control/src/main/java/com/savvasdalkitsis/gameframe/feature/control/view/ControlView.kt | 3534756710 |
package br.com.battista.bgscore.robot
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.v7.widget.Toolbar
import android.widget.TextView
import br.com.battista.bgscore.R
import br.com.battista.bgscore.helper.CustomViewMatcher.withBottomBarItemCheckedStatus
import org.hamcrest.Matchers.allOf
abstract class BaseRobot {
protected fun doWait(millis: Long) {
try {
Thread.sleep(millis)
} catch (var4: InterruptedException) {
throw RuntimeException("Could not sleep.", var4)
}
}
fun navigationToHome() = apply {
onView(withId(R.id.action_home))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_home)))
}
fun navigationToMatches() = apply {
onView(withId(R.id.action_matches))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_matches)))
}
fun navigationToGames() = apply {
onView(withId(R.id.action_games))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_games)))
}
fun navigationToAccount() = apply {
onView(withId(R.id.action_more))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_account)))
}
fun checkBottomBarHomeChecked() = apply {
onView(withId(R.id.action_home))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarMatchesChecked() = apply {
onView(withId(R.id.action_matches))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarGamesChecked() = apply {
onView(withId(R.id.action_games))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarAccountChecked() = apply {
onView(withId(R.id.action_more))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun closeWelcomeDialog() = apply {
try {
onView(withText(R.string.btn_ok))
.perform(click())
} catch (e: Exception) {
}
}
companion object {
val DO_WAIT_MILLIS = 500
}
}
| app/src/androidTest/java/br/com/battista/bgscore/robot/BaseRobot.kt | 4082465933 |
package org.walleth.nfc
import android.os.Bundle
class NDEFTagHandlingActivity : BaseNFCActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
finish()
}
}
| app/src/main/java/org/walleth/nfc/NDEFTagHandlingActivity.kt | 2450991685 |
package bobzien.com.smartrecyclerviewadapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.Adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bobzien.com.smartrecyclerviewadapter.SmartRecyclerViewAdapter.ViewHolder
import java.util.*
open class SmartRecyclerViewAdapter @Throws(DuplicateItemViewTypeException::class)
constructor(viewHolders: Array<ViewHolder<Any>>) : Adapter<ViewHolder<Any>>() {
private val viewHolders = HashMap<Class<Any>, ViewHolder<Any>>()
private val itemViewTypeToViewHolders = HashMap<Int, ViewHolder<Any>>()
private var items: MutableList<Any> = ArrayList()
private val typeViewHolders = ArrayList<TypeViewHolder<Any>>()
var selectedPosition: Int = 0
set(selectedPosition: Int) {
val oldSelectedPosition = this.selectedPosition
field = selectedPosition
notifyItemChanged(oldSelectedPosition)
notifyItemChanged(selectedPosition)
}
init {
for (viewHolder in viewHolders) {
addViewHolder(viewHolder)
}
}
constructor(viewHolder: ViewHolder<Any>) : this(arrayOf(viewHolder)) {
}
fun addViewHolders(vararg viewHolders: ViewHolder<Any>) {
for (viewHolder in viewHolders) {
addViewHolder(viewHolder)
}
}
fun addViewHolder(viewHolder: ViewHolder<Any>) {
if (itemViewTypeToViewHolders.containsKey(viewHolder.genericItemViewType)) {
throw (DuplicateItemViewTypeException((itemViewTypeToViewHolders[viewHolder.genericItemViewType] as Any).javaClass.simpleName
+ " has same ItemViewType as " + viewHolder.javaClass.simpleName
+ ". Overwrite getGenericItemViewType() in one of the two classes and assign a new type. Consider using an android id."))
}
itemViewTypeToViewHolders.put(viewHolder.genericItemViewType, viewHolder)
if (viewHolder is TypeViewHolder<Any>) {
typeViewHolders.add(viewHolder)
}
this.viewHolders.put(viewHolder.getHandledClass() as Class<Any>, viewHolder)
}
fun setItems(items: List<Any>) {
this.items = ArrayList(items)
wrapItems()
notifyDataSetChanged()
}
fun addItems(position: Int, vararg newItems: Any) {
var index = position
val insertionPosition = position
for (item in newItems) {
items.add(index++, wrapItem(item))
}
notifyItemRangeInserted(insertionPosition, newItems.size)
}
fun addItems(position: Int, newItems: List<Any>) {
var index = position
val insertionPosition = position
for (item in newItems) {
items.add(index++, wrapItem(item))
}
wrapItems()
notifyItemRangeInserted(insertionPosition, newItems.size)
}
fun removeItemAt(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun removeItem(item: Any) {
val index = items.indexOf(item)
items.removeAt(index)
notifyItemRemoved(index)
}
fun removeItemRange(startPosition: Int, itemCount: Int) {
for (i in 0..itemCount - 1) {
items.removeAt(startPosition)
}
notifyItemRangeRemoved(startPosition, itemCount)
}
fun getItem(position: Int): Any? {
if (position >= itemCount || position < 0) {
return null
}
val item = items[position]
if (item is Wrapper) {
return item.item
}
return item
}
fun indexOf(item: Any?): Int {
return items.indexOf(item)
}
private fun wrapItems() {
if (typeViewHolders.size > 0) {
var i = 0
for (item in items) {
items[i] = wrapItem(item)
i++
}
}
}
private fun wrapItem(item: Any): Any {
for (typeViewHolder in typeViewHolders) {
if (typeViewHolder.internalCanHandle(item)) {
val wrappedObject = typeViewHolder.getWrappedObject(item)
return wrappedObject
}
}
return item
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<Any> {
val viewHolder = itemViewTypeToViewHolders[viewType]
val instance = viewHolder!!.getInstance(parent)
instance.adapter = this
return instance
}
override fun onBindViewHolder(holder: ViewHolder<Any>?, position: Int) {
var item = items[position]
if (holder is TypeViewHolder<*>) {
item = (item as Wrapper).item
}
(holder as ViewHolder<Any>).bindViewHolder(item, position == selectedPosition)
}
override fun getItemCount(): Int {
return items.size
}
override fun getItemViewType(position: Int): Int {
val viewHolder = getViewHolder(position)
return viewHolder.genericItemViewType
}
private fun getViewHolder(position: Int): ViewHolder<Any> {
val item = items[position]
val itemClass = item.javaClass
var viewHolder: ViewHolder<Any>? = viewHolders[itemClass]
if (viewHolder == null) {
viewHolder = tryToFindSuperClass(itemClass)
if (viewHolder != null) {
return viewHolder
}
throw (MissingViewHolderException("There is no Viewholder for " + itemClass.simpleName + " or one of its superClasses."))
}
return viewHolder
}
private fun tryToFindSuperClass(itemClass: Class<*>): ViewHolder<Any>? {
var viewHolder: ViewHolder<Any>?
var superclass: Class<*>? = itemClass.superclass
while (superclass != null) {
viewHolder = viewHolders[superclass]
if (viewHolder != null) {
viewHolders.put(superclass as Class<Any>, viewHolder)
return viewHolder
}
superclass = superclass.superclass
}
return null
}
abstract class ViewHolder<T>
/**
* This constructor is just used to create a factory that can produce the
* ViewHolder that contains the actual itemView using the getInstance(View parent) method.
* @param context
* *
* @param handledClass
*/
(val context: Context, handledClass: Class<*>, itemView: View? = null) : RecyclerView.ViewHolder(itemView ?: View(context)) {
var adapter: SmartRecyclerViewAdapter? = null
private var _handledClass: Class<*>
open fun getHandledClass(): Class<*> {
return _handledClass
}
init {
_handledClass = handledClass
}
fun getInstance(parent: ViewGroup): ViewHolder<Any> {
val view = LayoutInflater.from(context).inflate(layoutResourceId, parent, false)
return getInstance(view)
}
/**
* This has to create a new instance which was created using a constructor which calls super(itemView).
* @param itemView
* *
* @return the new ViewHolder
*/
abstract fun getInstance(itemView: View): ViewHolder<Any>
/**
* Gets the LayoutResourceId of the layout this ViewHolder uses
* @return
*/
abstract val layoutResourceId: Int
/**
* Override this if itemViewTypes are colliding. Consider using an android Id.
* @return itemViewType
*/
open val genericItemViewType: Int
get() = layoutResourceId
/**
* Bind the ViewHolder and return it.
* @param item
* *
* @param selected
* *
* @return ViewHolder
*/
abstract fun bindViewHolder(item: T, selected: Boolean)
}
abstract class TypeViewHolder<T>(context: Context, clazz: Class<Any>, itemView: View? = null) : ViewHolder<T>(context, clazz, itemView) {
private lateinit var _handledClass: Class<*>
init {
_handledClass = getWrappedObject(null).javaClass
}
fun internalCanHandle(item: Any): Boolean {
if (item.javaClass == super.getHandledClass()) {
return canHandle(item as T)
}
return false
}
protected abstract fun canHandle(item: T): Boolean
abstract fun getWrappedObject(item: T?): Wrapper
override fun getHandledClass(): Class<*> {
return _handledClass
}
}
interface Wrapper {
val item: Any
}
class DuplicateItemViewTypeException(detailMessage: String) : RuntimeException(detailMessage)
class MissingViewHolderException(detailMessage: String) : RuntimeException(detailMessage)
}
| smartrecyclerviewadapter/src/main/kotlin/bobzien/com/smartrecyclerviewadapter/SmartRecyclerViewAdapter.kt | 478122302 |
package org.dictat.wikistat.utils
public class IteratorAdapter<R, T>(val iterator : Iterator<R>, val mapping : (R) -> T) : Iterator<T> {
public override fun next(): T {
return mapping(iterator.next())
}
public override fun hasNext(): Boolean {
return iterator.hasNext()
}
} | src/main/kotlin/org/dictat/wikistat/utils/IteratorAdapter.kt | 2570782599 |
package com.jdiazcano.modulartd.beans
/**
* Layer: this defines a layer in the map. The map can be composed by multiple layers, more or less like how they work
* in any image editing program. The thing is that you will be able to have different layers one with the background
* (animated background!) and then some forest in front of it (before building any turrets over it!)
*
* Created by javierdiaz on 16/11/2016.
*/
data class Layer(
var name: String,
var visible: Boolean = true
) {
lateinit var tiles: Array<Array<Tile>>
init {
}
} | editor/core/src/main/kotlin/com/jdiazcano/modulartd/beans/Layer.kt | 1883274703 |
/*
* Copyright 2022 Block 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 com.squareup.wire
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.SchemaException
import okio.Path.Companion.toPath
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import kotlin.test.assertFailsWith
class SchemaBuilderTest {
@Test fun emptySchema() {
val exception = assertFailsWith<SchemaException> {
buildSchema {}
}
assertThat(exception.message).isEqualTo("no sources")
}
@Test fun sourcePathOnly() {
val schema = buildSchema {
add(
"example1.proto".toPath(),
"""
|syntax = "proto2";
|
|message A {
| optional B b = 1;
|}
|message B {
| optional C c = 1;
|}
|message C {
|}
|""".trimMargin()
)
add(
"example2.proto".toPath(),
"""
|syntax = "proto2";
|
|message D {
|}
|""".trimMargin()
)
}
assertThat(schema.protoFiles.map { it.location }).containsExactlyInAnyOrder(
Location.get("/source", "example1.proto"),
Location.get("/source", "example2.proto"),
Location.get("google/protobuf/descriptor.proto"),
)
}
}
| wire-library/wire-schema-tests/src/test/java/com/squareup/wire/SchemaBuilderTest.kt | 3253124032 |
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("GrpcResponseCloseable")
package com.squareup.wire
import com.squareup.wire.internal.addSuppressed
import okio.IOException
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
expect class GrpcResponse {
@get:JvmName("body") val body: GrpcResponseBody?
@JvmOverloads fun header(name: String, defaultValue: String? = null): String?
@Throws(IOException::class)
fun trailers(): GrpcHeaders
fun close()
}
internal inline fun <T : GrpcResponse?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
closeFinally(exception)
}
}
private fun GrpcResponse?.closeFinally(cause: Throwable?) = when {
this == null -> {
}
cause == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}
| wire-library/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt | 2021849040 |
package failchat.youtube
import failchat.chat.ImageFormat
import failchat.chat.badge.ImageBadge
object RoleBadges {
val verified = ImageBadge("../_shared/icons/youtube-verified.svg", ImageFormat.VECTOR, "Verified")
val streamer = ImageBadge("../_shared/icons/youtube-streamer.svg", ImageFormat.VECTOR, "Streamer")
val moderator = ImageBadge("../_shared/icons/youtube-moderator.svg", ImageFormat.VECTOR, "Moderator")
}
| src/main/kotlin/failchat/youtube/RoleBadges.kt | 2188295690 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
import org.jetbrains.intellij.build.IdeaCommunityProperties
import org.jetbrains.intellij.build.IdeaProjectLoaderUtil
import org.jetbrains.intellij.build.kotlin.KotlinPluginBuilder
object KotlinPluginBuildTarget {
@JvmStatic
fun main(args: Array<String>) {
val communityHome = IdeaProjectLoaderUtil.guessCommunityHome(javaClass)
KotlinPluginBuilder(communityHome, communityHome.communityRoot, IdeaCommunityProperties(communityHome)).build()
}
}
| build/groovy/KotlinPluginBuildTarget.kt | 2214119679 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.util
import android.os.Process
import arcs.core.util.TaggedLog
import java.io.File
/**
* An utility singleton queries binder stats directly from the kernel binder driver.
*
* Note:
* If a permission denial shows up at i.e. a privileged application, try to execute the command
* to configure secure Linux to permissive mode:
* $> adb shell setenforce 0
*
* By default, a privileged application is disallowed to access any debugfs file attributes.
* neverallow priv_app debugfs:file read;
*/
object AndroidBinderStats {
private const val STATS_FILE_NODE = "/sys/kernel/debug/binder/stats"
private val log = TaggedLog { "AndroidBinderStats" }
private val parser = AndroidBinderStatsParser()
/** Query the stats of the given binder process record [tags]. */
fun query(vararg tags: String): List<String> = with(
parser.parse(readBinderStats(), Process.myPid())
) {
tags.map { this[it] ?: "" }
}
private fun readBinderStats(): Sequence<String> {
return try {
File(STATS_FILE_NODE).bufferedReader().lineSequence()
} catch (e: Exception) {
// The possible reasons could be Linux debugfs is not mounted on some Android
// devices and builds, denial of permission, etc.
log.warning { e.message ?: "Unknown exception on accessing $STATS_FILE_NODE" }
emptySequence()
}
}
}
| java/arcs/android/util/AndroidBinderStats.kt | 1562129044 |
package au.com.dius.pact.core.model
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
import java.nio.charset.Charset
class OptionalBodyTest : StringSpec() {
val nullBodyVar: OptionalBody? = null
val missingBody = OptionalBody.missing()
val nullBody = OptionalBody.nullBody()
val emptyBody = OptionalBody.empty()
val presentBody = OptionalBody.body("present".toByteArray())
init {
"a null body variable is missing" {
nullBodyVar.isMissing() shouldBe true
}
"a missing body is missing" {
missingBody.isMissing() shouldBe true
}
"a body that contains a null is not missing" {
nullBody.isMissing() shouldBe false
}
"an empty body is not missing" {
emptyBody.isMissing() shouldBe false
}
"a present body is not missing" {
presentBody.isMissing() shouldBe false
}
"a null body variable is null" {
nullBodyVar.isNull() shouldBe true
}
"a missing body is not null" {
missingBody.isNull() shouldBe false
}
"a body that contains a null is null" {
nullBody.isNull() shouldBe true
}
"an empty body is not null" {
emptyBody.isNull() shouldBe false
}
"a present body is not null" {
presentBody.isNull() shouldBe false
}
"a null body variable is not empty" {
nullBodyVar.isEmpty() shouldBe false
}
"a missing body is not empty" {
missingBody.isEmpty() shouldBe false
}
"a body that contains a null is not empty" {
nullBody.isEmpty() shouldBe false
}
"an empty body is empty" {
emptyBody.isEmpty() shouldBe true
}
"a present body is not empty" {
presentBody.isEmpty() shouldBe false
}
"a null body variable is not present" {
nullBodyVar.isPresent() shouldBe false
}
"a missing body is not present" {
missingBody.isPresent() shouldBe false
}
"a body that contains a null is not present" {
nullBody.isPresent() shouldBe false
}
"an empty body is not present" {
emptyBody.isPresent() shouldBe false
}
"a present body is present" {
presentBody.isPresent() shouldBe true
}
"a null body or else returns the else" {
nullBodyVar.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"a missing body or else returns the else" {
missingBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"a body that contains a null or else returns the else" {
nullBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"an empty body or else returns empty" {
emptyBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe ""
}
"a present body or else returns the body" {
presentBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "present"
}
}
}
| core/model/src/test/kotlin/au/com/dius/pact/core/model/OptionalBodyTest.kt | 2893335881 |
package org.wordpress.android.util
import java.util.Locale
import javax.inject.Inject
class LocaleProvider @Inject constructor() {
fun getAppLocale(): Locale {
return LanguageUtils.getCurrentDeviceLanguage()
}
fun getAppLanguageDisplayString(): String {
return LocaleManager.getLanguageString(getAppLocale().toString(), getAppLocale())
}
fun createSortedLocalizedLanguageDisplayStrings(
availableLocales: Array<String>,
targetLocale: Locale
): Triple<Array<String>, Array<String>, Array<String>>? {
return LocaleManager.createSortedLanguageDisplayStrings(availableLocales, targetLocale)
}
}
| WordPress/src/main/java/org/wordpress/android/util/LocaleProvider.kt | 1352440977 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* 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 core.layers.recurrent.deltarnn
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.RecurrentLayerUnit
import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow
import com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn.DeltaRNNLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn.DeltaRNNLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
*
*/
internal sealed class DeltaLayersWindow: LayersWindow {
/**
*
*/
object Empty : DeltaLayersWindow() {
override fun getPrevState(): Nothing? = null
override fun getNextState(): Nothing? = null
}
/**
*
*/
object Back : DeltaLayersWindow() {
override fun getPrevState(): DeltaRNNLayer<DenseNDArray> = buildPrevStateLayer()
override fun getNextState(): Nothing? = null
}
/**
*
*/
object Front : DeltaLayersWindow() {
override fun getPrevState(): Nothing? = null
override fun getNextState(): DeltaRNNLayer<DenseNDArray> = buildNextStateLayer()
}
/**
*
*/
object Bilateral : DeltaLayersWindow() {
override fun getPrevState(): DeltaRNNLayer<DenseNDArray> = buildPrevStateLayer()
override fun getNextState(): DeltaRNNLayer<DenseNDArray> = buildNextStateLayer()
}
}
/**
*
*/
private fun buildPrevStateLayer(): DeltaRNNLayer<DenseNDArray> = DeltaRNNLayer(
inputArray = AugmentedArray(size = 4),
inputType = LayerType.Input.Dense,
outputArray = RecurrentLayerUnit<DenseNDArray>(5).apply {
assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, 0.2, -0.3, -0.9, -0.8)))
setActivation(Tanh)
activate()
},
params = DeltaRNNLayerParameters(inputSize = 4, outputSize = 5),
activationFunction = Tanh,
layersWindow = DeltaLayersWindow.Empty,
dropout = 0.0
)
/**
*
*/
private fun buildNextStateLayer(): DeltaRNNLayer<DenseNDArray> = DeltaRNNLayer(
inputArray = AugmentedArray<DenseNDArray>(size = 4),
inputType = LayerType.Input.Dense,
outputArray = RecurrentLayerUnit<DenseNDArray>(5).apply {
assignErrors(errors = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, -0.5, 0.7, 0.2)))
},
params = DeltaRNNLayerParameters(inputSize = 4, outputSize = 5),
activationFunction = Tanh,
layersWindow = DeltaLayersWindow.Empty,
dropout = 0.0
).apply {
wx.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, -0.7, -0.2, 0.8, -0.6)))
partition.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, -0.1, 0.6, -0.8, 0.5)))
candidate.assignErrors(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.4, 0.6, -0.1, 0.3, 0.0)))
}
| src/test/kotlin/core/layers/recurrent/deltarnn/DeltaLayersWindow.kt | 1010483476 |
package org.wordpress.android.ui.main.jetpack.migration.compose
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
const val DIM_ALPHA = 0.2f
fun Modifier.dimmed(shouldDim: Boolean) = alpha(if (shouldDim) DIM_ALPHA else 1f)
| WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/compose/UiHelpers.kt | 2590350230 |
package org.wordpress.android.ui.main.jetpack.migration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.accounts.HelpActivity.Origin.JETPACK_MIGRATION_HELP
import org.wordpress.android.ui.compose.theme.AppTheme
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent.CompleteFlow
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent.ShowHelp
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Content
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Error
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Loading
import org.wordpress.android.ui.main.jetpack.migration.compose.state.DeleteStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.DoneStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.ErrorStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.LoadingState
import org.wordpress.android.ui.main.jetpack.migration.compose.state.NotificationsStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.WelcomeStep
import javax.inject.Inject
@AndroidEntryPoint
class JetpackMigrationFragment : Fragment() {
@Inject lateinit var dispatcher: Dispatcher
private val viewModel: JetpackMigrationViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ComposeView(requireContext()).apply {
setContent {
AppTheme {
JetpackMigrationScreen()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeViewModelEvents()
val showDeleteWpState = arguments?.getBoolean(KEY_SHOW_DELETE_WP_STATE, false) ?: false
viewModel.start(showDeleteWpState)
}
private fun observeViewModelEvents() {
viewModel.actionEvents.onEach(this::handleActionEvents).launchIn(viewLifecycleOwner.lifecycleScope)
}
private fun handleActionEvents(actionEvent: JetpackMigrationActionEvent) {
when (actionEvent) {
is CompleteFlow -> ActivityLauncher.showMainActivity(requireContext())
is ShowHelp -> launchHelpScreen()
}
}
private fun launchHelpScreen() {
ActivityLauncher.viewHelpAndSupport(
requireContext(),
JETPACK_MIGRATION_HELP,
null,
null
)
}
companion object {
private const val KEY_SHOW_DELETE_WP_STATE = "KEY_SHOW_DELETE_WP_STATE"
fun newInstance(showDeleteWpState: Boolean = false): JetpackMigrationFragment =
JetpackMigrationFragment().apply {
arguments = Bundle().apply {
putBoolean(KEY_SHOW_DELETE_WP_STATE, showDeleteWpState)
}
}
}
}
@Composable
private fun JetpackMigrationScreen(viewModel: JetpackMigrationViewModel = viewModel()) {
Box {
val uiState by viewModel.uiState.collectAsState(Loading)
Crossfade(targetState = uiState) { state ->
when (state) {
is Content.Welcome -> WelcomeStep(state)
is Content.Notifications -> NotificationsStep(state)
is Content.Done -> DoneStep(state)
is Content.Delete -> DeleteStep(state)
is Error -> ErrorStep(state)
is Loading -> LoadingState()
}
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/JetpackMigrationFragment.kt | 847049489 |
// "Add non-null asserted (!!) call" "true"
fun test() {
var i: Int? = 0
i--<caret>
} | plugins/kotlin/idea/tests/testData/quickfix/addExclExclCall/operationDecrement.kt | 3996431087 |
// "Create abstract function 'A.Companion.foo'" "false"
// ACTION: Create extension function 'A.Companion.foo'
// ACTION: Create member function 'A.Companion.foo'
// ACTION: Rename reference
// ERROR: Unresolved reference: foo
abstract class A
fun test() {
val a: Int = A.<caret>foo(2)
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/abstract/companion.kt | 2026906300 |
/*
* VoIP.ms SMS
* Copyright (C) 2021 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.database.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import net.kourlas.voipms_sms.sms.Message
import java.util.*
@Entity(tableName = Sms.TABLE_NAME)
data class Sms(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = COLUMN_DATABASE_ID) val databaseId: Long = 0,
@ColumnInfo(name = COLUMN_VOIP_ID) val voipId: Long? = null,
@ColumnInfo(name = COLUMN_DATE) val date: Long = Date().time / 1000L,
@ColumnInfo(name = COLUMN_INCOMING) val incoming: Long = 0,
@ColumnInfo(name = COLUMN_DID) val did: String = "",
@ColumnInfo(name = COLUMN_CONTACT) val contact: String = "",
@ColumnInfo(name = COLUMN_TEXT) val text: String = "",
@ColumnInfo(name = COLUMN_UNREAD) val unread: Long = 0,
@ColumnInfo(name = COLUMN_DELIVERED) val delivered: Long = 0,
@ColumnInfo(name = COLUMN_DELIVERY_IN_PROGRESS)
val deliveryInProgress: Long = 0
) {
fun toMessage(): Message = Message(this)
fun toMessage(databaseId: Long): Message = Message(this, databaseId)
companion object {
const val TABLE_NAME = "sms"
const val COLUMN_DATABASE_ID = "DatabaseId"
const val COLUMN_VOIP_ID = "VoipId"
const val COLUMN_DATE = "Date"
const val COLUMN_INCOMING = "Type"
const val COLUMN_DID = "Did"
const val COLUMN_CONTACT = "Contact"
const val COLUMN_TEXT = "Text"
const val COLUMN_UNREAD = "Unread"
const val COLUMN_DELIVERED = "Delivered"
const val COLUMN_DELIVERY_IN_PROGRESS = "DeliveryInProgress"
}
} | voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/database/entities/Sms.kt | 94812108 |
package io.github.bkmioa.nexusrss.download.ui
import android.app.Activity
import android.content.Intent
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 androidx.appcompat.widget.PopupMenu
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.airbnb.epoxy.EpoxyController
import com.google.android.material.snackbar.Snackbar
import io.github.bkmioa.nexusrss.R
import io.github.bkmioa.nexusrss.base.BaseFragment
import io.github.bkmioa.nexusrss.model.DownloadNodeModel
import io.github.bkmioa.nexusrss.ui.TabListActivity
import kotlinx.android.synthetic.main.activity_tab_list.*
class DownloadNodeListFragment : BaseFragment() {
companion object {
const val REQUEST_CODE_ADD = 0x1
const val REQUEST_CODE_EDIT = 0x2
}
private val listViewModel: DownloadNodeListViewModel by viewModels()
private val listController = ListController()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_download_node_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = listController.adapter
listViewModel.getAllLiveData().observe(viewLifecycleOwner, {
it ?: throw IllegalStateException()
listController.update(it)
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.add("Add")
.setIcon(R.drawable.ic_menu_add)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
.setOnMenuItemClickListener {
val intent = DownloadEditActivity.createIntent(requireContext())
startActivityForResult(intent, REQUEST_CODE_ADD)
true
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
TabListActivity.REQUEST_CODE_ADD -> {
val downloadNode: DownloadNodeModel = data?.getParcelableExtra(DownloadEditActivity.KEY_DOWNLOAD_NODE)
?: throw IllegalStateException()
listViewModel.addDownloadNode(downloadNode)
}
TabListActivity.REQUEST_CODE_EDIT -> {
val downloadNode: DownloadNodeModel = data?.getParcelableExtra(DownloadEditActivity.KEY_DOWNLOAD_NODE)
?: throw IllegalStateException()
listViewModel.addDownloadNode(downloadNode)
}
}
}
}
private fun onItemClicked(model: DownloadNodeModel) {
val intent = DownloadEditActivity.createIntent(requireContext(), model)
startActivityForResult(intent, REQUEST_CODE_EDIT)
}
private fun onMoreClicked(clickedView: View, model: DownloadNodeModel) {
val popupMenu = PopupMenu(requireContext(), clickedView)
popupMenu.menu
.add(R.string.action_duplicate).setOnMenuItemClickListener {
listViewModel.addDownloadNode(model.copy(id = null))
true
}
popupMenu.menu
.add(R.string.action_delete).setOnMenuItemClickListener {
deleteNode(model)
true
}
popupMenu.show()
}
private fun deleteNode(model: DownloadNodeModel) {
listViewModel.delete(model)
Snackbar.make(requireView(), R.string.deleted, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.undo_action) {
listViewModel.addDownloadNode(model)
}
.show()
}
inner class ListController : EpoxyController() {
private var nodeList: List<DownloadNodeModel> = emptyList()
override fun buildModels() {
nodeList.forEach { item ->
DownloadNodeItemViewModel_(item)
.onClickListener(View.OnClickListener { onItemClicked(item) })
.onMoreClickListener(View.OnClickListener { onMoreClicked(it, item) })
.addTo(this)
}
}
fun update(list: List<DownloadNodeModel>) {
nodeList = list
requestModelBuild()
}
}
} | app/src/main/java/io/github/bkmioa/nexusrss/download/ui/DownloadNodeListFragment.kt | 3148922496 |
/*
* BlankTransitData.kt
*
* Copyright 2015-2018 Michael Farrell <[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 au.id.micolous.metrodroid.transit.unknown
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.ui.HeaderListItem
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.ui.TextListItem
/**
* Base class for all types of cards that are blank.
*/
abstract class BlankTransitData : TransitData() {
override val serialNumber: String?
get() = null
override val info: List<ListItem>?
get() = listOf(
HeaderListItem(R.string.fully_blank_title, headingLevel = 1),
TextListItem(R.string.fully_blank_desc)
)
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/transit/unknown/BlankTransitData.kt | 637879960 |
package com.wengelef.kotlinmvvmtest.rest.repo
import com.wengelef.kotlinmvvmtest.db.UserDB
import com.wengelef.kotlinmvvmtest.model.User
import com.wengelef.kotlinmvvmtest.rest.service.UserService
import com.wengelef.kotlinmvvmtest.util.ConnectionObserver
import rx.Observable
import javax.inject.Inject
class UserRepository @Inject constructor(
private val userService: UserService,
private val userDB: UserDB,
connectionObserver: ConnectionObserver): CacheRepository<List<User>>(connectionObserver) {
private var memory: List<User>? = null
override val memoryCall: Observable<List<User>>
get() = Observable.just(memory)
override val cacheCall: Observable<List<User>>
get() = Observable.just(userDB.get())
override val restCall: Observable<List<User>>
get() = userService.getUsers()
override fun serialize(response: List<User>) {
userDB.put(response)
}
override fun keepMemory(response: List<User>?) {
memory = response
}
} | app/src/main/java/com/wengelef/kotlinmvvmtest/rest/repo/UserRepository.kt | 1798479875 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.jabberwockd
object HttpConstants {
object Methods {
const val GET = "GET"
const val PUT = "PUT"
const val DELETE = "DELETE"
}
object ReturnCodes {
/** Success */
const val R_200 = 200
/** Success, resulted in resource creation */
const val R_201 = 201
/** Requested resource not found */
const val R_404 = 404
/** Operation not allowed (i.e. deleting a read-only resource) */
const val R_405 = 405
}
} | jabberwockd/src/main/kotlin/com/efficios/jabberwocky/jabberwockd/HttpConstants.kt | 2707650776 |
package sample
import kotlin.test.Test
import kotlin.test.assertTrue
// JS
actual class <lineMarker descr="Run Test" settings=":cleanJsBrowserTest :jsBrowserTest --tests \"sample.SampleTests\" :cleanJsNodeTest :jsNodeTest --tests \"sample.SampleTests\" --continue"><lineMarker descr="Has expects in ?common? module">SampleTests</lineMarker></lineMarker> {
@Test
actual fun <lineMarker descr="Run Test" settings=":cleanJsBrowserTest :jsBrowserTest --tests \"sample.SampleTests.testMe\" :cleanJsNodeTest :jsNodeTest --tests \"sample.SampleTests.testMe\" --continue"><lineMarker descr="Has expects in ?common? module">testMe</lineMarker></lineMarker>() {
}
}
| plugins/kotlin/idea/tests/testData/gradle/testRunConfigurations/expectClassWithTests/src/jsTest/kotlin/sample/SampleTestsJS.kt | 1921169197 |
package lib
class /*rename*/Foo
fun Foo(p: Int): Foo = Foo() | plugins/kotlin/idea/tests/testData/refactoring/rename/ambiguousClassFunImportRenameClass/before/lib/lib.kt | 2478544822 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.profile.settings.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import no.nordicsemi.android.dfu.analytics.*
import no.nordicsemi.android.common.navigation.NavigationManager
import no.nordicsemi.android.dfu.profile.DfuWelcomeScreen
import no.nordicsemi.android.dfu.profile.settings.domain.DFUSettings
import no.nordicsemi.android.dfu.profile.settings.repository.SettingsRepository
import no.nordicsemi.android.dfu.profile.settings.view.*
import javax.inject.Inject
private const val INFOCENTER_LINK = "https://infocenter.nordicsemi.com/topic/sdk_nrf5_v17.1.0/examples_bootloader.html"
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val repository: SettingsRepository,
private val navigationManager: NavigationManager,
private val analytics: DfuAnalytics
) : ViewModel() {
val state = repository.settings.stateIn(viewModelScope, SharingStarted.Eagerly, DFUSettings())
fun onEvent(event: SettingsScreenViewEvent) {
when (event) {
NavigateUp -> navigationManager.navigateUp()
OnResetButtonClick -> restoreDefaultSettings()
OnAboutAppClick -> navigationManager.navigateTo(DfuWelcomeScreen)
OnAboutDfuClick -> navigationManager.openLink(INFOCENTER_LINK)
OnExternalMcuDfuSwitchClick -> onExternalMcuDfuSwitchClick()
OnKeepBondInformationSwitchClick -> onKeepBondSwitchClick()
OnPacketsReceiptNotificationSwitchClick -> onPacketsReceiptNotificationSwitchClick()
OnDisableResumeSwitchClick -> onDisableResumeSwitchClick()
OnForceScanningAddressesSwitchClick -> onForceScanningAddressesSwitchClick()
is OnNumberOfPocketsChange -> onNumberOfPocketsChange(event.numberOfPockets)
is OnPrepareDataObjectDelayChange -> onPrepareDataObjectDelayChange(event.delay)
is OnRebootTimeChange -> onRebootTimeChange(event.time)
is OnScanTimeoutChange -> onScanTimeoutChange(event.timeout)
}
}
private fun restoreDefaultSettings() {
viewModelScope.launch {
repository.storeSettings(DFUSettings().copy(showWelcomeScreen = false))
}
analytics.logEvent(ResetSettingsEvent)
}
private fun onExternalMcuDfuSwitchClick() {
val currentValue = state.value.externalMcuDfu
val newSettings = state.value.copy(externalMcuDfu = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ExternalMCUSettingsEvent(newSettings.externalMcuDfu))
}
private fun onKeepBondSwitchClick() {
val currentValue = state.value.keepBondInformation
val newSettings = state.value.copy(keepBondInformation = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(KeepBondSettingsEvent(newSettings.keepBondInformation))
}
private fun onPacketsReceiptNotificationSwitchClick() {
val currentValue = state.value.packetsReceiptNotification
val newSettings = state.value.copy(packetsReceiptNotification = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(PacketsReceiptNotificationSettingsEvent(newSettings.packetsReceiptNotification))
}
private fun onDisableResumeSwitchClick() {
val currentValue = state.value.disableResume
val newSettings = state.value.copy(disableResume = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(DisableResumeSettingsEvent(newSettings.disableResume))
}
private fun onForceScanningAddressesSwitchClick() {
val currentValue = state.value.forceScanningInLegacyDfu
val newSettings = state.value.copy(forceScanningInLegacyDfu = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ForceScanningSettingsEvent(newSettings.forceScanningInLegacyDfu))
}
private fun onNumberOfPocketsChange(numberOfPockets: Int) {
val newSettings = state.value.copy(numberOfPackets = numberOfPockets)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(NumberOfPacketsSettingsEvent(newSettings.numberOfPackets))
}
private fun onPrepareDataObjectDelayChange(delay: Int) {
val newSettings = state.value.copy(prepareDataObjectDelay = delay)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(PrepareDataObjectDelaySettingsEvent(newSettings.prepareDataObjectDelay))
}
private fun onRebootTimeChange(rebootTime: Int) {
val newSettings = state.value.copy(rebootTime = rebootTime)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(RebootTimeSettingsEvent(newSettings.rebootTime))
}
private fun onScanTimeoutChange(scanTimeout: Int) {
val newSettings = state.value.copy(scanTimeout = scanTimeout)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ScanTimeoutSettingsEvent(newSettings.scanTimeout))
}
}
| profile_dfu/src/main/java/no/nordicsemi/android/dfu/profile/settings/viewmodel/SettingsViewModel.kt | 770813256 |
// IS_APPLICABLE: false
@Suppress("UNSUPPORTED_FEATURE")
expect class Foo()<caret> | plugins/kotlin/idea/tests/testData/intentions/removeEmptyPrimaryConstructor/expectClassPrimaryConstructor.kt | 29878062 |
/*
* 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.java.navigation
import com.intellij.ide.util.gotoByName.GotoSymbolModel2
import com.intellij.psi.PsiJavaFile
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class ModuleNavigationTest : LightJavaCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = JAVA_9
fun testNavigation() {
val file = myFixture.configureByText("module-info.java", "module my.mod.name { }")
(file as PsiJavaFile).moduleDeclaration!!.navigate(true)
assertThat(myFixture.editor.caretModel.offset).isEqualTo(file.text.indexOf("my.mod.name"))
}
fun testGoToSymbol() {
val file = myFixture.configureByText("module-info.java", "module my.mod.name { }")
val items = GotoSymbolModel2(myFixture.project, myFixture.testRootDisposable).getElementsByName("my.mod.name", false, "my.mod")
assertThat(items).containsExactly((file as PsiJavaFile).moduleDeclaration!!)
}
} | java/java-tests/testSrc/com/intellij/java/navigation/ModuleNavigationTest.kt | 913647532 |
package org.thoughtcrime.securesms.stories.viewer
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import org.thoughtcrime.securesms.PassphraseRequiredActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.voice.VoiceNoteMediaController
import org.thoughtcrime.securesms.components.voice.VoiceNoteMediaControllerOwner
import org.thoughtcrime.securesms.stories.StoryViewerArgs
class StoryViewerActivity : PassphraseRequiredActivity(), VoiceNoteMediaControllerOwner {
override lateinit var voiceNoteMediaController: VoiceNoteMediaController
override fun attachBaseContext(newBase: Context) {
delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
super.attachBaseContext(newBase)
}
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
supportPostponeEnterTransition()
super.onCreate(savedInstanceState, ready)
setContentView(R.layout.fragment_container)
voiceNoteMediaController = VoiceNoteMediaController(this)
if (savedInstanceState == null) {
replaceStoryViewerFragment()
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
replaceStoryViewerFragment()
}
override fun onEnterAnimationComplete() {
if (Build.VERSION.SDK_INT >= 21) {
window.transitionBackgroundFadeDuration = 100
}
}
private fun replaceStoryViewerFragment() {
supportFragmentManager.beginTransaction()
.replace(
R.id.fragment_container,
StoryViewerFragment.create(intent.getParcelableExtra(ARGS)!!)
)
.commit()
}
companion object {
private const val ARGS = "story.viewer.args"
@JvmStatic
fun createIntent(
context: Context,
storyViewerArgs: StoryViewerArgs
): Intent {
return Intent(context, StoryViewerActivity::class.java).putExtra(ARGS, storyViewerArgs)
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryViewerActivity.kt | 1024592701 |
package org.thoughtcrime.securesms.badges.gifts.viewgift.received
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.DimensionUnit
import org.signal.core.util.logging.Log
import org.signal.libsignal.zkgroup.InvalidInputException
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.BadgeRepository
import org.thoughtcrime.securesms.badges.gifts.ExpiredGiftSheetConfiguration.forExpiredGiftBadge
import org.thoughtcrime.securesms.badges.gifts.viewgift.ViewGiftRepository
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.badges.models.BadgeDisplay112
import org.thoughtcrime.securesms.badges.models.BadgeDisplay160
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsBottomSheetFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationError
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorDialogs
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorSource
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.components.settings.models.IndeterminateLoadingCircle
import org.thoughtcrime.securesms.components.settings.models.OutlinedSwitch
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
import java.util.concurrent.TimeUnit
/**
* Handles all interactions for received gift badges.
*/
class ViewReceivedGiftBottomSheet : DSLSettingsBottomSheetFragment() {
companion object {
private val TAG = Log.tag(ViewReceivedGiftBottomSheet::class.java)
private const val ARG_GIFT_BADGE = "arg.gift.badge"
private const val ARG_SENT_FROM = "arg.sent.from"
private const val ARG_MESSAGE_ID = "arg.message.id"
@JvmField
val REQUEST_KEY: String = TAG
const val RESULT_NOT_NOW = "result.not.now"
@JvmStatic
fun show(fragmentManager: FragmentManager, messageRecord: MmsMessageRecord) {
ViewReceivedGiftBottomSheet().apply {
arguments = Bundle().apply {
putParcelable(ARG_SENT_FROM, messageRecord.recipient.id)
putByteArray(ARG_GIFT_BADGE, messageRecord.giftBadge!!.toByteArray())
putLong(ARG_MESSAGE_ID, messageRecord.id)
}
show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
private val lifecycleDisposable = LifecycleDisposable()
private val sentFrom: RecipientId
get() = requireArguments().getParcelable(ARG_SENT_FROM)!!
private val messageId: Long
get() = requireArguments().getLong(ARG_MESSAGE_ID)
private val viewModel: ViewReceivedGiftViewModel by viewModels(
factoryProducer = { ViewReceivedGiftViewModel.Factory(sentFrom, messageId, ViewGiftRepository(), BadgeRepository(requireContext())) }
)
private var errorDialog: DialogInterface? = null
private lateinit var progressDialog: AlertDialog
override fun bindAdapter(adapter: DSLSettingsAdapter) {
BadgeDisplay112.register(adapter)
OutlinedSwitch.register(adapter)
BadgeDisplay160.register(adapter)
IndeterminateLoadingCircle.register(adapter)
progressDialog = MaterialAlertDialogBuilder(requireContext())
.setView(R.layout.redeeming_gift_dialog)
.setCancelable(false)
.create()
lifecycleDisposable.bindTo(viewLifecycleOwner)
lifecycleDisposable += DonationError
.getErrorsForSource(DonationErrorSource.GIFT_REDEMPTION)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { donationError ->
onRedemptionError(donationError)
}
lifecycleDisposable += viewModel.state.observeOn(AndroidSchedulers.mainThread()).subscribe { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
override fun onDestroy() {
super.onDestroy()
progressDialog.hide()
}
private fun onRedemptionError(throwable: Throwable?) {
Log.w(TAG, "onRedemptionError", throwable, true)
if (errorDialog != null) {
Log.i(TAG, "Already displaying an error dialog. Skipping.")
return
}
errorDialog = DonationErrorDialogs.show(
requireContext(), throwable,
object : DonationErrorDialogs.DialogCallback() {
override fun onDialogDismissed() {
findNavController().popBackStack()
}
}
)
}
private fun getConfiguration(state: ViewReceivedGiftState): DSLConfiguration {
return configure {
if (state.giftBadge == null) {
customPref(IndeterminateLoadingCircle)
} else if (isGiftBadgeExpired(state.giftBadge)) {
forExpiredGiftBadge(
giftBadge = state.giftBadge,
onMakeAMonthlyDonation = {
requireActivity().startActivity(AppSettingsActivity.subscriptions(requireContext()))
requireActivity().finish()
},
onNotNow = {
dismissAllowingStateLoss()
}
)
} else {
if (state.giftBadge.redemptionState == GiftBadge.RedemptionState.STARTED) {
progressDialog.show()
} else {
progressDialog.hide()
}
if (state.recipient != null && !isGiftBadgeRedeemed(state.giftBadge)) {
noPadTextPref(
title = DSLSettingsText.from(
charSequence = requireContext().getString(R.string.ViewReceivedGiftBottomSheet__s_sent_you_a_gift, state.recipient.getShortDisplayName(requireContext())),
DSLSettingsText.CenterModifier, DSLSettingsText.Title2BoldModifier
)
)
space(DimensionUnit.DP.toPixels(12f).toInt())
presentSubheading(state.recipient)
space(DimensionUnit.DP.toPixels(37f).toInt())
}
if (state.badge != null && state.controlState != null) {
presentForUnexpiredGiftBadge(state, state.giftBadge, state.controlState, state.badge)
space(DimensionUnit.DP.toPixels(16f).toInt())
}
}
}
}
private fun DSLConfiguration.presentSubheading(recipient: Recipient) {
noPadTextPref(
title = DSLSettingsText.from(
charSequence = requireContext().getString(R.string.ViewReceivedGiftBottomSheet__youve_received_a_gift_badge, recipient.getDisplayName(requireContext())),
DSLSettingsText.CenterModifier
)
)
}
private fun DSLConfiguration.presentForUnexpiredGiftBadge(
state: ViewReceivedGiftState,
giftBadge: GiftBadge,
controlState: ViewReceivedGiftState.ControlState,
badge: Badge
) {
when (giftBadge.redemptionState) {
GiftBadge.RedemptionState.REDEEMED -> {
customPref(
BadgeDisplay160.Model(
badge = badge
)
)
state.recipient?.run {
presentSubheading(this)
}
}
else -> {
customPref(
BadgeDisplay112.Model(
badge = badge
)
)
customPref(
OutlinedSwitch.Model(
text = DSLSettingsText.from(
when (controlState) {
ViewReceivedGiftState.ControlState.DISPLAY -> R.string.SubscribeThanksForYourSupportBottomSheetDialogFragment__display_on_profile
ViewReceivedGiftState.ControlState.FEATURE -> R.string.SubscribeThanksForYourSupportBottomSheetDialogFragment__make_featured_badge
}
),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
isChecked = state.getControlChecked(),
onClick = {
viewModel.setChecked(!it.isChecked)
}
)
)
if (state.hasOtherBadges && state.displayingOtherBadges) {
noPadTextPref(DSLSettingsText.from(R.string.ThanksForYourSupportBottomSheetFragment__when_you_have_more))
}
space(DimensionUnit.DP.toPixels(36f).toInt())
primaryButton(
text = DSLSettingsText.from(R.string.ViewReceivedGiftSheet__redeem),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
onClick = {
lifecycleDisposable += viewModel.redeem().subscribeBy(
onComplete = {
dismissAllowingStateLoss()
},
onError = {
onRedemptionError(it)
}
)
}
)
secondaryButtonNoOutline(
text = DSLSettingsText.from(R.string.ViewReceivedGiftSheet__not_now),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
onClick = {
setFragmentResult(
REQUEST_KEY,
Bundle().apply {
putBoolean(RESULT_NOT_NOW, true)
}
)
dismissAllowingStateLoss()
}
)
}
}
}
private fun isGiftBadgeRedeemed(giftBadge: GiftBadge): Boolean {
return giftBadge.redemptionState == GiftBadge.RedemptionState.REDEEMED
}
private fun isGiftBadgeExpired(giftBadge: GiftBadge): Boolean {
return try {
val receiptCredentialPresentation = ReceiptCredentialPresentation(giftBadge.redemptionToken.toByteArray())
receiptCredentialPresentation.receiptExpirationTime <= TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
} catch (e: InvalidInputException) {
Log.w(TAG, "Failed to check expiration of given badge.", e)
true
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/badges/gifts/viewgift/received/ViewReceivedGiftBottomSheet.kt | 3323892292 |
package org.thoughtcrime.securesms.badges.gifts.viewgift.sent
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.gifts.viewgift.ViewGiftRepository
import org.thoughtcrime.securesms.badges.models.BadgeDisplay112
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsBottomSheetFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
/**
* Handles all interactions for received gift badges.
*/
class ViewSentGiftBottomSheet : DSLSettingsBottomSheetFragment() {
companion object {
private const val ARG_GIFT_BADGE = "arg.gift.badge"
private const val ARG_SENT_TO = "arg.sent.to"
@JvmStatic
fun show(fragmentManager: FragmentManager, messageRecord: MmsMessageRecord) {
ViewSentGiftBottomSheet().apply {
arguments = Bundle().apply {
putParcelable(ARG_SENT_TO, messageRecord.recipient.id)
putByteArray(ARG_GIFT_BADGE, messageRecord.giftBadge!!.toByteArray())
}
show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
private val sentTo: RecipientId
get() = requireArguments().getParcelable(ARG_SENT_TO)!!
private val giftBadge: GiftBadge
get() = GiftBadge.parseFrom(requireArguments().getByteArray(ARG_GIFT_BADGE))
private val lifecycleDisposable = LifecycleDisposable()
private val viewModel: ViewSentGiftViewModel by viewModels(
factoryProducer = { ViewSentGiftViewModel.Factory(sentTo, giftBadge, ViewGiftRepository()) }
)
override fun bindAdapter(adapter: DSLSettingsAdapter) {
BadgeDisplay112.register(adapter)
lifecycleDisposable.bindTo(viewLifecycleOwner)
lifecycleDisposable += viewModel.state.observeOn(AndroidSchedulers.mainThread()).subscribe { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
private fun getConfiguration(state: ViewSentGiftState): DSLConfiguration {
return configure {
noPadTextPref(
title = DSLSettingsText.from(
stringId = R.string.ViewSentGiftBottomSheet__thanks_for_your_support,
DSLSettingsText.CenterModifier, DSLSettingsText.Title2BoldModifier
)
)
space(DimensionUnit.DP.toPixels(8f).toInt())
if (state.recipient != null) {
noPadTextPref(
title = DSLSettingsText.from(
charSequence = getString(R.string.ViewSentGiftBottomSheet__youve_gifted_a_badge, state.recipient.getDisplayName(requireContext())),
DSLSettingsText.CenterModifier
)
)
space(DimensionUnit.DP.toPixels(30f).toInt())
}
if (state.badge != null) {
customPref(
BadgeDisplay112.Model(
badge = state.badge
)
)
}
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/badges/gifts/viewgift/sent/ViewSentGiftBottomSheet.kt | 2522967149 |
package com.kondroid.sampleproject.model
import com.kondroid.sampleproject.request.RequestFactory
import com.kondroid.sampleproject.request.UserRequest
import io.reactivex.Observable
/**
* Created by kondo on 2017/10/02.
*/
class UsersModel {
private val request = RequestFactory.createRequest<UserRequest>()
fun createUser(params: UserRequest.CreateParams): Observable<UserRequest.CreateResult> {
return request.create(params)
}
} | app/src/main/java/com/kondroid/sampleproject/model/UsersModel.kt | 409018946 |
package org.thoughtcrime.securesms.stories.viewer.reply.direct
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.livedata.Store
class StoryDirectReplyViewModel(
private val storyId: Long,
private val groupDirectReplyRecipientId: RecipientId?,
private val repository: StoryDirectReplyRepository
) : ViewModel() {
private val store = Store(StoryDirectReplyState())
private val disposables = CompositeDisposable()
val state: LiveData<StoryDirectReplyState> = store.stateLiveData
init {
if (groupDirectReplyRecipientId != null) {
store.update(Recipient.live(groupDirectReplyRecipientId).liveDataResolved) { recipient, state ->
state.copy(groupDirectReplyRecipient = recipient)
}
}
disposables += repository.getStoryPost(storyId).subscribe { record ->
store.update { it.copy(storyRecord = record) }
}
}
fun sendReply(charSequence: CharSequence): Completable {
return repository.send(storyId, groupDirectReplyRecipientId, charSequence, false)
}
fun sendReaction(emoji: CharSequence): Completable {
return repository.send(storyId, groupDirectReplyRecipientId, emoji, true)
}
override fun onCleared() {
super.onCleared()
disposables.clear()
}
class Factory(
private val storyId: Long,
private val groupDirectReplyRecipientId: RecipientId?,
private val repository: StoryDirectReplyRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(
StoryDirectReplyViewModel(storyId, groupDirectReplyRecipientId, repository)
) as T
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/direct/StoryDirectReplyViewModel.kt | 4025970074 |
package com.beust.kobalt
import java.io.File
abstract public class JavaInfo {
public var javaExecutable: File? = null
get() = findExecutable("java")
public var javacExecutable: File? = null
get() = findExecutable("javac")
public var javadocExecutable: File? = null
get() = findExecutable("javadoc")
abstract public var javaHome: File?
abstract public var runtimeJar: File?
abstract public var toolsJar: File?
abstract public fun findExecutable(command: String) : File
companion object {
fun create(javaBase: File?): Jvm {
val vendor = System.getProperty("java.vm.vendor")
if (vendor.toLowerCase().startsWith("apple inc.")) {
return AppleJvm(OperatingSystem.Companion.current(), javaBase!!)
}
if (vendor.toLowerCase().startsWith("ibm corporation")) {
return IbmJvm(OperatingSystem.Companion.current(), javaBase!!)
}
return Jvm(OperatingSystem.Companion.current(), javaBase)
}
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/JavaInfo.kt | 228792861 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util.collections
internal const val INITIAL_CAPACITY = 32
/**
* Ktor concurrent map implementation. Please do not use it.
*/
public expect class ConcurrentMap<Key, Value>(
initialCapacity: Int = INITIAL_CAPACITY
) : MutableMap<Key, Value> {
/**
* Computes [block] and inserts result in map. The [block] will be evaluated at most once.
*/
public fun computeIfAbsent(key: Key, block: () -> Value): Value
/**
* Removes [key] from map if it is mapped to [value].
*/
public fun remove(key: Key, value: Value): Boolean
}
| ktor-utils/common/src/io/ktor/util/collections/ConcurrentMap.kt | 3081677508 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty.cio
import io.ktor.http.*
import io.ktor.server.netty.*
import io.ktor.server.netty.http1.*
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import io.netty.channel.*
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http2.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import java.io.*
import kotlin.coroutines.*
private const val UNFLUSHED_LIMIT = 65536
/**
* Contains methods for handling http request with Netty
*/
internal class NettyHttpResponsePipeline constructor(
private val context: ChannelHandlerContext,
private val httpHandlerState: NettyHttpHandlerState,
override val coroutineContext: CoroutineContext
) : CoroutineScope {
/**
* True if there is unflushed written data in channel
*/
private val isDataNotFlushed: AtomicBoolean = atomic(false)
/**
* Represents promise which is marked as success when the last read request is handled.
* Marked as fail when last read request is failed.
* Default value is success on purpose to start first request handle
*/
private var previousCallHandled: ChannelPromise = context.newPromise().also {
it.setSuccess()
}
/** Flush if all is true:
* - there is some unflushed data
* - nothing to read from the channel
* - there are no active requests
*/
internal fun flushIfNeeded() {
if (
isDataNotFlushed.value &&
httpHandlerState.isChannelReadCompleted.value &&
httpHandlerState.activeRequests.value == 0L
) {
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
}
}
internal fun processResponse(call: NettyApplicationCall) {
call.previousCallFinished = previousCallHandled
call.finishedEvent = context.newPromise()
previousCallHandled = call.finishedEvent
processElement(call)
}
private fun processElement(call: NettyApplicationCall) = setOnResponseReadyHandler(call) {
try {
handleRequestMessage(call)
} catch (actualException: Throwable) {
respondWithFailure(call, actualException)
} finally {
call.responseWriteJob.cancel()
}
}
/**
* Process [call] with [block] when the response is ready and previous call is successfully processed.
* [call] won't be processed with [block] if previous call is failed.
*/
private fun setOnResponseReadyHandler(call: NettyApplicationCall, block: () -> Unit) {
call.response.responseReady.addListener responseFlag@{ responseFlagResult ->
call.previousCallFinished.addListener waitPreviousCall@{ previousCallResult ->
if (!previousCallResult.isSuccess) {
respondWithFailure(call, previousCallResult.cause())
return@waitPreviousCall
}
if (!responseFlagResult.isSuccess) {
respondWithFailure(call, responseFlagResult.cause())
return@waitPreviousCall
}
block.invoke()
}
}
}
private fun respondWithFailure(call: NettyApplicationCall, actualException: Throwable) {
val t = when {
actualException is IOException && actualException !is ChannelIOException ->
ChannelWriteException(exception = actualException)
else -> actualException
}
call.response.responseChannel.cancel(t)
call.responseWriteJob.cancel()
call.response.cancel()
call.dispose()
call.finishedEvent.setFailure(t)
}
private fun respondWithUpgrade(call: NettyApplicationCall, responseMessage: Any): ChannelFuture {
val future = context.write(responseMessage)
call.upgrade(context)
call.isByteBufferContent = true
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
return future
}
/**
* Writes the [lastMessage] to the channel, schedules flush and close the channel if needed
*/
private fun handleLastResponseMessage(
call: NettyApplicationCall,
lastMessage: Any?,
lastFuture: ChannelFuture
) {
val prepareForClose = call.isContextCloseRequired() &&
(!call.request.keepAlive || call.response.isUpgradeResponse())
val lastMessageFuture = if (lastMessage != null) {
val future = context.write(lastMessage)
isDataNotFlushed.compareAndSet(expect = false, update = true)
future
} else {
null
}
httpHandlerState.onLastResponseMessage(context)
call.finishedEvent.setSuccess()
lastMessageFuture?.addListener {
if (prepareForClose) {
close(lastFuture)
return@addListener
}
}
if (prepareForClose) {
close(lastFuture)
return
}
scheduleFlush()
}
fun close(lastFuture: ChannelFuture) {
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
lastFuture.addListener {
context.close()
}
}
private fun scheduleFlush() {
context.executor().execute {
flushIfNeeded()
}
}
/**
* Gets the request message and decides how it should be handled
*/
private fun handleRequestMessage(call: NettyApplicationCall) {
val responseMessage = call.response.responseMessage
val response = call.response
val requestMessageFuture = if (response.isUpgradeResponse()) {
respondWithUpgrade(call, responseMessage)
} else {
respondWithHeader(responseMessage)
}
if (responseMessage is FullHttpResponse) {
return handleLastResponseMessage(call, null, requestMessageFuture)
} else if (responseMessage is Http2HeadersFrame && responseMessage.isEndStream) {
return handleLastResponseMessage(call, null, requestMessageFuture)
}
val responseChannel = response.responseChannel
val bodySize = when {
responseChannel === ByteReadChannel.Empty -> 0
responseMessage is HttpResponse -> responseMessage.headers().getInt("Content-Length", -1)
responseMessage is Http2HeadersFrame -> responseMessage.headers().getInt("content-length", -1)
else -> -1
}
launch(context.executor().asCoroutineDispatcher(), start = CoroutineStart.UNDISPATCHED) {
respondWithBodyAndTrailerMessage(
call,
response,
bodySize,
requestMessageFuture
)
}
}
/**
* Writes response header to the channel and makes a flush
* if client is waiting for the response header
*/
private fun respondWithHeader(responseMessage: Any): ChannelFuture {
return if (isHeaderFlushNeeded()) {
val future = context.writeAndFlush(responseMessage)
isDataNotFlushed.compareAndSet(expect = true, update = false)
future
} else {
val future = context.write(responseMessage)
isDataNotFlushed.compareAndSet(expect = false, update = true)
future
}
}
/**
* True if client is waiting for response header, false otherwise
*/
private fun isHeaderFlushNeeded(): Boolean {
val activeRequestsValue = httpHandlerState.activeRequests.value
return httpHandlerState.isChannelReadCompleted.value &&
!httpHandlerState.isCurrentRequestFullyRead.value &&
activeRequestsValue == 1L
}
/**
* Writes response body of size [bodySize] and trailer message to the channel and makes flush if needed
*/
private suspend fun respondWithBodyAndTrailerMessage(
call: NettyApplicationCall,
response: NettyApplicationResponse,
bodySize: Int,
requestMessageFuture: ChannelFuture
) {
try {
when (bodySize) {
0 -> respondWithEmptyBody(call, requestMessageFuture)
in 1..65536 -> respondWithSmallBody(call, response, bodySize)
-1 -> respondBodyWithFlushOnLimitOrEmptyChannel(call, response, requestMessageFuture)
else -> respondBodyWithFlushOnLimit(call, response, requestMessageFuture)
}
} catch (actualException: Throwable) {
respondWithFailure(call, actualException)
}
}
/**
* Writes trailer message to the channel and makes flush if needed when response body is empty.
*/
private fun respondWithEmptyBody(call: NettyApplicationCall, lastFuture: ChannelFuture) {
return handleLastResponseMessage(call, call.prepareEndOfStreamMessage(false), lastFuture)
}
/**
* Writes body and trailer message to the channel if response body size is up to 65536 bytes.
* Makes flush if needed.
*/
private suspend fun respondWithSmallBody(
call: NettyApplicationCall,
response: NettyApplicationResponse,
size: Int
) {
val buffer = context.alloc().buffer(size)
val channel = response.responseChannel
val start = buffer.writerIndex()
channel.readFully(buffer.nioBuffer(start, buffer.writableBytes()))
buffer.writerIndex(start + size)
val future = context.write(call.prepareMessage(buffer, true))
isDataNotFlushed.compareAndSet(expect = false, update = true)
val lastMessage = response.prepareTrailerMessage() ?: call.prepareEndOfStreamMessage(true)
handleLastResponseMessage(call, lastMessage, future)
}
/**
* Writes body and trailer message to the channel if body size is more than 65536 bytes.
* Makes flush only when limit of written bytes is reached.
*/
private suspend fun respondBodyWithFlushOnLimit(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture
) = respondWithBigBody(call, response, requestMessageFuture) { _, unflushedBytes ->
unflushedBytes >= UNFLUSHED_LIMIT
}
/**
* Writes body and trailer message to the channel if body size is unknown.
* Makes flush when there is nothing to read from the response channel or
* limit of written bytes is reached.
*/
private suspend fun respondBodyWithFlushOnLimitOrEmptyChannel(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture
) = respondWithBigBody(call, response, requestMessageFuture) { channel, unflushedBytes ->
unflushedBytes >= UNFLUSHED_LIMIT || channel.availableForRead == 0
}
private suspend fun respondWithBigBody(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture,
shouldFlush: (channel: ByteReadChannel, unflushedBytes: Int) -> Boolean
) {
val channel = response.responseChannel
var unflushedBytes = 0
var lastFuture: ChannelFuture = requestMessageFuture
@Suppress("DEPRECATION")
channel.lookAheadSuspend {
while (true) {
val buffer = request(0, 1)
if (buffer == null) {
if (!awaitAtLeast(1)) break
continue
}
val rc = buffer.remaining()
val buf = context.alloc().buffer(rc)
val idx = buf.writerIndex()
buf.setBytes(idx, buffer)
buf.writerIndex(idx + rc)
consumed(rc)
unflushedBytes += rc
val message = call.prepareMessage(buf, false)
if (shouldFlush.invoke(channel, unflushedBytes)) {
context.read()
val future = context.writeAndFlush(message)
isDataNotFlushed.compareAndSet(expect = true, update = false)
lastFuture = future
future.suspendAwait()
unflushedBytes = 0
} else {
lastFuture = context.write(message)
isDataNotFlushed.compareAndSet(expect = false, update = true)
}
}
}
val lastMessage = response.prepareTrailerMessage() ?: call.prepareEndOfStreamMessage(false)
handleLastResponseMessage(call, lastMessage, lastFuture)
}
}
private fun NettyApplicationResponse.isUpgradeResponse() =
status()?.value == HttpStatusCode.SwitchingProtocols.value
public class NettyResponsePipelineException(message: String) : Exception(message)
| ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyHttpResponsePipeline.kt | 4178301885 |
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.orca.pipelinetemplate.v1schema.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.orca.pipelinetemplate.handler.Handler
import com.netflix.spinnaker.orca.pipelinetemplate.handler.HandlerChain
import com.netflix.spinnaker.orca.pipelinetemplate.handler.PipelineTemplateContext
import com.netflix.spinnaker.orca.pipelinetemplate.loader.TemplateLoader
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.TemplateMerge
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.PipelineTemplate
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.TemplateConfiguration
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.DefaultRenderContext
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderContext
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderUtil
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.Renderer
import java.util.stream.Collectors
class V1TemplateLoaderHandler(
private val templateLoader: TemplateLoader,
private val renderer: Renderer,
private val objectMapper: ObjectMapper
) : Handler {
override fun handle(chain: HandlerChain, context: PipelineTemplateContext) {
val config = objectMapper.convertValue(context.getRequest().config, TemplateConfiguration::class.java)
// Allow template inlining to perform plans without publishing the template
if (context.getRequest().plan && context.getRequest().template != null) {
val template = objectMapper.convertValue(context.getRequest().template, PipelineTemplate::class.java)
val templates = templateLoader.load(template)
context.setSchemaContext(V1PipelineTemplateContext(config, TemplateMerge.merge(templates)))
return
}
val trigger = context.getRequest().trigger as MutableMap<String, Any>?
setTemplateSourceWithJinja(config, trigger)
// If a template source isn't provided by the configuration, we're assuming that the configuration is fully-formed.
val template: PipelineTemplate
if (config.pipeline.template == null) {
template = PipelineTemplate().apply {
variables = config.pipeline.variables.entries.stream()
.map { PipelineTemplate.Variable().apply {
name = it.key
defaultValue = it.value
}}
.collect(Collectors.toList())
}
} else {
val templates = templateLoader.load(config.pipeline.template)
template = TemplateMerge.merge(templates)
}
// ensure that any expressions contained with template variables are rendered
val renderContext = RenderUtil.createDefaultRenderContext(template, config, trigger)
renderTemplateVariables(renderContext, template)
context.setSchemaContext(V1PipelineTemplateContext(
config,
template
))
}
private fun renderTemplateVariables(renderContext: RenderContext, pipelineTemplate: PipelineTemplate) {
if (pipelineTemplate.variables == null) {
return
}
pipelineTemplate.variables.forEach { v ->
val value = v.defaultValue
if (v.isNullable() && value == null) {
renderContext.variables.putIfAbsent(v.name, v.defaultValue)
} else if (value != null && value is String) {
v.defaultValue = renderer.renderGraph(value.toString(), renderContext)
renderContext.variables.putIfAbsent(v.name, v.defaultValue)
}
}
}
private fun setTemplateSourceWithJinja(tc: TemplateConfiguration, trigger: MutableMap<String, Any>?) {
if (trigger == null || tc.pipeline.template == null) {
return
}
val context = DefaultRenderContext(tc.pipeline.application, null, trigger)
tc.pipeline.template.source = renderer.render(tc.pipeline.template.source, context)
}
}
| orca-pipelinetemplate/src/main/java/com/netflix/spinnaker/orca/pipelinetemplate/v1schema/handler/V1TemplateLoaderHandler.kt | 2506306919 |
package org.commcare.androidTests
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.commcare.annotations.BrowserstackTests
import org.commcare.dalvik.R
import org.commcare.utils.InstrumentationUtility
import org.commcare.utils.doesNotExist
import org.commcare.utils.isNotDisplayed
import org.commcare.utils.isDisplayed
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author $|-|!˅@M
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
@BrowserstackTests
class ClearButtonTest: BaseTest() {
companion object {
const val CCZ_NAME = "clear_button_test.ccz"
const val APP_NAME = "ClearButton"
}
@Before
fun setup() {
installApp(APP_NAME, CCZ_NAME)
InstrumentationUtility.login("test_user_1", "123")
}
@Test
fun testClearButton() {
// Open the only form in the app.
InstrumentationUtility.openForm(0, 0)
withText("Select One Widget tests").isDisplayed()
// Check clear button works with radio group.
// Make sure the clear button isn't displayed until we make a selection.
withText("Clear").isNotDisplayed()
onView(withText("First choice"))
.perform(click())
withText("Clear").isDisplayed()
onView(withText("First choice"))
.check(matches(isChecked()))
// Make sure clicking the clear button removes the selection and also hides the clear button.
onView(withText("Clear"))
.perform(click())
onView(withText("First choice"))
.check(matches(isNotChecked()))
withText("Clear").isNotDisplayed()
// Go to next question. and confirm clear button doesn't exists for checkboxes.
onView(withId(R.id.nav_btn_next))
.perform(click())
withText("Select Multi Widget.").isDisplayed()
withText("Clear").doesNotExist()
// Select a choice
onView(withText("First"))
.perform(click())
// Clear button is still not visible.
withText("Clear").doesNotExist()
// Even if we select all the choices, it isn't visible.
onView(withText("Second"))
.perform(click())
withText("Clear").doesNotExist()
// Check clear button with AutoAdvance Radio group.
onView(withId(R.id.nav_btn_next))
.perform(click())
withText("Select One Auto Advanced").isDisplayed()
withText("Clear").isNotDisplayed()
// selecting any choice automatically moves user to next question.
onView(withText("first"))
.perform(click())
withText("Select One Auto Advanced").doesNotExist()
withText("Should be automatically visible").isDisplayed()
// Go back and see that clear button is visible now.
onView(withId(R.id.nav_btn_prev))
.perform(click())
withText("Clear").isDisplayed()
onView(withText("first"))
.check(matches(isChecked()))
// Clicking the clear button should remove the selection and shoudn't auto advance to next question.
onView(withText("Clear"))
.perform(click())
onView(withText("first"))
.check(matches(isNotChecked()))
withText("Clear").isNotDisplayed()
withText("Select One Auto Advanced").isDisplayed()
// Again selection a choice should move to next question.
onView(withText("first"))
.perform(click())
withText("Select One Auto Advanced").doesNotExist()
withText("Should be automatically visible").isDisplayed()
// We should be able to submit the form.
onView(withId(R.id.nav_btn_finish))
.perform(click())
}
}
| app/instrumentation-tests/src/org/commcare/androidTests/ClearButtonTest.kt | 20538933 |
/*
* Copyright 2021 Michael Rozumyanskiy
*
* 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.michaelrocks.grip.mirrors
import io.michaelrocks.grip.commons.LazyList
import io.michaelrocks.grip.mirrors.signature.EmptyFieldSignatureMirror
import io.michaelrocks.grip.mirrors.signature.FieldSignatureMirror
import io.michaelrocks.grip.mirrors.signature.GenericDeclaration
import io.michaelrocks.grip.mirrors.signature.LazyFieldSignatureMirror
interface FieldMirror : Element<Type>, Annotated {
val signature: FieldSignatureMirror
val value: Any?
class Builder(
private val asmApi: Int,
private val enclosingGenericDeclaration: GenericDeclaration
) {
private var access = 0
private var name: String? = null
private var type: Type? = null
private var signature: String? = null
private var value: Any? = null
private val annotations = LazyList<AnnotationMirror>()
fun access(access: Int) = apply {
this.access = access
}
fun name(name: String) = apply {
this.name = name
this.type = getTypeByInternalName(name)
}
fun type(type: Type) = apply {
this.type = type
}
fun signature(signature: String?) = apply {
this.signature = signature
}
fun value(value: Any?) = apply {
this.value = value
}
fun addAnnotation(mirror: AnnotationMirror) = apply {
this.annotations += mirror
}
fun build(): FieldMirror = ImmutableFieldMirror(this)
private fun buildSignature(): FieldSignatureMirror =
signature?.let { LazyFieldSignatureMirror(asmApi, enclosingGenericDeclaration, it) }
?: EmptyFieldSignatureMirror(type!!)
private class ImmutableFieldMirror(builder: Builder) : FieldMirror {
override val access = builder.access
override val name = builder.name!!
override val type = builder.type!!
override val signature = builder.buildSignature()
override val value = builder.value
override val annotations = ImmutableAnnotationCollection(builder.annotations)
override fun toString() = "FieldMirror{name = $name, type = $type}"
}
}
}
| library/src/main/java/io/michaelrocks/grip/mirrors/FieldMirror.kt | 2267221473 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_pipeline_robustness = "EXTPipelineRobustness".nativeClassVK("EXT_pipeline_robustness", type = "device", postfix = "EXT") {
documentation =
"""
{@code VK_EXT_pipeline_robustness} allows users to request robustness on a per-pipeline stage basis.
As <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> and other robustness features may have an adverse effect on performance, this extension is designed to allow users to request robust behavior only where it may be needed.
<h5>VK_EXT_pipeline_robustness</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_pipeline_robustness}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>69</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Jarred Davies</li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2022-07-12</dd>
<dt><b>Interactions and External Dependencies</b></dt>
<dd><ul>
<li>Interacts with {@link EXTRobustness2 VK_EXT_robustness2}</li>
<li>Interacts with {@link EXTImageRobustness VK_EXT_image_robustness}</li>
<li>Interacts with {@link KHRRayTracingPipeline VK_KHR_ray_tracing_pipeline}</li>
</ul></dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Jarred Davies, Imagination Technologies</li>
<li>Alex Walters, Imagination Technologies</li>
<li>Piers Daniell, NVIDIA</li>
<li>Graeme Leese, Broadcom Corporation</li>
<li>Jeff Leger, Qualcomm Technologies, Inc.</li>
<li>Jason Ekstrand, Intel</li>
<li>Lionel Landwerlin, Intel</li>
<li>Shahbaz Youssefi, Google, Inc.</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_PIPELINE_ROBUSTNESS_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_PIPELINE_ROBUSTNESS_EXTENSION_NAME".."VK_EXT_pipeline_robustness"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO_EXT".."1000068000",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT".."1000068001",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_PROPERTIES_EXT".."1000068002"
)
EnumConstant(
"""
VkPipelineRobustnessBufferBehaviorEXT - Enum controlling the robustness of buffer accesses in a pipeline stage
<h5>Description</h5>
<ul>
<li>#PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT specifies that this pipeline stage follows the robustness behavior of the logical device that created this pipeline</li>
<li>#PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT specifies that buffer accesses by this pipeline stage to the relevant resource types <b>must</b> not be out of bounds</li>
<li>#PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT specifies that out of bounds accesses by this pipeline stage to the relevant resource types behave as if the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess">{@code robustBufferAccess}</a> feature is enabled</li>
<li>#PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT specifies that out of bounds accesses by this pipeline stage to the relevant resource types behave as if the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustBufferAccess2">{@code robustBufferAccess2}</a> feature is enabled</li>
</ul>
<h5>See Also</h5>
##VkPhysicalDevicePipelineRobustnessPropertiesEXT, ##VkPipelineRobustnessCreateInfoEXT
""",
"PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DEVICE_DEFAULT_EXT".."0",
"PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT".."1",
"PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT".."2",
"PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT".."3"
)
EnumConstant(
"""
VkPipelineRobustnessImageBehaviorEXT - Enum controlling the robustness of image accesses in a pipeline stage
<h5>Description</h5>
<ul>
<li>#PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT specifies that this pipeline stage follows the robustness behavior of the logical device that created this pipeline</li>
<li>#PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT specifies that image accesses by this pipeline stage to the relevant resource types <b>must</b> not be out of bounds</li>
<li>#PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT specifies that out of bounds accesses by this pipeline stage to images behave as if the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustImageAccess">{@code robustImageAccess}</a> feature is enabled</li>
<li>#PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT specifies that out of bounds accesses by this pipeline stage to images behave as if the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#features-robustImageAccess2">{@code robustImageAccess2}</a> feature is enabled</li>
</ul>
<h5>See Also</h5>
##VkPhysicalDevicePipelineRobustnessPropertiesEXT, ##VkPipelineRobustnessCreateInfoEXT
""",
"PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DEVICE_DEFAULT_EXT".."0",
"PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_DISABLED_EXT".."1",
"PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_EXT".."2",
"PIPELINE_ROBUSTNESS_IMAGE_BEHAVIOR_ROBUST_IMAGE_ACCESS_2_EXT".."3"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_pipeline_robustness.kt | 936281662 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.intents
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.PendingIntent.getActivity
import android.app.PendingIntent.getBroadcast
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import org.isoron.uhabits.activities.habits.list.ListHabitsActivity
import org.isoron.uhabits.activities.habits.show.ShowHabitActivity
import org.isoron.uhabits.core.AppScope
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.inject.AppContext
import org.isoron.uhabits.receivers.ReminderReceiver
import org.isoron.uhabits.receivers.WidgetReceiver
import javax.inject.Inject
@AppScope
class PendingIntentFactory
@Inject constructor(
@AppContext private val context: Context,
private val intentFactory: IntentFactory
) {
fun addCheckmark(habit: Habit, timestamp: Timestamp?): PendingIntent =
getBroadcast(
context,
1,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = WidgetReceiver.ACTION_ADD_REPETITION
if (timestamp != null) putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun dismissNotification(habit: Habit): PendingIntent =
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
action = WidgetReceiver.ACTION_DISMISS_REMINDER
data = Uri.parse(habit.uriString)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun removeRepetition(habit: Habit, timestamp: Timestamp?): PendingIntent =
getBroadcast(
context,
3,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_REMOVE_REPETITION
data = Uri.parse(habit.uriString)
if (timestamp != null) putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun showHabit(habit: Habit): PendingIntent =
androidx.core.app.TaskStackBuilder
.create(context)
.addNextIntentWithParentStack(
intentFactory.startShowHabitActivity(
context,
habit
)
)
.getPendingIntent(0, FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT)!!
fun showHabitTemplate(): PendingIntent {
return getActivity(
context,
0,
Intent(context, ShowHabitActivity::class.java),
getIntentTemplateFlags()
)
}
fun showHabitFillIn(habit: Habit) =
Intent().apply {
data = Uri.parse(habit.uriString)
}
fun showReminder(
habit: Habit,
reminderTime: Long?,
timestamp: Long
): PendingIntent =
getBroadcast(
context,
(habit.id!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ReminderReceiver::class.java).apply {
action = ReminderReceiver.ACTION_SHOW_REMINDER
data = Uri.parse(habit.uriString)
putExtra("timestamp", timestamp)
putExtra("reminderTime", reminderTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun snoozeNotification(habit: Habit): PendingIntent =
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = ReminderReceiver.ACTION_SNOOZE_REMINDER
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun toggleCheckmark(habit: Habit, timestamp: Long?): PendingIntent =
getBroadcast(
context,
2,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = WidgetReceiver.ACTION_TOGGLE_REPETITION
if (timestamp != null) putExtra("timestamp", timestamp)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun updateWidgets(): PendingIntent =
getBroadcast(
context,
0,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_UPDATE_WIDGETS_VALUE
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun showNumberPicker(habit: Habit, timestamp: Timestamp): PendingIntent? {
return getActivity(
context,
(habit.id!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ListHabitsActivity::class.java).apply {
action = ListHabitsActivity.ACTION_EDIT
putExtra("habit", habit.id)
putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
}
fun showNumberPickerTemplate(): PendingIntent {
return getActivity(
context,
1,
Intent(context, ListHabitsActivity::class.java).apply {
action = ListHabitsActivity.ACTION_EDIT
},
getIntentTemplateFlags()
)
}
fun showNumberPickerFillIn(habit: Habit, timestamp: Timestamp) = Intent().apply {
putExtra("habit", habit.id)
putExtra("timestamp", timestamp.unixTime)
}
private fun getIntentTemplateFlags(): Int {
var flags = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or FLAG_MUTABLE
}
return flags
}
fun toggleCheckmarkTemplate(): PendingIntent =
getBroadcast(
context,
2,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_TOGGLE_REPETITION
},
getIntentTemplateFlags()
)
fun toggleCheckmarkFillIn(habit: Habit, timestamp: Timestamp) = Intent().apply {
data = Uri.parse(habit.uriString)
putExtra("timestamp", timestamp.unixTime)
}
}
| uhabits-android/src/main/java/org/isoron/uhabits/intents/PendingIntentFactory.kt | 3256858980 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.event.internal
import com.google.common.truth.Truth.assertThat
import org.hisp.dhis.android.core.common.State
import org.hisp.dhis.android.core.event.EventStatus
import org.hisp.dhis.android.core.maintenance.D2Error
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestMetadataEnqueable
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(D2JunitRunner::class)
class EventEndpointCallMockIntegrationShould : BaseMockIntegrationTestMetadataEnqueable() {
@After
@Throws(D2Error::class)
fun tearDown() {
d2.wipeModule().wipeData()
}
@Test
@Throws(Exception::class)
fun download_number_of_events_according_to_page_default_query() {
enqueue("event/events_1.json")
d2.eventModule().eventDownloader().blockingDownload()
assertThat(d2.eventModule().events().blockingCount()).isEqualTo(1)
}
@Test
@Throws(Exception::class)
fun rollback_transaction_when_insert_a_event_with_wrong_foreign_key() {
enqueue("event/two_events_first_good_second_wrong_foreign_key.json")
d2.eventModule().eventDownloader().blockingDownload()
assertThat(d2.eventModule().events().blockingCount()).isEqualTo(0)
assertThat(d2.trackedEntityModule().trackedEntityDataValues().blockingCount())
.isEqualTo(0)
}
@Test
@Throws(Exception::class)
fun download_events_by_uid() {
enqueue("event/events_with_uids.json")
d2.eventModule().eventDownloader().byUid().`in`("wAiGPfJGMxt", "PpNGhvEYnXe").blockingDownload()
assertThat(d2.eventModule().events().blockingCount()).isEqualTo(2)
}
@Throws(Exception::class)
private fun checkOverwrite(state: State, finalStatus: EventStatus) {
enqueue("event/events_1.json")
d2.eventModule().eventDownloader().blockingDownload()
val events = d2.eventModule().events().blockingGet()
val event = events[0]
assertThat(event.uid()).isEqualTo("V1CerIi3sdL")
assertThat(events.size).isEqualTo(1)
EventStoreImpl.create(d2.databaseAdapter()).update(
event.toBuilder()
.syncState(state)
.aggregatedSyncState(state)
.status(EventStatus.SKIPPED).build()
)
enqueue("event/events_1.json")
d2.eventModule().eventDownloader().blockingDownload()
val event1 = d2.eventModule().events().one().blockingGet()
assertThat(event1.uid()).isEqualTo("V1CerIi3sdL")
assertThat(event1.status()).isEqualTo(finalStatus)
}
@Test
@Throws(Exception::class)
fun overwrite_when_state_sync() {
checkOverwrite(State.SYNCED, EventStatus.COMPLETED)
}
@Test
@Throws(Exception::class)
fun not_overwrite_when_state_to_post() {
checkOverwrite(State.TO_POST, EventStatus.SKIPPED)
}
@Test
@Throws(Exception::class)
fun not_overwrite_when_state_error() {
checkOverwrite(State.ERROR, EventStatus.SKIPPED)
}
@Test
@Throws(Exception::class)
fun not_overwrite_when_state_to_update() {
checkOverwrite(State.TO_UPDATE, EventStatus.SKIPPED)
}
private fun enqueue(url: String) {
dhis2MockServer.enqueueSystemInfoResponse()
dhis2MockServer.enqueueMockResponse(url)
}
}
| core/src/androidTest/java/org/hisp/dhis/android/core/event/internal/EventEndpointCallMockIntegrationShould.kt | 1833213432 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.parser.internal.expression.function
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor
import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItem
import org.hisp.dhis.antlr.AntlrParserUtils
import org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext
/**
* Function if
* <pre>
*
* In-memory Logic:
*
* arg0 returns
* ---- -------
* true arg1
* false arg2
* null null
*
* SQL logic (CASE WHEN arg0 THEN arg1 ELSE arg2 END):
*
* arg0 returns
* ---- -------
* true arg1
* false arg2
* null arg2
</pre> *
*
* @author Jim Grace
*/
internal class FunctionIf : ExpressionItem {
override fun evaluate(ctx: ExprContext, visitor: CommonExpressionVisitor): Any? {
val arg0 = visitor.castBooleanVisit(ctx.expr(0))
return when {
arg0 == null -> null
arg0 -> visitor.visit(ctx.expr(1))
else -> visitor.visit(ctx.expr(2))
}
}
override fun evaluateAllPaths(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
val arg0 = visitor.castBooleanVisit(ctx.expr(0))
val arg1 = visitor.visit(ctx.expr(1))
val arg2 = visitor.visit(ctx.expr(2))
if (arg1 != null) {
AntlrParserUtils.castClass(arg1.javaClass, arg2)
}
return when {
arg0 != null && arg0 -> arg1
else -> arg2
}
}
override fun getSql(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
return "CASE WHEN ${visitor.castStringVisit(ctx.expr(0))} " +
"THEN ${visitor.castStringVisit(ctx.expr(1))} " +
"ELSE ${visitor.castStringVisit(ctx.expr(2))} END"
}
}
| core/src/main/java/org/hisp/dhis/android/core/parser/internal/expression/function/FunctionIf.kt | 2461880721 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.common
import dagger.Reusable
import java.util.*
import javax.inject.Inject
import org.hisp.dhis.android.core.event.EventDataFilter
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.internal.CalendarProvider
import org.hisp.dhis.android.core.period.internal.ParentPeriodGenerator
@Reusable
internal class DateFilterPeriodHelper @Inject constructor(
private val calendarProvider: CalendarProvider,
private val parentPeriodGenerator: ParentPeriodGenerator
) {
companion object {
@JvmStatic
fun mergeDateFilterPeriods(baseFilter: DateFilterPeriod?, newFilter: DateFilterPeriod?): DateFilterPeriod? {
return when {
newFilter == null -> baseFilter
baseFilter == null -> newFilter
newFilter.period() != null -> newFilter
newFilter.startBuffer() != null || newFilter.endBuffer() != null -> {
val builder = baseFilter.toBuilder()
builder.period(null)
builder.startDate(null)
builder.endDate(null)
builder.type(DatePeriodType.RELATIVE)
newFilter.startBuffer()?.let { builder.startBuffer(it) }
newFilter.endBuffer()?.let { builder.endBuffer(it) }
builder.build()
}
newFilter.startDate() != null || newFilter.endDate() != null -> {
val builder = baseFilter.toBuilder()
builder.period(null)
builder.startBuffer(null)
builder.endBuffer(null)
builder.type(DatePeriodType.ABSOLUTE)
newFilter.startDate()?.let { builder.startDate(it) }
newFilter.endDate()?.let { builder.endDate(it) }
builder.build()
}
else -> null
}
}
@JvmStatic
fun mergeEventDataFilters(list: List<EventDataFilter>, item: EventDataFilter): List<EventDataFilter> {
return list + item
}
}
fun getStartDate(filter: DateFilterPeriod): Date? {
return when (filter.type()) {
DatePeriodType.RELATIVE ->
when {
filter.period() != null -> getPeriod(filter.period()!!)?.startDate()
filter.startBuffer() != null -> addDaysToCurrentDate(filter.startBuffer()!!)
else -> null
}
DatePeriodType.ABSOLUTE -> filter.startDate()
else -> null
}
}
fun getEndDate(filter: DateFilterPeriod): Date? {
return when (filter.type()) {
DatePeriodType.RELATIVE ->
when {
filter.period() != null -> getPeriod(filter.period()!!)?.endDate()
filter.endBuffer() != null -> addDaysToCurrentDate(filter.endBuffer()!!)
else -> null
}
DatePeriodType.ABSOLUTE -> filter.endDate()
else -> null
}
}
private fun getPeriod(period: RelativePeriod): Period? {
val periods = parentPeriodGenerator.generateRelativePeriods(period)
return if (periods.isNotEmpty()) {
Period.builder()
.startDate(periods.first().startDate())
.endDate(periods.last().endDate())
.build()
} else {
null
}
}
private fun addDaysToCurrentDate(days: Int): Date {
val calendar = calendarProvider.calendar.clone() as Calendar
calendar.add(Calendar.DATE, days)
return calendar.time
}
}
| core/src/main/java/org/hisp/dhis/android/core/common/DateFilterPeriodHelper.kt | 1033699542 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.commands
import org.isoron.uhabits.core.AppScope
import org.isoron.uhabits.core.tasks.Task
import org.isoron.uhabits.core.tasks.TaskRunner
import java.util.LinkedList
import javax.inject.Inject
@AppScope
open class CommandRunner
@Inject constructor(
private val taskRunner: TaskRunner,
) {
private val listeners: LinkedList<Listener> = LinkedList()
open fun run(command: Command) {
taskRunner.execute(
object : Task {
override fun doInBackground() {
command.run()
}
override fun onPostExecute() {
notifyListeners(command)
}
}
)
}
fun addListener(l: Listener) {
listeners.add(l)
}
fun notifyListeners(command: Command) {
for (l in listeners) l.onCommandFinished(command)
}
fun removeListener(l: Listener) {
listeners.remove(l)
}
interface Listener {
fun onCommandFinished(command: Command)
}
}
| uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/commands/CommandRunner.kt | 2006850538 |
// 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.openapi.ui
import com.intellij.openapi.util.Key
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import javax.swing.JComponent
/**
* Defines switcher component which can change visibility state of component
* in UI view, for example collapsible groups in Kotlin UI DSL.
* Use [UiSwitcher.append] to add a switcher to a component. At the same time component can belong to several UiSwitcher
*
* @see UIUtil#showComponent(Component)
*/
@ApiStatus.Experimental
interface UiSwitcher {
/**
* Returns false if the component assigned to this UiSwitcher cannot be shown
*/
fun show(): Boolean
companion object {
private val UI_SWITCHER = Key.create<UiSwitcher>("com.intellij.openapi.ui.UI_SWITCHER")
@JvmStatic
fun append(component: JComponent, uiSwitcher: UiSwitcher) {
val existingSwitcher = component.getUserData(UI_SWITCHER)
component.putUserData(UI_SWITCHER, if (existingSwitcher == null) uiSwitcher
else UnionUiSwitcher(
listOf(existingSwitcher, uiSwitcher)))
}
/**
* Tries to show the component in UI hierarchy:
* * Expands collapsable groups if the component is inside such groups
*/
@JvmStatic
fun show(component: Component) {
var c = component
while (!c.isShowing) {
if (c is JComponent) {
val uiSwitcher = c.getUserData(UI_SWITCHER)
if (uiSwitcher?.show() == false) {
return
}
}
c = c.parent
}
}
}
}
private class UnionUiSwitcher(private val uiSwitchers: List<UiSwitcher>) : UiSwitcher {
override fun show(): Boolean {
return uiSwitchers.all { it.show() }
}
}
| platform/platform-api/src/com/intellij/openapi/ui/UiSwitcher.kt | 2470221209 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.fe10.binding
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.fir.fe10.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class ToDescriptorBindingContextValueProviders(bindingContext: KtSymbolBasedBindingContext) {
private val context = bindingContext.context
private val declarationToDescriptorGetters = mutableListOf<(PsiElement) -> DeclarationDescriptor?>()
private inline fun <reified K : PsiElement, V : DeclarationDescriptor> KtSymbolBasedBindingContext.registerDeclarationToDescriptorByKey(
slice: ReadOnlySlice<K, V>,
crossinline getter: (K) -> V?
) {
declarationToDescriptorGetters.add {
if (it is K) getter(it) else null
}
registerGetterByKey(slice, { getter(it) })
}
init {
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CLASS, this::getClass)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.TYPE_PARAMETER, this::getTypeParameter)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.FUNCTION, this::getFunction)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CONSTRUCTOR, this::getConstructor)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.VARIABLE, this::getVariable)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, this::getPrimaryConstructorParameter)
bindingContext.registerGetterByKey(BindingContext.DECLARATION_TO_DESCRIPTOR, this::getDeclarationToDescriptor)
}
private inline fun <reified T : Any> PsiElement.getKtSymbolOfTypeOrNull(): T? =
this@ToDescriptorBindingContextValueProviders.context.withAnalysisSession {
[email protected]<KtDeclaration>()?.getSymbol().safeAs<T>()
}
private fun getClass(key: PsiElement): ClassDescriptor? {
val ktClassSymbol = key.getKtSymbolOfTypeOrNull<KtNamedClassOrObjectSymbol>() ?: return null
return KtSymbolBasedClassDescriptor(ktClassSymbol, context)
}
private fun getTypeParameter(key: KtTypeParameter): TypeParameterDescriptor {
val ktTypeParameterSymbol = context.withAnalysisSession { key.getTypeParameterSymbol() }
return KtSymbolBasedTypeParameterDescriptor(ktTypeParameterSymbol, context)
}
private fun getFunction(key: PsiElement): SimpleFunctionDescriptor? {
val ktFunctionLikeSymbol = key.getKtSymbolOfTypeOrNull<KtFunctionLikeSymbol>() ?: return null
return ktFunctionLikeSymbol.toDeclarationDescriptor(context) as? SimpleFunctionDescriptor
}
private fun getConstructor(key: PsiElement): ConstructorDescriptor? {
val ktConstructorSymbol = key.getKtSymbolOfTypeOrNull<KtConstructorSymbol>() ?: return null
val containerClass = context.withAnalysisSession { ktConstructorSymbol.getContainingSymbol() }
check(containerClass is KtNamedClassOrObjectSymbol) {
"Unexpected contained for Constructor symbol: $containerClass, ktConstructorSymbol = $ktConstructorSymbol"
}
return KtSymbolBasedConstructorDescriptor(ktConstructorSymbol, KtSymbolBasedClassDescriptor(containerClass, context))
}
private fun getVariable(key: PsiElement): VariableDescriptor? {
if (key !is KtVariableDeclaration) return null
if (key is KtProperty) {
val symbol = context.withAnalysisSession { key.getVariableSymbol() }
if (symbol !is KtPropertySymbol) context.implementationPlanned("Local property not supported: $symbol")
return KtSymbolBasedPropertyDescriptor(symbol, context)
} else {
context.implementationPostponed("Destruction declaration is not supported yet: $key")
}
}
private fun getPrimaryConstructorParameter(key: PsiElement): PropertyDescriptor? {
val parameter = key.safeAs<KtParameter>() ?: return null
val parameterSymbol = context.withAnalysisSession { parameter.getParameterSymbol() }
val propertySymbol = parameterSymbol.safeAs<KtValueParameterSymbol>()?.generatedPrimaryConstructorProperty ?: return null
return KtSymbolBasedPropertyDescriptor(propertySymbol, context)
}
private fun getDeclarationToDescriptor(key: PsiElement): DeclarationDescriptor? {
for (getter in declarationToDescriptorGetters) {
getter(key)?.let { return it }
}
return null
}
}
| plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/binding/ToDescriptorBindingContextValueProviders.kt | 1759377737 |
package androidx.recyclerview.widget
import androidx.recyclerview.widget.RecyclerView.LayoutManager
/**
* Why the class name? Because it guarantees zero naming conflicts!
*
* With this really long name, I recommend `import static *.*` !
*
* Created by jayson on 3/27/2016.
*/
@Suppress("all")
object com_mikepenz_fastadapter_extensions_scroll {
@JvmStatic fun postOnRecyclerView(layoutManager: LayoutManager, action: Runnable): Boolean {
if (layoutManager.mRecyclerView != null) {
layoutManager.mRecyclerView.post(action)
return true
}
return false
}
}
| fastadapter-extensions-scroll/src/main/java/androidx/recyclerview/widget/com_mikepenz_fastadapter_extensions_scroll.kt | 1757508331 |
class K1 : MyJavaClass() {
override fun coll(c: Collection<Any?>?) = Unit
}
class K2 : MyJavaClass() {
override fun coll(c: Collection<Any?>) = Unit
}
class K3 : MyJavaClass() {
override fun coll(c: MutableCollection<Any?>) = Unit
}
class K4 : MyJavaClass() {
override fun coll(c: MutableCollection<Any?>?) = Unit
}
| plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ChangeJavaMethodWithRawTypeBefore.1.kt | 3156612939 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.expectactual
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddActualFix(
actualClassOrObject: KtClassOrObject,
missedDeclarations: List<KtDeclaration>
) : KotlinQuickFixAction<KtClassOrObject>(actualClassOrObject) {
private val missedDeclarationPointers = missedDeclarations.map { it.createSmartPointer() }
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("fix.create.missing.actual.members")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val factory = KtPsiFactory(element)
val codeStyleManager = CodeStyleManager.getInstance(project)
fun PsiElement.clean() {
ShortenReferences.DEFAULT.process(codeStyleManager.reformat(this) as KtElement)
}
val module = element.module ?: return
val checker = TypeAccessibilityChecker.create(project, module)
val errors = linkedMapOf<KtDeclaration, KotlinTypeInaccessibleException>()
for (missedDeclaration in missedDeclarationPointers.mapNotNull { it.element }) {
val actualDeclaration = try {
when (missedDeclaration) {
is KtClassOrObject -> factory.generateClassOrObject(project, false, missedDeclaration, checker)
is KtFunction, is KtProperty -> missedDeclaration.toDescriptor()?.safeAs<CallableMemberDescriptor>()?.let {
generateCallable(project, false, missedDeclaration, it, element, checker = checker)
}
else -> null
} ?: continue
} catch (e: KotlinTypeInaccessibleException) {
errors += missedDeclaration to e
continue
}
if (actualDeclaration is KtPrimaryConstructor) {
if (element.primaryConstructor == null)
element.addAfter(actualDeclaration, element.nameIdentifier).clean()
} else {
element.addDeclaration(actualDeclaration).clean()
}
}
if (errors.isNotEmpty()) {
val message = errors.entries.joinToString(
separator = "\n",
prefix = KotlinBundle.message("fix.create.declaration.error.some.types.inaccessible") + "\n"
) { (declaration, error) ->
getExpressionShortText(declaration) + " -> " + error.message
}
showInaccessibleDeclarationError(element, message, editor)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val missedDeclarations = DiagnosticFactory.cast(diagnostic, Errors.NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS).b.mapNotNull {
DescriptorToSourceUtils.descriptorToDeclaration(it.first) as? KtDeclaration
}.ifEmpty { return null }
return (diagnostic.psiElement as? KtClassOrObject)?.let {
AddActualFix(it, missedDeclarations)
}
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/AddActualFix.kt | 4135608186 |
/*
* The MIT License
*
* Copyright 2015 tibo.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.pixplicity.cryptogram.stringsimilarity
import java.io.Serializable
/**
* @author Thibault Debatty
*/
interface StringDistance : Serializable {
fun distance(s1: String, s2: String): Double
} | app/src/test/java/com/pixplicity/cryptogram/stringsimilarity/StringDistance.kt | 3869124328 |
package com.packt.chapter2
import java.io.File
import java.math.BigDecimal
import java.time.LocalDate
import java.util.*
fun new() {
val file = File("/etc/nginx/nginx.conf")
val date = BigDecimal(100)
}
| Chapter07/src/main/kotlin/com/packt/chapter2/new.kt | 699677132 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.models.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import android.graphics.Bitmap
import android.os.Parcel
import android.os.Parcelable
import de.dreier.mytargets.shared.utils.readBitmap
import de.dreier.mytargets.shared.utils.writeBitmap
@Entity
data class Signature(
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
var name: String = "",
/** A bitmap of the signature or null if no signature has been set. */
@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
var bitmap: Bitmap? = null
) : Parcelable {
val isSigned: Boolean
get() = bitmap != null
fun getName(defaultName: String): String {
return if (name.isEmpty()) defaultName else name
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id)
dest.writeString(name)
dest.writeBitmap(bitmap)
}
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<Signature> {
override fun createFromParcel(source: Parcel): Signature {
val id = source.readLong()
val name = source.readString()!!
val bitmap = source.readBitmap()
return Signature(id, name, bitmap)
}
override fun newArray(size: Int) = arrayOfNulls<Signature>(size)
}
}
}
| shared/src/main/java/de/dreier/mytargets/shared/models/db/Signature.kt | 4132233600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.