path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/pr0gramm/app/Instant.kt | Zz9uk3 | 158,547,370 | true | {"Kotlin": 1116937, "Shell": 6640, "IDL": 3408, "Python": 1124, "Prolog": 737} | package com.pr0gramm.app
import android.os.Parcel
import android.os.Parcelable
import com.pr0gramm.app.parcel.Freezable
import com.pr0gramm.app.parcel.Unfreezable
import com.pr0gramm.app.parcel.creator
import com.pr0gramm.app.util.logger
import org.slf4j.Logger
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
class Instant(val millis: Long) : Comparable<Instant>, Freezable, Parcelable {
override fun freeze(sink: Freezable.Sink) {
sink.writeLong(millis)
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(millis)
}
fun plus(offsetInMillis: Long, unit: TimeUnit): Instant {
return Instant(millis + unit.toMillis(offsetInMillis))
}
fun minus(offsetInMillis: Long, unit: TimeUnit): Instant {
return Instant(millis - unit.toMillis(offsetInMillis))
}
operator fun plus(d: Duration): Instant {
return Instant(millis + d.millis)
}
operator fun minus(d: Duration): Instant {
return Instant(millis - d.millis)
}
fun isBefore(other: Instant): Boolean {
return millis < other.millis
}
fun isAfter(other: Instant): Boolean {
return millis > other.millis
}
val isAfterNow: Boolean
get() {
return millis > TimeFactory.currentTimeMillis()
}
val isBeforeNow: Boolean
get() {
return millis < TimeFactory.currentTimeMillis()
}
constructor(parcel: Parcel) : this(parcel.readLong())
override fun compareTo(other: Instant): Int {
return millis.compareTo(other.millis)
}
override fun hashCode(): Int {
return millis.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is Instant && other.millis == millis
}
fun toString(format: SimpleDateFormat): String {
return format.format(Date(millis))
}
companion object : Unfreezable<Instant> {
override fun unfreeze(source: Freezable.Source): Instant {
return Instant(source.readLong())
}
@JvmStatic
fun now(): Instant = Instant(TimeFactory.currentTimeMillis())
@JvmField
val CREATOR = creator { p -> Instant(p.readLong()) }
}
}
object TimeFactory {
private val logger: Logger = logger("TimeFactory")
private val buffer = androidx.collection.CircularArray<Long>(16)
private val deltaInMillis = AtomicLong(0)
fun updateServerTime(serverTime: Instant) {
synchronized(buffer) {
if (buffer.size() >= 16) {
buffer.popFirst()
}
val delta = serverTime.millis - System.currentTimeMillis()
logger.info("Storing time delta of {}ms", this.deltaInMillis)
buffer.addLast(delta)
// calculate average server/client delta
var sum = 0L
for (idx in 0 until buffer.size()) {
sum += buffer.get(idx)
}
this.deltaInMillis.set(sum / buffer.size())
}
Stats.get().time("server.time.delta", this.deltaInMillis.get())
}
fun currentTimeMillis(): Long = System.currentTimeMillis() + this.deltaInMillis.get()
}
| 0 | Kotlin | 0 | 0 | c173fa90bfef3266b80fece6fc67909cd90eaf0b | 3,285 | Pr0 | MIT License |
src/main/kotlin/de/sambalmueslie/openevent/core/model/NotificationTypeChangeRequest.kt | Black-Forrest-Development | 542,810,521 | false | {"Kotlin": 334759, "TypeScript": 179633, "HTML": 73007, "SCSS": 3950, "Batchfile": 202} | package de.sambalmueslie.openevent.core.model
import de.sambalmueslie.openevent.core.BusinessObjectChangeRequest
import io.micronaut.serde.annotation.Serdeable
@Serdeable
data class NotificationTypeChangeRequest(
val key: String,
val name: String,
val description: String
) : BusinessObjectChangeRequest
| 6 | Kotlin | 0 | 1 | 43cf66668db937150ae8f14078437c1e5a7287e2 | 318 | open-event | Apache License 2.0 |
felles/src/main/kotlin/no/nav/familie/kontrakter/felles/journalpost/Journalstatus.kt | navikt | 206,793,193 | false | null | package no.nav.familie.kontrakter.felles.journalpost
enum class Journalstatus {
MOTTATT,
JOURNALFOERT,
FERDIGSTILT,
EKSPEDERT,
UNDER_ARBEID,
FEILREGISTRERT,
UTGAAR,
AVBRUTT,
UKJENT_BRUKER,
RESERVERT,
OPPLASTING_DOKUMENT,
UKJENT
} | 6 | Kotlin | 0 | 2 | 7f218f3c15be62cd438c690c6d4a670afe73fd65 | 278 | familie-kontrakter | MIT License |
tasks-app-desktop/src/main/kotlin/mainApp.kt | opatry | 860,583,716 | false | {"Kotlin": 570616, "Shell": 7905, "HTML": 398, "Ruby": 196} | /*
* Copyright (c) 2024 Olivier Patry
*
* 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.
*/
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import net.opatry.tasks.app.di.authModule
import net.opatry.tasks.app.di.dataModule
import net.opatry.tasks.app.di.networkModule
import net.opatry.tasks.app.di.platformModule
import net.opatry.tasks.app.di.tasksAppModule
import net.opatry.tasks.app.ui.TaskListsViewModel
import net.opatry.tasks.app.ui.TasksApp
import net.opatry.tasks.app.ui.UserState
import net.opatry.tasks.app.ui.UserViewModel
import net.opatry.tasks.app.ui.screen.AuthorizationScreen
import net.opatry.tasks.app.ui.theme.TasksAppTheme
import org.koin.compose.KoinApplication
import org.koin.compose.viewmodel.koinViewModel
import java.awt.Dimension
import java.awt.Toolkit
import javax.swing.UIManager
private const val GCP_CLIENT_ID = "191682949161-esokhlfh7uugqptqnu3su9vgqmvltv95.apps.googleusercontent.com"
fun main() {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
application {
val screenSize by remember {
mutableStateOf(Toolkit.getDefaultToolkit().screenSize)
}
val defaultSize = DpSize(1024.dp, 800.dp)
val minSize = Dimension(600, 400)
var windowState = rememberWindowState(
position = WindowPosition(Alignment.Center), width = defaultSize.width, height = defaultSize.height
)
Window(
onCloseRequest = ::exitApplication,
state = windowState,
title = "Tasks App",
) {
if (window.minimumSize != minSize) window.minimumSize = minSize
if (windowState.placement == WindowPlacement.Floating) {
val insets = window.insets
val maxWidth = screenSize.width - insets.left - insets.right
val finalWidth = if (window.size.width > maxWidth) maxWidth else window.size.width
val maxHeight = screenSize.height - insets.bottom - insets.top
val finalHeight = if (window.size.height > maxHeight) maxHeight else window.size.height
if (finalWidth != window.size.width || finalHeight != window.size.height) {
windowState = WindowState(
placement = windowState.placement,
position = windowState.position,
isMinimized = windowState.isMinimized,
width = finalWidth.dp,
height = finalHeight.dp
)
}
}
KoinApplication(application = {
modules(
platformModule(),
dataModule,
authModule(GCP_CLIENT_ID),
networkModule,
tasksAppModule,
)
}) {
val userViewModel = koinViewModel<UserViewModel>()
val userState by userViewModel.state.collectAsState(null)
if (userState == null) {
LaunchedEffect(userState) {
userViewModel.refreshUserState()
}
}
TasksAppTheme {
Surface {
when (userState) {
null -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 1.dp)
}
is UserState.Unsigned,
is UserState.SignedIn -> {
val tasksViewModel = koinViewModel<TaskListsViewModel>()
TasksApp(userViewModel, tasksViewModel)
}
is UserState.Newcomer -> AuthorizationScreen(
onSkip = userViewModel::skipSignIn,
onSuccess = userViewModel::signIn,
)
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 85094c58834cfa84b2527f55dd9cd5756db9c606 | 6,044 | task-craftr | MIT License |
slpwallet/src/test/java/com/bitcoin/slpwallet/slp/SlpTokenDetailsTest.kt | Bitcoin-com | 178,391,446 | false | null | package com.bitcoin.slpwallet.slp
import org.junit.Assert.assertEquals
import org.junit.Test
import java.math.BigDecimal
class SlpTokenDetailsTest {
@Test
fun toRawAmount_happy() {
val decimals = 6
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount : ULong = 12530000u
assertEquals(expectedAmount, details.toRawAmount(BigDecimal("12.53")))
}
@Test
fun toRawAmount_zeroDecimals() {
val decimals = 0
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount : ULong = 12u
assertEquals(expectedAmount, details.toRawAmount(BigDecimal("12")))
}
@Test(expected = IllegalArgumentException::class)
fun toRawAmount_tooManyDecimals() {
val details = SlpTokenDetails(SlpTokenId(""), "", "", 0)
details.toRawAmount(BigDecimal("23.1"))
}
@Test
fun toRawAmount_supportUnsigned8Bytes() {
val decimals = 5
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount = ULong.MAX_VALUE - 1000u
assertEquals(expectedAmount, details.toRawAmount(BigDecimal("184467440737095.50615")))
}
@Test
fun toReadableAmount_supportUnsigned8Bytes() {
val decimals = 6
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount = BigDecimal("18446744073709.550615")
assertEquals(expectedAmount, details.toReadableAmount(BigDecimal("18446744073709550615")))
}
@Test
fun toReadableAmount_happy() {
val decimals = 6
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount = BigDecimal("12.53")
assertEquals(expectedAmount, details.toReadableAmount(BigDecimal("12530000")))
}
@Test
fun toReadableAmount_zeroDecimals() {
val decimals = 0
val details = SlpTokenDetails(SlpTokenId(""), "", "", decimals)
val expectedAmount = BigDecimal("12")
assertEquals(expectedAmount, details.toReadableAmount(BigDecimal("12")))
}
}
| 1 | Kotlin | 11 | 11 | 5049603074cf22e90e9f69b3ccb98f47bc1362ea | 2,111 | slp-wallet-sdk-android | MIT License |
src/main/java/org/eln2/mc/common/blocks/cell/DiodeCellBlock.kt | age-series | 248,378,503 | false | null | package org.eln2.mc.common.blocks.cell
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.phys.shapes.BooleanOp
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.Shapes
import net.minecraft.world.phys.shapes.VoxelShape
import org.eln2.mc.common.blocks.CellBlockBase
import org.eln2.mc.common.cell.CellRegistry
import org.eln2.mc.extensions.VoxelShapeExtensions.align
class DiodeCellBlock: CellBlockBase() {
override fun getCellProvider(): ResourceLocation {
return CellRegistry.DIODE_CELL.id
}
override fun getCollisionShape(
pState: BlockState,
pLevel: BlockGetter,
pPos: BlockPos,
pContext: CollisionContext
): VoxelShape {
return getFor(pState)
}
// TODO: This is deprecated
override fun getShape(
pState: BlockState,
pLevel: BlockGetter,
pPos: BlockPos,
pContext: CollisionContext
): VoxelShape {
return getFor(pState)
}
companion object {
private val resistorBody = box(7.0, 0.0, 0.0, 9.0, 2.0, 4.0)
private val resistorLeadLeft = box(6.0, 0.0, 4.0, 10.0, 3.0, 12.0)
private val resistorLeadRight = box(7.0, 0.0, 12.0, 9.0, 2.0, 16.0)
private val shape = Shapes.joinUnoptimized(
Shapes.joinUnoptimized(resistorLeadLeft, resistorLeadRight, BooleanOp.OR), resistorBody, BooleanOp.OR
)
private val cache = HashMap<BlockState, VoxelShape>()
fun getFor(state : BlockState) : VoxelShape{
return cache.computeIfAbsent(state){
when(val facing = state.getValue(FACING)){
Direction.NORTH -> shape
Direction.SOUTH -> shape
Direction.EAST -> shape.align(Direction.NORTH, Direction.EAST)
Direction.WEST -> shape.align(Direction.NORTH, Direction.WEST)
else -> error("Unhandled dir: $facing")
}
}
}
}
}
| 50 | Kotlin | 18 | 52 | 89047d77ef6879b1cf715ac074d1d64ad2996d18 | 2,207 | ElectricalAge2 | MIT License |
Final/data/src/main/java/ubb/thesis/david/data/mappers/LandmarkMapper.kt | davidleiti | 163,836,279 | false | {"Text": 1, "Markdown": 1, "Gradle": 6, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Kotlin": 123, "JSON": 1, "Proguard": 2, "XML": 66, "Java": 2} | package ubb.thesis.david.data.mappers
import ubb.license.david.foursquareapi.model.Location
import ubb.license.david.foursquareapi.model.Venue
import ubb.thesis.david.domain.common.Mapper
import ubb.thesis.david.domain.entities.Landmark
class LandmarkMapper : Mapper<Venue, Landmark>() {
override fun mapFrom(obj: Venue): Landmark =
Landmark(id = obj.id,
lat = obj.location.lat.toDouble(),
lng = obj.location.lng.toDouble(),
label = obj.name)
override fun mapTo(obj: Landmark): Venue =
Venue(id = obj.id,
name = if (obj.label != null) obj.label!! else "Unknown",
location = Location(lat = obj.lat.toString(), lng = obj.lng.toString()))
} | 0 | Kotlin | 0 | 2 | 59ca0edd6bf8f004c0a712ce532fcc107f58d147 | 743 | Monumental | MIT License |
app/src/main/java/com/franzliszt/magicmusic/route/nav/recommend/songs/SongEvent.kt | FranzLiszt-1847 | 753,088,527 | false | {"Kotlin": 879960, "Java": 1923} | package com.franzliszt.magicmusic.route.nav.recommend.songs
import com.franzliszt.magicmusic.bean.recommend.newsongs.Result
import com.franzliszt.magicmusic.bean.recommend.songs.DailySong
sealed class SongEvent {
data class InsertDaySong(val bean:DailySong):SongEvent()
data class InsertNewSong(val bean:Result):SongEvent()
} | 0 | Kotlin | 1 | 1 | dcbc4c0cb9c0478e617423812712659df52a3b7d | 335 | MagicPlayer | Apache License 2.0 |
app/src/main/java/demo/simple/checker/App.kt | simplepeng | 436,210,209 | false | {"Gradle": 6, "YAML": 1, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "INI": 4, "Proguard": 4, "XML": 21, "Java": 19, "Kotlin": 4} | package demo.simple.checker
import android.app.Application
import me.simple.checker.HeGuiChecker
class App : Application() {
override fun onCreate() {
super.onCreate()
// HeGuiChecker.SHOW_LOG = false
// HeGuiChecker.SHOW_TOAST = false
}
} | 1 | Java | 20 | 189 | 24bb888a6a95862578ade509257f0b165133b79c | 272 | HeGuiChecker | MIT License |
domain/src/main/java/com/pedronsouza/domain/models/PropertyLocation.kt | pedronsouza | 771,484,746 | false | {"Kotlin": 166729} | package com.pedronsouza.domain.models
data class PropertyLocation(
val city: City
) | 0 | Kotlin | 0 | 0 | b19573e0e89e2916b0510cf94367d86acec4aa56 | 88 | challenge-hostelworld | Creative Commons Zero v1.0 Universal |
wear/wear-watchface-style/src/main/java/androidx/wear/watchface/style/UserStyleSetting.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.style
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.graphics.BitmapFactory
import android.graphics.RectF
import android.graphics.drawable.Icon
import android.icu.text.MessageFormat
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import androidx.annotation.Px
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.annotation.StringRes
import androidx.wear.watchface.complications.ComplicationSlotBounds
import androidx.wear.watchface.complications.IllegalNodeException
import androidx.wear.watchface.complications.NAMESPACE_ANDROID
import androidx.wear.watchface.complications.NAMESPACE_APP
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.getIntRefAttribute
import androidx.wear.watchface.complications.getStringRefAttribute
import androidx.wear.watchface.complications.hasValue
import androidx.wear.watchface.complications.iterate
import androidx.wear.watchface.complications.moveToStart
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotOverlay
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotsOption
import androidx.wear.watchface.style.data.BooleanOptionWireFormat
import androidx.wear.watchface.style.data.BooleanUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.ComplicationOverlayWireFormat
import androidx.wear.watchface.style.data.ComplicationsOptionWireFormat
import androidx.wear.watchface.style.data.ComplicationsUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.CustomValueOption2WireFormat
import androidx.wear.watchface.style.data.CustomValueOptionWireFormat
import androidx.wear.watchface.style.data.CustomValueUserStyleSetting2WireFormat
import androidx.wear.watchface.style.data.CustomValueUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.DoubleRangeOptionWireFormat
import androidx.wear.watchface.style.data.DoubleRangeUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.ListOptionWireFormat
import androidx.wear.watchface.style.data.ListUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.LongRangeOptionWireFormat
import androidx.wear.watchface.style.data.LongRangeUserStyleSettingWireFormat
import androidx.wear.watchface.style.data.OptionWireFormat
import androidx.wear.watchface.style.data.PerComplicationTypeMargins
import androidx.wear.watchface.style.data.UserStyleSettingWireFormat
import java.io.DataOutputStream
import java.io.InputStream
import java.nio.ByteBuffer
import java.security.DigestOutputStream
import java.security.InvalidParameterException
import java.util.Locale
import org.xmlpull.v1.XmlPullParser
/** Wrapper around either a [CharSequence] or a string resource. */
internal sealed class DisplayText {
abstract fun toCharSequence(): CharSequence
override fun toString(): String = toCharSequence().toString()
/** Used in evaluating [UserStyleSchema.getDigestHash]. */
internal open fun write(dos: DataOutputStream) {
// Intentionally empty.
}
class CharSequenceDisplayText(private val charSequence: CharSequence) : DisplayText() {
override fun toCharSequence() = charSequence
// This is used purely to estimate the wireformat size.
override fun write(dos: DataOutputStream) {
dos.writeUTF(toCharSequence().toString())
}
}
open class ResourceDisplayText(
protected val resources: Resources,
@StringRes protected val id: Int
) : DisplayText() {
override fun toCharSequence() = resources.getString(id)
}
class ResourceDisplayTextWithIndex(
resources: Resources,
@StringRes id: Int,
) : ResourceDisplayText(resources, id) {
private var indexString: String = ""
fun setIndex(index: Int) {
indexString = MessageFormat("{0,ordinal}", Locale.getDefault()).format(arrayOf(index))
}
override fun toCharSequence() = resources.getString(id, indexString)
}
}
/**
* Watch faces often have user configurable styles, the definition of what is a style is left up to
* the watch face but it typically incorporates a variety of settings such as: color, visual theme
* for watch hands, font, tick shape, complication slots, audio elements, etc...
*
* A UserStyleSetting represents one of these dimensions. See also [UserStyleSchema] which defines
* the list of UserStyleSettings provided by the watch face.
*
* Styling data gets shared with the companion phone to support editors (typically over bluetooth),
* as a result the size of serialized UserStyleSettings could become an issue if large.
*
* It is possible to define a hierarchy of styles, (e.g. a watch face might have support a number of
* different looks, each with their own settings). A hierarchy is defined by setting child styles in
* [ListUserStyleSetting.ListOption.childSettings]. A setting is deemed to be active if it's either
* in the top level of the tree, or if it's the child of an [Option] selected by the user in the
* [UserStyle]. In a hierarchy multiple [ComplicationSlotsUserStyleSetting] are allowed but only one
* can be active at any time, for more details see
* [UserStyleSchema.findComplicationSlotsOptionForUserStyle].
*
* @property id Identifier for the element, must be unique. Styling data gets shared with the
* companion (typically via bluetooth) so size is a consideration and short ids are encouraged.
* There is a maximum length see [UserStyleSetting.Id.MAX_LENGTH].
* @property icon [Icon] for use in the companion editor style selection UI.
* @property watchFaceEditorData Optional data for an on watch face editor, this will not be sent to
* the companion and its contents may be used in preference to other fields by an on watch face
* editor.
* @property options List of options for this UserStyleSetting. Depending on the type of
* UserStyleSetting this may be an exhaustive list, or just examples to populate a ListView in
* case the UserStyleSetting isn't supported by the UI (e.g. a new WatchFace with an old
* companion).
* @property defaultOptionIndex The default option index, used if nothing has been selected within
* the [options] list.
* @property affectedWatchFaceLayers Used by the style configuration UI. Describes which rendering
* layers this style affects.
*/
public sealed class UserStyleSetting
private constructor(
public val id: Id,
private val displayNameInternal: DisplayText,
private val descriptionInternal: DisplayText,
public val icon: Icon?,
public val watchFaceEditorData: WatchFaceEditorData?,
public val options: List<Option>,
public val defaultOptionIndex: Int,
public val affectedWatchFaceLayers: Collection<WatchFaceLayer>
) {
init {
require(defaultOptionIndex >= 0 && defaultOptionIndex < options.size) {
"defaultOptionIndex must be within the range of the options list"
}
requireUniqueOptionIds(id, options)
// Assign 1 based indices to display names to allow names such as Option 1, Option 2,
// etc...
for ((index, option) in options.withIndex()) {
option.displayNameInternal?.let {
if (it is DisplayText.ResourceDisplayTextWithIndex) {
it.setIndex(index + 1)
}
}
option.screenReaderNameInternal?.let {
if (it is DisplayText.ResourceDisplayTextWithIndex) {
it.setIndex(index + 1)
}
}
}
}
internal fun setDisplayNameIndex(index: Int) {
if (displayNameInternal is DisplayText.ResourceDisplayTextWithIndex) {
displayNameInternal.setIndex(index)
}
if (descriptionInternal is DisplayText.ResourceDisplayTextWithIndex) {
descriptionInternal.setIndex(index)
}
}
/**
* Optional data for an on watch face editor (not the companion editor).
*
* @property icon The icon to use on the watch face editor in preference to
* [UserStyleSetting.icon], [ListUserStyleSetting.ListOption.icon] and
* [ComplicationSlotsOption.icon]. This Icon should be smaller than the one used by the
* companion due to the watches smaller screen size.
*/
public class WatchFaceEditorData(public val icon: Icon?) {
@Suppress("DEPRECATION")
internal constructor(wireFormat: Bundle) : this(wireFormat.getParcelable(ICON_KEY))
internal fun toWireFormat() = Bundle().apply { icon?.let { putParcelable(ICON_KEY, it) } }
internal fun write(dos: DataOutputStream) {
icon?.write(dos)
}
internal companion object {
internal const val ICON_KEY = "ICON"
@SuppressLint("ResourceType")
fun inflate(resources: Resources, parser: XmlResourceParser): WatchFaceEditorData {
val icon = createIcon(resources, parser)
return WatchFaceEditorData(icon)
}
}
}
/** Localized human readable name for the element, used in the userStyle selection UI. */
public val displayName: CharSequence
get() = displayNameInternal.toCharSequence()
/** Localized description string displayed under the displayName. */
public val description: CharSequence
get() = descriptionInternal.toCharSequence()
/**
* For hierarchical style schemas, whether this UserStyleSetting has a parent [Option]. Editors
* should respect the hierarchy for the best user experience.
*/
internal var hasParent: Boolean = false
internal set
/**
* Estimates the wire size of the UserStyleSetting in bytes. This does not account for the
* overhead of the serialization method. Where possible the exact wire size for any referenced
* [Icon]s is used but this isn't possible in all cases and as a fallback width x height x 4 is
* used.
*
* Note this method can be slow.
*
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun estimateWireSizeInBytesAndValidateIconDimensions(
context: Context,
@Px maxWidth: Int,
@Px maxHeight: Int
): Int {
var sizeEstimate =
id.value.length +
displayName.length +
description.length +
4 +
/** [defaultOptionIndex] */
affectedWatchFaceLayers.size * 4
icon?.getWireSizeAndDimensions(context)?.let { wireSizeAndDimensions ->
wireSizeAndDimensions.wireSizeBytes?.let { sizeEstimate += it }
require(
wireSizeAndDimensions.width <= maxWidth && wireSizeAndDimensions.height <= maxHeight
) {
"UserStyleSetting id $id has a ${wireSizeAndDimensions.width} x " +
"${wireSizeAndDimensions.height} icon. This is too big, the maximum size is " +
"$maxWidth x $maxHeight."
}
}
for (option in options) {
sizeEstimate +=
option.estimateWireSizeInBytesAndValidateIconDimensions(
context,
maxWidth,
maxHeight
)
}
return sizeEstimate
}
/**
* Machine readable identifier for [UserStyleSetting]s. The length of this identifier may not
* exceed [MAX_LENGTH].
*/
public class Id(public val value: String) {
public companion object {
/** Maximum length of the [value] field. */
public const val MAX_LENGTH: Int = 40
}
init {
require(value.length <= MAX_LENGTH) {
"UserStyleSetting.value.length (${value.length}) must be less than MAX_LENGTH " +
"($MAX_LENGTH)"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Id
return value == other.value
}
override fun hashCode(): Int {
return value.hashCode()
}
override fun toString(): String = value
}
public companion object {
@Suppress("NewApi") // LargeCustomValueUserStyleSetting
internal fun createFromWireFormat(
wireFormat: UserStyleSettingWireFormat
): UserStyleSetting =
when (wireFormat) {
is BooleanUserStyleSettingWireFormat -> BooleanUserStyleSetting(wireFormat)
is ComplicationsUserStyleSettingWireFormat ->
ComplicationSlotsUserStyleSetting(wireFormat)
is CustomValueUserStyleSettingWireFormat -> CustomValueUserStyleSetting(wireFormat)
is CustomValueUserStyleSetting2WireFormat ->
LargeCustomValueUserStyleSetting(wireFormat)
is DoubleRangeUserStyleSettingWireFormat -> DoubleRangeUserStyleSetting(wireFormat)
is ListUserStyleSettingWireFormat -> ListUserStyleSetting(wireFormat)
is LongRangeUserStyleSettingWireFormat -> LongRangeUserStyleSetting(wireFormat)
else ->
throw IllegalArgumentException(
"Unknown UserStyleSettingWireFormat " + wireFormat::javaClass.name
)
}
internal fun affectsWatchFaceLayersFlagsToSet(affectsWatchFaceLayers: Int) =
HashSet<WatchFaceLayer>().apply {
if ((affectsWatchFaceLayers and 0x1) != 0) {
add(WatchFaceLayer.BASE)
}
if ((affectsWatchFaceLayers and 0x2) != 0) {
add(WatchFaceLayer.COMPLICATIONS)
}
if ((affectsWatchFaceLayers and 0x4) != 0) {
add(WatchFaceLayer.COMPLICATIONS_OVERLAY)
}
}
internal fun createDisplayText(
resources: Resources,
parser: XmlResourceParser,
attributeId: String,
defaultValue: DisplayText? = null,
indexedResourceNamesSupported: Boolean = false
): DisplayText {
val displayNameId = parser.getAttributeResourceValue(NAMESPACE_APP, attributeId, -1)
return if (displayNameId != -1) {
if (indexedResourceNamesSupported) {
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameId)
} else {
DisplayText.ResourceDisplayText(resources, displayNameId)
}
} else if (parser.hasValue(attributeId) || defaultValue == null) {
DisplayText.CharSequenceDisplayText(
parser.getAttributeValue(NAMESPACE_APP, attributeId) ?: ""
)
} else {
defaultValue
}
}
internal fun createIcon(resources: Resources, parser: XmlResourceParser): Icon? {
val iconId = parser.getAttributeResourceValue(NAMESPACE_ANDROID, "icon", -1)
return if (iconId != -1) {
Icon.createWithResource(resources.getResourcePackageName(iconId), iconId)
} else {
null
}
}
/** Creates appropriate UserStyleSetting base on parent="@xml/..." resource reference. */
internal fun <T> createParent(
resources: Resources,
parser: XmlResourceParser,
parentNodeName: String,
inflateSetting: (resources: Resources, parser: XmlResourceParser) -> T
): T? {
val parentRef = parser.getAttributeResourceValue(NAMESPACE_APP, "parent", 0)
return if (0 != parentRef) {
val parentParser = resources.getXml(parentRef)
parentParser.moveToStart(parentNodeName)
inflateSetting(resources, parentParser)
} else {
null
}
}
internal class Params(
val id: Id,
val displayName: DisplayText,
val description: DisplayText,
val icon: Icon?,
val watchFaceEditorData: WatchFaceEditorData?,
val options: List<Option>,
val defaultOptionIndex: Int?,
val affectedWatchFaceLayers: Collection<WatchFaceLayer>
)
/**
* Parses base UserStyleSettings params. If a parent is specified, inherits its attributes
* unless they are explicitly specified.
*/
internal fun createBaseWithParent(
resources: Resources,
parser: XmlResourceParser,
parent: UserStyleSetting?,
inflateDefault: Boolean,
optionInflater:
Pair<String, ((resources: Resources, parser: XmlResourceParser) -> Option)>? =
null
): Params {
val settingType = "UserStyleSetting"
val id =
getStringRefAttribute(resources, parser, "id")
?: parent?.id?.value
?: throw IllegalArgumentException("$settingType must have id")
val displayName =
createDisplayText(resources, parser, "displayName", parent?.displayNameInternal)
val description =
createDisplayText(resources, parser, "description", parent?.descriptionInternal)
val icon = createIcon(resources, parser) ?: parent?.icon
val defaultOptionIndex =
if (inflateDefault) {
getAttributeChecked(
parser,
"defaultOptionIndex",
String::toInt,
parent?.defaultOptionIndex ?: 0,
settingType
)
} else null
val affectsWatchFaceLayers =
getAttributeChecked(
parser,
"affectedWatchFaceLayers",
{ value -> affectsWatchFaceLayersFlagsToSet(Integer.decode(value)) },
parent?.affectedWatchFaceLayers ?: WatchFaceLayer.ALL_WATCH_FACE_LAYERS,
settingType
)
var watchFaceEditorData: WatchFaceEditorData? = null
val options = ArrayList<Option>()
parser.iterate {
if (parser.name == "OnWatchEditorData") {
if (watchFaceEditorData == null) {
watchFaceEditorData = WatchFaceEditorData.inflate(resources, parser)
} else {
throw IllegalNodeException(parser)
}
} else if (optionInflater != null && optionInflater.first == parser.name) {
options.add(optionInflater.second(resources, parser))
} else {
throw IllegalNodeException(parser)
}
}
return Params(
Id(id),
displayName,
description,
icon,
watchFaceEditorData ?: parent?.watchFaceEditorData,
if (parent == null || options.isNotEmpty()) options else parent.options,
defaultOptionIndex,
affectsWatchFaceLayers
)
}
}
internal fun getSettingOptionForId(id: ByteArray?) =
if (id == null) {
options[defaultOptionIndex]
} else {
getOptionForId(Option.Id(id))
}
private constructor(
wireFormat: UserStyleSettingWireFormat
) : this(
Id(wireFormat.mId),
DisplayText.CharSequenceDisplayText(wireFormat.mDisplayName),
DisplayText.CharSequenceDisplayText(wireFormat.mDescription),
wireFormat.mIcon,
wireFormat.mOnWatchFaceEditorBundle?.let { WatchFaceEditorData(it) },
wireFormat.mOptions.map { Option.createFromWireFormat(it) },
wireFormat.mDefaultOptionIndex,
wireFormat.mAffectsLayers.map { WatchFaceLayer.values()[it] }
)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public abstract fun toWireFormat(): UserStyleSettingWireFormat
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun getWireFormatOptionsList(): List<OptionWireFormat> =
options.map { it.toWireFormat() }
internal fun updateMessageDigest(digestOutputStream: DigestOutputStream) {
val dos = DataOutputStream(digestOutputStream)
dos.writeUTF(id.value)
displayNameInternal.write(dos)
descriptionInternal.write(dos)
icon?.write(dos)
watchFaceEditorData?.write(dos)
for (option in options) {
option.write(dos)
}
dos.writeInt(defaultOptionIndex)
for (layer in affectedWatchFaceLayers.toSortedSet()) {
dos.writeInt(layer.ordinal)
}
dos.close()
}
/** Returns the default for when the user hasn't selected an option. */
public val defaultOption: Option
get() = options[defaultOptionIndex]
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UserStyleSetting
return id == other.id
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String =
"{${id.value} : " + options.joinToString(transform = { it.toString() }) + "}"
/**
* Represents a choice within a style setting which can either be an option from the list or a
* an arbitrary value depending on the nature of the style setting.
*
* @property id Machine readable [Id] for the style setting. Identifier for the option (or the
* option itself for [CustomValueUserStyleSetting.CustomValueOption]), must be unique within
* the UserStyleSetting. Short ids are encouraged.
* @property childSettings The list of child [UserStyleSetting]s, if any, forming a hierarchy of
* [UserStyleSetting]s. These must be in [UserStyleSchema.userStyleSettings]. Child
* [UserStyleSetting]s are deemed to be active if the [Option] is selected by the [UserStyle].
* This is particularly important is there are multiple [ComplicationSlotsUserStyleSetting]s,
* only one of which is allowed to be active at any time.
*/
public abstract class Option
internal constructor(
public val id: Id,
public val childSettings: Collection<UserStyleSetting>
) {
/**
* This constructor is unused (the parent class is sealed), but is required to make tooling
* happy.
*/
constructor(id: Id) : this(id, emptyList())
/** Returns the maximum allowed size for IDs for this Option in bytes. */
internal open fun getMaxIdSizeBytes(): Int = Id.MAX_LENGTH
init {
for (child in childSettings) {
child.hasParent = true
}
require(id.value.size <= getMaxIdSizeBytes()) {
"Option.Id.value.size (${id.value.size}) must be less than MAX_LENGTH " +
getMaxIdSizeBytes()
}
}
/**
* Computes a lower bound estimate of the wire size of the Option in bytes. This does not
* account for the overhead of the serialization method.
*/
internal open fun estimateWireSizeInBytesAndValidateIconDimensions(
context: Context,
@Px maxWidth: Int,
@Px maxHeight: Int
): Int = id.value.size
// We don't want Option to be subclassed by users.
@SuppressWarnings("HiddenAbstractMethod")
internal abstract fun getUserStyleSettingClass(): Class<out UserStyleSetting>
internal open val displayNameInternal: DisplayText?
get() = null
internal open val screenReaderNameInternal: DisplayText?
get() = null
/**
* Machine readable identifier for [Option]s. The length of this identifier may not exceed
* [MAX_LENGTH].
*
* @param value The [ByteArray] value of this Id.
*/
public class Id(public val value: ByteArray) {
/**
* Constructs an [Id] with a [String] encoded to a [ByteArray] by
* [String.encodeToByteArray].
*/
public constructor(value: String) : this(value.encodeToByteArray())
public companion object {
/**
* Maximum length of the [value] field to ensure acceptable companion editing
* latency. Please note the [UserStyleSchema] and the [UserStyleSetting] are sent
* over bluetooth to the companion phone when editing, and that bandwidth is limited
* (2mbps is common). Best practice is to keep these Ids short, ideally under 10
* bytes.
*
* Note the [UserStyle] has a maximum size ([UserStyle.MAXIMUM_SIZE_BYTES]) and that
* Option Ids are a significant contributor to the overall size of a UserStyle.
*/
public const val MAX_LENGTH: Int = 1024
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Id
return value.contentEquals(other.value)
}
override fun hashCode(): Int {
return value.contentHashCode()
}
override fun toString(): String =
try {
value.decodeToString()
} catch (e: Exception) {
value.toString()
}
}
public companion object {
@Suppress("NewApi")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun createFromWireFormat(wireFormat: OptionWireFormat): Option =
when (wireFormat) {
is BooleanOptionWireFormat ->
BooleanUserStyleSetting.BooleanOption.fromWireFormat(wireFormat)
is ComplicationsOptionWireFormat ->
ComplicationSlotsUserStyleSetting.ComplicationSlotsOption(wireFormat)
is CustomValueOptionWireFormat ->
CustomValueUserStyleSetting.CustomValueOption(wireFormat)
is CustomValueOption2WireFormat ->
LargeCustomValueUserStyleSetting.CustomValueOption(wireFormat)
is DoubleRangeOptionWireFormat ->
DoubleRangeUserStyleSetting.DoubleRangeOption(wireFormat)
is ListOptionWireFormat -> ListUserStyleSetting.ListOption(wireFormat)
is LongRangeOptionWireFormat ->
LongRangeUserStyleSetting.LongRangeOption(wireFormat)
else ->
throw IllegalArgumentException(
"Unknown UserStyleSettingWireFormat.OptionWireFormat " +
wireFormat::javaClass.name
)
}
}
@Suppress("HiddenAbstractMethod")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public abstract fun toWireFormat(): OptionWireFormat
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Option
return id == other.id
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String =
try {
id.value.decodeToString()
} catch (e: Exception) {
id.value.toString()
}
internal open fun write(dos: DataOutputStream) {
// Intentionally empty.
}
}
/**
* Translates an option name into an option. This will need to be overridden for userStyle
* categories that can't sensibly be fully enumerated (e.g. a full 24-bit color picker).
*
* @param optionId The [Option.Id] of the option
* @return An [Option] corresponding to the name. This could either be one of the options from
* [UserStyleSetting]s or a newly constructed Option depending on the nature of the
* UserStyleSetting. If optionName is unrecognized then the default value for the setting
* should be returned.
*/
public open fun getOptionForId(optionId: Option.Id): Option =
options.find { it.id.value.contentEquals(optionId.value) } ?: options[defaultOptionIndex]
/** A BooleanUserStyleSetting represents a setting with a true and a false setting. */
public class BooleanUserStyleSetting : UserStyleSetting {
/**
* Constructs a BooleanUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the userStyle
* selection UI.
* @param description Localized description string displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this BooleanUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@JvmOverloads
public constructor(
id: Id,
displayName: CharSequence,
description: CharSequence,
icon: Icon?,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Boolean,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.CharSequenceDisplayText(displayName),
DisplayText.CharSequenceDisplayText(description),
icon,
watchFaceEditorData,
listOf(BooleanOption.TRUE, BooleanOption.FALSE),
when (defaultValue) {
true -> 0
false -> 1
},
affectsWatchFaceLayers
)
/**
* Constructs a BooleanUserStyleSetting where [BooleanUserStyleSetting.displayName] and
* [BooleanUserStyleSetting.description] are specified as resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] and
* [descriptionResourceId] are loaded.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI.
* @param descriptionResourceId String resource id for a human readable description string
* displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this BooleanUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes descriptionResourceId: Int,
icon: Icon?,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Boolean,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId),
DisplayText.ResourceDisplayTextWithIndex(resources, descriptionResourceId),
icon,
watchFaceEditorData,
listOf(BooleanOption.TRUE, BooleanOption.FALSE),
when (defaultValue) {
true -> 0
false -> 1
},
affectsWatchFaceLayers
)
internal constructor(
id: Id,
displayName: DisplayText,
description: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Boolean
) : super(
id,
displayName,
description,
icon,
watchFaceEditorData,
listOf(BooleanOption.TRUE, BooleanOption.FALSE),
when (defaultValue) {
true -> 0
false -> 1
},
affectsWatchFaceLayers
)
internal constructor(wireFormat: BooleanUserStyleSettingWireFormat) : super(wireFormat)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): BooleanUserStyleSettingWireFormat =
BooleanUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
defaultOptionIndex,
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
/* optionsOnWatchFaceEditorIcons = */ null
)
/** Returns the default value. */
public fun getDefaultValue(): Boolean = (options[defaultOptionIndex] as BooleanOption).value
internal companion object {
@SuppressLint("ResourceType")
fun inflate(resources: Resources, parser: XmlResourceParser): BooleanUserStyleSetting {
val settingType = "BooleanUserStyleSetting"
val parent = createParent(resources, parser, settingType, ::inflate)
val defaultValue =
getAttributeChecked(
parser,
"defaultBoolean",
String::toBoolean,
parent?.getDefaultValue(),
settingType
)
val params = createBaseWithParent(resources, parser, parent, inflateDefault = false)
return BooleanUserStyleSetting(
params.id,
params.displayName,
params.description,
params.icon,
params.watchFaceEditorData,
params.affectedWatchFaceLayers,
defaultValue
)
}
}
/**
* Represents a true or false option in the [BooleanUserStyleSetting].
*
* @param value The boolean value this instance represents.
*/
public class BooleanOption private constructor(public val value: Boolean) :
Option(Id(ByteArray(1).apply { this[0] = if (value) 1 else 0 }), emptyList()) {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): BooleanOptionWireFormat = BooleanOptionWireFormat(id.value)
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
BooleanUserStyleSetting::class.java
override fun toString(): String = if (id.value[0] == 1.toByte()) "true" else "false"
override fun write(dos: DataOutputStream) {
dos.write(id.value)
dos.writeBoolean(value)
}
public companion object {
@JvmField public val TRUE = BooleanOption(true)
@JvmField public val FALSE = BooleanOption(false)
@JvmStatic
public fun from(value: Boolean): BooleanOption {
return if (value) TRUE else FALSE
}
@JvmStatic
internal fun fromWireFormat(wireFormat: BooleanOptionWireFormat): BooleanOption {
return from(wireFormat.mId[0] == 1.toByte())
}
}
}
}
/**
* ComplicationSlotsUserStyleSetting is the recommended [UserStyleSetting] for representing
* complication slot configuration, options such as the number of active complication slots,
* their location, etc... The [ComplicationSlotsOption] class allows you to apply a list of
* [ComplicationSlotOverlay]s on top of the base config as specified by the
* [androidx.wear.watchface.ComplicationSlot] constructor.
*
* The ComplicationsManager listens for style changes with this setting and when a
* [ComplicationSlotsOption] is selected the overrides are automatically applied. Note its
* suggested that the default [ComplicationSlotOverlay] (the first entry in the list) does not
* apply any overrides.
*
* From android T multiple [ComplicationSlotsUserStyleSetting] are allowed in a style hierarchy
* as long as at most one is active for any permutation of [UserStyle]. Prior to android T only
* a single ComplicationSlotsUserStyleSetting was allowed.
*
* Not to be confused with complication data source selection.
*/
public class ComplicationSlotsUserStyleSetting : UserStyleSetting {
private constructor(
id: Id,
displayNameInternal: DisplayText,
descriptionInternal: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
options: List<ComplicationSlotsOption>,
defaultOptionIndex: Int,
affectedWatchFaceLayers: Collection<WatchFaceLayer>
) : super(
id,
displayNameInternal,
descriptionInternal,
icon,
watchFaceEditorData,
options,
defaultOptionIndex,
affectedWatchFaceLayers
) {
require(affectedWatchFaceLayers.contains(WatchFaceLayer.COMPLICATIONS)) {
"ComplicationSlotsUserStyleSetting must affect the complications layer"
}
}
/**
* Overrides to be applied to the corresponding [androidx.wear.watchface.ComplicationSlot]'s
* initial config (as specified in it's constructor) when the setting is selected.
*
* @param complicationSlotId The id of the [androidx.wear.watchface.ComplicationSlot] to
* configure.
* @param enabled If non null, whether the complication should be enabled for this
* configuration. If null then no changes are made.
* @param complicationSlotBounds If non null, the [ComplicationSlotBounds] for this
* configuration. If null then no changes are made.
* @param accessibilityTraversalIndex If non null the accessibility traversal index for this
* configuration. This is used to determine the order in which accessibility labels for
* the watch face are read to the user.
* @param nameResourceId If non null, the string resource identifier for name of the
* complication slot, for this configuration. These strings should be short (perhaps 10
* characters max) E.g. complication slots named 'left' and 'right' might be shown by the
* editor in a list from which the user selects a complication slot for editing.
* @param screenReaderNameResourceId If non null, the string resource identifier for the
* screen reader name of the complication slot, for this configuration. While similar to
* [nameResourceId] this string can be longer and should be more descriptive. E.g. saying
* 'left complication' rather than just 'left'.
*/
public class ComplicationSlotOverlay
constructor(
public val complicationSlotId: Int,
@Suppress("AutoBoxing")
@get:Suppress("AutoBoxing")
@get:JvmName("isEnabled")
public val enabled: Boolean? = null,
public val complicationSlotBounds: ComplicationSlotBounds? = null,
@SuppressWarnings("AutoBoxing")
@get:SuppressWarnings("AutoBoxing")
public val accessibilityTraversalIndex: Int? = null,
@SuppressWarnings("AutoBoxing")
@get:Suppress("AutoBoxing")
public val nameResourceId: Int? = null,
@SuppressWarnings("AutoBoxing")
@get:Suppress("AutoBoxing")
public val screenReaderNameResourceId: Int? = null
) {
init {
require(nameResourceId != 0)
require(screenReaderNameResourceId != 0)
}
/**
* @deprecated This constructor is deprecated in favour of the one that specifies
* optional parameters nameResourceId and screenReaderNameResourceId
* [ComplicationSlotOverlay(Int, Boolean?, ComplicationSlotBounds?, Int?, Int?, Int?]
*/
@Deprecated(
message =
"This constructor is deprecated in favour of the one that specifies " +
"optional parameters nameResourceId and screenReaderNameResourceId",
level = DeprecationLevel.WARNING
)
public constructor(
complicationSlotId: Int,
@Suppress("AutoBoxing") enabled: Boolean? = null,
complicationSlotBounds: ComplicationSlotBounds? = null,
@SuppressWarnings("AutoBoxing") accessibilityTraversalIndex: Int? = null
) : this(
complicationSlotId,
enabled,
complicationSlotBounds,
accessibilityTraversalIndex,
null,
null
)
internal fun write(dos: DataOutputStream) {
dos.write(complicationSlotId)
enabled?.let { dos.writeBoolean(it) }
complicationSlotBounds?.write(dos)
accessibilityTraversalIndex?.let { dos.writeInt(it) }
nameResourceId?.let { dos.writeInt(it) }
screenReaderNameResourceId?.let { dos.writeInt(it) }
}
/**
* Constructs a [ComplicationSlotOverlay].Builder.
*
* @param complicationSlotId The id of the [androidx.wear.watchface.ComplicationSlot] to
* configure.
*/
public class Builder(private val complicationSlotId: Int) {
private var enabled: Boolean? = null
private var complicationSlotBounds: ComplicationSlotBounds? = null
private var accessibilityTraversalIndex: Int? = null
private var nameResourceId: Int? = null
private var screenReaderNameResourceId: Int? = null
/** Overrides the complication's enabled flag. */
@Suppress("MissingGetterMatchingBuilder")
public fun setEnabled(enabled: Boolean): Builder = apply { this.enabled = enabled }
/** Overrides the complication's per [ComplicationSlotBounds]. */
public fun setComplicationSlotBounds(
complicationSlotBounds: ComplicationSlotBounds
): Builder = apply { this.complicationSlotBounds = complicationSlotBounds }
/**
* Overrides the [androidx.wear.watchface.ComplicationSlot]'s accessibility
* traversal index. This is used to sort
* [androidx.wear.watchface.ContentDescriptionLabel]s. If unset we will order the
* complications by their initial accessibilityTraversalIndex (usually the same as
* their id).
*/
public fun setAccessibilityTraversalIndex(
accessibilityTraversalIndex: Int
): Builder = apply {
this.accessibilityTraversalIndex = accessibilityTraversalIndex
}
/**
* Overrides the ID of a string resource containing the name of this complication
* slot, for use by a screen reader. This resource should be a short sentence. E.g.
* "Left complication" for the left complication.
*/
public fun setNameResourceId(nameResourceId: Int): Builder = apply {
this.nameResourceId = nameResourceId
}
/**
* Overrides the ID of a string resource containing the name of this complication
* slot, for use by a screen reader. This resource should be a short sentence. E.g.
* "Left complication" for the left complication.
*/
public fun setScreenReaderNameResourceId(screenReaderNameResourceId: Int): Builder =
apply {
this.screenReaderNameResourceId = screenReaderNameResourceId
}
public fun build(): ComplicationSlotOverlay =
ComplicationSlotOverlay(
complicationSlotId,
enabled,
complicationSlotBounds,
accessibilityTraversalIndex,
nameResourceId,
screenReaderNameResourceId
)
}
internal constructor(
wireFormat: ComplicationOverlayWireFormat,
perComplicationTypeMargins: Map<Int, RectF>?,
nameResourceId: Int? = null,
screenReaderNameResourceId: Int? = null
) : this(
wireFormat.mComplicationSlotId,
when (wireFormat.mEnabled) {
ComplicationOverlayWireFormat.ENABLED_UNKNOWN -> null
ComplicationOverlayWireFormat.ENABLED_YES -> true
ComplicationOverlayWireFormat.ENABLED_NO -> false
else ->
throw InvalidParameterException(
"Unrecognised wireFormat.mEnabled " + wireFormat.mEnabled
)
},
wireFormat.mPerComplicationTypeBounds?.let { perComplicationTypeBounds ->
ComplicationSlotBounds.createFromPartialMap(
perComplicationTypeBounds.mapKeys { ComplicationType.fromWireType(it.key) },
perComplicationTypeMargins?.let { margins ->
margins.mapKeys { ComplicationType.fromWireType(it.key) }
}
?: emptyMap()
)
},
wireFormat.accessibilityTraversalIndex,
nameResourceId,
screenReaderNameResourceId
)
/**
* Computes a lower bound estimate of the wire format size of this
* ComplicationSlotOverlay.
*/
internal fun estimateWireSizeInBytes(): Int {
var estimate = 16 // Estimate for everything except complicationSlotBounds
complicationSlotBounds?.let {
estimate += it.perComplicationTypeBounds.size * (4 + 16)
}
return estimate
}
internal fun toWireFormat() =
ComplicationOverlayWireFormat(
complicationSlotId,
enabled,
complicationSlotBounds?.perComplicationTypeBounds?.mapKeys {
it.key.toWireComplicationType()
},
accessibilityTraversalIndex
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ComplicationSlotOverlay
if (complicationSlotId != other.complicationSlotId) return false
if (enabled != other.enabled) return false
if (complicationSlotBounds != other.complicationSlotBounds) return false
if (accessibilityTraversalIndex != other.accessibilityTraversalIndex) return false
if (nameResourceId != other.nameResourceId) return false
if (screenReaderNameResourceId != other.screenReaderNameResourceId) return false
return true
}
override fun hashCode(): Int {
var result = complicationSlotId
result = 31 * result + (enabled?.hashCode() ?: 0)
result = 31 * result + (complicationSlotBounds?.hashCode() ?: 0)
result = 31 * result + (accessibilityTraversalIndex ?: 0)
result = 31 * result + (nameResourceId ?: 0)
result = 31 * result + (screenReaderNameResourceId ?: 0)
return result
}
override fun toString(): String {
return "ComplicationSlotOverlay(complicationSlotId=$complicationSlotId, " +
"enabled=$enabled, complicationSlotBounds=$complicationSlotBounds, " +
"accessibilityTraversalIndex=$accessibilityTraversalIndex, " +
"nameResourceId=$nameResourceId, " +
"screenReaderNameResourceId=$screenReaderNameResourceId)"
}
internal companion object {
@SuppressLint("ResourceType")
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotOverlay {
val complicationSlotId =
getIntRefAttribute(resources, parser, "complicationSlotId")
require(complicationSlotId != null) {
"ComplicationSlotOverlay missing complicationSlotId"
}
val enabled =
if (parser.hasValue("enabled")) {
parser.getAttributeBooleanValue(NAMESPACE_APP, "enabled", true)
} else {
null
}
val accessibilityTraversalIndex =
if (parser.hasValue("accessibilityTraversalIndex")) {
parser.getAttributeIntValue(
NAMESPACE_APP,
"accessibilityTraversalIndex",
0
)
} else {
null
}
val nameResourceId =
if (parser.hasValue("name")) {
parser.getAttributeResourceValue(NAMESPACE_APP, "name", 0)
} else {
null
}
val screenReaderNameResourceId =
if (parser.hasValue("screenReaderName")) {
parser.getAttributeResourceValue(NAMESPACE_APP, "screenReaderName", 0)
} else {
null
}
val bounds =
ComplicationSlotBounds.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
return ComplicationSlotOverlay(
complicationSlotId,
enabled,
bounds,
accessibilityTraversalIndex,
nameResourceId,
screenReaderNameResourceId
)
}
}
}
/**
* Constructs a ComplicationSlotsUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the userStyle
* selection UI.
* @param description Localized description string displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param complicationConfig The configuration for affected complications.
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects, must include [WatchFaceLayer.COMPLICATIONS].
* @param defaultOption The default option, used when data isn't persisted. Optional
* parameter which defaults to the first element of [complicationConfig].
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public constructor(
id: Id,
displayName: CharSequence,
description: CharSequence,
icon: Icon?,
complicationConfig: List<ComplicationSlotsOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOption: ComplicationSlotsOption = complicationConfig.first(),
watchFaceEditorData: WatchFaceEditorData? = null
) : this(
id,
DisplayText.CharSequenceDisplayText(displayName),
DisplayText.CharSequenceDisplayText(description),
icon,
watchFaceEditorData,
complicationConfig,
complicationConfig.indexOf(defaultOption),
affectsWatchFaceLayers
)
/**
* Constructs a ComplicationSlotsUserStyleSetting where
* [ComplicationSlotsUserStyleSetting.displayName] and
* [ComplicationSlotsUserStyleSetting.description] are specified as resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] and
* [descriptionResourceId] are loaded.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI.
* @param descriptionResourceId String resource id for a human readable description string
* displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param complicationConfig The configuration for affected complications.
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects, must include [WatchFaceLayer.COMPLICATIONS].
* @param defaultOption The default option, used when data isn't persisted. Optional
* parameter which defaults to the first element of [complicationConfig].
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes descriptionResourceId: Int,
icon: Icon?,
complicationConfig: List<ComplicationSlotsOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOption: ComplicationSlotsOption = complicationConfig.first(),
watchFaceEditorData: WatchFaceEditorData? = null
) : this(
id,
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId),
DisplayText.ResourceDisplayTextWithIndex(resources, descriptionResourceId),
icon,
watchFaceEditorData,
complicationConfig,
complicationConfig.indexOf(defaultOption),
affectsWatchFaceLayers
)
internal constructor(
id: Id,
displayName: DisplayText,
description: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData? = null,
options: List<ComplicationSlotsOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOptionIndex: Int
) : this(
id,
displayName,
description,
icon,
watchFaceEditorData,
options,
defaultOptionIndex,
affectsWatchFaceLayers
)
internal constructor(
wireFormat: ComplicationsUserStyleSettingWireFormat
) : super(wireFormat) {
wireFormat.mPerOptionOnWatchFaceEditorBundles?.let { optionsOnWatchFaceEditorIcons ->
val optionsIterator = options.iterator()
for (bundle in optionsOnWatchFaceEditorIcons) {
val option = optionsIterator.next() as ComplicationSlotsOption
bundle?.let { option.watchFaceEditorData = WatchFaceEditorData(it) }
}
}
wireFormat.mPerOptionScreenReaderNames?.let { perOptionScreenReaderNames ->
val optionsIterator = options.iterator()
for (screenReaderName in perOptionScreenReaderNames) {
val option = optionsIterator.next() as ComplicationSlotsOption
screenReaderName?.let {
option.screenReaderNameInternal =
DisplayText.CharSequenceDisplayText(screenReaderName)
}
}
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): ComplicationsUserStyleSettingWireFormat =
ComplicationsUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
defaultOptionIndex,
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
options.map {
(it as ComplicationSlotsOption).watchFaceEditorData?.toWireFormat() ?: Bundle()
},
options.map {
it as ComplicationSlotsOption
it.screenReaderName ?: it.displayName
}
)
internal companion object {
private fun <T> bindScale(
function:
( // ktlint-disable parameter-list-wrapping
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
) -> T,
complicationScaleX: Float,
complicationScaleY: Float
): (resources: Resources, parser: XmlResourceParser) -> T {
return { resources: Resources, parser: XmlResourceParser ->
function(resources, parser, complicationScaleX, complicationScaleY)
}
}
@SuppressLint("ResourceType")
@Suppress("UNCHECKED_CAST")
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotsUserStyleSetting {
val params =
createBaseWithParent(
resources,
parser,
createParent(
resources,
parser,
"ComplicationSlotsUserStyleSetting",
bindScale(::inflate, complicationScaleX, complicationScaleY)
),
inflateDefault = true,
optionInflater =
"ComplicationSlotsOption" to
bindScale(
ComplicationSlotsOption::inflate,
complicationScaleX,
complicationScaleY
)
)
return ComplicationSlotsUserStyleSetting(
params.id,
params.displayName,
params.description,
params.icon,
params.watchFaceEditorData,
params.options as List<ComplicationSlotsOption>,
params.affectedWatchFaceLayers,
params.defaultOptionIndex!!
)
}
}
/**
* Represents an override to the initial [androidx.wear.watchface.ComplicationSlotsManager]
* configuration.
*/
public class ComplicationSlotsOption : Option {
/**
* Overlays to be applied when this ComplicationSlotsOption is selected. If this is
* empty then the net result is the initial complication configuration.
*/
public val complicationSlotOverlays: Collection<ComplicationSlotOverlay>
/** Backing field for [displayName]. */
override val displayNameInternal: DisplayText
/**
* Localized human readable name for the setting, used in the editor style selection UI.
* This should be short (ideally < 20 characters).
*/
public val displayName: CharSequence
get() = displayNameInternal.toCharSequence()
/** Backing field for [screenReaderName]. */
override var screenReaderNameInternal: DisplayText?
/**
* Optional localized human readable name for the setting, used by screen readers. This
* should be more descriptive than [displayName]. Note prior to android T this is
* ignored by companion editors.
*/
public val screenReaderName: CharSequence?
get() = screenReaderNameInternal?.toCharSequence()
/** Icon for use in the companion style selection UI. */
public val icon: Icon?
/**
* Optional data for an on watch face editor, this will not be sent to the companion and
* its contents may be used in preference to other fields by an on watch face editor.
*/
public var watchFaceEditorData: WatchFaceEditorData?
internal set
/**
* Constructs a ComplicationSlotsUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the
* userStyle selection UI. This should be short, ideally < 20 characters.
* @param screenReaderName Localized human readable name for the element, used by screen
* readers. This should be more descriptive than [displayName].
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param complicationSlotOverlays Overlays to be applied when this
* ComplicationSlotsOption is selected. If this is empty then the net result is the
* initial complication configuration.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@JvmOverloads
public constructor(
id: Id,
displayName: CharSequence,
screenReaderName: CharSequence,
icon: Icon?,
complicationSlotOverlays: Collection<ComplicationSlotOverlay>,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, emptyList()) {
this.complicationSlotOverlays = complicationSlotOverlays
displayNameInternal = DisplayText.CharSequenceDisplayText(displayName)
screenReaderNameInternal = DisplayText.CharSequenceDisplayText(screenReaderName)
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
/**
* Constructs a ComplicationSlotsUserStyleSetting with [displayName] constructed from
* Resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] is load.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI. This should be short, ideally < 20
* characters. Note if the resource string contains `%1$s` that will get replaced with
* the 1-based ordinal (1st, 2nd, 3rd etc...) of the ComplicationSlotsOption in the
* list of ComplicationSlotsOptions.
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param complicationSlotOverlays Overlays to be applied when this
* ComplicationSlotsOption is selected. If this is empty then the net result is the
* initial complication configuration.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@Deprecated("Use a constructor that sets the screenReaderNameResourceId")
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
icon: Icon?,
complicationSlotOverlays: Collection<ComplicationSlotOverlay>,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, emptyList()) {
this.complicationSlotOverlays = complicationSlotOverlays
displayNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId)
screenReaderNameInternal = null
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
/**
* Constructs a ComplicationSlotsUserStyleSetting with [displayName] constructed from
* Resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] is load.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI. This should be short, ideally < 20
* characters. Note if the resource string contains `%1$s` that will get replaced with
* the 1-based ordinal (1st, 2nd, 3rd etc...) of the ComplicationSlotsOption in the
* list of ComplicationSlotsOptions.
* @param screenReaderNameResourceId String resource id for a human readable name for
* the element, used by screen readers. This should be more descriptive than
* [displayNameResourceId]. Note if the resource string contains `%1$s` that will get
* replaced with the 1-based ordinal (1st, 2nd, 3rd etc...) of the
* ComplicationSlotsOption in the list of ComplicationSlotsOptions. Note prior to
* android T this is ignored by companion editors.
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param complicationSlotOverlays Overlays to be applied when this
* ComplicationSlotsOption is selected. If this is empty then the net result is the
* initial complication configuration.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes screenReaderNameResourceId: Int,
icon: Icon?,
complicationSlotOverlays: Collection<ComplicationSlotOverlay>,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, emptyList()) {
this.complicationSlotOverlays = complicationSlotOverlays
this.displayNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId)
this.screenReaderNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, screenReaderNameResourceId)
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
internal constructor(
id: Id,
displayName: DisplayText,
screenReaderName: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
complicationSlotOverlays: Collection<ComplicationSlotOverlay>
) : super(id, emptyList()) {
this.complicationSlotOverlays = complicationSlotOverlays
this.displayNameInternal = displayName
this.screenReaderNameInternal = screenReaderName
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
internal constructor(
wireFormat: ComplicationsOptionWireFormat
) : super(Id(wireFormat.mId), emptyList()) {
complicationSlotOverlays =
wireFormat.mComplicationOverlays.mapIndexed { index, value ->
ComplicationSlotOverlay(
value,
wireFormat.mComplicationOverlaysMargins
?.get(index)
?.mPerComplicationTypeMargins,
wireFormat.mComplicationNameResourceIds?.get(index)?.asResourceId(),
wireFormat.mComplicationScreenReaderNameResourceIds
?.get(index)
?.asResourceId()
)
}
displayNameInternal = DisplayText.CharSequenceDisplayText(wireFormat.mDisplayName)
screenReaderNameInternal = null // This will get overwritten.
icon = wireFormat.mIcon
watchFaceEditorData = null // This will get overwritten.
}
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
ComplicationSlotsUserStyleSetting::class.java
internal override fun estimateWireSizeInBytesAndValidateIconDimensions(
context: Context,
@Px maxWidth: Int,
@Px maxHeight: Int
): Int {
var sizeEstimate = id.value.size + displayName.length
screenReaderName?.let { sizeEstimate + it.length }
for (overlay in complicationSlotOverlays) {
sizeEstimate += overlay.estimateWireSizeInBytes()
}
icon?.getWireSizeAndDimensions(context)?.let { wireSizeAndDimensions ->
wireSizeAndDimensions.wireSizeBytes?.let { sizeEstimate += it }
require(
wireSizeAndDimensions.width <= maxWidth &&
wireSizeAndDimensions.height <= maxHeight
) {
"ComplicationSlotsOption id $id has a ${wireSizeAndDimensions.width} x " +
"${wireSizeAndDimensions.height} icon. This is too big, the maximum " +
"size is $maxWidth x $maxHeight."
}
}
return sizeEstimate
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): ComplicationsOptionWireFormat =
ComplicationsOptionWireFormat(
id.value,
displayName,
icon,
complicationSlotOverlays.map { it.toWireFormat() }.toTypedArray(),
complicationSlotOverlays.map { overlay ->
PerComplicationTypeMargins(
overlay.complicationSlotBounds?.perComplicationTypeMargins?.mapKeys {
it.key.toWireComplicationType()
}
?: emptyMap()
)
},
complicationSlotOverlays.map { it.nameResourceId ?: 0 },
complicationSlotOverlays.map { it.screenReaderNameResourceId ?: 0 },
)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
for (overlay in complicationSlotOverlays) {
overlay.write(dos)
}
displayNameInternal.write(dos)
screenReaderNameInternal?.write(dos)
icon?.write(dos)
watchFaceEditorData?.write(dos)
}
internal companion object {
@SuppressLint("ResourceType")
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotsOption {
val id = getStringRefAttribute(resources, parser, "id")
require(id != null) { "ComplicationSlotsOption must have an id" }
val displayName =
createDisplayText(
resources,
parser,
"displayName",
indexedResourceNamesSupported = true
)
val screenReaderName =
createDisplayText(
resources,
parser,
"nameForScreenReaders",
defaultValue = displayName,
indexedResourceNamesSupported = true
)
val icon = createIcon(resources, parser)
var watchFaceEditorData: WatchFaceEditorData? = null
val complicationSlotOverlays = ArrayList<ComplicationSlotOverlay>()
parser.iterate {
when (parser.name) {
"ComplicationSlotOverlay" ->
complicationSlotOverlays.add(
ComplicationSlotOverlay.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
)
"OnWatchEditorData" -> {
if (watchFaceEditorData == null) {
watchFaceEditorData =
WatchFaceEditorData.inflate(resources, parser)
} else {
throw IllegalNodeException(parser)
}
}
else -> throw IllegalNodeException(parser)
}
}
return ComplicationSlotsOption(
Id(id),
displayName,
screenReaderName,
icon,
watchFaceEditorData,
complicationSlotOverlays
)
}
}
}
}
/**
* A DoubleRangeUserStyleSetting represents a setting with a [Double] value in the range
* `[minimumValue .. maximumValue]`.
*/
public class DoubleRangeUserStyleSetting : UserStyleSetting {
internal companion object {
internal fun createOptionsList(
minimumValue: Double,
maximumValue: Double,
defaultValue: Double
): List<DoubleRangeOption> {
require(minimumValue < maximumValue)
require(defaultValue >= minimumValue)
require(defaultValue <= maximumValue)
return if (defaultValue != minimumValue && defaultValue != maximumValue) {
listOf(
DoubleRangeOption(minimumValue),
DoubleRangeOption(defaultValue),
DoubleRangeOption(maximumValue)
)
} else {
listOf(DoubleRangeOption(minimumValue), DoubleRangeOption(maximumValue))
}
}
@SuppressLint("ResourceType")
fun inflate(
resources: Resources,
parser: XmlResourceParser
): DoubleRangeUserStyleSetting {
val settingType = "DoubleRangeUserStyleSetting"
val parent = createParent(resources, parser, settingType, ::inflate)
val maxDouble =
getAttributeChecked(
parser,
"maxDouble",
String::toDouble,
parent?.maximumValue,
settingType
)
val minDouble =
getAttributeChecked(
parser,
"minDouble",
String::toDouble,
parent?.minimumValue,
settingType
)
val defaultDouble =
getAttributeChecked(
parser,
"defaultDouble",
String::toDouble,
parent?.defaultValue,
settingType
)
val params = createBaseWithParent(resources, parser, parent, inflateDefault = false)
return DoubleRangeUserStyleSetting(
params.id,
params.displayName,
params.description,
params.icon,
params.watchFaceEditorData,
minDouble,
maxDouble,
params.affectedWatchFaceLayers,
defaultDouble
)
}
}
/**
* Constructs a DoubleRangeUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the user style
* selection UI.
* @param description Localized description string displayed under the displayName.
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param minimumValue Minimum value (inclusive).
* @param maximumValue Maximum value (inclusive).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this DoubleRangeUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@JvmOverloads
public constructor(
id: Id,
displayName: CharSequence,
description: CharSequence,
icon: Icon?,
minimumValue: Double,
maximumValue: Double,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Double,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.CharSequenceDisplayText(displayName),
DisplayText.CharSequenceDisplayText(description),
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
/**
* Constructs a DoubleRangeUserStyleSetting where [DoubleRangeUserStyleSetting.displayName]
* and [DoubleRangeUserStyleSetting.description] are specified as resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] and
* [descriptionResourceId] are loaded.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI.
* @param descriptionResourceId String resource id for a human readable description string
* displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param minimumValue Minimum value (inclusive).
* @param maximumValue Maximum value (inclusive).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this DoubleRangeUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes descriptionResourceId: Int,
icon: Icon?,
minimumValue: Double,
maximumValue: Double,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Double,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId),
DisplayText.ResourceDisplayTextWithIndex(resources, descriptionResourceId),
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
internal constructor(
id: Id,
displayName: DisplayText,
description: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
minimumValue: Double,
maximumValue: Double,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Double
) : super(
id,
displayName,
description,
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
internal constructor(wireFormat: DoubleRangeUserStyleSettingWireFormat) : super(wireFormat)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): DoubleRangeUserStyleSettingWireFormat =
DoubleRangeUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
defaultOptionIndex,
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
/* optionsOnWatchFaceEditorIcons = */ null
)
/** Represents an option as a [Double] in the range [minimumValue .. maximumValue]. */
public class DoubleRangeOption : Option {
/* The value for this option. Must be within the range [minimumValue .. maximumValue].*/
public val value: Double
/**
* Constructs a DoubleRangeOption.
*
* @param value The value of this DoubleRangeOption
*/
public constructor(
value: Double
) : super(
Id(ByteArray(8).apply { ByteBuffer.wrap(this).putDouble(value) }),
emptyList()
) {
this.value = value
}
internal constructor(
wireFormat: DoubleRangeOptionWireFormat
) : super(Id(wireFormat.mId), emptyList()) {
value = ByteBuffer.wrap(wireFormat.mId).double
}
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
DoubleRangeUserStyleSetting::class.java
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): DoubleRangeOptionWireFormat =
DoubleRangeOptionWireFormat(id.value)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
dos.writeDouble(value)
}
override fun toString(): String = value.toString()
}
/** Returns the minimum value. */
public val minimumValue: Double
get() = (options.first() as DoubleRangeOption).value
/** Returns the maximum value. */
public val maximumValue: Double
get() = (options.last() as DoubleRangeOption).value
/** Returns the default value. */
public val defaultValue: Double
get() = (options[defaultOptionIndex] as DoubleRangeOption).value
/** We support all values in the range [min ... max] not just min & max. */
override fun getOptionForId(optionId: Option.Id): Option =
options.find { it.id.value.contentEquals(optionId.value) }
?: checkedOptionForId(optionId.value)
private fun checkedOptionForId(optionId: ByteArray): DoubleRangeOption {
return try {
val value = ByteBuffer.wrap(optionId).double
if (value < minimumValue || value > maximumValue) {
options[defaultOptionIndex] as DoubleRangeOption
} else {
DoubleRangeOption(value)
}
} catch (e: Exception) {
options[defaultOptionIndex] as DoubleRangeOption
}
}
}
/** A ListUserStyleSetting represents a setting with options selected from a List. */
public open class ListUserStyleSetting : UserStyleSetting {
/**
* Constructs a ListUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the userStyle
* selection UI.
* @param description Localized description string displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param options List of all options for this ListUserStyleSetting.
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultOption The default option, used when data isn't persisted.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public constructor(
id: Id,
displayName: CharSequence,
description: CharSequence,
icon: Icon?,
options: List<ListOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOption: ListOption = options.first(),
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.CharSequenceDisplayText(displayName),
DisplayText.CharSequenceDisplayText(description),
icon,
watchFaceEditorData,
options,
options.indexOf(defaultOption),
affectsWatchFaceLayers
)
/**
* Constructs a ListUserStyleSetting where [ListUserStyleSetting.displayName] and
* [ListUserStyleSetting.description] are specified as resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] and
* [descriptionResourceId] are loaded.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI.
* @param descriptionResourceId String resource id for a human readable description string
* displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param options List of all options for this ListUserStyleSetting.
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultOption The default option, used when data isn't persisted.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes descriptionResourceId: Int,
icon: Icon?,
options: List<ListOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOption: ListOption = options.first(),
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId),
DisplayText.ResourceDisplayTextWithIndex(resources, descriptionResourceId),
icon,
watchFaceEditorData,
options,
options.indexOf(defaultOption),
affectsWatchFaceLayers
)
internal constructor(
id: Id,
displayName: DisplayText,
description: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
options: List<ListOption>,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultOptionIndex: Int
) : super(
id,
displayName,
description,
icon,
watchFaceEditorData,
options,
defaultOptionIndex,
affectsWatchFaceLayers
)
internal constructor(wireFormat: ListUserStyleSettingWireFormat) : super(wireFormat) {
wireFormat.mPerOptionOnWatchFaceEditorBundles?.let { optionsOnWatchFaceEditorIcons ->
val optionsIterator = options.iterator()
for (bundle in optionsOnWatchFaceEditorIcons) {
val option = optionsIterator.next() as ListOption
bundle?.let { option.watchFaceEditorData = WatchFaceEditorData(it) }
}
}
wireFormat.mPerOptionScreenReaderNames?.let { perOptionScreenReaderNames ->
val optionsIterator = options.iterator()
for (screenReaderName in perOptionScreenReaderNames) {
val option = optionsIterator.next() as ListOption
screenReaderName?.let {
option.screenReaderNameInternal =
DisplayText.CharSequenceDisplayText(screenReaderName)
}
}
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): ListUserStyleSettingWireFormat =
ListUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
defaultOptionIndex,
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
options.map { (it as ListOption).watchFaceEditorData?.toWireFormat() ?: Bundle() },
options.map {
it as ListOption
it.screenReaderName ?: it.displayName
}
)
internal companion object {
private fun <T> bindIdToSetting(
function:
( // ktlint-disable parameter-list-wrapping
resources: Resources,
parser: XmlResourceParser,
idToSetting: Map<String, UserStyleSetting>
) -> T,
idToSetting: Map<String, UserStyleSetting>
): (resources: Resources, parser: XmlResourceParser) -> T {
return { resources: Resources, parser: XmlResourceParser ->
function(resources, parser, idToSetting)
}
}
@SuppressLint("ResourceType")
@Suppress("UNCHECKED_CAST")
fun inflate(
resources: Resources,
parser: XmlResourceParser,
idToSetting: Map<String, UserStyleSetting>
): ListUserStyleSetting {
val params =
createBaseWithParent(
resources,
parser,
createParent(
resources,
parser,
"ListUserStyleSetting",
bindIdToSetting(::inflate, idToSetting)
),
inflateDefault = true,
"ListOption" to bindIdToSetting(ListOption::inflate, idToSetting)
)
return ListUserStyleSetting(
params.id,
params.displayName,
params.description,
params.icon,
params.watchFaceEditorData,
params.options as List<ListOption>,
params.affectedWatchFaceLayers,
params.defaultOptionIndex!!
)
}
}
/**
* Represents choice within a [ListUserStyleSetting], these must be enumerated up front.
*
* If [childSettings] is not empty, then an editor needs to treat this as a node in a
* hierarchy of editor widgets.
*/
public class ListOption : Option {
/** Backing field for [displayName]. */
override val displayNameInternal: DisplayText
/**
* Localized human readable name for the setting, used in the editor style selection UI.
* This should be short (ideally < 20 characters).
*/
public val displayName: CharSequence
get() = displayNameInternal.toCharSequence()
/** Backing field for [screenReaderName]. */
override var screenReaderNameInternal: DisplayText?
/**
* Optional localized human readable name for the setting, used by screen readers. This
* should be more descriptive than [displayName]. Note prior to android T this is
* ignored by companion editors.
*/
public val screenReaderName: CharSequence?
get() = screenReaderNameInternal?.toCharSequence()
/** Icon for use in the companion style selection UI. */
public val icon: Icon?
/**
* Optional data for an on watch face editor, this will not be sent to the companion and
* its contents may be used in preference to other fields by an on watch face editor.
*/
public var watchFaceEditorData: WatchFaceEditorData?
internal set
/**
* Constructs a ListOption.
*
* @param id The [Id] of this ListOption, must be unique within the
* [ListUserStyleSetting].
* * @param displayName Localized human readable name for the element, used in the
* userStyle selection UI. This should be short, ideally < 20 characters.
*
* @param screenReaderName Localized human readable name for the element, used by screen
* readers. This should be more descriptive than [displayName].
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param childSettings The list of child [UserStyleSetting]s, which may be empty. Any
* child settings must be listed in [UserStyleSchema.userStyleSettings].
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
constructor(
id: Id,
displayName: CharSequence,
screenReaderName: CharSequence,
icon: Icon?,
childSettings: Collection<UserStyleSetting> = emptyList(),
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, childSettings) {
displayNameInternal = DisplayText.CharSequenceDisplayText(displayName)
screenReaderNameInternal = DisplayText.CharSequenceDisplayText(screenReaderName)
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
/**
* Constructs a ListOption.
*
* @param id The [Id] of this ListOption, must be unique within the
* [ListUserStyleSetting].
* @param resources The [Resources] used to load [displayNameResourceId].
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI. This should be short, ideally < 20
* characters. Note if the resource string contains `%1$s` that will get replaced with
* the 1-based ordinal (1st, 2nd, 3rd etc...) of the ListOption in the list of
* ListOptions.
* @param icon [Icon] for use in the companion style selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size)
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@JvmOverloads
@Deprecated("Use a constructor that sets the screenReaderNameResourceId")
constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, emptyList()) {
displayNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId)
screenReaderNameInternal = null
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
/**
* Constructs a ListOption.
*
* @param id The [Id] of this ListOption, must be unique within the
* [ListUserStyleSetting].
* @param resources The [Resources] used to load [displayNameResourceId].
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI. This should be short, ideally < 20
* characters.
* @param icon [Icon] for use in the style selection UI. This gets sent to the companion
* over bluetooth and should be small (ideally a few kb in size).
* @param childSettings The list of child [UserStyleSetting]s, which may be empty. Any
* child settings must be listed in [UserStyleSchema.userStyleSettings].
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@Deprecated("Use a constructor that sets the screenReaderNameResourceId")
constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
icon: Icon?,
childSettings: Collection<UserStyleSetting> = emptyList(),
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, childSettings) {
displayNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId)
screenReaderNameInternal = null
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
/**
* Constructs a ListOption.
*
* @param id The [Id] of this ListOption, must be unique within the
* [ListUserStyleSetting].
* @param resources The [Resources] used to load [displayNameResourceId].
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI. This should be short, ideally < 20
* characters. Note if the resource string contains `%1$s` that will get replaced with
* the 1-based ordinal (1st, 2nd, 3rd etc...) of the ListOption in the list of
* ListOptions.
* @param screenReaderNameResourceId String resource id for a human readable name for
* the element, used by screen readers. This should be more descriptive than
* [displayNameResourceId]. Note if the resource string contains `%1$s` that will get
* replaced with the 1-based ordinal (1st, 2nd, 3rd etc...) of the ListOption in the
* list of ListOptions. Note prior to android T this is ignored by companion editors.
* @param icon [Icon] for use in the style selection UI. This gets sent to the companion
* over bluetooth and should be small (ideally a few kb in size).
* @param childSettings The list of child [UserStyleSetting]s, which may be empty. Any
* child settings must be listed in [UserStyleSchema.userStyleSettings].
* @param watchFaceEditorData Optional data for an on watch face editor, this will not
* be sent to the companion and its contents may be used in preference to other fields
* by an on watch face editor.
*/
@JvmOverloads
constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes screenReaderNameResourceId: Int,
icon: Icon?,
childSettings: Collection<UserStyleSetting> = emptyList(),
watchFaceEditorData: WatchFaceEditorData? = null
) : super(id, childSettings) {
displayNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId)
screenReaderNameInternal =
DisplayText.ResourceDisplayTextWithIndex(resources, screenReaderNameResourceId)
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
internal constructor(
id: Id,
displayName: DisplayText,
screenReaderName: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
childSettings: Collection<UserStyleSetting> = emptyList()
) : super(id, childSettings) {
displayNameInternal = displayName
screenReaderNameInternal = screenReaderName
this.icon = icon
this.watchFaceEditorData = watchFaceEditorData
}
internal constructor(
wireFormat: ListOptionWireFormat
) : super(Id(wireFormat.mId), ArrayList()) {
displayNameInternal = DisplayText.CharSequenceDisplayText(wireFormat.mDisplayName)
screenReaderNameInternal = null // This will get overwritten.
icon = wireFormat.mIcon
watchFaceEditorData = null // This gets overwritten.
}
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
ListUserStyleSetting::class.java
internal override fun estimateWireSizeInBytesAndValidateIconDimensions(
context: Context,
@Px maxWidth: Int,
@Px maxHeight: Int
): Int {
var sizeEstimate = id.value.size + displayName.length
screenReaderName?.let { sizeEstimate + it.length }
icon?.getWireSizeAndDimensions(context)?.let { wireSizeAndDimensions ->
wireSizeAndDimensions.wireSizeBytes?.let { sizeEstimate += it }
require(
wireSizeAndDimensions.width <= maxWidth &&
wireSizeAndDimensions.height <= maxHeight
) {
"ListOption id $id has a ${wireSizeAndDimensions.width} x " +
"${wireSizeAndDimensions.height} icon. This is too big, the maximum " +
"size is $maxWidth x $maxHeight."
}
}
return sizeEstimate
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): ListOptionWireFormat =
ListOptionWireFormat(id.value, displayName, icon)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
displayNameInternal.write(dos)
screenReaderNameInternal?.write(dos)
icon?.write(dos)
watchFaceEditorData?.write(dos)
}
internal companion object {
@SuppressLint("ResourceType")
fun inflate(
resources: Resources,
parser: XmlResourceParser,
idToSetting: Map<String, UserStyleSetting>
): ListOption {
val id = getStringRefAttribute(resources, parser, "id")
require(id != null) { "ListOption must have an id" }
val displayName =
createDisplayText(
resources,
parser,
"displayName",
indexedResourceNamesSupported = true
)
val screenReaderName =
createDisplayText(
resources,
parser,
"nameForScreenReaders",
defaultValue = displayName,
indexedResourceNamesSupported = true
)
val icon = createIcon(resources, parser)
var watchFaceEditorData: WatchFaceEditorData? = null
val childSettings = ArrayList<UserStyleSetting>()
parser.iterate {
when (parser.name) {
"ChildSetting" -> {
val childId = getStringRefAttribute(resources, parser, "id")
require(childId != null) { "ChildSetting must have an id" }
val setting = idToSetting[childId]
require(setting != null) {
"Unknown ChildSetting id $childId, note only backward " +
"references are supported."
}
childSettings.add(setting)
}
"OnWatchEditorData" -> {
if (watchFaceEditorData == null) {
watchFaceEditorData =
WatchFaceEditorData.inflate(resources, parser)
} else {
throw IllegalNodeException(parser)
}
}
else -> throw IllegalNodeException(parser)
}
}
return ListOption(
Id(id),
displayName,
screenReaderName,
icon,
watchFaceEditorData,
childSettings
)
}
}
}
}
/**
* A LongRangeUserStyleSetting represents a setting with a [Long] value in the range
* [minimumValue .. maximumValue].
*/
public class LongRangeUserStyleSetting : UserStyleSetting {
internal companion object {
internal fun createOptionsList(
minimumValue: Long,
maximumValue: Long,
defaultValue: Long
): List<LongRangeOption> {
require(minimumValue < maximumValue)
require(defaultValue >= minimumValue)
require(defaultValue <= maximumValue)
return if (defaultValue != minimumValue && defaultValue != maximumValue) {
listOf(
LongRangeOption(minimumValue),
LongRangeOption(defaultValue),
LongRangeOption(maximumValue)
)
} else {
listOf(LongRangeOption(minimumValue), LongRangeOption(maximumValue))
}
}
@SuppressLint("ResourceType")
fun inflate(
resources: Resources,
parser: XmlResourceParser
): LongRangeUserStyleSetting {
val settingType = "LongRangeUserStyleSetting"
val parent = createParent(resources, parser, settingType, ::inflate)
val maxInteger =
getAttributeChecked(
parser,
"maxLong",
String::toLong,
parent?.maximumValue,
settingType
)
val minInteger =
getAttributeChecked(
parser,
"minLong",
String::toLong,
parent?.minimumValue,
settingType
)
val defaultInteger =
getAttributeChecked(
parser,
"defaultLong",
String::toLong,
parent?.defaultValue,
settingType
)
val params = createBaseWithParent(resources, parser, parent, inflateDefault = false)
return LongRangeUserStyleSetting(
params.id,
params.displayName,
params.description,
params.icon,
params.watchFaceEditorData,
minInteger,
maxInteger,
params.affectedWatchFaceLayers,
defaultInteger
)
}
}
/**
* Constructs a LongRangeUserStyleSetting.
*
* @param id [Id] for the element, must be unique.
* @param displayName Localized human readable name for the element, used in the userStyle
* selection UI.
* @param description Localized description string displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param minimumValue Minimum value (inclusive).
* @param maximumValue Maximum value (inclusive).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this LongRangeUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@JvmOverloads
public constructor(
id: Id,
displayName: CharSequence,
description: CharSequence,
icon: Icon?,
minimumValue: Long,
maximumValue: Long,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Long,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.CharSequenceDisplayText(displayName),
DisplayText.CharSequenceDisplayText(description),
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
/**
* Constructs a LongRangeUserStyleSetting where [LongRangeUserStyleSetting.displayName] and
* [LongRangeUserStyleSetting.description] are specified as resources.
*
* @param id [Id] for the element, must be unique.
* @param resources The [Resources] from which [displayNameResourceId] and
* [descriptionResourceId] are loaded.
* @param displayNameResourceId String resource id for a human readable name for the
* element, used in the userStyle selection UI.
* @param descriptionResourceId String resource id for a human readable description string
* displayed under the displayName.
* @param icon [Icon] for use in the companion userStyle selection UI. This gets sent to the
* companion over bluetooth and should be small (ideally a few kb in size).
* @param minimumValue Minimum value (inclusive).
* @param maximumValue Maximum value (inclusive).
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value for this LongRangeUserStyleSetting.
* @param watchFaceEditorData Optional data for an on watch face editor, this will not be
* sent to the companion and its contents may be used in preference to other fields by an
* on watch face editor.
*/
@JvmOverloads
public constructor(
id: Id,
resources: Resources,
@StringRes displayNameResourceId: Int,
@StringRes descriptionResourceId: Int,
icon: Icon?,
minimumValue: Long,
maximumValue: Long,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Long,
watchFaceEditorData: WatchFaceEditorData? = null
) : super(
id,
DisplayText.ResourceDisplayTextWithIndex(resources, displayNameResourceId),
DisplayText.ResourceDisplayTextWithIndex(resources, descriptionResourceId),
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
internal constructor(
id: Id,
displayName: DisplayText,
description: DisplayText,
icon: Icon?,
watchFaceEditorData: WatchFaceEditorData?,
minimumValue: Long,
maximumValue: Long,
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: Long
) : super(
id,
displayName,
description,
icon,
watchFaceEditorData,
createOptionsList(minimumValue, maximumValue, defaultValue),
// The index of defaultValue can only ever be 0 or 1.
when (defaultValue) {
minimumValue -> 0
else -> 1
},
affectsWatchFaceLayers
)
internal constructor(wireFormat: LongRangeUserStyleSettingWireFormat) : super(wireFormat)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): LongRangeUserStyleSettingWireFormat =
LongRangeUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
defaultOptionIndex,
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
/* optionsOnWatchFaceEditorIcons = */ null
)
/** Represents an option a [Long] in the range [minimumValue .. maximumValue]. */
public class LongRangeOption : Option {
/* The value for this option. Must be within the range [minimumValue..maximumValue]. */
public val value: Long
/**
* Constructs a LongRangeOption.
*
* @param value The value of this LongRangeOption
*/
public constructor(
value: Long
) : super(
Id(ByteArray(8).apply { ByteBuffer.wrap(this).putLong(value) }),
emptyList()
) {
this.value = value
}
internal constructor(
wireFormat: LongRangeOptionWireFormat
) : super(Id(wireFormat.mId), emptyList()) {
value = ByteBuffer.wrap(wireFormat.mId).long
}
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
LongRangeUserStyleSetting::class.java
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): LongRangeOptionWireFormat =
LongRangeOptionWireFormat(id.value)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
dos.writeLong(value)
}
override fun toString(): String = value.toString()
}
/** The minimum value. */
public val minimumValue: Long
get() = (options.first() as LongRangeOption).value
/** The maximum value. */
public val maximumValue: Long
get() = (options.last() as LongRangeOption).value
/** The default value. */
public val defaultValue: Long
get() = (options[defaultOptionIndex] as LongRangeOption).value
/** We support all values in the range [min ... max] not just min & max. */
override fun getOptionForId(optionId: Option.Id): Option =
options.find { it.id.value.contentEquals(optionId.value) }
?: checkedOptionForId(optionId.value)
private fun checkedOptionForId(optionId: ByteArray): LongRangeOption {
return try {
val value = ByteBuffer.wrap(optionId).long
if (value < minimumValue || value > maximumValue) {
options[defaultOptionIndex] as LongRangeOption
} else {
LongRangeOption(value)
}
} catch (e: Exception) {
options[defaultOptionIndex] as LongRangeOption
}
}
}
/**
* An application specific style setting. This style is ignored by the system editor. This is
* expected to be used in conjunction with an on watch face editor. Only a single
* [ComplicationSlotsUserStyleSetting] or [LargeCustomValueUserStyleSetting] is permitted in the
* [UserStyleSchema].
*
* The [CustomValueOption] can store at most [Option.Id.MAX_LENGTH] bytes. If you need more
* storage, consider using [LargeCustomValueUserStyleSetting].
*/
public class CustomValueUserStyleSetting : UserStyleSetting {
internal companion object {
internal const val CUSTOM_VALUE_USER_STYLE_SETTING_ID = "CustomValue"
}
/**
* Constructs a CustomValueUserStyleSetting.
*
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value [ByteArray].
*/
public constructor(
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: ByteArray
) : super(
Id(CUSTOM_VALUE_USER_STYLE_SETTING_ID),
DisplayText.CharSequenceDisplayText(""),
DisplayText.CharSequenceDisplayText(""),
null,
null,
listOf(CustomValueOption(defaultValue)),
0,
affectsWatchFaceLayers
)
internal constructor(wireFormat: CustomValueUserStyleSettingWireFormat) : super(wireFormat)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): CustomValueUserStyleSettingWireFormat =
CustomValueUserStyleSettingWireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
/* optionsOnWatchFaceEditorIcons = */ null
)
/**
* An application specific custom value. NB the [CustomValueOption.customValue] is the same
* as the [CustomValueOption.id].
*/
public class CustomValueOption : Option {
/**
* The [ByteArray] value for this option which is the same as the [id]. Note the maximum
* size in bytes is [Option.Id.MAX_LENGTH].
*/
public val customValue: ByteArray
get() = id.value
/**
* Constructs a CustomValueOption.
*
* @param customValue The [ByteArray] [id] and value of this CustomValueOption. This may
* not exceed [Option.Id.MAX_LENGTH].
*/
public constructor(customValue: ByteArray) : super(Id(customValue), emptyList())
internal constructor(
wireFormat: CustomValueOptionWireFormat
) : super(Id(wireFormat.mId), emptyList())
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
CustomValueUserStyleSetting::class.java
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): CustomValueOptionWireFormat =
CustomValueOptionWireFormat(id.value)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
}
}
override fun getOptionForId(optionId: Option.Id): Option =
options.find { it.id.value.contentEquals(optionId.value) }
?: CustomValueOption(optionId.value)
}
/**
* An application specific style setting which supports a larger maximum size than
* [CustomValueUserStyleSetting]. This style is ignored by the system editor. This is expected
* to be used in conjunction with an on watch face editor. Only a single
* [ComplicationSlotsUserStyleSetting] or [LargeCustomValueUserStyleSetting] is permitted in the
* [UserStyleSchema].
*
* The [CustomValueOption] can store at most [Option.Id.MAX_LENGTH] bytes.
*/
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public class LargeCustomValueUserStyleSetting : UserStyleSetting {
internal companion object {
internal const val CUSTOM_VALUE_USER_STYLE_SETTING_ID = "CustomValue"
}
/**
* Constructs a LargeCustomValueUserStyleSetting.
*
* @param affectsWatchFaceLayers Used by the style configuration UI. Describes which watch
* face rendering layers this style affects.
* @param defaultValue The default value [ByteArray].
*/
public constructor(
affectsWatchFaceLayers: Collection<WatchFaceLayer>,
defaultValue: ByteArray
) : super(
Id(CUSTOM_VALUE_USER_STYLE_SETTING_ID),
DisplayText.CharSequenceDisplayText(""),
DisplayText.CharSequenceDisplayText(""),
null,
null,
listOf(CustomValueOption(defaultValue)),
0,
affectsWatchFaceLayers
)
internal constructor(wireFormat: CustomValueUserStyleSetting2WireFormat) : super(wireFormat)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): CustomValueUserStyleSetting2WireFormat =
CustomValueUserStyleSetting2WireFormat(
id.value,
displayName,
description,
icon,
getWireFormatOptionsList(),
affectedWatchFaceLayers.map { it.ordinal },
watchFaceEditorData?.toWireFormat(),
/* optionsOnWatchFaceEditorIcons = */ null
)
/**
* An application specific custom value. NB the [CustomValueOption.customValue] is the same
* as the [CustomValueOption.id].
*/
public class CustomValueOption : Option {
/**
* The [ByteArray] value for this option which is the same as the [id]. Note the maximum
* size in bytes is [MAX_SIZE].
*/
public val customValue: ByteArray
get() = id.value
/**
* Constructs a CustomValueOption.
*
* @param customValue The [ByteArray] [id] and value of this CustomValueOption. This may
* not exceed [Option.Id.MAX_LENGTH].
*/
public constructor(customValue: ByteArray) : super(Id(customValue), emptyList())
internal constructor(
wireFormat: CustomValueOption2WireFormat
) : super(Id(wireFormat.mId), emptyList())
internal override fun getUserStyleSettingClass(): Class<out UserStyleSetting> =
LargeCustomValueUserStyleSetting::class.java
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
override fun toWireFormat(): CustomValueOption2WireFormat =
CustomValueOption2WireFormat(id.value)
override fun write(dos: DataOutputStream) {
dos.write(id.value)
}
public companion object {
/**
* The maximum size of [customValue] in bytes. This is based on the following
* assumptions: 2mbps bluetooth bandwidth and a 50 millisecond transfer time (above
* 50ms delays become quite noticeable).
*/
public const val MAX_SIZE: Int = 125000
}
override fun getMaxIdSizeBytes(): Int = CustomValueOption.MAX_SIZE
}
override fun getOptionForId(optionId: Option.Id): Option =
options.find { it.id.value.contentEquals(optionId.value) }
?: CustomValueOption(optionId.value)
}
}
internal fun requireUniqueOptionIds(
setting: UserStyleSetting.Id,
options: List<UserStyleSetting.Option>
) {
val uniqueIds = HashSet<UserStyleSetting.Option.Id>()
for (option in options) {
require(uniqueIds.add(option.id)) { "duplicated option id: ${option.id} in $setting" }
}
}
internal class WireSizeAndDimensions(val wireSizeBytes: Int?, val width: Int, val height: Int)
@RequiresApi(Build.VERSION_CODES.P)
internal class IconHelper {
internal companion object {
@SuppressLint("ResourceType")
fun getWireSizeAndDimensions(icon: Icon, context: Context): WireSizeAndDimensions? {
when (icon.type) {
Icon.TYPE_RESOURCE -> {
return getWireSizeAndDimensionsFromStream(
context.resources.openRawResource(icon.resId, TypedValue()),
context.resources
)
}
Icon.TYPE_URI -> {
if (icon.uri.scheme == ContentResolver.SCHEME_CONTENT) {
context.contentResolver.openInputStream(icon.uri)?.let {
return getWireSizeAndDimensionsFromStream(it, context.resources)
}
}
}
Icon.TYPE_URI_ADAPTIVE_BITMAP -> {
if (icon.uri.scheme == ContentResolver.SCHEME_CONTENT) {
context.contentResolver.openInputStream(icon.uri)?.let {
return getWireSizeAndDimensionsFromStream(it, context.resources)
}
}
}
}
return null
}
fun writeToDataOutputStream(icon: Icon, dos: DataOutputStream) {
dos.writeInt(icon.type)
when (icon.type) {
Icon.TYPE_RESOURCE -> {
dos.writeInt(icon.resId)
dos.writeUTF(icon.resPackage)
}
Icon.TYPE_URI -> dos.writeUTF(icon.uri.toString())
Icon.TYPE_URI_ADAPTIVE_BITMAP -> dos.writeUTF(icon.uri.toString())
}
// Unsupported cases are ignored, as a fallback we could load the icon drawable and
// convert to a png but that requires a context and is computationally expensive.
}
}
}
internal fun Icon.getWireSizeAndDimensions(context: Context): WireSizeAndDimensions {
// Where possible use the exact wire size.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val wireSizeAndDimensions = IconHelper.getWireSizeAndDimensions(this, context)
if (wireSizeAndDimensions != null) {
return wireSizeAndDimensions
}
}
// Fall back to loading the full drawable (comparatively expensive). We can't provide the
// wire size in this instance.
val drawable = loadDrawable(context)!!
return WireSizeAndDimensions(null, drawable.minimumWidth, drawable.minimumHeight)
}
@SuppressLint("ClassVerificationFailure")
internal fun Icon.write(dos: DataOutputStream) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
IconHelper.writeToDataOutputStream(this, dos)
}
}
private fun getWireSizeAndDimensionsFromStream(
stream: InputStream,
resources: Resources
): WireSizeAndDimensions {
try {
val wireSize = stream.available()
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeResourceStream(resources, TypedValue(), stream, null, options)
return WireSizeAndDimensions(wireSize, options.outWidth, options.outHeight)
} finally {
stream.close()
}
}
/**
* Gets the attribute specified by name. If there is no such attribute, applies defaultValue. Throws
* exception if calculated result is null.
*/
private fun <T> getAttributeChecked(
parser: XmlResourceParser,
name: String,
converter: (String) -> T,
defaultValue: T?,
settingType: String
): T {
return if (parser.hasValue(name)) {
converter(parser.getAttributeValue(NAMESPACE_APP, name)!!)
} else {
defaultValue ?: throw IllegalArgumentException("$name is required for $settingType")
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun getStringRefAttribute(resources: Resources, parser: XmlResourceParser, name: String): String? {
return if (parser.hasValue(name)) {
val resId = parser.getAttributeResourceValue(NAMESPACE_APP, name, 0)
if (resId == 0) {
parser.getAttributeValue(NAMESPACE_APP, name)
} else {
resources.getString(resId)
}
} else null
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun getIntRefAttribute(resources: Resources, parser: XmlResourceParser, name: String): Int? {
return if (parser.hasValue(name)) {
val resId = parser.getAttributeResourceValue(NAMESPACE_APP, name, 0)
if (resId == 0) {
parser.getAttributeValue(NAMESPACE_APP, name).toInt()
} else {
resources.getInteger(resId)
}
} else null
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun XmlPullParser.moveToStart(expectedNode: String) {
var type: Int
do {
type = next()
} while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG)
require(name == expectedNode) { "Expected a $expectedNode node but is $name" }
}
/** Converts 0 to null. Since 0 is never a valid resource id. */
internal fun Int.asResourceId(): Int? = if (this == 0) null else this
| 6 | null | 984 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 140,622 | androidx | Apache License 2.0 |
app/src/main/java/com/matthew/carvalhodagenais/coinhuntingbuddy/ui/components/FindListItem.kt | mcd-3 | 474,478,959 | false | {"Kotlin": 242534} | package com.matthew.carvalhodagenais.coinhuntingbuddy.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.matthew.carvalhodagenais.coinhuntingbuddy.R
import com.matthew.carvalhodagenais.coinhuntingbuddy.data.entities.Find
import com.matthew.carvalhodagenais.coinhuntingbuddy.utils.DateToStringConverter
import com.matthew.carvalhodagenais.coinhuntingbuddy.utils.FindStringGenerator
import com.matthew.carvalhodagenais.coinhuntingbuddy.viewmodels.MainActivityViewModel
@Composable
fun FindListItem(
find: Find,
viewModel: MainActivityViewModel,
onClick: () -> Unit,
) {
val strArray = FindStringGenerator.generate(
context = LocalContext.current,
year = find.year,
mintMark = find.mintMark,
error = find.error,
variety = find.variety,
)
Column(
modifier = Modifier
.clickable { onClick() }
.padding(top = 4.dp, bottom = 4.dp)
) {
val rowPadding = 16.dp
Row(modifier = Modifier.padding(start = rowPadding)) {
val grade = viewModel
.getGradeById(find.gradeId!!)
.observeAsState()
Text(text = "${strArray[0]} - ${grade.value?.code}")
}
Row(
modifier = Modifier
.padding(
start = rowPadding,
bottom = 8.dp
)
) {
if (strArray[1] == stringResource(id = R.string.no_varieties_or_errors_label)) {
Text(
text = strArray[1],
fontStyle = FontStyle.Italic,
fontSize = 14.sp
)
} else {
Text(text = strArray[1], fontSize = 14.sp)
}
}
Row(
modifier = Modifier
.padding(
start = rowPadding,
end = rowPadding
)
) {
val dateHunted = viewModel
.getDateHuntedForFind(find.huntId)
.observeAsState()
val coinTypeName = viewModel
.getCoinTypeNameById(find.coinTypeId)
.observeAsState()
Column(modifier = Modifier.weight(1f)) {
HalfBoldLabel(
first = stringResource(id = R.string.date_hunted_half_label),
second = if (dateHunted.value == null) {
""
} else {
DateToStringConverter.getString(dateHunted.value!!)
},
fontSize = 16,
modifier = Modifier
)
}
Column(
modifier = Modifier.weight(0.5f),
horizontalAlignment = Alignment.End
) {
Text(
text = if (coinTypeName.value == null) {
""
} else {
coinTypeName.value!!
},
textAlign = TextAlign.End,
fontSize = 12.sp,
color = Color.Gray,
modifier = Modifier.padding(top = 4.dp)
)
}
}
}
} | 4 | Kotlin | 0 | 1 | af1eec1593abdef3c83a85cb398093d4f9c29f0e | 3,931 | coin-hunting-buddy | MIT License |
embrace-test-fakes/src/main/kotlin/io/embrace/android/embracesdk/fakes/FakeTracerBuilder.kt | embrace-io | 704,537,857 | false | {"Kotlin": 2807710, "C": 190147, "Java": 175321, "C++": 13140, "CMake": 4261} | package io.embrace.android.embracesdk.fakes
import io.embrace.android.embracesdk.internal.opentelemetry.TracerKey
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.api.trace.TracerBuilder
public class FakeTracerBuilder(
public val instrumentationScopeName: String
) : TracerBuilder {
public var scopeVersion: String? = null
public var schema: String? = null
override fun setInstrumentationVersion(instrumentationScopeVersion: String): TracerBuilder {
scopeVersion = instrumentationScopeVersion
return this
}
override fun setSchemaUrl(schemaUrl: String): TracerBuilder {
schema = schemaUrl
return this
}
override fun build(): Tracer =
FakeTracer(
TracerKey(
instrumentationScopeName = instrumentationScopeName,
instrumentationScopeVersion = scopeVersion,
schemaUrl = schema
)
)
}
| 19 | Kotlin | 8 | 133 | c3d8b882d91f7200c812d8ffa2dee5b820263c0d | 952 | embrace-android-sdk | Apache License 2.0 |
library/src/main/java/com/herry/libs/draw/DrawView.kt | HerryPark | 273,154,769 | false | {"Kotlin": 1362527, "Java": 602} | package com.herry.libs.draw
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.graphics.ColorUtils
class DrawView : View {
private var paths = LinkedHashMap<DrawPath, PaintOption>()
private var lastPaths = LinkedHashMap<DrawPath, PaintOption>()
private var undonePaths =LinkedHashMap<DrawPath, PaintOption>()
private val paint = Paint()
private var path = DrawPath()
private var paintOption = PaintOption()
private var currentX = 0f
private var currentY = 0f
private var startX = 0f
private var startY = 0f
private var isSaving = false
private var isStrokeWidthBarEnabled = false
private var isEraserOn = false
constructor(context: Context): this(context, null)
constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0): super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
paint.apply {
this.color = paintOption.color
this.style = Paint.Style.STROKE
this.strokeJoin = Paint.Join.ROUND
this.strokeCap = Paint.Cap.ROUND
this.strokeWidth = paintOption.strokeWidth
this.isAntiAlias = true
}
}
fun canUndo(): Boolean {
if (paths.isEmpty() && lastPaths.isNotEmpty()) {
return true
}
if (paths.isNotEmpty()) {
return true
}
return false
}
fun undo() {
if (paths.isEmpty() && lastPaths.isNotEmpty()) {
@Suppress("UNCHECKED_CAST")
paths = lastPaths.clone() as LinkedHashMap<DrawPath, PaintOption>
lastPaths.clear()
invalidate()
return
}
if (paths.isEmpty()) {
return
}
val lastPath = paths.values.lastOrNull()
val lastKey = paths.keys.lastOrNull()
paths.remove(lastKey)
if (lastPath != null && lastKey != null) {
undonePaths[lastKey] = lastPath
}
invalidate()
}
fun canRedo(): Boolean {
return undonePaths.keys.isNotEmpty()
}
fun redo() {
if (!canRedo()) {
return
}
val lastKey = undonePaths.keys.last()
addPath(lastKey, undonePaths.values.last())
undonePaths.remove(lastKey)
invalidate()
}
fun hasDrawing(): Boolean {
return paths.isNotEmpty()
}
fun setColor(@ColorInt color: Int) {
paintOption.color = ColorUtils.setAlphaComponent(color, paintOption.alpha)
if (isStrokeWidthBarEnabled) {
invalidate()
}
}
@ColorInt fun getColor(): Int = paintOption.color
fun setAlpha(alpha: Int) {
paintOption.alpha = (alpha * 255) / 100
setColor(paintOption.color)
}
fun getStrokeWidth(): Float = paintOption.strokeWidth
fun setStrokeWidth(width: Float) {
paintOption.strokeWidth = width
if (isStrokeWidthBarEnabled) {
invalidate()
}
}
fun getBitmap(): Bitmap? {
if (!hasDrawing()) {
return null
}
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE)
isSaving = true
draw(canvas)
isSaving = false
return bitmap
}
fun addPath(path: DrawPath, option: PaintOption) {
paths[path] = option
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for ((key, value) in paths) {
changePaint(value)
canvas.drawPath(key, paint)
}
changePaint(paintOption)
canvas.drawPath(path, paint)
}
private fun changePaint(paintOption: PaintOption) {
paint.color = if (paintOption.isEraserOn) Color.WHITE else paintOption.color
paint.strokeWidth = paintOption.strokeWidth
}
fun clear() {
@Suppress("UNCHECKED_CAST")
lastPaths = paths.clone() as LinkedHashMap<DrawPath, PaintOption>
path.reset()
paths.clear()
invalidate()
}
private fun actionDown(x: Float, y: Float) {
path.reset()
path.moveTo(x, y)
currentX = x
currentY = y
}
private fun actionMove(x: Float, y: Float) {
path.quadTo(currentX, currentY, (x + currentX) / 2, (y + currentY) / 2)
currentX = x
currentY = y
}
private fun actionUp() {
path.lineTo(currentX, currentY)
// draw a dot on click
if (startX == currentX && startY == currentY) {
path.lineTo(currentX, currentY + 2)
path.lineTo(currentX + 1, currentY + 2)
path.lineTo(currentX + 1, currentY)
}
paths[path] = paintOption
path = DrawPath()
paintOption = PaintOption(
color = paintOption.color,
strokeWidth = paintOption.strokeWidth,
alpha = paintOption.alpha,
isEraserOn = paintOption.isEraserOn
)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
event ?: return false
val x = event.x
val y = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
startX = x
startY = y
actionDown(x, y)
undonePaths.clear()
}
MotionEvent.ACTION_MOVE -> {
actionMove(x, y)
}
MotionEvent.ACTION_UP -> {
actionUp()
}
}
invalidate()
return true
}
fun toggleEraser() {
isEraserOn = !isEraserOn
paintOption.isEraserOn = isEraserOn
invalidate()
}
fun isEraseOn() = this.isEraserOn
} | 0 | Kotlin | 0 | 0 | a0fdf428ef056565aa829597ee02d3c4a26608c9 | 6,201 | HerryApiDemo | Apache License 2.0 |
src/main/kotlin/com/yapp/giljob/domain/subquest/application/SubQuestService.kt | YAPP-19th | 399,059,024 | false | null | package com.yapp.giljob.domain.subquest.application
import com.yapp.giljob.domain.quest.domain.Quest
import com.yapp.giljob.domain.subquest.dao.SubQuestParticipationRepository
import com.yapp.giljob.domain.subquest.domain.SubQuest
import com.yapp.giljob.domain.subquest.dto.request.SubQuestRequestDto
import org.springframework.stereotype.Service
@Service
class SubQuestService(
private val subQuestParticipationRepository: SubQuestParticipationRepository
) {
fun convertToSubQuestList(quest: Quest, subQuestRequestList: List<SubQuestRequestDto>) =
subQuestRequestList.map {
SubQuest(quest = quest, name = it.name)
}
fun countCompletedSubQuest(questId: Long, participantId: Long) =
subQuestParticipationRepository.countByQuestIdAndParticipantIdAndIsCompletedTrue(questId, participantId)
} | 2 | Kotlin | 0 | 12 | 2a72cbf5f546537d0fd808e9e4d5c927163cf3d0 | 839 | Web-Team-1-Backend | Apache License 2.0 |
compiler/testData/diagnostics/tests/cast/IsRecursionSustainable.kt | JetBrains | 3,432,266 | false | null | open class RecA<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>RecB<T><!>()
open class RecB<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>RecA<T><!>()
open class SelfR<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>SelfR<T><!>()
fun test(f: SelfR<String>) = <!USELESS_IS_CHECK!>f is <!CANNOT_CHECK_FOR_ERASED!>RecA<String><!><!>
fun test(f: RecB<String>) = <!USELESS_IS_CHECK!>f is <!CANNOT_CHECK_FOR_ERASED!>RecA<String><!><!>
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 397 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/cast/IsRecursionSustainable.kt | JetBrains | 3,432,266 | false | null | open class RecA<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>RecB<T><!>()
open class RecB<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>RecA<T><!>()
open class SelfR<T>: <!CYCLIC_INHERITANCE_HIERARCHY!>SelfR<T><!>()
fun test(f: SelfR<String>) = <!USELESS_IS_CHECK!>f is <!CANNOT_CHECK_FOR_ERASED!>RecA<String><!><!>
fun test(f: RecB<String>) = <!USELESS_IS_CHECK!>f is <!CANNOT_CHECK_FOR_ERASED!>RecA<String><!><!>
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 397 | kotlin | Apache License 2.0 |
core/src/commonMain/kotlin/net/peanuuutz/tomlkt/internal/parser/TreeNode.kt | Peanuuutz | 444,688,345 | false | null | /*
Copyright 2023 Peanuuutz
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.peanuuutz.tomlkt.internal.parser
import net.peanuuutz.tomlkt.TomlElement
import net.peanuuutz.tomlkt.internal.Path
internal sealed class TreeNode(val key: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as TreeNode
return key == other.key
}
override fun hashCode(): Int {
return key.hashCode()
}
}
internal class KeyNode(
key: String,
val isLast: Boolean
) : TreeNode(key) {
val children: MutableMap<String, TreeNode> = mutableMapOf()
fun add(node: TreeNode) {
children[node.key] = node
}
operator fun get(key: String): TreeNode? {
return children[key]
}
}
internal class ArrayNode(key: String) : TreeNode(key) {
val children: MutableList<KeyNode> = mutableListOf()
fun add(node: KeyNode) {
children.add(node)
}
operator fun get(index: Int): KeyNode {
return children[index]
}
}
internal class ValueNode(
key: String,
val element: TomlElement
) : TreeNode(key)
// -------- Extensions --------
internal fun KeyNode.addByPath(
path: Path,
node: TreeNode,
arrayOfTableIndices: Map<Path, Int>?
): Boolean {
return addByPathRecursively(path, node, arrayOfTableIndices, 0)
}
private tailrec fun KeyNode.addByPathRecursively(
path: Path,
node: TreeNode,
arrayOfTableIndices: Map<Path, Int>?,
index: Int
): Boolean {
val child = get(path[index])
if (index == path.lastIndex) {
return when {
child == null -> {
add(node)
true
}
child !is KeyNode -> {
false
}
node !is KeyNode -> {
false
}
else -> {
// If false, this table is a super-table after a sub-table.
child.isLast.not()
}
}
}
return when (child) {
null -> {
val intermediate = KeyNode(path[index], isLast = node is ValueNode)
add(intermediate)
intermediate.addByPathRecursively(path, node, arrayOfTableIndices, index + 1)
}
is KeyNode -> {
child.addByPathRecursively(path, node, arrayOfTableIndices, index + 1)
}
is ArrayNode -> {
check(arrayOfTableIndices != null)
val currentPath = path.subList(0, index + 1)
val childIndex = arrayOfTableIndices[currentPath]!!
val grandChild = child[childIndex]
grandChild.addByPathRecursively(path, node, arrayOfTableIndices, index + 1)
}
is ValueNode -> {
false
}
}
}
internal fun <N : TreeNode> KeyNode.getByPath(
path: Path,
arrayOfTableIndices: Map<Path, Int>?
): N {
return getByPathRecursively(path, arrayOfTableIndices, 0)
}
private tailrec fun <N : TreeNode> KeyNode.getByPathRecursively(
path: Path,
arrayOfTableIndices: Map<Path, Int>?,
index: Int
): N {
val child = get(path[index])
if (index == path.lastIndex) {
@Suppress("UNCHECKED_CAST")
return child as? N ?: error("Node on $path not found")
}
return when (child) {
null, is ValueNode -> {
error("Node on $path not found")
}
is KeyNode -> {
child.getByPathRecursively(path, arrayOfTableIndices, index + 1)
}
is ArrayNode -> {
check(arrayOfTableIndices != null)
val currentPath = path.subList(0, index + 1)
val childIndex = arrayOfTableIndices[currentPath]!!
val grandChild = child[childIndex]
grandChild.getByPathRecursively(path, arrayOfTableIndices, index + 1)
}
}
}
| 3 | null | 3 | 95 | 35856a68678b96dda4b5f71a0cc391957c3e66b5 | 4,433 | tomlkt | Apache License 2.0 |
src/main/kotlin/de/flapdoodle/kfx/types/Key.kt | flapdoodle-oss | 451,526,335 | false | {"Kotlin": 998080, "Java": 154205, "CSS": 44422, "Shell": 297} | /*
* Copyright (C) 2022
* Michael Mosmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.flapdoodle.kfx.types
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import kotlin.reflect.KClass
interface Key<K: Any> {
fun type(): KClass<K>
data class ClassKey<K: Any>(val clazz: KClass<K>) : Key<K> {
override fun toString(): String {
return "Key(${clazz.simpleName})"
}
override fun type(): KClass<K> = clazz
}
companion object {
private val keyIdGeneratorMap = ConcurrentHashMap<Key<out Any>, AtomicInteger>()
private fun nextIdFor(key: Key<out Any>): Int {
return keyIdGeneratorMap.getOrPut(key) { AtomicInteger() }.incrementAndGet()
}
fun <T: Any> nextId(type:KClass<T>): Int {
return nextId(keyOf(type))
}
fun <T: Any> nextId(key: Key<T>): Int {
return nextIdFor(key)
}
fun <T: Any> keyOf(type: KClass<T>): Key<T> {
return ClassKey(type)
}
}
} | 0 | Kotlin | 1 | 0 | a97b72ffadf7847a3086454fbf7c2325a1b1daab | 1,540 | de.flapdoodle.kfx | Apache License 2.0 |
libs/shape/src/main/kotlin/mono/shape/extra/style/RectangleFillStyle.kt | tuanchauict | 325,686,408 | false | null | package mono.shape.extra.style
import mono.graphics.bitmap.drawable.Drawable
/**
* A class for defining a fill style for rectangle.
*
* @param id is the key for retrieving predefined [RectangleFillStyle] when serialization.
* @param displayName is the text visible on the UI tool for selection.
*/
class RectangleFillStyle(
val id: String,
val displayName: String,
val drawable: Drawable
)
| 15 | Kotlin | 9 | 91 | 21cef26b45c984eee31ea2c3ba769dfe5eddd92e | 409 | MonoSketch | Apache License 2.0 |
app/src/main/kotlin/com/softteco/template/ui/components/PermissionDialog.kt | SoftTeco | 644,768,318 | false | {"Kotlin": 265161, "Shell": 354} | package com.softteco.template.ui.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.softteco.template.R
import com.softteco.template.ui.theme.AppTheme
@Composable
fun PermissionDialog(
modifier: Modifier = Modifier,
onRequestPermission: () -> Unit = {}
) {
var showWarningDialog by remember { mutableStateOf(true) }
if (showWarningDialog) {
AlertDialog(
modifier = modifier.fillMaxWidth(),
title = { Text(text = stringResource(id = R.string.notification_permission_title)) },
text = { Text(text = stringResource(id = R.string.notification_permission_description)) },
confirmButton = {
Button(
onClick = {
onRequestPermission()
showWarningDialog = false
},
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(
contentColor = Color.White
)
) { Text(text = stringResource(id = R.string.request_notification_permission)) }
},
onDismissRequest = { }
)
}
}
@Composable
fun RationaleDialog(modifier: Modifier = Modifier) {
var showWarningDialog by remember { mutableStateOf(true) }
if (showWarningDialog) {
AlertDialog(
modifier = modifier.fillMaxWidth(),
title = {
Text(
text = stringResource(id = R.string.notification_permission_title)
)
},
text = { Text(text = stringResource(id = R.string.notification_permission_description)) },
confirmButton = {
Button(
onClick = { showWarningDialog = false },
modifier = modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(
contentColor = Color.White
)
) { Text(text = stringResource(id = R.string.ok)) }
},
onDismissRequest = { showWarningDialog = false }
)
}
}
@Preview
@Composable
private fun Preview() {
AppTheme {
PermissionDialog {
}
}
}
| 6 | Kotlin | 7 | 7 | 2adda3282a15f09d7e5de588e6cf462b4f4bbf4e | 2,842 | AndroidAppTemplate | MIT License |
src/main/kotlin/git/semver/plugin/changelog/ChangeLogTexts.kt | jmongard | 248,187,973 | false | {"Kotlin": 90559} | package git.semver.plugin.changelog
class ChangeLogTexts {
companion object {
const val HEADER = "#"
const val BREAKING_CHANGE = "!"
const val OTHER_CHANGE = "?"
}
val headerTexts = mutableMapOf(
HEADER to "## What's Changed",
BREAKING_CHANGE to "### Breaking Changes 🛠",
OTHER_CHANGE to "### Other Changes \uD83D\uDCA1",
"fix" to "### Bug Fixes \uD83D\uDC1E",
"feat" to "### New Features \uD83C\uDF89",
"test" to "### Tests ✅",
"docs" to "### Docs \uD83D\uDCD6",
"deps" to "### Dependency updates \uD83D\uDE80",
"build" to "### Build \uD83D\uDC18 & CI ⚙\uFE0F",
"ci" to "### Build \uD83D\uDC18 & CI ⚙\uFE0F",
"chore" to "### Chores \uD83D\uDD27",
"perf" to "### Performance Enhancements ⚡",
"refactor" to "### Refactorings \uD83D\uDE9C"
)
var header: String
get() = headerTexts[HEADER].orEmpty()
set(value) {
headerTexts[HEADER] = value
}
var footer: String = ""
var breakingChange
get() = headerTexts[BREAKING_CHANGE].orEmpty()
set(value) {
headerTexts[BREAKING_CHANGE] = value
}
var otherChange
get() = headerTexts[OTHER_CHANGE].orEmpty()
set(value) {
headerTexts[OTHER_CHANGE] = value
}
} | 4 | Kotlin | 4 | 27 | e98c52690876bcb3b70e0c8c61a715dbedb256f9 | 1,366 | Git.SemVersioning.Gradle | Apache License 2.0 |
app/src/main/java/dev/sdex/currencyexchanger/domain/model/Balance.kt | sdex | 735,589,378 | false | {"Kotlin": 46337} | package dev.sdex.currencyexchanger.domain.model
import java.math.BigDecimal
data class Balance(
val currency: String,
val amount: BigDecimal,
) | 0 | Kotlin | 0 | 0 | f321bd093e4035c82fbad6b99f37fda4be63b71d | 153 | CurrencyExchanger | MIT License |
step6/null1.kt | shilpasayura | 400,781,913 | false | null | fun main(args: Array<String>) {
var notNull : String = "Hello"
//notNull = null // not allowed
var len = notNull.length
println("Value is $notNull and length is ${notNull.length} ")
var mayBeNull : String?
mayBeNull = null // allowed
}
| 0 | Kotlin | 0 | 0 | d0898fef7231adc9c6661ab6f75f9020696d0600 | 265 | kotlin | MIT License |
web/src/main/kotlin/org/kotlinacademy/views/ErrorView.kt | MaurizioX | 113,477,274 | true | {"CSS": 389213, "Kotlin": 113380, "JavaScript": 5134, "HTML": 1738} | package org.kotlinacademy.views
import org.kotlinacademy.common.HttpError
import kotlinext.js.js
import kotlinx.html.style
import react.RBuilder
import react.ReactElement
import react.dom.div
import react.dom.h3
import react.dom.style
fun RBuilder.errorView(error: Throwable): ReactElement? = div(classes = "error") {
val message = if (error is HttpError) "Http ${error.code} error :(<br>Message: ${error.message}" else error.message.orEmpty()
h3(classes = "center-on-screen") { +message }
} | 0 | CSS | 0 | 2 | ff2ef2c3ec8aff0673077c350734435cf7ea6a39 | 501 | KotlinAcademyApp | Apache License 2.0 |
app/src/main/java/com/example/meuprimeiroprojeto/ResultActivity.kt | maiatiago | 596,355,613 | false | null | package com.example.meuprimeiroprojeto
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val tvResult = findViewById<TextView>(R.id.textview_result)
val tvClassificacao = findViewById<TextView>(R.id.textview_classificacao)
val result = intent.getFloatExtra("EXTRA_RESULT", 0.1f)
tvResult.text = result.toString()
/*
MENOR QUE 18,5 ABAIXO DO PESO
ENTRE 18,5 E 24,9 PESO NORMAL
ENTRE 25,0 E 29,0 EXCESSO DE PESO
ENTRE 30,0 E 34,9 OBESIDADE CLASSE I
ENTRE 35,0 E 39,9 OBESIDADE CLASSE II
MAIOR QUE 40,0 OBSEDIDADE GRAVE
*/
var classificacao = ""
if (result < 18.5f) {
classificacao = "ABAIXODO PESO"
} else if (result >= 18.5 && result <= 24.9) {
classificacao = "PESO NORMAL"
} else if (result >= 25 && result <= 29.9) {
classificacao = "EXCESSO DE PESO"
} else if (result >= 30 && result <= 34.9) {
classificacao = "OBESIDADE CLASSE I"
} else if (result >= 35 && result <= 39.9) {
classificacao = "OBESIDADE CLASSE II"
} else if (result >= 40) {
classificacao = "OBSEDIDADE GRAVE"
}
tvClassificacao.text = getString(R.string.message_classificacao, classificacao)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
finish()
return super.onOptionsItemSelected(item)
}
} | 0 | Kotlin | 0 | 0 | 5e9d08c0177fc54bdbac9a9fb03080dcf92101b1 | 1,804 | CalculadoraIMC | MIT License |
src/main/kotlin/net/devoev/vanilla_cubed/block/entity/beacon/upgrades/IncreaseXPDropUpgrade.kt | Devoev | 473,273,645 | false | {"Kotlin": 259348, "Java": 37528} | package net.devoev.vanilla_cubed.block.entity.beacon.upgrades
import net.devoev.vanilla_cubed.block.entity.beacon.upgrades.IncreaseXPDropUpgrade.INCREASE_XP
import net.minecraft.util.math.Vec3d
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable
/**
* Increases the XP drop of mobs by [INCREASE_XP].
*/
object IncreaseXPDropUpgrade : ToggledUpgrade() {
private const val INCREASE_XP = 1.5
/**
* Increases the XP drop
*/
fun increaseXP(pos: Vec3d, cir: CallbackInfoReturnable<Int>) {
if (inRange(pos)) cir.returnValue = (cir.returnValue * INCREASE_XP).toInt()
}
} | 0 | Kotlin | 2 | 1 | faad984d3da21910d0153a0a14b32666cf145751 | 627 | vanilla-cubed | MIT License |
app/src/main/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt | Aquaogen | 379,457,840 | false | null | /*
Copyright 2020 RethinkDNS and its 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 com.celzero.bravedns.adapter
import android.content.Context
import android.content.res.TypedArray
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.celzero.bravedns.R
import com.celzero.bravedns.database.ConnectionTracker
import com.celzero.bravedns.databinding.ConnectionTransactionRowBinding
import com.celzero.bravedns.glide.GlideApp
import com.celzero.bravedns.service.BraveVPNService
import com.celzero.bravedns.ui.ConnTrackerBottomSheetFragment
import com.celzero.bravedns.util.Constants
import com.celzero.bravedns.util.Constants.Companion.LOG_TAG
import com.celzero.bravedns.util.KnownPorts
import com.celzero.bravedns.util.Protocol
import com.celzero.bravedns.util.Utilities
import java.util.*
class ConnectionTrackerAdapter(val context: Context) : PagedListAdapter<ConnectionTracker, ConnectionTrackerAdapter.ConnectionTrackerViewHolder>(DIFF_CALLBACK) {
companion object {
private val DIFF_CALLBACK = object :
DiffUtil.ItemCallback<ConnectionTracker>() {
override fun areItemsTheSame(oldConnection: ConnectionTracker, newConnection: ConnectionTracker)
= oldConnection.id == newConnection.id
override fun areContentsTheSame(oldConnection: ConnectionTracker, newConnection: ConnectionTracker) = oldConnection == newConnection
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConnectionTrackerViewHolder {
val itemBinding = ConnectionTransactionRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ConnectionTrackerViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ConnectionTrackerViewHolder, position: Int) {
val connTracker: ConnectionTracker = getItem(position) ?: return
holder.update(connTracker)
}
inner class ConnectionTrackerViewHolder(private val b: ConnectionTransactionRowBinding) : RecyclerView.ViewHolder(b.root) {
fun update(connTracker: ConnectionTracker) {
val time = Utilities.convertLongToTime(connTracker.timeStamp)
b.connectionResponseTime.text = time
b.connectionFlag.text = connTracker.flag
b.connectionIpAddress.text = connTracker.ipAddress
// Instead of showing the port name and protocol, now the ports are resolved with
// known ports(reserved port and protocol identifiers).
// https://github.com/celzero/rethink-app/issues/42 - #3 - transport + protocol.
val resolvedPort = KnownPorts.resolvePort(connTracker.port)
if(resolvedPort != Constants.PORT_VAL_UNKNOWN){
b.connLatencyTxt.text = resolvedPort?.toUpperCase(Locale.ROOT)
}else {
b.connLatencyTxt.text = Protocol.getProtocolName(connTracker.protocol).name
}
b.connectionAppName.text = connTracker.appName
when {
connTracker.isBlocked -> {
b.connectionStatusIndicator.visibility = View.VISIBLE
b.connectionStatusIndicator.setBackgroundColor(ContextCompat.getColor(context, R.color.colorRed_A400))
}
connTracker.blockedByRule.equals(BraveVPNService.BlockedRuleNames.RULE7.ruleName) -> {
b.connectionStatusIndicator.visibility = View.VISIBLE
b.connectionStatusIndicator.setBackgroundColor(fetchTextColor(R.color.dividerColor))
}
else -> {
b.connectionStatusIndicator.visibility = View.INVISIBLE
}
}
if (connTracker.appName != "Unknown") {
try {
val appArray = context.packageManager.getPackagesForUid(connTracker.uid)
val appCount = (appArray?.size)?.minus(1)
if (appArray?.size!! > 2) {
b.connectionAppName.text = context.getString(R.string.ctbs_app_other_apps, connTracker.appName, appCount.toString())
} else if (appArray.size == 2) {
b.connectionAppName.text = context.getString(R.string.ctbs_app_other_app, connTracker.appName, appCount.toString())
}
GlideApp.with(context).load(context.packageManager.getApplicationIcon(appArray[0]!!)).error(AppCompatResources.getDrawable(context, R.drawable.default_app_icon)).into(b.connectionAppIcon)
} catch (e: Exception) {
GlideApp.with(context).load(AppCompatResources.getDrawable(context, R.drawable.default_app_icon)).error(AppCompatResources.getDrawable(context, R.drawable.default_app_icon)).into(b.connectionAppIcon)
Log.w(LOG_TAG, "Package Not Found - " + e.message)
}
} else {
GlideApp.with(context).load(AppCompatResources.getDrawable(context, R.drawable.default_app_icon)).error(AppCompatResources.getDrawable(context, R.drawable.default_app_icon)).into(b.connectionAppIcon)
}
b.connectionParentLayout.setOnClickListener {
b.connectionParentLayout.isEnabled = false
val bottomSheetFragment = ConnTrackerBottomSheetFragment(context, connTracker)
val frag = context as FragmentActivity
bottomSheetFragment.show(frag.supportFragmentManager, bottomSheetFragment.tag)
b.connectionParentLayout.isEnabled = true
}
}
private fun fetchTextColor(attr: Int): Int {
val attributeFetch = if (attr == R.color.dividerColor) {
R.attr.dividerColor
} else {
R.attr.accentGood
}
val typedValue = TypedValue()
val a: TypedArray = context.obtainStyledAttributes(typedValue.data, intArrayOf(attributeFetch))
val color = a.getColor(0, 0)
a.recycle()
return color
}
}
}
| 1 | null | 1 | 1 | a9bdd6d59b6d2e961fc478b78d90ade0fc67bca6 | 6,935 | redns | Apache License 2.0 |
src/main/kotlin/apibuilder/database/device/UpdateDeviceByIdItem.kt | BAC2-Graf-Rohatynski | 208,084,076 | false | null | package apibuilder.database.device
import apibuilder.database.device.item.DeviceItem
import apibuilder.database.header.DatabaseResponse
import apibuilder.database.header.Header
import apibuilder.database.interfaces.IDevice
import enumstorage.device.Device
import enumstorage.database.DatabaseCommand
import enumstorage.database.DatabaseType
import org.json.JSONArray
import org.json.JSONObject
class AddDeviceItem: IDevice, DatabaseResponse() {
lateinit var item: DeviceItem
fun create(item: DeviceItem): AddDeviceItem {
this.item = item
buildHeader()
return this
}
override fun getRequestId(): Int = header.requestId
override fun toJson(): String {
val body = item.toJson()
return encryptApiMessage(message = JSONArray()
.put(header.toJson())
.put(body))
}
override fun toObject(message: String): AddDeviceItem {
header = parseToHeaderObject(message = message)
val body = parseToBodyObject(message = message).last() as JSONObject
item = DeviceItem().build(
id = body.getInt(Device.Id.name),
deviceDe = body.getString(Device.DeviceDe.name),
deviceEn = body.getString(Device.DeviceEn.name),
isStandard = body.getBoolean(Device.IsStandard.name)
)
return this
}
override fun buildHeader() {
this.header = Header().build(
command = DatabaseCommand.AddDevice,
table = DatabaseType.Device
)
}
} | 0 | Kotlin | 0 | 0 | 1521a5c7bdd4fc2d6c021d4c28a292f1f1347529 | 1,561 | ApiBuilder | MIT License |
platforms/core-configuration/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/normalization/KotlinApiClassExtractor.kt | gradle | 302,322 | false | null | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.normalization
import kotlinx.metadata.Flag
import kotlinx.metadata.KmDeclarationContainer
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
import kotlinx.metadata.jvm.signature
import org.gradle.api.GradleException
import org.gradle.internal.normalization.java.ApiClassExtractor
import org.gradle.internal.normalization.java.impl.AnnotationMember
import org.gradle.internal.normalization.java.impl.ApiMemberWriter
import org.gradle.internal.normalization.java.impl.ArrayAnnotationValue
import org.gradle.internal.normalization.java.impl.ClassMember
import org.gradle.internal.normalization.java.impl.FieldMember
import org.gradle.internal.normalization.java.impl.InnerClassMember
import org.gradle.internal.normalization.java.impl.MethodMember
import org.gradle.internal.normalization.java.impl.MethodStubbingApiMemberAdapter
import org.gradle.internal.normalization.java.impl.SimpleAnnotationValue
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
class KotlinApiClassExtractor : ApiClassExtractor(
emptySet(),
{ classReader, classWriter ->
KotlinApiMemberWriter(
MethodStubbingApiMemberAdapter(classWriter),
MethodCopyingApiMemberAdapter(classReader, classWriter)
)
}
)
private
class KotlinApiMemberWriter(apiMemberAdapter: ClassVisitor, val inlineMethodWriter: MethodCopyingApiMemberAdapter) : ApiMemberWriter(apiMemberAdapter) {
val kotlinMetadataAnnotationSignature = "Lkotlin/Metadata;"
val inlineFunctions: MutableSet<String> = HashSet()
val internalFunctions: MutableSet<String> = HashSet()
override fun writeClass(classMember: ClassMember, methods: Set<MethodMember>, fields: Set<FieldMember>, innerClasses: Set<InnerClassMember>) {
classMember.annotations.firstOrNull {
it.name == kotlinMetadataAnnotationSignature
}?.let {
when (val kotlinMetadata = KotlinClassMetadata.read(parseKotlinClassHeader(it))) {
is KotlinClassMetadata.Class -> kotlinMetadata.toKmClass().extractFunctionMetadata()
is KotlinClassMetadata.FileFacade -> kotlinMetadata.toKmPackage().extractFunctionMetadata()
is KotlinClassMetadata.MultiFileClassPart -> kotlinMetadata.toKmPackage().extractFunctionMetadata()
is KotlinClassMetadata.MultiFileClassFacade -> {
// This metadata appears on a generated Java class resulting from @file:JvmName("ClassName") + @file:JvmMultiFileClass annotations in Kotlin scripts.
// The resulting facade class contains references to classes generated from each script pointing to this class.
// Each of those classes is visited separately and have KotlinClassMetadata.MultiFileClassPart on them
}
is KotlinClassMetadata.SyntheticClass -> {
}
is KotlinClassMetadata.Unknown -> {
throw GradleException("Unknown Kotlin metadata with kind: ${kotlinMetadata.header.kind} on class ${classMember.name} - don't know how to extract its API class")
}
}
}
super.writeClass(classMember, methods, fields, innerClasses)
}
override fun writeClassAnnotations(annotationMembers: Set<AnnotationMember>) {
super.writeClassAnnotations(annotationMembers.filter { it.name != kotlinMetadataAnnotationSignature }.toSet())
}
override fun writeMethod(method: MethodMember) {
when {
method.isInternal() -> return
method.isInline() -> inlineMethodWriter.writeMethod(method)
else -> super.writeMethod(method)
}
}
private
fun KmDeclarationContainer.extractFunctionMetadata() {
this.extractInternalFunctions()
this.extractInlineFunctions()
}
private
fun KmDeclarationContainer.extractInlineFunctions() {
inlineFunctions.addAll(
this.functions.asSequence()
.filter { Flag.Function.IS_INLINE(it.flags) }
.mapNotNull { it.signature?.asString() }
)
}
private
fun KmDeclarationContainer.extractInternalFunctions() {
internalFunctions.addAll(
this.functions.asSequence()
.filter { Flag.Common.IS_INTERNAL(it.flags) }
.mapNotNull { it.signature?.asString() }
)
}
private
fun parseKotlinClassHeader(kotlinMetadataAnnotation: AnnotationMember): KotlinClassHeader {
var kind: Int? = null
var metadataVersion: IntArray? = null
var bytecodeVersion: IntArray? = null
var data1: Array<String>? = null
var data2: Array<String>? = null
var extraString: String? = null
var packageName: String? = null
var extraInt: Int? = null
kotlinMetadataAnnotation.values.forEach {
// see Metadata.kt
when (it) {
is SimpleAnnotationValue ->
when (it.name) {
"k" -> kind = it.value as Int
"mv" -> metadataVersion = it.value as IntArray
"bv" -> bytecodeVersion = it.value as IntArray
"xs" -> extraString = it.value as String
"pn" -> packageName = it.value as String
"xi" -> extraInt = it.value as Int
}
is ArrayAnnotationValue ->
when (it.name) {
"d1" -> data1 = it.value.map { arrayItem -> arrayItem.value as String }.toTypedArray()
"d2" -> data2 = it.value.map { arrayItem -> arrayItem.value as String }.toTypedArray()
}
}
}
return KotlinClassHeader(kind, metadataVersion, bytecodeVersion, data1, data2, extraString, packageName, extraInt)
}
private
fun MethodMember.binarySignature() = this.name + this.typeDesc
private
fun MethodMember.isInternal() = internalFunctions.contains(this.binarySignature())
private
fun MethodMember.isInline() = inlineFunctions.contains(this.binarySignature())
}
private
class MethodCopyingApiMemberAdapter(val classReader: ClassReader, val classWriter: ClassWriter) {
fun writeMethod(method: MethodMember) {
classReader.accept(MethodCopyingVisitor(method, classWriter), ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
}
}
private
class MethodCopyingVisitor(val method: MethodMember, val classWriter: ClassWriter) : ClassVisitor(Opcodes.ASM7) {
override fun visitMethod(access: Int, name: String?, descriptor: String?, signature: String?, exceptions: Array<out String>?): MethodVisitor? {
if (method.access == access && method.name == name && method.typeDesc == descriptor && method.signature == signature) {
return classWriter.visitMethod(access, name, descriptor, signature, exceptions)
}
return super.visitMethod(access, name, descriptor, signature, exceptions)
}
}
| 4 | null | 4552 | 15,640 | 3fde2e4dd65124d0f3b2ef42f7e93446ccd7cced | 7,839 | gradle | Apache License 2.0 |
app/src/main/java/com/capan/truefalse/TrueFalseApplication.kt | Colibri91 | 532,779,054 | false | null | package com.capan.truefalse
import android.app.Application
import com.capan.truefalse.di.appModule
import com.capan.truefalse.di.firebaseModule
import com.capan.truefalse.di.questionModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin
import timber.log.Timber
import timber.log.Timber.Forest.plant
class TrueFalseApplication : Application() {
override fun onCreate() {
super.onCreate()
injectKoin()
injectTimber()
}
private fun injectKoin(){
startKoin{
androidLogger()
androidContext(this@TrueFalseApplication)
modules(appModule, questionModule, firebaseModule)
}
}
private fun injectTimber(){
if (BuildConfig.DEBUG) {
plant(Timber.DebugTree())
}
}
} | 0 | Kotlin | 0 | 0 | 0f2e15a1febde9f828ee9f884bc0c72b229e75ad | 886 | TrueFalseGameWithComposeAndStateFlow | Apache License 2.0 |
app/src/main/java/com/jayabreezefsm/features/dashboard/presentation/api/gteroutelistapi/GetRouteListRepo.kt | DebashisINT | 674,180,669 | false | {"Kotlin": 13478860, "Java": 994064} | package com.jayabreezefsm.features.dashboard.presentation.api.gteroutelistapi
import com.jayabreezefsm.app.Pref
import com.jayabreezefsm.features.dashboard.presentation.model.SelectedRouteListResponseModel
import io.reactivex.Observable
/**
* Created by Saikat on 03-12-2018.
*/
class GetRouteListRepo(val apiService: GetRouteListApi) {
fun routeList(): Observable<SelectedRouteListResponseModel> {
return apiService.getRouteList(Pref.session_token!!, Pref.user_id!!)
}
} | 0 | Kotlin | 0 | 0 | 0642af23a4db33e4a472cd194d09e6b81b2d369e | 491 | JayaIndustries | Apache License 2.0 |
src/main/java/com/tang/intellij/lua/debugger/remote/value/LuaRFunction.kt | Benjamin-Dobell | 231,814,734 | false | null | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.debugger.remote.value
import com.intellij.xdebugger.frame.XValueNode
import com.intellij.xdebugger.frame.XValuePlace
import com.tang.intellij.lua.lang.LuaIcons
import org.luaj.vm2.LuaValue
/**
*
* Created by tangzx on 2017/4/16.
*/
class LuaRFunction(name: String) : LuaRValue(name) {
private var type = "function"
private lateinit var data: String
override fun parse(data: LuaValue, desc: String) {
this.data = desc
}
override fun computePresentation(xValueNode: XValueNode, xValuePlace: XValuePlace) {
xValueNode.setPresentation(LuaIcons.LOCAL_FUNCTION, type, data, false)
}
}
| 61 | Kotlin | 9 | 83 | 68b0a63d3ddd5bc7be9ed304534b601fedcc8319 | 1,268 | IntelliJ-Luanalysis | Apache License 2.0 |
feature/src/main/java/com/tatsuki/purchasing/feature/model/AmazonPurchasedReceipt.kt | TatsukiIshijima | 669,807,579 | false | {"Kotlin": 68270} | package com.tatsuki.purchasing.feature.model
import com.amazon.device.iap.model.Receipt
import com.amazon.device.iap.model.UserData
data class AmazonPurchasedReceipt(
val userData: UserData,
val receipt: Receipt,
)
| 0 | Kotlin | 0 | 0 | 47674bcae07460ca9f84c57a980d6d3218c451a7 | 221 | amazon-purchasing | MIT License |
src/main/kotlin/logic/creep/tasks/LMTasksLogist.kt | Solovova | 273,570,019 | false | null | package logic.creep.tasks
import mainContext.MainContext
import mainContext.dataclass.TypeOfTask
import mainContext.dataclass.mainRoom
import mainContext.mainRoomCollecror.mainRoom.MainRoom
import mainContext.tasks.CreepTask
import screeps.api.*
import screeps.api.structures.StructureLink
import screeps.api.structures.StructureNuker
import screeps.api.structures.StructureStorage
import screeps.api.structures.StructureTerminal
import screeps.utils.toMap
import kotlin.math.min
class LMTasksLogist(val mc: MainContext) {
fun newTaskEmptyCreep(creep: Creep): Boolean {
val mainRoom: MainRoom = mc.mainRoomCollector.rooms[creep.memory.mainRoom] ?: return false
val storage: StructureStorage = mainRoom.structureStorage[0] ?: return false
if (creep.store.getUsedCapacity() != 0) {
val resTransfer = creep.store.toMap().filter { it.value != 0 }.toList().firstOrNull()
if (resTransfer != null) {
mc.tasks.add(creep.id, CreepTask(TypeOfTask.TransferTo, storage.id, storage.pos, resource = resTransfer.first, quantity = resTransfer.second))
return true
}
}
return false
}
private fun linkTransfer(creep: Creep, storage: StructureStorage, mainRoom: MainRoom): CreepTask? {
val link: StructureLink = mainRoom.structureLinkNearStorage[0] ?: return null
if (mainRoom.getLevelOfRoom() == 3
&& mainRoom.have[19] != 0
&& mainRoom.source.size == 1
&& link.store[RESOURCE_ENERGY] ?: 0 == 0) {
return CreepTask(TypeOfTask.Transport, storage.id, storage.pos, link.id, link.pos, RESOURCE_ENERGY, creep.store.getCapacity() ?: 0)
}
//Need for don't take mineral back to storage
if (mainRoom.getLevelOfRoom() == 3
&& mainRoom.have[19] != 0
&& mainRoom.source.size == 1) {
return null
}
if (link.store[RESOURCE_ENERGY] ?: 0 != 0) {
return CreepTask(TypeOfTask.Transport, link.id, link.pos, storage.id, storage.pos, RESOURCE_ENERGY, 0)
}
return null
}
private fun energyLogist(creep: Creep, storage: StructureStorage, terminal: StructureTerminal, mainRoom: MainRoom): CreepTask? {
var carry: Int
// 01 Terminal > 0 && Storage < this.constant.energyMinStorage
val needInStorage01: Int = mainRoom.constant.energyMinStorage - mainRoom.getResourceInStorage()
val haveInTerminal01: Int = mainRoom.getResourceInTerminal()
carry = min(min(needInStorage01, haveInTerminal01), creep.store.getCapacity() ?: 0)
if (carry > 0) return CreepTask(TypeOfTask.Transport, terminal.id, terminal.pos, storage.id, storage.pos, RESOURCE_ENERGY, carry)
// 02 Storage > this.constant.energyMaxStorage -> Terminal < this.constant.energyMaxTerminal
val needInTerminal02: Int = mainRoom.constant.energyMaxTerminal - mainRoom.getResourceInTerminal()
val haveInStorage02: Int = mainRoom.getResourceInStorage() - mainRoom.constant.energyMaxStorage
carry = min(min(haveInStorage02, needInTerminal02), creep.store.getCapacity() ?: 0)
if (carry > 0 && (carry == creep.store.getCapacity() || carry == needInTerminal02))
return CreepTask(TypeOfTask.Transport, storage.id, storage.pos, terminal.id, terminal.pos, RESOURCE_ENERGY, carry)
// 03 Storage > this.constant.energyMinStorage -> Terminal < this.constant.energyMinTerminal or this.constant.energyMaxTerminal if sent
val needInTerminal03: Int = if (mainRoom.constant.sentEnergyToRoom == "") mainRoom.constant.energyMinTerminal - mainRoom.getResourceInTerminal()
else mainRoom.constant.energyMaxTerminal - mainRoom.getResourceInTerminal()
val haveInStorage03: Int = mainRoom.getResourceInStorage() - mainRoom.constant.energyMinStorage
carry = min(min(needInTerminal03, haveInStorage03), creep.store.getCapacity() ?: 0)
if (carry > 0 && (carry == creep.store.getCapacity() || carry == needInTerminal03))
return CreepTask(TypeOfTask.Transport, storage.id, storage.pos, terminal.id, terminal.pos, RESOURCE_ENERGY, carry)
// 04 Terminal > this.constant.energyMinTerminal or this.constant.energyMaxTerminal if sent && Storage < this.constant.energyMaxStorageEmergency
val haveInTerminal04: Int = if (mainRoom.constant.sentEnergyToRoom == "") mainRoom.getResourceInTerminal() - mainRoom.constant.energyMinTerminal
else mainRoom.getResourceInTerminal() - mainRoom.constant.energyMaxTerminal
val needInStorage04: Int = mainRoom.constant.energyMaxStorage - mainRoom.getResourceInStorage()
carry = min(min(haveInTerminal04, needInStorage04), creep.store.getCapacity() ?: 0)
if (carry > 0)
return CreepTask(TypeOfTask.Transport, terminal.id, terminal.pos, storage.id, storage.pos, RESOURCE_ENERGY, carry)
return null
}
private fun mineralStorageToTerminal(creep: Creep, storage: StructureStorage, terminal: StructureTerminal, mainRoom: MainRoom): CreepTask? {
//Mineral work
//Storage -> Terminal this.constant.mineralMinTerminal but < this.constant.mineralAllMaxTerminal
var carry: Int
for (resInStorage in storage.store) {
if (resInStorage.component1() == RESOURCE_ENERGY) continue
val resourceStorage: ResourceConstant = resInStorage.component1()
val quantityStorage: Int = resInStorage.component2()
val quantityTerminal: Int = mainRoom.getResourceInTerminal(resourceStorage)
val needInTerminal = mainRoom.constant.mineralMinTerminal - quantityTerminal
val canMineralAllTerminal = mainRoom.constant.mineralAllMaxTerminal - (terminal.store.toMap().map { it.value }.sum()
- mainRoom.getResourceInTerminal(RESOURCE_ENERGY))
if (canMineralAllTerminal <= 0) mc.lm.lmMessenger.log("INFO", mainRoom.name, "Terminal mineral is full", COLOR_RED)
carry = min(min(min(needInTerminal, quantityStorage), creep.store.getCapacity() ?: 0), canMineralAllTerminal)
if (carry > 0)
return CreepTask(TypeOfTask.Transport, storage.id, storage.pos, terminal.id, terminal.pos, resourceStorage, carry)
}
return null
}
private fun fullNuker(creep: Creep, storage: StructureStorage, terminal: StructureTerminal, mainRoom: MainRoom, nuker: StructureNuker): CreepTask? {
val globNeedEnergy: Int = (mc.mineralData[RESOURCE_ENERGY]?.need ?: 0) - (mc.mineralData[RESOURCE_ENERGY]?.quantity ?: 0)
if (globNeedEnergy >0 ) return null
val needEnergy: Int = nuker.store.getFreeCapacity(RESOURCE_ENERGY) ?: 0
if (needEnergy != 0 && mainRoom.getResource(RESOURCE_ENERGY) > mainRoom.constant.energyUpgradeLvl8Controller) {
return CreepTask(TypeOfTask.Transport, storage.id, storage.pos, nuker.id, nuker.pos, RESOURCE_ENERGY,
min(creep.store.getCapacity() ?: 0,needEnergy))
}
val needG: Int = nuker.store.getFreeCapacity(RESOURCE_GHODIUM) ?: 0
if (needG != 0 && mainRoom.getResource(RESOURCE_GHODIUM) > 0) {
return CreepTask(TypeOfTask.Transport, terminal.id, terminal.pos, nuker.id, nuker.pos, RESOURCE_GHODIUM,
min(min(creep.store.getCapacity() ?: 0,needG),mainRoom.getResource(RESOURCE_GHODIUM)))
}
return null
}
private fun mineralTerminalToStorage(creep: Creep, storage: StructureStorage, terminal: StructureTerminal, mainRoom: MainRoom): CreepTask? {
//Terminal -> Storage all mineral > this.constant.mineralMinTerminal
var carry: Int
for (resInTerminal in terminal.store) {
if (resInTerminal.component1() == RESOURCE_ENERGY) continue
val resourceTerminal: ResourceConstant = resInTerminal.component1()
val quantityTerminal: Int = resInTerminal.component2()
val haveInTerminal = quantityTerminal - mainRoom.constant.mineralMinTerminal
carry = min(haveInTerminal, creep.store.getCapacity() ?: 0)
if (carry > 0)
return CreepTask(TypeOfTask.Transport, terminal.id, terminal.pos, storage.id, storage.pos, resourceTerminal, carry)
}
return null
}
fun newTaskLinkAndTerminalStorageBalance(creep: Creep): Boolean {
val mainRoom: MainRoom = mc.mainRoomCollector.rooms[creep.memory.mainRoom] ?: return false
val terminal: StructureTerminal = mainRoom.structureTerminal[0] ?: return false
val storage: StructureStorage = mainRoom.structureStorage[0] ?: return false
var creepTask: CreepTask? = null
if (creepTask == null) creepTask = this.linkTransfer(creep, storage, mainRoom)
if (creepTask == null) creepTask = this.energyLogist(creep, storage, terminal, mainRoom)
if (creepTask == null) creepTask = this.mineralStorageToTerminal(creep, storage, terminal, mainRoom)
if (creepTask == null) creepTask = this.mineralTerminalToStorage(creep, storage, terminal, mainRoom)
if (creepTask != null) {
mc.tasks.add(creep.id, creepTask)
return true
}
return false
}
fun newTaskNuke(creep: Creep): Boolean {
val mainRoom: MainRoom = mc.mainRoomCollector.rooms[creep.memory.mainRoom] ?: return false
if (!(mc.constants.globalConstant.nukerFilInRooms.isEmpty()
|| mainRoom.name in mc.constants.globalConstant.nukerFilInRooms)) return false
val terminal: StructureTerminal = mainRoom.structureTerminal[0] ?: return false
val storage: StructureStorage = mainRoom.structureStorage[0] ?: return false
val nuker: StructureNuker = mainRoom.structureNuker[0] ?: return false
var creepTask: CreepTask? = null
if (creepTask == null) creepTask = this.fullNuker(creep, storage, terminal, mainRoom, nuker)
if (creepTask != null) {
mc.tasks.add(creep.id, creepTask)
return true
}
return false
}
} | 0 | Kotlin | 0 | 0 | b9a4319d604fc7106f3c0bf43e49631227ae6449 | 10,136 | Screeps_KT | MIT License |
jipp-core/src/main/java/com/hp/jipp/trans/IppClientTransport.kt | HPInc | 129,298,798 | false | null | // Copyright 2017 HP Development Company, L.P.
// SPDX-License-Identifier: MIT
package com.hp.jipp.trans
import java.io.IOException
import java.net.URI
/** Transport used to send packets and collect responses from a IPP server */
interface IppClientTransport {
/**
* Deliver an IPP packet to the specified URL along with any additional data, and return the response
* packet (or throw an error).
*
* Note: implementations should check [Thread.interrupted] periodically and fail gracefully.
*/
@Throws(IOException::class)
fun sendData(uri: URI, request: IppPacketData): IppPacketData
}
| 7 | null | 40 | 99 | f1f96d5da88d24197e7b0f90eec4ceee0fe66550 | 626 | jipp | MIT License |
kotest-tests/kotest-tests-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/junit5/StringSpecExceptionInBeforeTest.kt | sw-samuraj | 234,562,169 | true | {"Kotlin": 1832333, "JavaScript": 457, "HTML": 423, "Java": 153, "Shell": 125} | package com.sksamuel.kotest.junit5
import io.kotest.core.test.TestCase
import io.kotest.shouldBe
import io.kotest.core.spec.style.StringSpec
class StringSpecExceptionInBeforeTest : StringSpec() {
init {
"a failing test" {
1 shouldBe 2
}
"a passing test" {
1 shouldBe 1
}
}
override fun beforeTest(testCase: TestCase) {
throw RuntimeException("oooff!!")
}
}
| 0 | null | 0 | 0 | 068148734769f534223be89673639f46e8430ab4 | 402 | kotlintest | Apache License 2.0 |
server/src/main/kotlin/org/kryptonmc/krypton/entity/projectile/KryptonArrowLike.kt | KryptonMC | 255,582,002 | false | null | /*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.krypton.entity.projectile
import org.kryptonmc.api.block.BlockState
import org.kryptonmc.api.effect.sound.SoundEvent
import org.kryptonmc.api.effect.sound.SoundEvents
import org.kryptonmc.api.entity.projectile.ArrowLike
import org.kryptonmc.krypton.entity.metadata.MetadataKeys
import org.kryptonmc.krypton.entity.serializer.EntitySerializer
import org.kryptonmc.krypton.entity.serializer.projectile.ArrowLikeSerializer
import org.kryptonmc.krypton.world.KryptonWorld
import org.kryptonmc.krypton.world.block.state.KryptonBlockState
import org.kryptonmc.krypton.world.block.state.downcast
abstract class KryptonArrowLike(world: KryptonWorld) : KryptonProjectile(world), ArrowLike {
override val serializer: EntitySerializer<out KryptonArrowLike>
get() = ArrowLikeSerializer
final override var baseDamage: Double = 2.0
final override var isInGround: Boolean = false
var life: Int = 0
var shakeTime: Int = 0
var sound: SoundEvent = defaultHitGroundSound()
final override var stuckInBlock: BlockState?
get() = internalStuckInBlock
set(value) {
internalStuckInBlock = value?.downcast()
}
var internalStuckInBlock: KryptonBlockState? = null
final override var pickupRule: ArrowLike.PickupRule = ArrowLike.PickupRule.DISALLOWED
final override var isCritical: Boolean
get() = data.getFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_CRITICAL)
set(value) = data.setFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_CRITICAL, value)
final override var ignoresPhysics: Boolean
get() = data.getFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_IGNORES_PHYSICS)
set(value) = data.setFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_IGNORES_PHYSICS, value)
final override var wasShotFromCrossbow: Boolean
get() = data.getFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_WAS_SHOT_FROM_CROSSBOW)
set(value) = data.setFlag(MetadataKeys.ArrowLike.FLAGS, FLAG_WAS_SHOT_FROM_CROSSBOW, value)
final override var piercingLevel: Int
get() = data.get(MetadataKeys.ArrowLike.PIERCING_LEVEL).toInt()
set(value) = data.set(MetadataKeys.ArrowLike.PIERCING_LEVEL, value.toByte())
override fun defineData() {
super.defineData()
data.define(MetadataKeys.ArrowLike.FLAGS, 0)
data.define(MetadataKeys.ArrowLike.PIERCING_LEVEL, 0)
}
internal open fun defaultHitGroundSound(): SoundEvent = SoundEvents.ARROW_HIT.get()
companion object {
private const val FLAG_CRITICAL = 0
private const val FLAG_IGNORES_PHYSICS = 1
private const val FLAG_WAS_SHOT_FROM_CROSSBOW = 2
}
}
| 27 | Kotlin | 11 | 233 | a9eff5463328f34072cdaf37aae3e77b14fcac93 | 3,381 | Krypton | Apache License 2.0 |
core/network/src/main/kotlin/org/bmsk/network/di/NetworkModule.kt | AndroidStudy-bmsk | 632,254,827 | false | {"Kotlin": 63336} | package org.bmsk.lifemash.core.network.di
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.tickaroo.tikxml.TikXml
import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.bmsk.lifemash.core.network.BASE_URL_GOOGLE
import org.bmsk.lifemash.core.network.BASE_URL_SBS
import org.bmsk.lifemash.core.network.TIMEOUT_CONNECT
import org.bmsk.lifemash.core.network.TIMEOUT_READ
import org.bmsk.lifemash.core.network.TIMEOUT_WRITE
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Qualifier
import javax.inject.Singleton
@Qualifier
@Retention(AnnotationRetention.BINARY)
internal annotation class SbsRetrofit
@Qualifier
@Retention(AnnotationRetention.BINARY)
internal annotation class GoogleRetrofit
@Module
@InstallIn(SingletonComponent::class)
internal object NetworkModule {
@Provides
@Singleton
fun providesJsonConverterFactory(): MoshiConverterFactory {
return MoshiConverterFactory.create(
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build(),
)
}
@Provides
@Singleton
fun providesXmlConverterFactory(): TikXmlConverterFactory {
return TikXmlConverterFactory.create(
TikXml.Builder()
.exceptionOnUnreadXml(false)
.build(),
)
}
@Provides
@Singleton
fun providesHttpLogger(): HttpLoggingInterceptor {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.apply {
level = HttpLoggingInterceptor.Level.BODY
}
return loggingInterceptor
}
@Provides
@Singleton
fun providesOkHttpClient(
logger: HttpLoggingInterceptor,
): OkHttpClient.Builder {
return OkHttpClient.Builder().apply {
addInterceptor(logger)
connectTimeout(TIMEOUT_CONNECT, TimeUnit.SECONDS)
readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS)
}
}
@Provides
@Singleton
@SbsRetrofit
fun providesSbsRetrofit(
client: OkHttpClient.Builder,
xmlConverterFactory: TikXmlConverterFactory,
): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL_SBS)
.client(client.build())
.addConverterFactory(xmlConverterFactory)
.build()
}
@Provides
@Singleton
@GoogleRetrofit
fun providesGoogleRetrofit(
client: OkHttpClient.Builder,
xmlConverterFactory: TikXmlConverterFactory,
): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL_GOOGLE)
.client(client.build())
.addConverterFactory(xmlConverterFactory)
.build()
}
}
| 1 | Kotlin | 0 | 0 | d60445993d477d65583244c48c3e9132d5902789 | 3,083 | LifeMash-NewsApp | MIT License |
typescript/ts-lowerings/src/org/jetbrains/dukat/tsLowerings/introduceSyntheticExportQualifiers.kt | posix-dev | 270,574,458 | true | {"Kotlin": 2679797, "WebIDL": 323303, "TypeScript": 126912, "JavaScript": 15989, "ANTLR": 11333} | package org.jetbrains.dukat.tsLowerings
import MergeableDeclaration
import TopLevelDeclarationLowering
import org.jetbrains.dukat.ownerContext.NodeOwner
import org.jetbrains.dukat.tsmodel.ClassDeclaration
import org.jetbrains.dukat.tsmodel.ExportAssignmentDeclaration
import org.jetbrains.dukat.tsmodel.FunctionDeclaration
import org.jetbrains.dukat.tsmodel.FunctionOwnerDeclaration
import org.jetbrains.dukat.tsmodel.InterfaceDeclaration
import org.jetbrains.dukat.tsmodel.ModifierDeclaration
import org.jetbrains.dukat.tsmodel.ModuleDeclaration
import org.jetbrains.dukat.tsmodel.SourceSetDeclaration
import org.jetbrains.dukat.tsmodel.VariableDeclaration
class SyntheticExportModifiersLowering(private val exportAssignments: Map<String, Boolean>) : TopLevelDeclarationLowering {
private fun MergeableDeclaration.resolveSyntheticExport(): List<ModifierDeclaration> {
return exportAssignments[uid]?.let { exportAssignment ->
if (exportAssignment) {
listOf(ModifierDeclaration.SYNTH_EXPORT_ASSIGNMENT)
} else {
listOf(ModifierDeclaration.EXPORT_KEYWORD, ModifierDeclaration.DEFAULT_KEYWORD)
}
} ?: emptyList()
}
override fun lowerClassDeclaration(declaration: ClassDeclaration, owner: NodeOwner<ModuleDeclaration>?): ClassDeclaration {
return declaration.copy(modifiers = declaration.modifiers + declaration.resolveSyntheticExport())
}
override fun lowerInterfaceDeclaration(declaration: InterfaceDeclaration, owner: NodeOwner<ModuleDeclaration>?): InterfaceDeclaration {
return declaration.copy(modifiers = declaration.modifiers + declaration.resolveSyntheticExport())
}
override fun lowerFunctionDeclaration(declaration: FunctionDeclaration, owner: NodeOwner<FunctionOwnerDeclaration>?): FunctionDeclaration {
return declaration.copy(modifiers = declaration.modifiers + declaration.resolveSyntheticExport())
}
override fun lowerVariableDeclaration(declaration: VariableDeclaration, owner: NodeOwner<ModuleDeclaration>?): VariableDeclaration {
return declaration.copy(modifiers = declaration.modifiers + declaration.resolveSyntheticExport())
}
override fun lowerModuleModel(moduleDeclaration: ModuleDeclaration, owner: NodeOwner<ModuleDeclaration>?): ModuleDeclaration? {
return super.lowerModuleModel(moduleDeclaration.copy(modifiers = moduleDeclaration.modifiers + moduleDeclaration.resolveSyntheticExport()), owner)
}
}
fun ModuleDeclaration.collectExportAssignments(): List<ExportAssignmentDeclaration> {
return listOfNotNull(export) + declarations.filterIsInstance(ModuleDeclaration::class.java).flatMap { it.collectExportAssignments() }
}
class IntroduceSyntheticExportModifiers : TsLowering {
override fun lower(source: SourceSetDeclaration): SourceSetDeclaration {
return source.copy(sources = source.sources.map {
val exportAssignments = it.root.collectExportAssignments().flatMap { it.uids.map { uid -> Pair(uid, it.isExportEquals) } }.toMap()
it.copy(root = SyntheticExportModifiersLowering(exportAssignments).lowerSourceDeclaration(it.root))
})
}
} | 0 | null | 0 | 0 | 2a843bb20614e02c011b33ddb8bbe84c4755c107 | 3,195 | dukat | Apache License 2.0 |
src/main/java/com/github/shahrivari/redipper/base/map/RedisMap.kt | shahrivari | 199,589,734 | false | null | package com.github.shahrivari.redipper.base.map
import com.github.shahrivari.redipper.base.RedisCache
import com.github.shahrivari.redipper.base.builder.LoadingBuilder
import com.github.shahrivari.redipper.base.encoding.Encoder
import com.github.shahrivari.redipper.base.serialize.Serializer
import com.github.shahrivari.redipper.config.RedisConfig
import io.lettuce.core.ScanArgs
import java.io.Serializable
open class RedisMap<V : Serializable> : RedisCache<V> {
private val loader: ((String) -> V?)?
protected constructor(config: RedisConfig,
loader: ((String) -> V?)?,
space: String, ttlSeconds: Long,
serializer: Serializer<V>,
encoder: Encoder?)
: super(config, space, ttlSeconds, serializer, encoder) {
this.loader = loader
}
companion object {
private val EMPTY_BYTES = ByteArray(0)
inline fun <reified T : Serializable> newBuilder(config: RedisConfig,
space: String,
forceSpace: Boolean = false): Builder<T> {
return Builder(config, space, forceSpace, T::class.java)
}
}
private fun ByteArray.getKeyPart(): String {
val str = String(this)
return str.substring(str.indexOf(':') + 1)
}
private fun loadIfNeeded(key: String, value: ByteArray?): V? {
return when {
value == null -> {
if (loader != null) {
val result = loader.invoke(key)
set(key, result)
result
} else {
null
}
}
value.isEmpty() -> null
else -> deserialize(value)
}
}
fun set(key: String, value: V?) {
val bytes = if (value == null) EMPTY_BYTES else serialize(value)
if (ttlSeconds > 0)
redis.setex(key.prependSpace(), ttlSeconds, bytes)
else
redis.set(key.prependSpace(), bytes)
}
fun mset(kvs: Map<String, V?>) {
val map = kvs.entries.associate {
it.key.prependSpace() to (it.value?.let { value -> serialize(value) } ?: EMPTY_BYTES)
}
if (kvs.isNotEmpty()) redis.mset(map)
}
fun get(key: String): V? =
loadIfNeeded(key, redis.get(key.prependSpace()))
fun mget(keys: Iterable<String>): Map<String, V?> {
val array = keys.distinct().map { it.prependSpace() }.toTypedArray()
if (array.isEmpty()) return emptyMap()
val map = mutableMapOf<String, V?>()
redis.mget(*array).forEach {
//just return the present keys
val k = it.key.getKeyPart()
if (!it.hasValue()) {
val v = loadIfNeeded(k, null)
if (v != null) map[k] = v
} else {
map[k] = deserialize(it.value)
}
}
return map
}
fun del(vararg key: String) =
redis.del(*key.map { it.prependSpace() }.toTypedArray())
fun removeTtl(key: String) =
redis.set(key.prependSpace(), redis.get(key.prependSpace()))
fun keys() =
redis.keys("$space*".toByteArray()).map { String(it).stripSpace() }
/**
* Returns all keys in own space matching [pattern].
* It's maybe block server for long time if collection is big.
* It's better to use [scan] method instead of [keys] method.
*
* @param pattern keys should matching this parameter.
*/
fun keys(pattern: String) =
redis.keys("$space:$pattern*".toByteArray()).map { String(it).stripSpace() }
/**
* Returns all keys in own space matching [pattern].
* @param limit size of return list.
*/
fun scan(pattern: String = "", limit: Int = 1000) =
redis.scan(ScanArgs().match("$space:$pattern*").limit(limit.toLong())).keys.map {
String(it).substringAfter("$space:$pattern")
}
fun clear() =
keys().forEach { del(it) }
class Builder<V : Serializable>(config: RedisConfig,
space: String,
forceSpace: Boolean,
clazz: Class<V>)
: LoadingBuilder<RedisMap<V>, V>(config, space, clazz) {
init {
if (!forceSpace) checkSpaceExistence(space)
}
override fun build(): RedisMap<V> {
require(!space.contains(":")) { "space cannot have semicolon: $space" }
if (serializer == null)
specifySerializer()
return RedisMap(config, loader, space, ttlSeconds, serializer!!, encoder)
}
}
}
fun RedisMap<Short>.incr(key: String) =
redis.incr(key.prependSpace()).toShort()
fun RedisMap<Short>.decr(key: String) =
redis.decr(key.prependSpace()).toShort()
fun RedisMap<Int>.incr(key: String) =
redis.incr(key.prependSpace()).toInt()
fun RedisMap<Int>.decr(key: String) =
redis.decr(key.prependSpace()).toInt()
fun RedisMap<Long>.incr(key: String) =
redis.incr(key.prependSpace()).toLong()
fun RedisMap<Long>.decr(key: String) =
redis.decr(key.prependSpace()).toLong() | 0 | null | 1 | 5 | 8ef809c7577ead1c6cb85a785b9f34217af648ad | 5,358 | redipper | MIT License |
core/data/src/main/java/org/expenny/core/data/repository/RecordRepositoryImpl.kt | expenny-application | 712,607,222 | false | {"Kotlin": 943358} | package org.expenny.core.data.repository
import androidx.room.withTransaction
import kotlinx.coroutines.flow.*
import org.expenny.core.common.extensions.mapFlatten
import org.expenny.core.common.types.RecordType
import org.expenny.core.common.types.TransactionType
import org.expenny.core.data.mapper.DataMapper.toEntity
import org.expenny.core.data.mapper.DataMapper.toModel
import org.expenny.core.database.ExpennyDatabase
import org.expenny.core.domain.repository.*
import org.expenny.core.model.file.FileCreate
import org.expenny.core.model.record.Record
import org.expenny.core.model.record.RecordCreate
import org.expenny.core.model.record.RecordUpdate
import org.threeten.extra.LocalDateRange
import javax.inject.Inject
class RecordRepositoryImpl @Inject constructor(
private val database: ExpennyDatabase,
private val accountRepository: AccountRepository,
private val localRepository: LocalRepository,
private val recordLabelRepository: RecordLabelRepository,
private val recordFileRepository: RecordFileRepository,
private val fileRepository: FileRepository,
) : RecordRepository {
private val recordDao = database.recordDao()
override fun getRecordsDesc(): Flow<List<Record>> {
return localRepository.getCurrentProfileId()
.filterNotNull()
.flatMapLatest { profileId ->
recordDao.selectAllDesc(profileId)
}.mapFlatten { toModel() }
}
override fun getRecordsDesc(
labelIds: List<Long>,
accountIds: List<Long>,
categoryIds: List<Long>,
types: List<RecordType>,
dateRange: LocalDateRange?,
withoutCategory: Boolean,
): Flow<List<Record>> {
return localRepository.getCurrentProfileId()
.filterNotNull()
.flatMapLatest { profileId ->
recordDao.selectAllDesc(
profileId = profileId,
labelIds = labelIds,
accountIds = accountIds,
categoryIds = categoryIds,
types = types,
dateRange = dateRange,
withoutCategory = withoutCategory,
)
}.mapFlatten { toModel() }
}
override fun getRecord(id: Long): Flow<Record?> {
return recordDao.select(id).map { it?.toModel() }
}
override suspend fun createRecord(data: RecordCreate) {
return database.withTransaction {
val recordId = recordDao.insert(data.toEntity())
recordLabelRepository.createRecordLabels(recordId, data.labelIds)
data.receiptsUris
.map { fileRepository.createFile(FileCreate(data.profileId, it)) }
.also { recordFileRepository.createRecordFiles(recordId, it) }
when (data) {
is RecordCreate.Transaction -> {
val balanceAmendmentAmount = when (data.type) {
TransactionType.Incoming -> data.amount
TransactionType.Outgoing -> data.amount.negate()
}
accountRepository.updateAccountBalance(data.accountId, balanceAmendmentAmount)
}
is RecordCreate.Transfer -> {
accountRepository.updateAccountBalance(data.accountId, data.amount.negate())
accountRepository.updateAccountBalance(data.transferAccountId, data.transferAmount)
}
}
}
}
override suspend fun deleteRecords(vararg ids: Long) {
database.withTransaction {
ids.forEach { id ->
val record = recordDao.select(id).first()!!.toModel()
recordDao.delete(id)
recordLabelRepository.deleteRecordLabels(id)
recordFileRepository.deleteRecordFiles(id)
when (record) {
is Record.Transaction -> {
val balanceAmendmentAmount = when (record.type) {
TransactionType.Incoming -> record.amount.value.negate()
TransactionType.Outgoing -> record.amount.value
}
accountRepository.updateAccountBalance(record.account.id, balanceAmendmentAmount)
}
is Record.Transfer -> {
accountRepository.updateAccountBalance(record.account.id, record.amount.value)
accountRepository.updateAccountBalance(record.transferAccount.id, record.transferAmount.value.negate())
}
}
}
}
}
override suspend fun updateRecord(data: RecordUpdate) {
database.withTransaction {
val oldRecord = recordDao.select(data.id).first()!!
val newRecord = with(data) {
when (this) {
is RecordUpdate.Transaction -> {
RecordCreate.Transaction(
profileId = oldRecord.profile.profileId,
accountId = accountId,
labelIds = labelIds,
receiptsUris = receiptsUris,
description = description,
subject = subject,
amount = amount,
date = date,
categoryId = categoryId,
type = type
)
}
is RecordUpdate.Transfer -> {
RecordCreate.Transfer(
profileId = oldRecord.profile.profileId,
accountId = accountId,
labelIds = labelIds,
receiptsUris = receiptsUris,
description = description,
subject = subject,
amount = amount,
date = date,
transferAmount = transferAmount,
transferAccountId = transferAccountId,
transferFee = transferFee
)
}
}
}
deleteRecords(data.id)
createRecord(newRecord)
}
}
} | 0 | Kotlin | 0 | 0 | 6130f00476493c42847b0411664e5571ec85630b | 6,431 | expenny-android | Apache License 2.0 |
pillarbox-player/src/main/java/ch/srgssr/pillarbox/player/extension/Player.kt | SRGSSR | 519,157,987 | false | null | /*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.player.extension
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.Timeline.Window
import androidx.media3.exoplayer.dash.manifest.DashManifest
import androidx.media3.exoplayer.hls.HlsManifest
import ch.srgssr.pillarbox.player.asset.timeRange.Chapter
import ch.srgssr.pillarbox.player.asset.timeRange.Credit
import ch.srgssr.pillarbox.player.asset.timeRange.firstOrNullAtPosition
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.milliseconds
/**
* Get a snapshot of the current media items
*/
fun Player.getCurrentMediaItems(): List<MediaItem> {
val count = mediaItemCount
if (count == 0) {
return emptyList()
}
return buildList(count) {
repeat(count) { i ->
add(getMediaItemAt(i))
}
}
}
/**
* Get playback speed
*
* @return [Player.getPlaybackParameters] speed
*/
fun Player.getPlaybackSpeed(): Float {
return playbackParameters.speed
}
/**
* Current position percent
*
* @return the current position in percent [0,1].
*/
fun Player.currentPositionPercentage(): Float {
return currentPosition / duration.coerceAtLeast(1).toFloat()
}
/**
* Handle audio focus with the currently set [AudioAttributes][androidx.media3.common.AudioAttributes].
* @param handleAudioFocus `true` if the player should handle audio focus, `false` otherwise.
*/
fun Player.setHandleAudioFocus(handleAudioFocus: Boolean) {
setAudioAttributes(audioAttributes, handleAudioFocus)
}
/**
* @return The current media item chapters or an empty list.
*/
fun Player.getCurrentChapters(): List<Chapter> {
return currentMediaItem?.pillarboxData?.chapters ?: emptyList()
}
/**
* @return The current media item credits or an empty list.
*/
fun Player.getCurrentCredits(): List<Credit> {
return currentMediaItem?.pillarboxData?.credits.orEmpty()
}
/**
* Get the chapter at [position][positionMs].
*
* @param positionMs The position, in milliseconds, to find the chapter from.
* @return `null` if there is no chapter at [positionMs].
*/
fun Player.getChapterAtPosition(positionMs: Long = currentPosition): Chapter? {
return getCurrentChapters().firstOrNullAtPosition(positionMs)
}
/**
* Get the credit at [position][positionMs].
*
* @param positionMs The position, in milliseconds, to find the credit from.
* @return `null` if there is no credit at [positionMs].
*/
fun Player.getCreditAtPosition(positionMs: Long = currentPosition): Credit? {
return getCurrentCredits().firstOrNullAtPosition(positionMs)
}
/**
* Is at live edge
*
* @param positionMs The position in milliseconds.
* @param window The optional Window.
* @return if [positionMs] is at live edge.
*/
fun Player.isAtLiveEdge(positionMs: Long = currentPosition, window: Window = Window()): Boolean {
if (!isCurrentMediaItemLive) return false
currentTimeline.getWindow(currentMediaItemIndex, window)
val offsetSeconds = when (val manifest = currentManifest) {
is HlsManifest -> {
manifest.mediaPlaylist.targetDurationUs.microseconds.inWholeSeconds
}
is DashManifest -> {
manifest.minBufferTimeMs.milliseconds.inWholeSeconds
}
else -> {
0L
}
}
return playWhenReady && positionMs.milliseconds.inWholeSeconds >= window.defaultPositionMs.milliseconds.inWholeSeconds - offsetSeconds
}
| 27 | null | 1 | 13 | b155c6d3f2da29b8e30555f13ecce64f28f82db2 | 3,570 | pillarbox-android | MIT License |
jvm/src/test/kotlin/com/github/lagiilein/playground/jvm/MinimumAbsoluteDifferenceTest.kt | Lagiilein | 388,163,657 | false | null | package com.github.lagiilein.playground.jvm
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
import java.io.File
import java.util.Scanner
internal class MinimumAbsoluteDifferenceTest {
@Test
fun minimumAbsoluteDifference() {
assertEquals(3, minimumAbsoluteDifference(arrayOf(3, -7, 0)))
assertEquals(2, minimumAbsoluteDifference(arrayOf(-2, 2, 4)))
assertEquals(
1,
minimumAbsoluteDifference(
"-59 -36 -13 1 -53 -92 -2 -96 -54 75"
.split(' ')
.map { it.toInt() }
.toTypedArray()
)
)
assertEquals(3, minimumAbsoluteDifference(arrayOf(1, -3, 71, 68, 17)))
}
@TestFactory
fun `test minimumAbsoluteDifference with big inputs`(): Collection<DynamicTest> =
listOf("/MinimumAbsoluteDifferenceTestValue1.txt", "/MinimumAbsoluteDifferenceTestValue2.txt")
.map { filename ->
return@map DynamicTest.dynamicTest("test from file \"$filename\"") {
val scanner = Scanner(File(MinimumLossTest::class.java.getResource(filename)!!.file))
val expectedValue = scanner.nextLine()!!.trim().toInt()
val inputValues = sequence {
while (scanner.hasNextInt()) {
yield(scanner.nextInt())
}
}
assertEquals(
expectedValue,
minimumAbsoluteDifference(
inputValues.toList().toTypedArray()
)
)
}
}
}
| 0 | Kotlin | 0 | 0 | a1bf2620f657994fb8193fd54c3a0ddfc95caeb7 | 1,825 | playground.kt | MIT License |
browser-kotlin/src/jsMain/kotlin/web/idb/IDBKeyRange.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package web.idb
/**
* A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs:
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange)
*/
sealed external class IDBKeyRange {
/**
* Returns lower bound, or undefined if none.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/lower)
*/
val lower: Any?
/**
* Returns true if the lower open flag is set, and false otherwise.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/lowerOpen)
*/
val lowerOpen: Boolean
/**
* Returns upper bound, or undefined if none.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/upper)
*/
val upper: Any?
/**
* Returns true if the upper open flag is set, and false otherwise.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/upperOpen)
*/
val upperOpen: Boolean
/**
* Returns true if key is included in the range, and false otherwise.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/includes)
*/
fun includes(key: Any?): Boolean
companion object {
/**
* Returns a new IDBKeyRange spanning from lower to upper. If lowerOpen is true, lower is not included in the range. If upperOpen is true, upper is not included in the range.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/bound_static)
*/
fun bound(
lower: Any?,
upper: Any?,
lowerOpen: Boolean = definedExternally,
upperOpen: Boolean = definedExternally,
): IDBKeyRange
/**
* Returns a new IDBKeyRange starting at key with no upper bound. If open is true, key is not included in the range.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/lowerBound_static)
*/
fun lowerBound(
lower: Any?,
open: Boolean = definedExternally,
): IDBKeyRange
/**
* Returns a new IDBKeyRange spanning only key.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/only_static)
*/
fun only(value: Any?): IDBKeyRange
/**
* Returns a new IDBKeyRange with no lower bound and ending at key. If open is true, key is not included in the range.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBKeyRange/upperBound_static)
*/
fun upperBound(
upper: Any?,
open: Boolean = definedExternally,
): IDBKeyRange
}
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 3,118 | types-kotlin | Apache License 2.0 |
animatorhelpers/src/main/java/com/francescozoccheddu/animatorhelpers/ReadOnlyAnimatedValueWrapper.kt | francescozoccheddu | 199,296,063 | false | {"Kotlin": 21434} | package com.francescozoccheddu.animatorhelpers
private class ReadOnlyAnimatedValueWrapper<Type>(animatedValue: ReadOnlyAnimatedValue<Type>) :
ReadOnlyAnimatedValue<Type> by animatedValue
private class ReadOnlyObservableAnimatedValueWrapper<Type>(animatedValue: ReadOnlyObservableAnimatedValue<Type>) :
ReadOnlyObservableAnimatedValue<Type> by animatedValue
fun <Type> ReadOnlyAnimatedValue<Type>.asReadOnly(): ReadOnlyAnimatedValue<Type> =
ReadOnlyAnimatedValueWrapper(this)
fun <Type> ReadOnlyObservableAnimatedValue<Type>.asObservableReadOnly(): ReadOnlyObservableAnimatedValue<Type> =
ReadOnlyObservableAnimatedValueWrapper(this) | 2 | Kotlin | 0 | 0 | 47c14d8d474d89bc6257cc8eed51133a7d04b741 | 652 | android-AnimatorHelpers | MIT License |
src/rider/main/kotlin/com/jetbrains/rider/plugins/efcore/cli/api/DbContextCommandFactory.kt | JetBrains | 426,422,572 | false | {"Kotlin": 186978, "C#": 36332} | package com.jetbrains.rider.plugins.efcore.cli.api
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.jetbrains.rider.plugins.efcore.EfCoreUiBundle
import com.jetbrains.rider.plugins.efcore.cli.api.models.DotnetEfVersion
import com.jetbrains.rider.plugins.efcore.cli.execution.CommonOptions
import com.jetbrains.rider.plugins.efcore.cli.execution.DotnetCommand
import com.jetbrains.rider.plugins.efcore.cli.execution.EfCoreCommandBuilder
import com.jetbrains.rider.plugins.efcore.cli.execution.KnownEfCommands
@Service(Service.Level.PROJECT)
class DbContextCommandFactory(private val intellijProject: Project) {
companion object {
fun getInstance(project: Project) = project.service<DbContextCommandFactory>()
}
fun scaffold(efCoreVersion: DotnetEfVersion, options: CommonOptions, connection: String, provider: String,
outputFolder: String, useAttributes: Boolean, useDatabaseNames: Boolean, generateOnConfiguring: Boolean,
usePluralizer: Boolean, dbContextName: String, dbContextFolder: String, scaffoldAllTables: Boolean,
tablesList: List<String>, scaffoldAllSchemas: Boolean, schemasList: List<String>): DotnetCommand =
EfCoreCommandBuilder(intellijProject, KnownEfCommands.DbContext.scaffold, options, EfCoreUiBundle.message("scaffold.dbcontext.presentable.name")).apply {
add(connection)
add(provider)
addIf("--data-annotations", useAttributes)
addNamed("--context", dbContextName)
addNamed("--context-dir", dbContextFolder)
add("--force")
addNamed("--output-dir", outputFolder)
if (!scaffoldAllSchemas) {
schemasList.forEach {
addNamed("--schema", it)
}
}
if (!scaffoldAllTables) {
tablesList
.filter { it.isNotEmpty() }
.forEach { addNamed("--table", it) }
}
addIf("--use-database-names", useDatabaseNames)
if (efCoreVersion.major >= 5) {
addIf("--no-onconfiguring", !generateOnConfiguring)
addIf("--no-pluralize", !usePluralizer)
}
}.build()
} | 19 | Kotlin | 12 | 164 | d60fd2a923a4142065516e480193cf5af2d44c6e | 2,352 | rider-efcore | MIT License |
src/main/kotlin/com/demonwav/mcdev/platform/mcp/inspections/EntityConstructorInspection.kt | Earthcomputer | 240,984,777 | false | null | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.inspections
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.util.McpConstants
import com.demonwav.mcdev.platform.mixin.util.isMixin
import com.demonwav.mcdev.util.extendsOrImplements
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiTypeParameter
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import org.jetbrains.annotations.Nls
class EntityConstructorInspection : BaseInspection() {
@Nls
override fun getDisplayName(): String {
return "MCP Entity class missing World constructor"
}
override fun buildErrorString(vararg infos: Any): String {
return "All entities must have a constructor that takes one " + McpConstants.WORLD + " parameter."
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitClass(aClass: PsiClass) {
if (aClass is PsiTypeParameter) {
return
}
if (!aClass.extendsOrImplements(McpConstants.ENTITY)) {
return
}
if (aClass.extendsOrImplements(McpConstants.ENTITY_FX)) {
return
}
val module = ModuleUtilCore.findModuleForPsiElement(aClass) ?: return
val instance = MinecraftFacet.getInstance(module) ?: return
if (!instance.isOfType(McpModuleType)) {
return
}
if (aClass.isMixin) {
return
}
val constructors = aClass.constructors
for (constructor in constructors) {
if (constructor.parameterList.parameters.size != 1) {
continue
}
val parameter = constructor.parameterList.parameters[0]
val typeElement = parameter.typeElement ?: continue
val type = typeElement.type as? PsiClassType ?: continue
val resolve = type.resolve() ?: continue
if (resolve.qualifiedName == null) {
continue
}
if (resolve.qualifiedName == McpConstants.WORLD) {
return
}
}
registerClassError(aClass)
}
}
}
}
| 1 | null | 2 | 23 | ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5 | 2,774 | MinecraftDev | MIT License |
src/test/kotlin/io/kjson/testclasses/TestClasses.kt | pwall567 | 389,599,808 | false | null | /*
* @(#) TestClasses.kt
*
* kjson Reflection-based JSON serialization and deserialization for Kotlin
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* 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 io.kjson.testclasses
import java.time.LocalDate
import io.kjson.JSONException
import io.kjson.JSONInt
import io.kjson.JSONObject
import io.kjson.JSONString
import io.kjson.JSONValue
import io.kjson.annotation.JSONAllowExtra
import io.kjson.annotation.JSONIgnore
import io.kjson.annotation.JSONIncludeAllProperties
import io.kjson.annotation.JSONIncludeIfNull
import io.kjson.annotation.JSONName
data class Dummy1(val field1: String, val field2: Int = 999)
data class Dummy2(val field1: String, val field2: Int = 999) {
var extra: String? = null
}
data class Dummy3(val dummy1: Dummy1, val text: String)
data class Dummy4(val listDummy1: List<Dummy1>, val text: String)
data class Dummy5(val field1: String?, val field2: Int)
data class DummyFromJSON(val int1: Int) {
@Suppress("unused")
fun toJSON(): JSONObject {
return JSONObject.build {
add("dec", JSONString(int1.toString()))
add("hex", JSONString(int1.toString(16)))
}
}
companion object {
@Suppress("unused")
fun fromJSON(json: JSONValue): DummyFromJSON {
val jsonObject = json as JSONObject
val dec = (jsonObject["dec"] as JSONString).value.toInt()
val hex = (jsonObject["hex"] as JSONString).value.toInt(16)
if (dec != hex)
throw JSONException("Inconsistent values")
return DummyFromJSON(dec)
}
}
}
data class DummyMultipleFromJSON(val int1: Int) {
@Suppress("unused")
fun toJSON(): JSONObject {
return JSONObject.build {
add("dec", int1.toString())
add("hex", int1.toString(16))
}
}
companion object {
@Suppress("unused")
fun fromJSON(json: JSONObject): DummyMultipleFromJSON {
val dec = (json["dec"] as JSONString).value.toInt() // json.getString("dec").toInt()
val hex = (json["hex"] as JSONString).value.toInt(16) // json.getString("hex").toInt(16)
if (dec != hex)
throw JSONException("Inconsistent values")
return DummyMultipleFromJSON(dec)
}
@Suppress("unused")
fun fromJSON(json: JSONInt): DummyMultipleFromJSON {
return DummyMultipleFromJSON(json.value)
}
@Suppress("unused")
fun fromJSON(json: JSONString): DummyMultipleFromJSON {
return DummyMultipleFromJSON(json.value.toInt(16))
}
}
}
@Suppress("unused")
enum class DummyEnum { ALPHA, BETA, GAMMA }
open class Super {
var field1: String = "xxx"
var field2: Int = 111
override fun equals(other: Any?): Boolean {
return other is Super && field1 == other.field1 && field2 == other.field2
}
override fun hashCode(): Int {
return field1.hashCode() xor field2.hashCode()
}
}
class Derived : Super() {
var field3: Double = 0.1
override fun equals(other: Any?): Boolean {
return super.equals(other) && other is Derived && field3 == other.field3
}
override fun hashCode(): Int {
return super.hashCode() xor field3.toInt()
}
}
interface DummyInterface
object DummyObject : DummyInterface {
@Suppress("unused")
val field1: String = "abc"
}
class NestedDummy {
@Suppress("unused")
val obj = DummyObject
}
class DummyWithVal {
val field8: String = "blert"
override fun equals(other: Any?): Boolean {
return other is DummyWithVal && other.field8 == field8
}
override fun hashCode(): Int {
return field8.hashCode()
}
}
class DummyList(content: List<LocalDate>) : ArrayList<LocalDate>(content)
class DummyMap(content: Map<String, LocalDate>) : HashMap<String, LocalDate>(content)
data class DummyWithIgnore(val field1: String, @JSONIgnore val field2: String = "defaulted", val field3: String)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CustomIgnore
data class DummyWithCustomIgnore(val field1: String, @CustomIgnore val field2: String = "special", val field3: String)
class DummyWithNameAnnotation {
var field1: String = "xxx"
@JSONName("fieldX")
var field2: Int = 111
override fun equals(other: Any?): Boolean {
return other is DummyWithNameAnnotation && field1 == other.field1 && field2 == other.field2
}
override fun hashCode(): Int {
return field1.hashCode() xor field2.hashCode()
}
}
data class DummyWithParamNameAnnotation(val field1: String, @JSONName("fieldX") val field2: Int)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
@Suppress("unused")
annotation class CustomName(val symbol: String)
data class DummyWithCustomNameAnnotation(val field1: String, @CustomName("fieldX") val field2: Int)
data class DummyWithIncludeIfNull(val field1: String, @JSONIncludeIfNull val field2: String?, val field3: String)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CustomIncludeIfNull
data class DummyWithCustomIncludeIfNull(val field1: String, @CustomIncludeIfNull val field2: String?,
val field3: String)
@JSONIncludeAllProperties
data class DummyWithIncludeAllProperties(val field1: String, val field2: String?, val field3: String)
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class CustomIncludeAllProperties
@CustomIncludeAllProperties
data class DummyWithCustomIncludeAllProperties(val field1: String, val field2: String?, val field3: String)
@JSONAllowExtra
data class DummyWithAllowExtra(val field1: String, val field2: Int)
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class CustomAllowExtraProperties
@CustomAllowExtraProperties
data class DummyWithCustomAllowExtra(val field1: String, val field2: Int)
@Suppress("unused")
class MultiConstructor(val aaa: String) {
constructor(bbb: Int) : this(bbb.toString())
}
open class DummyA
open class DummyB : DummyA()
open class DummyC : DummyB()
class DummyD : DummyC()
data class Dummy9(val str: String) {
override fun toString(): String {
return str
}
}
class Circular1 {
var ref: Circular2? = null
}
class Circular2 {
var ref: Circular1? = null
}
open class PolymorphicBase
data class PolymorphicDerived1(val type: String, val extra1: Int) : PolymorphicBase()
data class PolymorphicDerived2(val type: String, val extra2: String) : PolymorphicBase()
| 0 | null | 0 | 9 | f7ba0cd4bc51b1ed00707e9b491cd6c1479e454f | 7,879 | kjson | MIT License |
app/src/main/java/com/noobexon/xposedfakelocation/xposed/utils/PreferencesUtil.kt | noobexon1 | 868,167,563 | false | {"Kotlin": 119934} | // PreferencesUtil.kt
package com.noobexon.xposedfakelocation.xposed.utils
import com.google.gson.Gson
import com.noobexon.xposedfakelocation.data.*
import com.noobexon.xposedfakelocation.data.model.LastClickedLocation
import de.robv.android.xposed.XSharedPreferences
import de.robv.android.xposed.XposedBridge
object PreferencesUtil {
private const val TAG = "[PreferencesUtil]"
private val preferences: XSharedPreferences = XSharedPreferences(MANAGER_APP_PACKAGE_NAME, SHARED_PREFS_FILE).apply {
makeWorldReadable()
reload()
}
fun getIsPlaying(): Boolean? {
return getPreference<Boolean>(KEY_IS_PLAYING)
}
fun getLastClickedLocation(): LastClickedLocation? {
return getPreference<LastClickedLocation>(KEY_LAST_CLICKED_LOCATION)
}
fun getUseAccuracy(): Boolean? {
return getPreference<Boolean>(KEY_USE_ACCURACY)
}
fun getAccuracy(): Double? {
return getPreference<Double>(KEY_ACCURACY)
}
fun getUseAltitude(): Boolean? {
return getPreference<Boolean>(KEY_USE_ALTITUDE)
}
fun getAltitude(): Double? {
return getPreference<Double>(KEY_ALTITUDE)
}
fun getUseRandomize(): Boolean? {
return getPreference<Boolean>(KEY_USE_RANDOMIZE)
}
fun getRandomizeRadius(): Double? {
return getPreference<Double>(KEY_RANDOMIZE_RADIUS)
}
fun getUseVerticalAccuracy(): Boolean? {
return getPreference<Boolean>(KEY_USE_VERTICAL_ACCURACY)
}
fun getVerticalAccuracy(): Float? {
return getPreference<Float>(KEY_VERTICAL_ACCURACY)
}
fun getUseMeanSeaLevel(): Boolean? {
return getPreference<Boolean>(KEY_USE_MEAN_SEA_LEVEL)
}
fun getMeanSeaLevel(): Double? {
return getPreference<Double>(KEY_MEAN_SEA_LEVEL)
}
fun getUseMeanSeaLevelAccuracy(): Boolean? {
return getPreference<Boolean>(KEY_USE_MEAN_SEA_LEVEL_ACCURACY)
}
fun getMeanSeaLevelAccuracy(): Float? {
return getPreference<Float>(KEY_MEAN_SEA_LEVEL_ACCURACY)
}
fun getUseSpeed(): Boolean? {
return getPreference<Boolean>(KEY_USE_SPEED)
}
fun getSpeed(): Float? {
return getPreference<Float>(KEY_SPEED)
}
fun getUseSpeedAccuracy(): Boolean? {
return getPreference<Boolean>(KEY_USE_SPEED_ACCURACY)
}
fun getSpeedAccuracy(): Float? {
return getPreference<Float>(KEY_SPEED_ACCURACY)
}
private inline fun <reified T> getPreference(key: String): T? {
preferences.reload()
return when (T::class) {
Double::class -> {
val defaultValue = when (key) {
KEY_ACCURACY -> java.lang.Double.doubleToRawLongBits(DEFAULT_ACCURACY)
KEY_ALTITUDE -> java.lang.Double.doubleToRawLongBits(DEFAULT_ALTITUDE)
KEY_RANDOMIZE_RADIUS -> java.lang.Double.doubleToRawLongBits(DEFAULT_RANDOMIZE_RADIUS)
KEY_MEAN_SEA_LEVEL -> java.lang.Double.doubleToRawLongBits(DEFAULT_MEAN_SEA_LEVEL)
else -> -1L
}
val bits = preferences.getLong(key, defaultValue)
java.lang.Double.longBitsToDouble(bits) as? T
}
Float::class -> {
val defaultValue = when (key) {
KEY_VERTICAL_ACCURACY -> DEFAULT_VERTICAL_ACCURACY
KEY_MEAN_SEA_LEVEL_ACCURACY -> DEFAULT_MEAN_SEA_LEVEL_ACCURACY
KEY_SPEED -> DEFAULT_SPEED
KEY_SPEED_ACCURACY -> DEFAULT_SPEED_ACCURACY
else -> -1f
}
preferences.getFloat(key, defaultValue) as? T
}
Boolean::class -> preferences.getBoolean(key, false) as? T
else -> {
val json = preferences.getString(key, null)
if (json != null) {
try {
Gson().fromJson(json, T::class.java).also {
XposedBridge.log("$TAG Retrieved $key: $it")
}
} catch (e: Exception) {
XposedBridge.log("$TAG Error parsing $key JSON: ${e.message}")
null
}
} else {
XposedBridge.log("$TAG $key not found in preferences.")
null
}
}
}
}
} | 0 | Kotlin | 3 | 21 | 64af161cb15cf5dfece93763a8706348c7b2c70e | 4,456 | XposedFakeLocation | MIT License |
plot-config-portable/src/commonMain/kotlin/jetbrains/datalore/plot/server/config/transform/bistro/util/LayerOptions.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2021. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.server.config.transform.bistro.util
import jetbrains.datalore.plot.base.Aes
import jetbrains.datalore.plot.base.GeomKind
import jetbrains.datalore.plot.base.render.linetype.LineType
import jetbrains.datalore.plot.base.render.point.PointShape
import jetbrains.datalore.plot.config.Option.Geom
import jetbrains.datalore.plot.config.Option.Layer
import jetbrains.datalore.plot.config.Option.Mapping.toOption
import jetbrains.datalore.plot.config.Option.PlotBase
import kotlin.properties.ReadWriteProperty
class LayerOptions : Options<PlotOptions>() {
var geom: GeomKind? by map(Layer.GEOM)
var data: Map<String, List<Any?>>? by map(PlotBase.DATA)
var mappings: Map<Aes<*>, String>? by map(PlotBase.MAPPING)
var tooltipsOptions: TooltipsOptions? by map(Layer.TOOLTIPS)
var samplingOptions: SamplingOptions? by map(Layer.SAMPLING)
var stat: String? by map(Layer.STAT)
var position: String? by map(Layer.POS)
var sizeUnit: Aes<*>? by map(Geom.Text.SIZE_UNIT)
var showLegend: Boolean? by map(Layer.SHOW_LEGEND)
var naText: String? by map(Geom.Text.NA_TEXT)
var labelFormat: String? by map(Geom.Text.LABEL_FORMAT)
// Aes
var x: Double? by map(Aes.X)
var y: Double? by map(Aes.Y)
var z: Double? by map(Aes.Z)
var color: Any? by map(Aes.COLOR)
var fill: Any? by map(Aes.FILL)
var alpha: Double? by map(Aes.ALPHA)
var shape: PointShape? by map(Aes.SHAPE)
var linetype: LineType? by map(Aes.LINETYPE)
var size: Double? by map(Aes.SIZE)
var width: Double? by map(Aes.WIDTH)
var height: Double? by map(Aes.HEIGHT)
var violinwidth: Double? by map(Aes.VIOLINWIDTH)
var weight: Double? by map(Aes.WEIGHT)
var intercept: Double? by map(Aes.INTERCEPT)
var slope: Double? by map(Aes.SLOPE)
var xintercept: Double? by map(Aes.XINTERCEPT)
var yintercept: Double? by map(Aes.YINTERCEPT)
var lower: Double? by map(Aes.LOWER)
var middle: Double? by map(Aes.MIDDLE)
var upper: Double? by map(Aes.UPPER)
var sample: Double? by map(Aes.SAMPLE)
var xmin: Double? by map(Aes.XMIN)
var xmax: Double? by map(Aes.XMAX)
var ymin: Double? by map(Aes.YMIN)
var ymax: Double? by map(Aes.YMAX)
var xend: Double? by map(Aes.XEND)
var yend: Double? by map(Aes.YEND)
var mapId: Any? by map(Aes.MAP_ID)
var frame: String? by map(Aes.FRAME)
var speed: Double? by map(Aes.SPEED)
var flow: Double? by map(Aes.FLOW)
var label: Any? by map(Aes.LABEL)
var family: String? by map(Aes.FAMILY)
var fontface: String? by map(Aes.FONTFACE)
var hjust: Any? by map(Aes.HJUST)
var vjust: Any? by map(Aes.VJUST)
var angle: Double? by map(Aes.ANGLE)
var symX: Double? by map(Aes.SYM_X)
var symY: Double? by map(Aes.SYM_Y)
inline operator fun <reified T> get(aes: Aes<T>): T = properties[toOption(aes)] as T
operator fun <T> set(aes: Aes<T>, v: T) { properties[toOption(aes)] = v }
fun <T> setParameter(name: String, v: T) { properties[name] = v }
private inline fun <T, reified TValue> T.map(key: Aes<*>): ReadWriteProperty<T, TValue?> = map(toOption(key))
}
fun layer(block: LayerOptions.() -> Unit) = LayerOptions().apply(block)
| 67 | null | 37 | 771 | ffa5728a09b348fae441a96aba27e5812a22c18c | 3,378 | lets-plot | MIT License |
ui/common/src/test/java/ly/david/ui/common/series/SeriesListItemTest.kt | lydavid | 458,021,427 | false | null | package ly.david.ui.common.series
import com.google.testing.junit.testparameterinjector.TestParameterInjector
import ly.david.musicsearch.core.models.listitem.SeriesListItemModel
import ly.david.ui.test.screenshot.ScreenshotTest
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(TestParameterInjector::class)
class SeriesListItemTest : ScreenshotTest() {
@Test
fun simple() {
snapshot {
SeriesListItem(
series = SeriesListItemModel(
id = "1",
name = "series name",
),
)
}
}
@Test
fun allInfo() {
snapshot {
SeriesListItem(
series = SeriesListItemModel(
id = "1",
name = "series name",
disambiguation = "that one",
type = "Tour",
),
)
}
}
}
| 115 | null | 0 | 6 | 15b148b54763f72965e3f1b0fbd7296bf7dbc010 | 945 | MusicSearch | Apache License 2.0 |
app/src/main/java/com/ozlem/superheroproject/MainActivity.kt | ozlemaybek | 518,407,563 | false | {"Kotlin": 3165} | package com.ozlem.superheroproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
// MainActivity ve XML arasındaki senkronizasyonu sağlamak için:
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// Bir değişkene her yerden ulaşmak istiyorsam burada tanımlamalıyım (global)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onClickCreateSuperHero(view : View){
// toString metodu sonucu String'e çevirmek için kullanılır:
// Girilen inputları string'e çevirip değişkenlere atayalım:
val name = plainTextNameID.text.toString()
// Primary constructor age parametresini integer olarak isteyeceği için çevirmeliyiz.
// Fakat kullanıcı String girerse uygulama çöker bu yüzden toInt() değil toIntOrNull() metodu kullanalım:
// Bu işlemi yaptığım takdirde age artık bir Int değil IntNullable
// Bu yüzden aşağıda age parametresi null değer olabileceğinden hata verir.
// Bunu bir null safety mekanizması ile düzeltebiliriz.
val age = plainTextAgeID.text.toString().toIntOrNull()
val job = plainTextJobID.text.toString()
//null safety:
if(age == null){
textViewID.text = "Please enter the correct age..."
}else{
// Şimdi oluşturduğumuz SuperHero sınıfını kullanarak işlemler yapalım:
val superHero = SuperHero(name,age!!,job)
// Yukarıdaki satırda !! koymayabilirim.
// Çünkü kotlin bir güvenlik mekanizmasında olduğunu ve artık age değerinin null olmayacağını anlıyor.
// Girilen inputları textView'da bastırdık:
textViewID.text = "name: ${superHero.name} , age: ${superHero.age} , job: ${superHero.job}"
}
}
} | 0 | Kotlin | 0 | 0 | 6751240ea3a5cac8433708b2e57f377b40a31dd0 | 1,926 | BTK-SuperHeroProject | Apache License 2.0 |
ollama-client/ollama-client-core/src/jvmTest/kotlin/com/tddworks/ollama/api/OllamaModelTest.kt | tddworks | 755,029,221 | false | {"Kotlin": 251129} | package com.tddworks.ollama.api
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class OllamaModelTest {
@Test
fun `should return correct latest API model name`() {
assertEquals("llama3", OllamaModel.LLAMA3.value)
assertEquals("llama2", OllamaModel.LLAMA2.value)
assertEquals("codellama", OllamaModel.CODE_LLAMA.value)
assertEquals("mistral", OllamaModel.MISTRAL.value)
}
} | 0 | Kotlin | 0 | 4 | 58e7ee96dce4c3b5a559deae6e886c50cf67683e | 447 | openai-kotlin | Apache License 2.0 |
features/bible/src/main/kotlin/app/ss/bible/ToolbarComponent.kt | Adventech | 65,243,816 | false | null | /*
* Copyright (c) 2022. Adventech <<EMAIL>>
*
* 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 app.ss.bible
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.ss.design.compose.extensions.previews.ThemePreviews
import app.ss.design.compose.theme.SsTheme
import app.ss.design.compose.theme.parse
import app.ss.design.compose.widget.icon.IconBox
import app.ss.design.compose.widget.icon.Icons
import com.cryart.sabbathschool.core.model.SSReadingDisplayOptions
import com.cryart.sabbathschool.core.model.displayTheme
import com.cryart.sabbathschool.core.model.themeColor
import kotlinx.coroutines.flow.Flow
@OptIn(ExperimentalLifecycleComposeApi::class)
internal class ToolbarComponent(
composeView: ComposeView,
private val stateFlow: Flow<ToolbarState>,
private val callbacks: Callbacks
) {
interface Callbacks {
fun onClose()
fun versionSelected(version: String)
}
init {
composeView.setContent {
SsTheme {
val uiState by stateFlow.collectAsStateWithLifecycle(ToolbarState.Loading)
BibleToolbar(
state = uiState,
callbacks = callbacks,
modifier = Modifier
)
}
}
}
}
@Composable
internal fun BibleToolbar(
state: ToolbarState,
callbacks: ToolbarComponent.Callbacks,
modifier: Modifier = Modifier
) {
var displayOptions: SSReadingDisplayOptions? = null
val spec = when (state) {
is ToolbarState.Success -> {
displayOptions = state.displayOptions
ToolbarSpec(
bibleVersions = state.bibleVersions,
preferredBible = state.preferredBibleVersion,
callbacks = callbacks
)
}
else -> {
ToolbarSpec(
bibleVersions = emptySet(),
preferredBible = "",
callbacks = callbacks
)
}
}
val options = displayOptions ?: SSReadingDisplayOptions(isSystemInDarkTheme())
val backgroundColor = Color.parse(options.themeColor(LocalContext.current))
val contentColor = contentColor(options.displayTheme(LocalContext.current))
Surface(
color = backgroundColor,
contentColor = contentColor,
modifier = modifier
) {
BibleToolbarRow(spec = spec)
}
}
@Composable
@Stable
private fun contentColor(theme: String): Color {
return when (theme) {
SSReadingDisplayOptions.SS_THEME_DARK -> Color.White
else -> Color.Black
}
}
@Composable
internal fun BibleToolbarRow(
spec: ToolbarSpec,
modifier: Modifier = Modifier,
contentColor: Color = LocalContentColor.current
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
) {
IconButton(
onClick = {
spec.callbacks.onClose()
}
) {
IconBox(
icon = Icons.Close,
contentColor = contentColor
)
}
Spacer(modifier = Modifier.weight(1f))
if (spec.bibleVersions.isNotEmpty()) {
BibleVersionsMenu(spec = spec)
}
}
}
@Composable
private fun BibleVersionsMenu(
spec: ToolbarSpec,
modifier: Modifier = Modifier,
contentColor: Color = LocalContentColor.current
) {
val (bibleVersions, preferredBible, callbacks) = spec
var expanded by remember { mutableStateOf(false) }
var selected by remember { mutableStateOf(preferredBible) }
val iconRotation by animateFloatAsState(
targetValue = if (expanded) 180f else 0f
)
Box(
modifier = modifier
.wrapContentSize(Alignment.CenterEnd)
) {
TextButton(onClick = { expanded = true }) {
Text(
selected,
style = MaterialTheme.typography.labelMedium.copy(
fontSize = 16.sp
),
color = contentColor
)
IconBox(
Icons.ArrowDropDown,
modifier = Modifier.rotate(iconRotation),
contentColor = contentColor
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
bibleVersions.forEach { version ->
DropdownMenuItem(
text = {
Text(
version,
style = MaterialTheme.typography.labelMedium.copy(
fontSize = 16.sp
),
color = MaterialTheme.colorScheme.onSurface
)
},
onClick = {
selected = version
expanded = false
callbacks.versionSelected(version)
},
modifier = Modifier,
trailingIcon = {
if (version == selected) {
IconBox(Icons.Check)
}
}
)
}
}
}
if (selected.isEmpty() && bibleVersions.isNotEmpty()) {
LaunchedEffect(
key1 = Any(),
block = {
selected = bibleVersions.first()
}
)
}
}
@ThemePreviews
@Composable
private fun HeaderRowPreview() {
SsTheme {
Surface {
BibleToolbar(
state = ToolbarState.Success(
bibleVersions = setOf("NKJV", "KJV"),
preferredBibleVersion = "KJV"
),
callbacks = object : ToolbarComponent.Callbacks {
override fun onClose() {
}
override fun versionSelected(version: String) {
}
},
modifier = Modifier
)
}
}
}
| 7 | null | 49 | 171 | 2cc105ea76c7fdf979b0b6ee1098f413c1aa009d | 8,558 | sabbath-school-android | MIT License |
domain/src/main/kotlin/no/nav/su/se/bakover/domain/sak/Sak.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.domain
import arrow.core.Either
import arrow.core.Tuple4
import arrow.core.flatMap
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.right
import no.nav.su.se.bakover.common.domain.Saksnummer
import no.nav.su.se.bakover.common.extensions.toNonEmptyList
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.periode.Måned
import no.nav.su.se.bakover.common.tid.periode.Periode
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.FraOgMedDatoMåVæreFørTilOgMedDato
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.FraOgMedDatoMåVæreFørsteDagIMåneden
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.TilOgMedDatoMåVæreSisteDagIMåneden
import no.nav.su.se.bakover.common.tid.periode.minsteAntallSammenhengendePerioder
import no.nav.su.se.bakover.domain.avkorting.Avkortingsvarsel
import no.nav.su.se.bakover.domain.behandling.Behandlinger
import no.nav.su.se.bakover.domain.behandling.avslag.Opphørsgrunn
import no.nav.su.se.bakover.domain.beregning.Beregning
import no.nav.su.se.bakover.domain.beregning.Månedsberegning
import no.nav.su.se.bakover.domain.brev.command.GenererDokumentCommand
import no.nav.su.se.bakover.domain.klage.Klage
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.TidslinjeForUtbetalinger
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.Utbetalinger
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.UtbetalingslinjePåTidslinje
import no.nav.su.se.bakover.domain.regulering.Regulering
import no.nav.su.se.bakover.domain.revurdering.AbstraktRevurdering
import no.nav.su.se.bakover.domain.revurdering.GjenopptaYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.IverksattRevurdering
import no.nav.su.se.bakover.domain.revurdering.StansAvYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.opphør.OpphørVedRevurdering
import no.nav.su.se.bakover.domain.revurdering.opphør.VurderOmVilkårGirOpphørVedRevurdering
import no.nav.su.se.bakover.domain.revurdering.steg.InformasjonSomRevurderes
import no.nav.su.se.bakover.domain.sak.SakInfo
import no.nav.su.se.bakover.domain.sak.Sakstype
import no.nav.su.se.bakover.domain.sak.oppdaterSøknadsbehandling
import no.nav.su.se.bakover.domain.statistikk.StatistikkEvent
import no.nav.su.se.bakover.domain.søknad.LukkSøknadCommand
import no.nav.su.se.bakover.domain.søknad.Søknad
import no.nav.su.se.bakover.domain.søknadsbehandling.LukketSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.StøtterIkkeOverlappendeStønadsperioder
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.stønadsperiode.Aldersvurdering
import no.nav.su.se.bakover.domain.tidslinje.Tidslinje
import no.nav.su.se.bakover.domain.vedtak.GjeldendeVedtaksdata
import no.nav.su.se.bakover.domain.vedtak.Vedtak
import no.nav.su.se.bakover.domain.vedtak.VedtakInnvilgetSøknadsbehandling
import no.nav.su.se.bakover.domain.vedtak.VedtakPåTidslinje
import no.nav.su.se.bakover.domain.vedtak.VedtakSomKanRevurderes
import no.nav.su.se.bakover.domain.vedtak.lagTidslinje
import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon
import no.nav.su.se.bakover.utenlandsopphold.domain.RegistrerteUtenlandsopphold
import tilbakekreving.domain.kravgrunnlag.Kravgrunnlag
import java.time.Clock
import java.time.LocalDate
import java.util.UUID
/**
* @param uteståendeAvkorting er enten [Avkortingsvarsel.Ingen] eller [Avkortingsvarsel.Utenlandsopphold.SkalAvkortes]
*/
data class Sak(
val id: UUID = UUID.randomUUID(),
val saksnummer: Saksnummer,
val opprettet: Tidspunkt,
val fnr: Fnr,
val søknader: List<Søknad> = emptyList(),
val behandlinger: Behandlinger = Behandlinger.empty(id),
// TODO jah: Bytt til [Utbetaling.Oversendt]
val utbetalinger: Utbetalinger,
val vedtakListe: List<Vedtak> = emptyList(),
val type: Sakstype,
val uteståendeAvkorting: Avkortingsvarsel = Avkortingsvarsel.Ingen,
val utenlandsopphold: RegistrerteUtenlandsopphold = RegistrerteUtenlandsopphold.empty(id),
val versjon: Hendelsesversjon,
val uteståendeKravgrunnlag: Kravgrunnlag?,
) {
init {
require(uteståendeAvkorting is Avkortingsvarsel.Ingen || uteståendeAvkorting is Avkortingsvarsel.Utenlandsopphold.SkalAvkortes)
}
val søknadsbehandlinger: List<Søknadsbehandling> = behandlinger.søknadsbehandlinger
val revurderinger: List<AbstraktRevurdering> = behandlinger.revurderinger
val reguleringer: List<Regulering> = behandlinger.reguleringer
val klager: List<Klage> = behandlinger.klager
val uteståendeAvkortingSkalAvkortes: Avkortingsvarsel.Utenlandsopphold.SkalAvkortes? =
uteståendeAvkorting as? Avkortingsvarsel.Utenlandsopphold.SkalAvkortes
fun info(): SakInfo {
return SakInfo(
sakId = id,
saksnummer = saksnummer,
fnr = fnr,
type = type,
)
}
fun utbetalingstidslinje(): TidslinjeForUtbetalinger? {
return utbetalinger.tidslinje().getOrNull()
}
fun kopierGjeldendeVedtaksdata(
fraOgMed: LocalDate,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeVedtaksdata, GjeldendeVedtaksdata> {
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().ifEmpty {
return KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(fraOgMed).left()
}.let { vedtakSomKanRevurderes ->
val tilOgMed = vedtakSomKanRevurderes.maxOf { it.periode.tilOgMed }
Periode.tryCreate(fraOgMed, tilOgMed).mapLeft {
when (it) {
FraOgMedDatoMåVæreFørTilOgMedDato -> KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(
fraOgMed,
tilOgMed,
)
FraOgMedDatoMåVæreFørsteDagIMåneden, TilOgMedDatoMåVæreSisteDagIMåneden,
-> KunneIkkeHenteGjeldendeVedtaksdata.UgyldigPeriode(it)
}
}.flatMap {
hentGjeldendeVedtaksdata(
periode = it,
clock = clock,
)
}
}
}
fun hentGjeldendeVedtaksdata(
periode: Periode,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes, GjeldendeVedtaksdata> {
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.ifEmpty { return KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(periode).left() }
.let { vedtakSomKanRevurderes ->
GjeldendeVedtaksdata(
periode = periode,
vedtakListe = vedtakSomKanRevurderes.toNonEmptyList(),
clock = clock,
).right()
}
}
sealed class KunneIkkeHenteGjeldendeVedtaksdata {
data class FinnesIngenVedtakSomKanRevurderes(
val fraOgMed: LocalDate,
val tilOgMed: LocalDate,
) : KunneIkkeHenteGjeldendeVedtaksdata() {
constructor(periode: Periode) : this(periode.fraOgMed, periode.tilOgMed)
constructor(fraOgMed: LocalDate) : this(fraOgMed, LocalDate.MAX)
}
data class UgyldigPeriode(val feil: Periode.UgyldigPeriode) : KunneIkkeHenteGjeldendeVedtaksdata()
}
/**
* Lager et snapshot av gjeldende vedtaksdata slik de så ut før vedtaket angitt av [vedtakId] ble
* iverksatt. Perioden for dataene begrenses til vedtaksperioden for [vedtakId].
* Brukes av vedtaksoppsummeringen for å vise differansen mellom nytt/gammelt grunnlag.
*/
fun historiskGrunnlagForVedtaketsPeriode(
vedtakId: UUID,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak, GjeldendeVedtaksdata> {
val vedtak = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().find { it.id == vedtakId }
?: return KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak.FantIkkeVedtak.left()
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().filter { it.opprettet < vedtak.opprettet }
.ifEmpty {
return KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak.IngenTidligereVedtak.left()
}.let {
GjeldendeVedtaksdata(
periode = vedtak.periode,
vedtakListe = it.toNonEmptyList(),
clock = clock,
).right()
}
}
sealed class KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak {
data object FantIkkeVedtak : KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak()
data object IngenTidligereVedtak : KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak()
}
/**
* Brukes for å hente den seneste gjeldenden/brukte beregningen for en gitt måned i saken.
*
* Per nå så er det kun Vedtak i form av [no.nav.su.se.bakover.domain.vedtak.VedtakEndringIYtelse] og [no.nav.su.se.bakover.domain.vedtak.VedtakIngenEndringIYtelse] som bidrar til dette.
*
* ##NB
* */
fun hentGjeldendeBeregningForEndringIYtelseForMåned(
måned: Måned,
clock: Clock,
): Beregning? {
return GjeldendeVedtaksdata(
periode = måned,
vedtakListe = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.filter { it.beregning != null }.ifEmpty { return null }.toNonEmptyList(),
clock = clock,
).gjeldendeVedtakForMåned(måned)?.beregning!!
}
fun hentGjeldendeMånedsberegninger(
periode: Periode,
clock: Clock,
): List<Månedsberegning> {
return GjeldendeVedtaksdata(
periode = periode,
vedtakListe = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.filter { it.beregning != null }.ifEmpty { return emptyList() }.toNonEmptyList(),
clock = clock,
).let { gjeldendeVedtaksdata ->
periode.måneder().mapNotNull { måned ->
gjeldendeVedtaksdata.gjeldendeVedtakForMåned(måned)?.beregning
?.getMånedsberegninger()?.single { it.måned == måned }
}
}
}
fun hentGjeldendeStønadsperiode(clock: Clock): Periode? =
hentIkkeOpphørtePerioder().filter { it.inneholder(LocalDate.now(clock)) }.maxByOrNull { it.tilOgMed }
fun harGjeldendeEllerFremtidigStønadsperiode(clock: Clock): Boolean {
val now = LocalDate.now(clock)
return hentIkkeOpphørtePerioder().any { it.inneholder(now) || it.starterEtter(now) }
}
fun hentRevurdering(id: UUID): Either<Unit, AbstraktRevurdering> {
return revurderinger.singleOrNull { it.id == id }?.right() ?: Unit.left()
}
fun hentSøknadsbehandling(id: UUID): Either<Unit, Søknadsbehandling> {
return søknadsbehandlinger.singleOrNull { it.id == id }?.right() ?: Unit.left()
}
/**
* Henter minste antall sammenhengende perioder hvor vedtakene ikke er av typen opphør.
*/
fun hentIkkeOpphørtePerioder(): List<Periode> =
vedtakstidslinje()?.filterNot { it.erOpphør() }?.map { it.periode }?.minsteAntallSammenhengendePerioder()
?: emptyList()
fun vedtakstidslinje(
fraOgMed: Måned,
): Tidslinje<VedtakPåTidslinje>? =
vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().lagTidslinje()?.fjernMånederFør(fraOgMed)
fun vedtakstidslinje(): Tidslinje<VedtakPåTidslinje>? =
vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().lagTidslinje()
/** Skal ikke kunne ha mer enn én åpen klage av gangen. */
fun kanOppretteKlage(): Boolean = klager.none { it.erÅpen() }
fun hentKlage(klageId: UUID): Klage? = klager.find { it.id == klageId }
fun kanUtbetalingerStansesEllerGjenopptas(clock: Clock): KanStansesEllerGjenopptas {
val tidslinje = utbetalingstidslinje()
if (tidslinje.isNullOrEmpty()) return KanStansesEllerGjenopptas.INGEN
if (!ingenKommendeOpphørEllerHull(tidslinje, clock)) return KanStansesEllerGjenopptas.INGEN
val last = tidslinje.last()
if (last is UtbetalingslinjePåTidslinje.Stans) {
return KanStansesEllerGjenopptas.GJENOPPTA
}
if (last is UtbetalingslinjePåTidslinje.Ny || last is UtbetalingslinjePåTidslinje.Reaktivering) {
return KanStansesEllerGjenopptas.STANS
}
return KanStansesEllerGjenopptas.INGEN
}
/**
* Tillater ikke stans dersom stønadsperiodene inneholder opphør eller hull frem i tid, siden det kan bli
* problematisk hvis man stanser og gjenopptar på tvers av disse. Ta opp igjen problemstillingen dersom
* fag trenger å stanse i et slikt tilfelle.
*/
private fun ingenKommendeOpphørEllerHull(
utbetalingslinjer: List<UtbetalingslinjePåTidslinje>,
clock: Clock,
): Boolean {
val kommendeUtbetalingslinjer = utbetalingslinjer.filter { it.periode.tilOgMed.isAfter(LocalDate.now(clock)) }
if (kommendeUtbetalingslinjer.any { it is UtbetalingslinjePåTidslinje.Opphør }) {
return false
}
return kommendeUtbetalingslinjer.map { linje -> linje.periode }.minsteAntallSammenhengendePerioder().size <= 1
}
fun ytelseUtløperVedUtløpAv(periode: Periode): Boolean = vedtakstidslinje()?.lastOrNull()?.let {
!it.erOpphør() && it.periode slutterSamtidig periode
} ?: false
sealed interface KunneIkkeOppretteEllerOppdatereRegulering {
data object FinnesIngenVedtakSomKanRevurderesForValgtPeriode : KunneIkkeOppretteEllerOppdatereRegulering
data object StøtterIkkeVedtaktidslinjeSomIkkeErKontinuerlig : KunneIkkeOppretteEllerOppdatereRegulering
data object BleIkkeLagetReguleringDaDenneUansettMåRevurderes : KunneIkkeOppretteEllerOppdatereRegulering
}
fun hentSøknad(id: UUID): Either<FantIkkeSøknad, Søknad> {
return søknader.singleOrNull { it.id == id }?.right() ?: FantIkkeSøknad.left()
}
data object FantIkkeSøknad
fun hentÅpneSøknadsbehandlinger(): List<Søknadsbehandling> = søknadsbehandlinger.filter { it.erÅpen() }
fun harÅpenSøknadsbehandling(): Boolean = hentÅpneSøknadsbehandlinger().isNotEmpty()
fun harÅpenStansbehandling(): Boolean = revurderinger
.filterIsInstance<StansAvYtelseRevurdering.SimulertStansAvYtelse>().isNotEmpty()
fun harÅpenGjenopptaksbehandling(): Boolean = revurderinger
.filterIsInstance<GjenopptaYtelseRevurdering.SimulertGjenopptakAvYtelse>().isNotEmpty()
fun hentSøknadsbehandlingForSøknad(søknadId: UUID): Either<FantIkkeSøknadsbehandlingForSøknad, Søknadsbehandling> {
return søknadsbehandlinger.singleOrNull { it.søknad.id == søknadId }?.right()
?: FantIkkeSøknadsbehandlingForSøknad.left()
}
sealed interface KunneIkkeOppretteSøknadsbehandling {
data object ErLukket : KunneIkkeOppretteSøknadsbehandling
data object ManglerOppgave : KunneIkkeOppretteSøknadsbehandling
data object FinnesAlleredeSøknadsehandlingForSøknad : KunneIkkeOppretteSøknadsbehandling
data object HarÅpenSøknadsbehandling : KunneIkkeOppretteSøknadsbehandling
}
internal fun hentGjeldendeVedtaksdataOgSjekkGyldighetForRevurderingsperiode(
periode: Periode,
clock: Clock,
): Either<GjeldendeVedtaksdataErUgyldigForRevurdering, GjeldendeVedtaksdata> {
return hentGjeldendeVedtaksdata(
periode = periode,
clock = clock,
).getOrElse {
return GjeldendeVedtaksdataErUgyldigForRevurdering.FantIngenVedtakSomKanRevurderes.left()
}.let {
if (!it.harVedtakIHelePerioden()) {
return GjeldendeVedtaksdataErUgyldigForRevurdering.HeleRevurderingsperiodenInneholderIkkeVedtak.left()
}
it.right()
}
}
sealed interface GjeldendeVedtaksdataErUgyldigForRevurdering {
data object FantIngenVedtakSomKanRevurderes : GjeldendeVedtaksdataErUgyldigForRevurdering
data object HeleRevurderingsperiodenInneholderIkkeVedtak : GjeldendeVedtaksdataErUgyldigForRevurdering
}
/**
* TODO Vurder å implementer alle varianter eller bytte ut hele mekanismen
* Brukes til å varsle om at vilkår man ikke har valgt å revurdere vil gir opphør. Avverger bla. at man havner
* på oppsummeringen uten å ane hva som fører til opphør. Hvis mekanismen skal leve videre bør den utvides med alle
* manglende vilkår, alternativt kan den erstattes med noe annet som f.eks at man alltid har muligheten til å
* finne vilkårene på oppsummeringssiden (også de som ikke ble revurdert aktivt av saksbehandler) eller lignende.
*/
internal fun InformasjonSomRevurderes.sjekkAtOpphørteVilkårRevurderes(gjeldendeVedtaksdata: GjeldendeVedtaksdata): Either<OpphørtVilkårMåRevurderes, Unit> {
return VurderOmVilkårGirOpphørVedRevurdering(gjeldendeVedtaksdata.vilkårsvurderinger).resultat.let {
when (it) {
is OpphørVedRevurdering.Ja -> {
if (!harValgtFormue() && it.opphørsgrunner.contains(Opphørsgrunn.FORMUE)) {
OpphørtVilkårMåRevurderes.FormueSomFørerTilOpphørMåRevurderes.left()
}
if (!harValgtUtenlandsopphold() && it.opphørsgrunner.contains(Opphørsgrunn.UTENLANDSOPPHOLD)) {
OpphørtVilkårMåRevurderes.UtenlandsoppholdSomFørerTilOpphørMåRevurderes.left()
}
Unit.right()
}
is OpphørVedRevurdering.Nei -> {
Unit.right()
}
}
}
}
sealed interface OpphørtVilkårMåRevurderes {
data object FormueSomFørerTilOpphørMåRevurderes : OpphørtVilkårMåRevurderes
data object UtenlandsoppholdSomFørerTilOpphørMåRevurderes : OpphørtVilkårMåRevurderes
}
/**
* @return Den oppdaterte saken, søknaden som er lukket og dersom den fantes, den lukkede søknadsbehandlingen.
*
* @throws IllegalArgumentException dersom søknadId ikke finnes på saken
* @throws IllegalArgumentException dersom søknaden ikke er i tilstanden [Søknad.Journalført.MedOppgave.IkkeLukket]
* @throws IllegalStateException dersom noe uventet skjer ved lukking av søknad/søknadsbehandling
*/
fun lukkSøknadOgSøknadsbehandling(
lukkSøknadCommand: LukkSøknadCommand,
saksbehandler: NavIdentBruker.Saksbehandler,
): LukkSøknadOgSøknadsbehandlingResponse {
val søknadId = lukkSøknadCommand.søknadId
val søknad = hentSøknad(søknadId).getOrElse {
throw IllegalArgumentException("Kunne ikke lukke søknad og søknadsbehandling. Fant ikke søknad for sak $id og søknad $søknadId. Underliggende feil: $it")
}
return hentSøknadsbehandlingForSøknad(søknadId).fold(
{
// Finnes ingen søknadsbehandling. Lukker kun søknaden.
val lukketSøknad = søknad.lukk(
lukkSøknadCommand = lukkSøknadCommand,
)
Tuple4(
this.copy(
søknader = this.søknader.filterNot { it.id == søknadId }.plus(lukketSøknad),
),
lukketSøknad,
null,
StatistikkEvent.Søknad.Lukket(lukketSøknad, saksnummer),
)
},
{ søknadsbehandlingSomSkalLukkes ->
// Finnes søknadsbehandling. Lukker søknadsbehandlingen, som i sin tur lukker søknaden.
søknadsbehandlingSomSkalLukkes.lukkSøknadsbehandlingOgSøknad(
lukkSøknadCommand = lukkSøknadCommand,
).getOrElse {
throw IllegalArgumentException("Kunne ikke lukke søknad ${lukkSøknadCommand.søknadId} og søknadsbehandling. Underliggende feil: $it")
}.let { lukketSøknadsbehandling ->
Tuple4(
this.oppdaterSøknadsbehandling(lukketSøknadsbehandling)
.copy(
søknader = this.søknader.filterNot { it.id == søknadId }
.plus(lukketSøknadsbehandling.søknad),
),
lukketSøknadsbehandling.søknad,
lukketSøknadsbehandling,
StatistikkEvent.Behandling.Søknad.Lukket(lukketSøknadsbehandling, saksbehandler),
)
}
},
).let { (sak, søknad, søknadsbehandling, statistikkhendelse) ->
val lagBrevRequest = søknad.lagGenererDokumentKommando { sak.saksnummer }
LukkSøknadOgSøknadsbehandlingResponse(
sak = sak,
søknad = søknad,
søknadsbehandling = søknadsbehandling,
hendelse = statistikkhendelse,
lagBrevRequest = lagBrevRequest.mapLeft { LukkSøknadOgSøknadsbehandlingResponse.IkkeLagBrevRequest },
)
}
}
/**
* @param søknadsbehandling null dersom det ikke eksisterer en søknadsbehandling
* @param lagBrevRequest null dersom vi ikke skal lage brev
*/
data class LukkSøknadOgSøknadsbehandlingResponse(
val sak: Sak,
val søknad: Søknad.Journalført.MedOppgave.Lukket,
val søknadsbehandling: LukketSøknadsbehandling?,
val hendelse: StatistikkEvent,
val lagBrevRequest: Either<IkkeLagBrevRequest, GenererDokumentCommand>,
) {
init {
// Guards spesielt med tanke på testdatasett.
require(
hendelse is StatistikkEvent.Behandling.Søknad.Lukket || hendelse is StatistikkEvent.Søknad.Lukket,
)
lagBrevRequest.onRight {
require(it.saksnummer == sak.saksnummer)
}
require(sak.hentSøknad(søknad.id).getOrNull()!! == søknad)
søknadsbehandling?.also {
require(sak.søknadsbehandlinger.contains(søknadsbehandling))
require(søknadsbehandling.søknad == søknad)
}
}
data object IkkeLagBrevRequest
}
data object FantIkkeSøknadsbehandlingForSøknad
sealed interface KunneIkkeOppdatereStønadsperiode {
data object FantIkkeBehandling : KunneIkkeOppdatereStønadsperiode
data class AldersvurderingGirIkkeRettPåUføre(val vurdering: Aldersvurdering) : KunneIkkeOppdatereStønadsperiode
data class KunneIkkeOppdatereGrunnlagsdata(
val feil: no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeOppdatereStønadsperiode,
) : KunneIkkeOppdatereStønadsperiode
data class OverlappendeStønadsperiode(val feil: StøtterIkkeOverlappendeStønadsperioder) :
KunneIkkeOppdatereStønadsperiode
}
fun avventerKravgrunnlag(): Boolean {
return revurderinger.filterIsInstance<IverksattRevurdering>()
.any { it.tilbakekrevingsbehandling.avventerKravgrunnlag() }
}
/**
* fraOgMed fra det første søknadsbehandlingsvedtaket, null hvis vi ikke har noen vedtak enda.
*/
val førsteYtelsesdato: LocalDate? = vedtakListe
.filterIsInstance<VedtakInnvilgetSøknadsbehandling>()
.minOfOrNull { it.periode.fraOgMed }
}
data class AlleredeGjeldendeSakForBruker(
val uføre: BegrensetSakinfo,
val alder: BegrensetSakinfo,
)
data class BegrensetSakinfo(
val harÅpenSøknad: Boolean,
val iverksattInnvilgetStønadsperiode: Periode?,
)
enum class KanStansesEllerGjenopptas {
STANS, GJENOPPTA, INGEN,
}
| 6 | Kotlin | 1 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 23,817 | su-se-bakover | MIT License |
domain/src/main/kotlin/no/nav/su/se/bakover/domain/sak/Sak.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.domain
import arrow.core.Either
import arrow.core.Tuple4
import arrow.core.flatMap
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.right
import no.nav.su.se.bakover.common.domain.Saksnummer
import no.nav.su.se.bakover.common.extensions.toNonEmptyList
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.periode.Måned
import no.nav.su.se.bakover.common.tid.periode.Periode
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.FraOgMedDatoMåVæreFørTilOgMedDato
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.FraOgMedDatoMåVæreFørsteDagIMåneden
import no.nav.su.se.bakover.common.tid.periode.Periode.UgyldigPeriode.TilOgMedDatoMåVæreSisteDagIMåneden
import no.nav.su.se.bakover.common.tid.periode.minsteAntallSammenhengendePerioder
import no.nav.su.se.bakover.domain.avkorting.Avkortingsvarsel
import no.nav.su.se.bakover.domain.behandling.Behandlinger
import no.nav.su.se.bakover.domain.behandling.avslag.Opphørsgrunn
import no.nav.su.se.bakover.domain.beregning.Beregning
import no.nav.su.se.bakover.domain.beregning.Månedsberegning
import no.nav.su.se.bakover.domain.brev.command.GenererDokumentCommand
import no.nav.su.se.bakover.domain.klage.Klage
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.TidslinjeForUtbetalinger
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.Utbetalinger
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.UtbetalingslinjePåTidslinje
import no.nav.su.se.bakover.domain.regulering.Regulering
import no.nav.su.se.bakover.domain.revurdering.AbstraktRevurdering
import no.nav.su.se.bakover.domain.revurdering.GjenopptaYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.IverksattRevurdering
import no.nav.su.se.bakover.domain.revurdering.StansAvYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.opphør.OpphørVedRevurdering
import no.nav.su.se.bakover.domain.revurdering.opphør.VurderOmVilkårGirOpphørVedRevurdering
import no.nav.su.se.bakover.domain.revurdering.steg.InformasjonSomRevurderes
import no.nav.su.se.bakover.domain.sak.SakInfo
import no.nav.su.se.bakover.domain.sak.Sakstype
import no.nav.su.se.bakover.domain.sak.oppdaterSøknadsbehandling
import no.nav.su.se.bakover.domain.statistikk.StatistikkEvent
import no.nav.su.se.bakover.domain.søknad.LukkSøknadCommand
import no.nav.su.se.bakover.domain.søknad.Søknad
import no.nav.su.se.bakover.domain.søknadsbehandling.LukketSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.StøtterIkkeOverlappendeStønadsperioder
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.stønadsperiode.Aldersvurdering
import no.nav.su.se.bakover.domain.tidslinje.Tidslinje
import no.nav.su.se.bakover.domain.vedtak.GjeldendeVedtaksdata
import no.nav.su.se.bakover.domain.vedtak.Vedtak
import no.nav.su.se.bakover.domain.vedtak.VedtakInnvilgetSøknadsbehandling
import no.nav.su.se.bakover.domain.vedtak.VedtakPåTidslinje
import no.nav.su.se.bakover.domain.vedtak.VedtakSomKanRevurderes
import no.nav.su.se.bakover.domain.vedtak.lagTidslinje
import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon
import no.nav.su.se.bakover.utenlandsopphold.domain.RegistrerteUtenlandsopphold
import tilbakekreving.domain.kravgrunnlag.Kravgrunnlag
import java.time.Clock
import java.time.LocalDate
import java.util.UUID
/**
* @param uteståendeAvkorting er enten [Avkortingsvarsel.Ingen] eller [Avkortingsvarsel.Utenlandsopphold.SkalAvkortes]
*/
data class Sak(
val id: UUID = UUID.randomUUID(),
val saksnummer: Saksnummer,
val opprettet: Tidspunkt,
val fnr: Fnr,
val søknader: List<Søknad> = emptyList(),
val behandlinger: Behandlinger = Behandlinger.empty(id),
// TODO jah: Bytt til [Utbetaling.Oversendt]
val utbetalinger: Utbetalinger,
val vedtakListe: List<Vedtak> = emptyList(),
val type: Sakstype,
val uteståendeAvkorting: Avkortingsvarsel = Avkortingsvarsel.Ingen,
val utenlandsopphold: RegistrerteUtenlandsopphold = RegistrerteUtenlandsopphold.empty(id),
val versjon: Hendelsesversjon,
val uteståendeKravgrunnlag: Kravgrunnlag?,
) {
init {
require(uteståendeAvkorting is Avkortingsvarsel.Ingen || uteståendeAvkorting is Avkortingsvarsel.Utenlandsopphold.SkalAvkortes)
}
val søknadsbehandlinger: List<Søknadsbehandling> = behandlinger.søknadsbehandlinger
val revurderinger: List<AbstraktRevurdering> = behandlinger.revurderinger
val reguleringer: List<Regulering> = behandlinger.reguleringer
val klager: List<Klage> = behandlinger.klager
val uteståendeAvkortingSkalAvkortes: Avkortingsvarsel.Utenlandsopphold.SkalAvkortes? =
uteståendeAvkorting as? Avkortingsvarsel.Utenlandsopphold.SkalAvkortes
fun info(): SakInfo {
return SakInfo(
sakId = id,
saksnummer = saksnummer,
fnr = fnr,
type = type,
)
}
fun utbetalingstidslinje(): TidslinjeForUtbetalinger? {
return utbetalinger.tidslinje().getOrNull()
}
fun kopierGjeldendeVedtaksdata(
fraOgMed: LocalDate,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeVedtaksdata, GjeldendeVedtaksdata> {
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().ifEmpty {
return KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(fraOgMed).left()
}.let { vedtakSomKanRevurderes ->
val tilOgMed = vedtakSomKanRevurderes.maxOf { it.periode.tilOgMed }
Periode.tryCreate(fraOgMed, tilOgMed).mapLeft {
when (it) {
FraOgMedDatoMåVæreFørTilOgMedDato -> KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(
fraOgMed,
tilOgMed,
)
FraOgMedDatoMåVæreFørsteDagIMåneden, TilOgMedDatoMåVæreSisteDagIMåneden,
-> KunneIkkeHenteGjeldendeVedtaksdata.UgyldigPeriode(it)
}
}.flatMap {
hentGjeldendeVedtaksdata(
periode = it,
clock = clock,
)
}
}
}
fun hentGjeldendeVedtaksdata(
periode: Periode,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes, GjeldendeVedtaksdata> {
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.ifEmpty { return KunneIkkeHenteGjeldendeVedtaksdata.FinnesIngenVedtakSomKanRevurderes(periode).left() }
.let { vedtakSomKanRevurderes ->
GjeldendeVedtaksdata(
periode = periode,
vedtakListe = vedtakSomKanRevurderes.toNonEmptyList(),
clock = clock,
).right()
}
}
sealed class KunneIkkeHenteGjeldendeVedtaksdata {
data class FinnesIngenVedtakSomKanRevurderes(
val fraOgMed: LocalDate,
val tilOgMed: LocalDate,
) : KunneIkkeHenteGjeldendeVedtaksdata() {
constructor(periode: Periode) : this(periode.fraOgMed, periode.tilOgMed)
constructor(fraOgMed: LocalDate) : this(fraOgMed, LocalDate.MAX)
}
data class UgyldigPeriode(val feil: Periode.UgyldigPeriode) : KunneIkkeHenteGjeldendeVedtaksdata()
}
/**
* Lager et snapshot av gjeldende vedtaksdata slik de så ut før vedtaket angitt av [vedtakId] ble
* iverksatt. Perioden for dataene begrenses til vedtaksperioden for [vedtakId].
* Brukes av vedtaksoppsummeringen for å vise differansen mellom nytt/gammelt grunnlag.
*/
fun historiskGrunnlagForVedtaketsPeriode(
vedtakId: UUID,
clock: Clock,
): Either<KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak, GjeldendeVedtaksdata> {
val vedtak = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().find { it.id == vedtakId }
?: return KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak.FantIkkeVedtak.left()
return vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().filter { it.opprettet < vedtak.opprettet }
.ifEmpty {
return KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak.IngenTidligereVedtak.left()
}.let {
GjeldendeVedtaksdata(
periode = vedtak.periode,
vedtakListe = it.toNonEmptyList(),
clock = clock,
).right()
}
}
sealed class KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak {
data object FantIkkeVedtak : KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak()
data object IngenTidligereVedtak : KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak()
}
/**
* Brukes for å hente den seneste gjeldenden/brukte beregningen for en gitt måned i saken.
*
* Per nå så er det kun Vedtak i form av [no.nav.su.se.bakover.domain.vedtak.VedtakEndringIYtelse] og [no.nav.su.se.bakover.domain.vedtak.VedtakIngenEndringIYtelse] som bidrar til dette.
*
* ##NB
* */
fun hentGjeldendeBeregningForEndringIYtelseForMåned(
måned: Måned,
clock: Clock,
): Beregning? {
return GjeldendeVedtaksdata(
periode = måned,
vedtakListe = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.filter { it.beregning != null }.ifEmpty { return null }.toNonEmptyList(),
clock = clock,
).gjeldendeVedtakForMåned(måned)?.beregning!!
}
fun hentGjeldendeMånedsberegninger(
periode: Periode,
clock: Clock,
): List<Månedsberegning> {
return GjeldendeVedtaksdata(
periode = periode,
vedtakListe = vedtakListe.filterIsInstance<VedtakSomKanRevurderes>()
.filter { it.beregning != null }.ifEmpty { return emptyList() }.toNonEmptyList(),
clock = clock,
).let { gjeldendeVedtaksdata ->
periode.måneder().mapNotNull { måned ->
gjeldendeVedtaksdata.gjeldendeVedtakForMåned(måned)?.beregning
?.getMånedsberegninger()?.single { it.måned == måned }
}
}
}
fun hentGjeldendeStønadsperiode(clock: Clock): Periode? =
hentIkkeOpphørtePerioder().filter { it.inneholder(LocalDate.now(clock)) }.maxByOrNull { it.tilOgMed }
fun harGjeldendeEllerFremtidigStønadsperiode(clock: Clock): Boolean {
val now = LocalDate.now(clock)
return hentIkkeOpphørtePerioder().any { it.inneholder(now) || it.starterEtter(now) }
}
fun hentRevurdering(id: UUID): Either<Unit, AbstraktRevurdering> {
return revurderinger.singleOrNull { it.id == id }?.right() ?: Unit.left()
}
fun hentSøknadsbehandling(id: UUID): Either<Unit, Søknadsbehandling> {
return søknadsbehandlinger.singleOrNull { it.id == id }?.right() ?: Unit.left()
}
/**
* Henter minste antall sammenhengende perioder hvor vedtakene ikke er av typen opphør.
*/
fun hentIkkeOpphørtePerioder(): List<Periode> =
vedtakstidslinje()?.filterNot { it.erOpphør() }?.map { it.periode }?.minsteAntallSammenhengendePerioder()
?: emptyList()
fun vedtakstidslinje(
fraOgMed: Måned,
): Tidslinje<VedtakPåTidslinje>? =
vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().lagTidslinje()?.fjernMånederFør(fraOgMed)
fun vedtakstidslinje(): Tidslinje<VedtakPåTidslinje>? =
vedtakListe.filterIsInstance<VedtakSomKanRevurderes>().lagTidslinje()
/** Skal ikke kunne ha mer enn én åpen klage av gangen. */
fun kanOppretteKlage(): Boolean = klager.none { it.erÅpen() }
fun hentKlage(klageId: UUID): Klage? = klager.find { it.id == klageId }
fun kanUtbetalingerStansesEllerGjenopptas(clock: Clock): KanStansesEllerGjenopptas {
val tidslinje = utbetalingstidslinje()
if (tidslinje.isNullOrEmpty()) return KanStansesEllerGjenopptas.INGEN
if (!ingenKommendeOpphørEllerHull(tidslinje, clock)) return KanStansesEllerGjenopptas.INGEN
val last = tidslinje.last()
if (last is UtbetalingslinjePåTidslinje.Stans) {
return KanStansesEllerGjenopptas.GJENOPPTA
}
if (last is UtbetalingslinjePåTidslinje.Ny || last is UtbetalingslinjePåTidslinje.Reaktivering) {
return KanStansesEllerGjenopptas.STANS
}
return KanStansesEllerGjenopptas.INGEN
}
/**
* Tillater ikke stans dersom stønadsperiodene inneholder opphør eller hull frem i tid, siden det kan bli
* problematisk hvis man stanser og gjenopptar på tvers av disse. Ta opp igjen problemstillingen dersom
* fag trenger å stanse i et slikt tilfelle.
*/
private fun ingenKommendeOpphørEllerHull(
utbetalingslinjer: List<UtbetalingslinjePåTidslinje>,
clock: Clock,
): Boolean {
val kommendeUtbetalingslinjer = utbetalingslinjer.filter { it.periode.tilOgMed.isAfter(LocalDate.now(clock)) }
if (kommendeUtbetalingslinjer.any { it is UtbetalingslinjePåTidslinje.Opphør }) {
return false
}
return kommendeUtbetalingslinjer.map { linje -> linje.periode }.minsteAntallSammenhengendePerioder().size <= 1
}
fun ytelseUtløperVedUtløpAv(periode: Periode): Boolean = vedtakstidslinje()?.lastOrNull()?.let {
!it.erOpphør() && it.periode slutterSamtidig periode
} ?: false
sealed interface KunneIkkeOppretteEllerOppdatereRegulering {
data object FinnesIngenVedtakSomKanRevurderesForValgtPeriode : KunneIkkeOppretteEllerOppdatereRegulering
data object StøtterIkkeVedtaktidslinjeSomIkkeErKontinuerlig : KunneIkkeOppretteEllerOppdatereRegulering
data object BleIkkeLagetReguleringDaDenneUansettMåRevurderes : KunneIkkeOppretteEllerOppdatereRegulering
}
fun hentSøknad(id: UUID): Either<FantIkkeSøknad, Søknad> {
return søknader.singleOrNull { it.id == id }?.right() ?: FantIkkeSøknad.left()
}
data object FantIkkeSøknad
fun hentÅpneSøknadsbehandlinger(): List<Søknadsbehandling> = søknadsbehandlinger.filter { it.erÅpen() }
fun harÅpenSøknadsbehandling(): Boolean = hentÅpneSøknadsbehandlinger().isNotEmpty()
fun harÅpenStansbehandling(): Boolean = revurderinger
.filterIsInstance<StansAvYtelseRevurdering.SimulertStansAvYtelse>().isNotEmpty()
fun harÅpenGjenopptaksbehandling(): Boolean = revurderinger
.filterIsInstance<GjenopptaYtelseRevurdering.SimulertGjenopptakAvYtelse>().isNotEmpty()
fun hentSøknadsbehandlingForSøknad(søknadId: UUID): Either<FantIkkeSøknadsbehandlingForSøknad, Søknadsbehandling> {
return søknadsbehandlinger.singleOrNull { it.søknad.id == søknadId }?.right()
?: FantIkkeSøknadsbehandlingForSøknad.left()
}
sealed interface KunneIkkeOppretteSøknadsbehandling {
data object ErLukket : KunneIkkeOppretteSøknadsbehandling
data object ManglerOppgave : KunneIkkeOppretteSøknadsbehandling
data object FinnesAlleredeSøknadsehandlingForSøknad : KunneIkkeOppretteSøknadsbehandling
data object HarÅpenSøknadsbehandling : KunneIkkeOppretteSøknadsbehandling
}
internal fun hentGjeldendeVedtaksdataOgSjekkGyldighetForRevurderingsperiode(
periode: Periode,
clock: Clock,
): Either<GjeldendeVedtaksdataErUgyldigForRevurdering, GjeldendeVedtaksdata> {
return hentGjeldendeVedtaksdata(
periode = periode,
clock = clock,
).getOrElse {
return GjeldendeVedtaksdataErUgyldigForRevurdering.FantIngenVedtakSomKanRevurderes.left()
}.let {
if (!it.harVedtakIHelePerioden()) {
return GjeldendeVedtaksdataErUgyldigForRevurdering.HeleRevurderingsperiodenInneholderIkkeVedtak.left()
}
it.right()
}
}
sealed interface GjeldendeVedtaksdataErUgyldigForRevurdering {
data object FantIngenVedtakSomKanRevurderes : GjeldendeVedtaksdataErUgyldigForRevurdering
data object HeleRevurderingsperiodenInneholderIkkeVedtak : GjeldendeVedtaksdataErUgyldigForRevurdering
}
/**
* TODO Vurder å implementer alle varianter eller bytte ut hele mekanismen
* Brukes til å varsle om at vilkår man ikke har valgt å revurdere vil gir opphør. Avverger bla. at man havner
* på oppsummeringen uten å ane hva som fører til opphør. Hvis mekanismen skal leve videre bør den utvides med alle
* manglende vilkår, alternativt kan den erstattes med noe annet som f.eks at man alltid har muligheten til å
* finne vilkårene på oppsummeringssiden (også de som ikke ble revurdert aktivt av saksbehandler) eller lignende.
*/
internal fun InformasjonSomRevurderes.sjekkAtOpphørteVilkårRevurderes(gjeldendeVedtaksdata: GjeldendeVedtaksdata): Either<OpphørtVilkårMåRevurderes, Unit> {
return VurderOmVilkårGirOpphørVedRevurdering(gjeldendeVedtaksdata.vilkårsvurderinger).resultat.let {
when (it) {
is OpphørVedRevurdering.Ja -> {
if (!harValgtFormue() && it.opphørsgrunner.contains(Opphørsgrunn.FORMUE)) {
OpphørtVilkårMåRevurderes.FormueSomFørerTilOpphørMåRevurderes.left()
}
if (!harValgtUtenlandsopphold() && it.opphørsgrunner.contains(Opphørsgrunn.UTENLANDSOPPHOLD)) {
OpphørtVilkårMåRevurderes.UtenlandsoppholdSomFørerTilOpphørMåRevurderes.left()
}
Unit.right()
}
is OpphørVedRevurdering.Nei -> {
Unit.right()
}
}
}
}
sealed interface OpphørtVilkårMåRevurderes {
data object FormueSomFørerTilOpphørMåRevurderes : OpphørtVilkårMåRevurderes
data object UtenlandsoppholdSomFørerTilOpphørMåRevurderes : OpphørtVilkårMåRevurderes
}
/**
* @return Den oppdaterte saken, søknaden som er lukket og dersom den fantes, den lukkede søknadsbehandlingen.
*
* @throws IllegalArgumentException dersom søknadId ikke finnes på saken
* @throws IllegalArgumentException dersom søknaden ikke er i tilstanden [Søknad.Journalført.MedOppgave.IkkeLukket]
* @throws IllegalStateException dersom noe uventet skjer ved lukking av søknad/søknadsbehandling
*/
fun lukkSøknadOgSøknadsbehandling(
lukkSøknadCommand: LukkSøknadCommand,
saksbehandler: NavIdentBruker.Saksbehandler,
): LukkSøknadOgSøknadsbehandlingResponse {
val søknadId = lukkSøknadCommand.søknadId
val søknad = hentSøknad(søknadId).getOrElse {
throw IllegalArgumentException("Kunne ikke lukke søknad og søknadsbehandling. Fant ikke søknad for sak $id og søknad $søknadId. Underliggende feil: $it")
}
return hentSøknadsbehandlingForSøknad(søknadId).fold(
{
// Finnes ingen søknadsbehandling. Lukker kun søknaden.
val lukketSøknad = søknad.lukk(
lukkSøknadCommand = lukkSøknadCommand,
)
Tuple4(
this.copy(
søknader = this.søknader.filterNot { it.id == søknadId }.plus(lukketSøknad),
),
lukketSøknad,
null,
StatistikkEvent.Søknad.Lukket(lukketSøknad, saksnummer),
)
},
{ søknadsbehandlingSomSkalLukkes ->
// Finnes søknadsbehandling. Lukker søknadsbehandlingen, som i sin tur lukker søknaden.
søknadsbehandlingSomSkalLukkes.lukkSøknadsbehandlingOgSøknad(
lukkSøknadCommand = lukkSøknadCommand,
).getOrElse {
throw IllegalArgumentException("Kunne ikke lukke søknad ${lukkSøknadCommand.søknadId} og søknadsbehandling. Underliggende feil: $it")
}.let { lukketSøknadsbehandling ->
Tuple4(
this.oppdaterSøknadsbehandling(lukketSøknadsbehandling)
.copy(
søknader = this.søknader.filterNot { it.id == søknadId }
.plus(lukketSøknadsbehandling.søknad),
),
lukketSøknadsbehandling.søknad,
lukketSøknadsbehandling,
StatistikkEvent.Behandling.Søknad.Lukket(lukketSøknadsbehandling, saksbehandler),
)
}
},
).let { (sak, søknad, søknadsbehandling, statistikkhendelse) ->
val lagBrevRequest = søknad.lagGenererDokumentKommando { sak.saksnummer }
LukkSøknadOgSøknadsbehandlingResponse(
sak = sak,
søknad = søknad,
søknadsbehandling = søknadsbehandling,
hendelse = statistikkhendelse,
lagBrevRequest = lagBrevRequest.mapLeft { LukkSøknadOgSøknadsbehandlingResponse.IkkeLagBrevRequest },
)
}
}
/**
* @param søknadsbehandling null dersom det ikke eksisterer en søknadsbehandling
* @param lagBrevRequest null dersom vi ikke skal lage brev
*/
data class LukkSøknadOgSøknadsbehandlingResponse(
val sak: Sak,
val søknad: Søknad.Journalført.MedOppgave.Lukket,
val søknadsbehandling: LukketSøknadsbehandling?,
val hendelse: StatistikkEvent,
val lagBrevRequest: Either<IkkeLagBrevRequest, GenererDokumentCommand>,
) {
init {
// Guards spesielt med tanke på testdatasett.
require(
hendelse is StatistikkEvent.Behandling.Søknad.Lukket || hendelse is StatistikkEvent.Søknad.Lukket,
)
lagBrevRequest.onRight {
require(it.saksnummer == sak.saksnummer)
}
require(sak.hentSøknad(søknad.id).getOrNull()!! == søknad)
søknadsbehandling?.also {
require(sak.søknadsbehandlinger.contains(søknadsbehandling))
require(søknadsbehandling.søknad == søknad)
}
}
data object IkkeLagBrevRequest
}
data object FantIkkeSøknadsbehandlingForSøknad
sealed interface KunneIkkeOppdatereStønadsperiode {
data object FantIkkeBehandling : KunneIkkeOppdatereStønadsperiode
data class AldersvurderingGirIkkeRettPåUføre(val vurdering: Aldersvurdering) : KunneIkkeOppdatereStønadsperiode
data class KunneIkkeOppdatereGrunnlagsdata(
val feil: no.nav.su.se.bakover.domain.søknadsbehandling.KunneIkkeOppdatereStønadsperiode,
) : KunneIkkeOppdatereStønadsperiode
data class OverlappendeStønadsperiode(val feil: StøtterIkkeOverlappendeStønadsperioder) :
KunneIkkeOppdatereStønadsperiode
}
fun avventerKravgrunnlag(): Boolean {
return revurderinger.filterIsInstance<IverksattRevurdering>()
.any { it.tilbakekrevingsbehandling.avventerKravgrunnlag() }
}
/**
* fraOgMed fra det første søknadsbehandlingsvedtaket, null hvis vi ikke har noen vedtak enda.
*/
val førsteYtelsesdato: LocalDate? = vedtakListe
.filterIsInstance<VedtakInnvilgetSøknadsbehandling>()
.minOfOrNull { it.periode.fraOgMed }
}
data class AlleredeGjeldendeSakForBruker(
val uføre: BegrensetSakinfo,
val alder: BegrensetSakinfo,
)
data class BegrensetSakinfo(
val harÅpenSøknad: Boolean,
val iverksattInnvilgetStønadsperiode: Periode?,
)
enum class KanStansesEllerGjenopptas {
STANS, GJENOPPTA, INGEN,
}
| 6 | Kotlin | 1 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 23,817 | su-se-bakover | MIT License |
src/main/kotlin/kotlinmud/path/Explored.kt | brandonlamb | 275,313,206 | true | {"Kotlin": 435931, "Dockerfile": 133, "Shell": 126} | package kotlinmud.path
import kotlinmud.room.model.Room
class Explored(val room: Room, var explored: Boolean = false)
| 0 | null | 0 | 0 | fc03c6230b9b3b66cd63994e74ddd7897732d527 | 120 | kotlinmud | MIT License |
serenity-app/src/main/java/us/nineworlds/serenity/ui/leanback/search/CardPresenter.kt | NineWorlds | 7,139,471 | false | null | /**
* The MIT License (MIT)
* Copyright (c) 2012 <NAME>
* 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 us.nineworlds.serenity.ui.leanback.search
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.annotation.VisibleForTesting
import androidx.leanback.widget.ImageCardView
import androidx.leanback.widget.Presenter
import androidx.core.content.ContextCompat
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import us.nineworlds.serenity.GlideApp
import us.nineworlds.serenity.R
import us.nineworlds.serenity.core.model.VideoContentInfo
class CardPresenter(private val context: Context) : Presenter() {
val imageWidth = context.resources.getDimensionPixelSize(R.dimen.movie_poster_image_width)
val imageHeight = context.resources.getDimensionPixelSize(R.dimen.movie_poster_image_height)
override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder {
val imageView = createImageView()
imageView.isFocusable = true
imageView.isFocusableInTouchMode = true
imageView.setBackgroundColor(ContextCompat.getColor(context, R.color.holo_color))
return CardPresenterViewHolder(imageView)
}
internal fun createImageView(): ImageCardView = ImageCardView(context)
override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) {
val video = item as VideoContentInfo
val cardHolder = viewHolder as CardPresenterViewHolder
val imageCardView = cardHolder.cardView
cardHolder.movie = video
video.imageURL?.let {
imageCardView.titleText = video.title
imageCardView.contentText = video.studio
val activity = getActivity(context)
activity?.let {
imageCardView.setMainImageDimensions(imageWidth, imageHeight)
imageCardView.setMainImageScaleType(ImageView.ScaleType.FIT_XY)
cardHolder.updateCardViewImage(video.imageURL)
}
}
}
internal fun getActivity(contextWrapper: Context): Activity? {
var context = contextWrapper
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
return null
}
override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) {
val vh = viewHolder as CardPresenterViewHolder
vh.reset()
}
@VisibleForTesting
inner class CardPresenterViewHolder(view: View) : Presenter.ViewHolder(view) {
var movie: VideoContentInfo? = null
val cardView: ImageCardView = view as ImageCardView
fun reset() {
cardView.badgeImage = null
cardView.mainImage = null
}
fun updateCardViewImage(url: String) {
GlideApp.with(context).load(url).fitCenter().into(cardView.mainImageView)
}
}
}
| 52 | null | 65 | 177 | 155cfb76bb58f2f06ccac8e3e45151221c59560d | 3,825 | serenity-android | MIT License |
app/src/main/java/eu/kanade/tachiyomi/data/backup/restore/BackupRestoreJob.kt | mihonapp | 743,704,912 | false | null | package eu.kanade.tachiyomi.data.backup.restore
import android.content.Context
import android.content.pm.ServiceInfo
import android.net.Uri
import android.os.Build
import androidx.core.net.toUri
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import eu.kanade.tachiyomi.data.backup.BackupNotifier
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.util.system.cancelNotification
import eu.kanade.tachiyomi.util.system.isRunning
import eu.kanade.tachiyomi.util.system.workManager
import kotlinx.coroutines.CancellationException
import logcat.LogPriority
import tachiyomi.core.i18n.stringResource
import tachiyomi.core.util.system.logcat
import tachiyomi.i18n.MR
class BackupRestoreJob(private val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
private val notifier = BackupNotifier(context)
override suspend fun doWork(): Result {
val uri = inputData.getString(LOCATION_URI_KEY)?.toUri()
val options = inputData.getBooleanArray(OPTIONS_KEY)?.let { RestoreOptions.fromBooleanArray(it) }
if (uri == null || options == null) {
return Result.failure()
}
val isSync = inputData.getBoolean(SYNC_KEY, false)
try {
setForeground(getForegroundInfo())
} catch (e: IllegalStateException) {
logcat(LogPriority.ERROR, e) { "Not allowed to run on foreground service" }
}
return try {
BackupRestorer(context, notifier, isSync).restore(uri, options)
Result.success()
} catch (e: Exception) {
if (e is CancellationException) {
notifier.showRestoreError(context.stringResource(MR.strings.restoring_backup_canceled))
Result.success()
} else {
logcat(LogPriority.ERROR, e)
notifier.showRestoreError(e.message)
Result.failure()
}
} finally {
context.cancelNotification(Notifications.ID_RESTORE_PROGRESS)
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
return ForegroundInfo(
Notifications.ID_RESTORE_PROGRESS,
notifier.showRestoreProgress().build(),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
} else {
0
},
)
}
companion object {
fun isRunning(context: Context): Boolean {
return context.workManager.isRunning(TAG)
}
fun start(
context: Context,
uri: Uri,
options: RestoreOptions,
sync: Boolean = false,
) {
val inputData = workDataOf(
LOCATION_URI_KEY to uri.toString(),
SYNC_KEY to sync,
OPTIONS_KEY to options.asBooleanArray(),
)
val request = OneTimeWorkRequestBuilder<BackupRestoreJob>()
.addTag(TAG)
.setInputData(inputData)
.build()
context.workManager.enqueueUniqueWork(TAG, ExistingWorkPolicy.KEEP, request)
}
fun stop(context: Context) {
context.workManager.cancelUniqueWork(TAG)
}
}
}
private const val TAG = "BackupRestore"
private const val LOCATION_URI_KEY = "location_uri" // String
private const val SYNC_KEY = "sync" // Boolean
private const val OPTIONS_KEY = "options" // BooleanArray
| 93 | null | 98 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 3,727 | mihon | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/data/backup/restore/BackupRestoreJob.kt | mihonapp | 743,704,912 | false | null | package eu.kanade.tachiyomi.data.backup.restore
import android.content.Context
import android.content.pm.ServiceInfo
import android.net.Uri
import android.os.Build
import androidx.core.net.toUri
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import eu.kanade.tachiyomi.data.backup.BackupNotifier
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.util.system.cancelNotification
import eu.kanade.tachiyomi.util.system.isRunning
import eu.kanade.tachiyomi.util.system.workManager
import kotlinx.coroutines.CancellationException
import logcat.LogPriority
import tachiyomi.core.i18n.stringResource
import tachiyomi.core.util.system.logcat
import tachiyomi.i18n.MR
class BackupRestoreJob(private val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
private val notifier = BackupNotifier(context)
override suspend fun doWork(): Result {
val uri = inputData.getString(LOCATION_URI_KEY)?.toUri()
val options = inputData.getBooleanArray(OPTIONS_KEY)?.let { RestoreOptions.fromBooleanArray(it) }
if (uri == null || options == null) {
return Result.failure()
}
val isSync = inputData.getBoolean(SYNC_KEY, false)
try {
setForeground(getForegroundInfo())
} catch (e: IllegalStateException) {
logcat(LogPriority.ERROR, e) { "Not allowed to run on foreground service" }
}
return try {
BackupRestorer(context, notifier, isSync).restore(uri, options)
Result.success()
} catch (e: Exception) {
if (e is CancellationException) {
notifier.showRestoreError(context.stringResource(MR.strings.restoring_backup_canceled))
Result.success()
} else {
logcat(LogPriority.ERROR, e)
notifier.showRestoreError(e.message)
Result.failure()
}
} finally {
context.cancelNotification(Notifications.ID_RESTORE_PROGRESS)
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
return ForegroundInfo(
Notifications.ID_RESTORE_PROGRESS,
notifier.showRestoreProgress().build(),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
} else {
0
},
)
}
companion object {
fun isRunning(context: Context): Boolean {
return context.workManager.isRunning(TAG)
}
fun start(
context: Context,
uri: Uri,
options: RestoreOptions,
sync: Boolean = false,
) {
val inputData = workDataOf(
LOCATION_URI_KEY to uri.toString(),
SYNC_KEY to sync,
OPTIONS_KEY to options.asBooleanArray(),
)
val request = OneTimeWorkRequestBuilder<BackupRestoreJob>()
.addTag(TAG)
.setInputData(inputData)
.build()
context.workManager.enqueueUniqueWork(TAG, ExistingWorkPolicy.KEEP, request)
}
fun stop(context: Context) {
context.workManager.cancelUniqueWork(TAG)
}
}
}
private const val TAG = "BackupRestore"
private const val LOCATION_URI_KEY = "location_uri" // String
private const val SYNC_KEY = "sync" // Boolean
private const val OPTIONS_KEY = "options" // BooleanArray
| 93 | null | 98 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 3,727 | mihon | Apache License 2.0 |
app/src/main/java/com/wuruoye/know/ui/home/ReviewFragment.kt | ruoyewu | 176,071,372 | false | null | package com.wuruoye.know.ui.home
import android.os.Bundle
import android.view.View
import com.wuruoye.know.R
import com.wuruoye.know.ui.home.contract.ReviewContract
import com.wuruoye.library.ui.WBaseFragment
/**
* Created : wuruoye
* Date : 2019/3/6 23:24.
* Description :
*/
class ReviewFragment : WBaseFragment<ReviewContract.Presenter>() {
override fun getContentView(): Int {
return R.layout.fragment_review
}
override fun initData(bundle: Bundle?) {
}
override fun initView(view: View) {
}
}
| 0 | Kotlin | 0 | 0 | e35ce90cadab323b7a33ec2d52d214dfd4868b20 | 541 | know | Apache License 2.0 |
wearapp/src/main/java/com/thewizrd/simpleweather/utils/InputMethodUtils.kt | SimpleAppProjects | 82,603,731 | false | {"Kotlin": 3475152, "Java": 2712561, "HTML": 32933} | package com.thewizrd.simpleweather.utils
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
fun View.showInputMethod() {
val imm =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
}
fun View.hideInputMethod() {
val imm =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
imm.hideSoftInputFromWindow(this.windowToken, 0)
} | 0 | Kotlin | 8 | 37 | 56ddf09611d786e3bb2b802bdbcbbec648f0df9a | 555 | SimpleWeather-Android | Apache License 2.0 |
wearapp/src/main/java/com/thewizrd/simpleweather/utils/InputMethodUtils.kt | SimpleAppProjects | 82,603,731 | false | {"Kotlin": 3475152, "Java": 2712561, "HTML": 32933} | package com.thewizrd.simpleweather.utils
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
fun View.showInputMethod() {
val imm =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
}
fun View.hideInputMethod() {
val imm =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
imm.hideSoftInputFromWindow(this.windowToken, 0)
} | 0 | Kotlin | 8 | 37 | 56ddf09611d786e3bb2b802bdbcbbec648f0df9a | 555 | SimpleWeather-Android | Apache License 2.0 |
src/main/kotlin/com/demonwav/mcdev/util/actions.kt | Earthcomputer | 240,984,777 | false | null | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2019 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.demonwav.mcdev.facet.MinecraftFacet
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.PsiFile
import java.util.Arrays
fun getDataFromActionEvent(e: AnActionEvent): ActionData? {
fun findModuleForLibrary(file: PsiFile): Module? {
val virtualFile = file.virtualFile ?: return null
val index = ProjectFileIndex.SERVICE.getInstance(file.project)
if (!index.isInLibrarySource(virtualFile) && !index.isInLibraryClasses(virtualFile)) {
return null
}
val orderEntries = index.getOrderEntriesForFile(virtualFile)
if (orderEntries.isEmpty()) {
return null
}
if (orderEntries.size == 1) {
return orderEntries[0].ownerModule
}
val ownerModules = orderEntries.map { it.ownerModule }.toTypedArray()
Arrays.sort(ownerModules, ModuleManager.getInstance(file.project).moduleDependencyComparator())
return ownerModules[0]
}
val project = e.project ?: return null
val editor = e.getData(CommonDataKeys.EDITOR) ?: return null
val file = e.getData(CommonDataKeys.PSI_FILE) ?: return null
val caret = e.getData(CommonDataKeys.CARET) ?: return null
val element = file.findElementAt(caret.offset) ?: return null
val module = ModuleUtil.findModuleForPsiElement(element) ?: findModuleForLibrary(file) ?: return null
val instance = MinecraftFacet.getInstance(module) ?: return null
return ActionData(project, editor, file, element, caret, instance)
}
| 204 | null | 2 | 23 | ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5 | 1,947 | MinecraftDev | MIT License |
room/room-runtime/src/test/java/androidx/room/util/UUIDUtilTest.kt | JetBrains | 351,708,598 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.util
import androidx.kruth.assertThat
import java.nio.ByteBuffer
import java.util.UUID
import kotlin.random.Random
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class UUIDUtilTest {
@Test
fun convertToByte() {
val uuid = UUID.randomUUID()
val expected =
ByteBuffer.wrap(ByteArray(16))
.apply {
putLong(uuid.mostSignificantBits)
putLong(uuid.leastSignificantBits)
}
.array()
val result = convertUUIDToByte(uuid)
assertThat(result).isEqualTo(expected)
}
@Test
fun convertToUUID() {
val byteArray = Random.Default.nextBytes(ByteArray(16))
val buffer = ByteBuffer.wrap(byteArray)
val expected = UUID(buffer.long, buffer.long)
val result = convertByteToUUID(byteArray)
assertThat(result).isEqualTo(expected)
}
}
| 29 | null | 937 | 59 | e18ad812b77fc8babb00aacfcea930607b0794b5 | 1,616 | androidx | Apache License 2.0 |
app/src/main/java/dev/alibagherifam/mentha/camera/CameraScreen.kt | alibagherifam | 586,387,395 | false | null | package dev.alibagherifam.mentha.camera
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.FilledTonalIconToggleButton
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import dev.alibagherifam.mentha.R
import dev.alibagherifam.mentha.comoon.LocalizationPreviews
import dev.alibagherifam.mentha.comoon.getSampleFood
import dev.alibagherifam.mentha.theme.MenthaTheme
@Composable
fun CameraScreen(
uiState: CameraUiState,
onFlashlightToggle: (Boolean) -> Unit,
onSettingsClick: () -> Unit,
onShowDetailsClick: () -> Unit,
onPreviewViewCreated: ((PreviewView) -> Unit)?,
modifier: Modifier = Modifier
) {
Box(modifier.fillMaxSize()) {
CameraPreviewView(onPreviewViewCreated)
ActionBar(
uiState.isFlashlightSupported,
uiState.isFlashlightEnabled,
onFlashlightToggle,
onSettingsClick,
modifier = Modifier
.align(Alignment.TopCenter)
.padding(horizontal = 16.dp)
.padding(top = 16.dp),
)
ScanAreaRectangle(Modifier.align(Alignment.Center))
AnimatedRecognitionCard(
uiState.food,
onShowDetailsClick,
Modifier
.align(Alignment.BottomCenter)
.padding(horizontal = 24.dp)
.padding(bottom = 20.dp),
)
}
}
@Composable
fun ActionBar(
isFlashlightSupported: Boolean,
isFlashlightEnabled: Boolean,
onFlashlightToggle: (Boolean) -> Unit,
onSettingsClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(modifier) {
// TODO: Add settings
/*FilledTonalIconButton(onClick = onSettingsClick) {
Icon(
painter = painterResource(id = R.drawable.ic_settings),
contentDescription = stringResource(R.string.a11y_settings_button)
)
}*/
Spacer(modifier = Modifier.weight(1f))
if (isFlashlightSupported) {
FilledTonalIconToggleButton(
checked = isFlashlightEnabled,
onCheckedChange = onFlashlightToggle
) {
val icon =
if (isFlashlightEnabled) R.drawable.ic_flash_on else R.drawable.ic_flash_off
Icon(
painter = painterResource(icon),
contentDescription = stringResource(R.string.a11y_flashlight_toggle)
)
}
}
}
}
@Composable
fun ScanAreaRectangle(modifier: Modifier = Modifier) {
Image(
contentScale = ContentScale.FillBounds,
modifier = modifier
.fillMaxWidth(fraction = 0.80f)
.fillMaxHeight(fraction = 0.56f)
.offset(y = (-50).dp),
painter = painterResource(id = R.drawable.bg_scan_square),
contentDescription = ""
)
}
@LocalizationPreviews
@Composable
fun CameraScreenPreview() {
MenthaTheme {
CameraScreen(
uiState = CameraUiState(food = getSampleFood()),
onFlashlightToggle = {},
onSettingsClick = {},
onShowDetailsClick = {},
onPreviewViewCreated = null
)
}
}
| 1 | Kotlin | 1 | 9 | 35283da73663fbe24a0b15d75a8cfbeb4e203814 | 3,934 | mentha | Apache License 2.0 |
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/projectUtils.kt | Maccimo | 18,582,736 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.configuration
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.search.FileTypeIndex
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.psi.UserDataProperty
fun hasKotlinFilesOnlyInTests(module: Module): Boolean {
return !hasKotlinFilesInSources(module) && FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, module.getModuleScope(true))
}
fun hasKotlinFilesInSources(module: Module): Boolean {
return FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, module.getModuleScope(false))
}
var Module.externalCompilerVersion: String? by UserDataProperty(Key.create("EXTERNAL_COMPILER_VERSION"))
fun findLatestExternalKotlinCompilerVersion(project: Project): IdeKotlinVersion? {
return findExternalKotlinCompilerVersions(project).maxOrNull()
}
fun findExternalKotlinCompilerVersions(project: Project): Set<IdeKotlinVersion> {
val result = LinkedHashSet<IdeKotlinVersion>()
var hasJpsModules = false
runReadAction {
for (module in ModuleManager.getInstance(project).modules) {
if (module.buildSystemType == BuildSystemType.JPS) {
if (!hasJpsModules) hasJpsModules = true
} else {
val externalVersion = module.externalCompilerVersion?.let(IdeKotlinVersion::opt)
if (externalVersion != null) {
result.add(externalVersion)
}
}
}
}
if (hasJpsModules) {
val projectGlobalVersion = KotlinJpsPluginSettings.jpsVersion(project)?.let(IdeKotlinVersion::opt)
if (projectGlobalVersion != null) {
result.add(projectGlobalVersion)
}
}
return result
}
fun <T> Project.syncNonBlockingReadAction(smartMode: Boolean = false, task: () -> T): T =
ReadAction.nonBlocking<T> {
task()
}
.expireWith(KotlinPluginDisposable.getInstance(this))
.let {
if (smartMode) it.inSmartMode(this) else it
}
.executeSynchronously()
| 1 | null | 1 | 1 | aa7852d5f99bd8dcd44f6cb430e4e9b94eb96dd1 | 2,629 | intellij-community | Apache License 2.0 |
okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt | square | 5,152,285 | false | null | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.curl
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import assertk.assertions.startsWith
import java.io.IOException
import kotlin.test.Test
import okhttp3.RequestBody
import okio.Buffer
class MainTest {
@Test
fun simple() {
val request = fromArgs("http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.body).isNull()
}
@Test
@Throws(IOException::class)
fun put() {
val request = fromArgs("-X", "PUT", "-d", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("PUT")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.body!!.contentLength()).isEqualTo(3)
}
@Test
fun dataPost() {
val request = fromArgs("-d", "foo", "http://example.com").createRequest()
val body = request.body
assertThat(request.method).isEqualTo("POST")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString()).isEqualTo(
"application/x-www-form-urlencoded; charset=utf-8",
)
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun dataPut() {
val request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest()
val body = request.body
assertThat(request.method).isEqualTo("PUT")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString()).isEqualTo(
"application/x-www-form-urlencoded; charset=utf-8",
)
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun contentTypeHeader() {
val request =
fromArgs(
"-d",
"foo",
"-H",
"Content-Type: application/json",
"http://example.com",
).createRequest()
val body = request.body
assertThat(request.method).isEqualTo("POST")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString())
.isEqualTo("application/json; charset=utf-8")
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun referer() {
val request = fromArgs("-e", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.header("Referer")).isEqualTo("foo")
assertThat(request.body).isNull()
}
@Test
fun userAgent() {
val request = fromArgs("-A", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.header("User-Agent")).isEqualTo("foo")
assertThat(request.body).isNull()
}
@Test
fun defaultUserAgent() {
val request = fromArgs("http://example.com").createRequest()
assertThat(request.header("User-Agent")!!).startsWith("okcurl/")
}
@Test
fun headerSplitWithDate() {
val request =
fromArgs(
"-H",
"If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT",
"http://example.com",
).createRequest()
assertThat(request.header("If-Modified-Since")).isEqualTo(
"Mon, 18 Aug 2014 15:16:06 GMT",
)
}
companion object {
fun fromArgs(vararg args: String): Main {
return Main().apply {
parse(args.toList())
}
}
private fun bodyAsString(body: RequestBody?): String {
return try {
val buffer = Buffer()
body!!.writeTo(buffer)
buffer.readString(body.contentType()!!.charset()!!)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
}
| 2 | null | 9281 | 45,832 | dbedfd000c8e84bc914c619714b8c9bf7f3e06d4 | 4,414 | okhttp | Apache License 2.0 |
okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt | square | 5,152,285 | false | null | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.curl
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import assertk.assertions.startsWith
import java.io.IOException
import kotlin.test.Test
import okhttp3.RequestBody
import okio.Buffer
class MainTest {
@Test
fun simple() {
val request = fromArgs("http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.body).isNull()
}
@Test
@Throws(IOException::class)
fun put() {
val request = fromArgs("-X", "PUT", "-d", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("PUT")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.body!!.contentLength()).isEqualTo(3)
}
@Test
fun dataPost() {
val request = fromArgs("-d", "foo", "http://example.com").createRequest()
val body = request.body
assertThat(request.method).isEqualTo("POST")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString()).isEqualTo(
"application/x-www-form-urlencoded; charset=utf-8",
)
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun dataPut() {
val request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest()
val body = request.body
assertThat(request.method).isEqualTo("PUT")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString()).isEqualTo(
"application/x-www-form-urlencoded; charset=utf-8",
)
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun contentTypeHeader() {
val request =
fromArgs(
"-d",
"foo",
"-H",
"Content-Type: application/json",
"http://example.com",
).createRequest()
val body = request.body
assertThat(request.method).isEqualTo("POST")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(body!!.contentType().toString())
.isEqualTo("application/json; charset=utf-8")
assertThat(bodyAsString(body)).isEqualTo("foo")
}
@Test
fun referer() {
val request = fromArgs("-e", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.header("Referer")).isEqualTo("foo")
assertThat(request.body).isNull()
}
@Test
fun userAgent() {
val request = fromArgs("-A", "foo", "http://example.com").createRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.url.toString()).isEqualTo("http://example.com/")
assertThat(request.header("User-Agent")).isEqualTo("foo")
assertThat(request.body).isNull()
}
@Test
fun defaultUserAgent() {
val request = fromArgs("http://example.com").createRequest()
assertThat(request.header("User-Agent")!!).startsWith("okcurl/")
}
@Test
fun headerSplitWithDate() {
val request =
fromArgs(
"-H",
"If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT",
"http://example.com",
).createRequest()
assertThat(request.header("If-Modified-Since")).isEqualTo(
"Mon, 18 Aug 2014 15:16:06 GMT",
)
}
companion object {
fun fromArgs(vararg args: String): Main {
return Main().apply {
parse(args.toList())
}
}
private fun bodyAsString(body: RequestBody?): String {
return try {
val buffer = Buffer()
body!!.writeTo(buffer)
buffer.readString(body.contentType()!!.charset()!!)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
}
| 2 | null | 9281 | 45,832 | dbedfd000c8e84bc914c619714b8c9bf7f3e06d4 | 4,414 | okhttp | Apache License 2.0 |
app/src/main/java/com/wkw/hot/data/api/HotApi.kt | zj-wukewei | 93,613,475 | false | null | package com.wkw.hot.data.api
import com.wkw.hot.domain.model.HotResponse
import com.wkw.hot.domain.model.PagePopularEntity
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Query
/**
* Created by hzwukewei on 2017-6-6.
*/
interface HotApi {
@GET("582-2")
fun getPopular(@Query("page") page: Int, @Query("key") word: String?,
@Query("showapi_appid") appid: String,
@Query("showapi_sign") sign: String): Observable<HotResponse<PagePopularEntity>>
} | 0 | Kotlin | 1 | 2 | 4d241aadc7a258a76a197198769e947abbb85b03 | 525 | Hot_Kotlin | Apache License 2.0 |
project/jimmer-ksp/src/main/kotlin/org/babyfish/jimmer/ksp/client/ClientExceptionMetadata.kt | babyfish-ct | 488,154,823 | false | null | package org.babyfish.jimmer.ksp.client
import com.google.devtools.ksp.symbol.KSClassDeclaration
data class ClientExceptionMetadata(
val declaration: KSClassDeclaration,
val family: String,
val code: String?,
val superMetadata: ClientExceptionMetadata?
) {
private lateinit var _subMetadatas: List<ClientExceptionMetadata>
var subMetadatas: List<ClientExceptionMetadata>
get() = _subMetadatas
internal set(value) { _subMetadatas = value }
} | 13 | null | 72 | 725 | 873f8405a268d95d0b2e0ff796e2d0925ced21e7 | 482 | jimmer | Apache License 2.0 |
src/main/kotlin/cadmium/chrome/Chrome.kt | clonejo | 213,063,430 | true | {"Kotlin": 35892} | package cadmium.chrome
import cadmium.Browser
import cadmium.BrowserConfig
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
/**
* Represents the Chrome Webbrowser
*/
class Chrome(config: ChromeConfig) : Browser(ChromeDriver(config.options), config)
/**
* Configuration object for Chrome
*
* @property options specific options of ChromeDriver
* @see org.openqa.selenium.chrome.ChromeOptions
*/
class ChromeConfig(
var options: ChromeOptions
) : BrowserConfig()
/**
* Initialize a Chrome instance with custom configuration
*
* @param configAction executed on ChromeConfig object before that is used to initialize ChromeWebDriver
* @return Chrome configured with given configuration
* @sample headlessChrome
*/
fun chrome(configAction: ChromeConfig.() -> Unit = {}): Chrome {
val config = ChromeConfig(ChromeOptions())
//set default parameter
config.options.setBinary("/usr/bin/chromium-browser") //this only works on linux atm
//apply user configurations
config.configAction()
return Chrome(config)
}
/**
* Initialize Chrome in headless mode
*/
fun headlessChrome() = chrome {
options.setHeadless(true)
} | 0 | null | 0 | 0 | 5d695f420be8660523eac0d4dd0dde942363c412 | 1,203 | cadmium | MIT License |
platform/build-scripts/src/org/jetbrains/intellij/build/impl/PlatformModules.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "ReplaceGetOrSet")
package org.jetbrains.intellij.build.impl
import com.intellij.util.xml.dom.readXmlAsModel
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.impl.PlatformJarNames.APP_JAR
import org.jetbrains.intellij.build.impl.PlatformJarNames.PRODUCT_CLIENT_JAR
import org.jetbrains.intellij.build.impl.PlatformJarNames.PRODUCT_JAR
import org.jetbrains.intellij.build.impl.PlatformJarNames.TEST_FRAMEWORK_JAR
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaClasspathKind
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsLibraryDependency
import org.jetbrains.jps.model.module.JpsModuleDependency
import org.jetbrains.jps.model.module.JpsModuleReference
import java.util.*
private val PLATFORM_API_MODULES = persistentListOf(
"intellij.platform.analysis",
"intellij.platform.builtInServer",
"intellij.platform.diff",
"intellij.platform.editor",
"intellij.platform.externalSystem",
"intellij.platform.externalSystem.dependencyUpdater",
"intellij.platform.codeStyle",
"intellij.platform.lang.core",
"intellij.platform.ml",
"intellij.platform.remote.core",
"intellij.platform.remoteServers.agent.rt",
"intellij.platform.remoteServers",
"intellij.platform.usageView",
"intellij.platform.execution",
"intellij.xml.analysis",
"intellij.xml",
"intellij.xml.psi",
"intellij.xml.structureView",
)
/**
* List of modules which are included in lib/app.jar in all IntelliJ based IDEs.
*/
private val PLATFORM_IMPLEMENTATION_MODULES = persistentListOf(
"intellij.platform.analysis.impl",
"intellij.platform.diff.impl",
"intellij.platform.editor.ex",
"intellij.platform.elevation",
"intellij.platform.externalProcessAuthHelper",
"intellij.platform.inspect",
// lvcs.xml - convert into product module
"intellij.platform.lvcs.impl",
"intellij.platform.macro",
"intellij.platform.scriptDebugger.protocolReaderRuntime",
"intellij.regexp",
"intellij.platform.remoteServers.impl",
"intellij.platform.scriptDebugger.backend",
"intellij.platform.scriptDebugger.ui",
"intellij.platform.smRunner",
"intellij.platform.smRunner.vcs",
"intellij.platform.structureView.impl",
"intellij.platform.tasks.impl",
"intellij.platform.testRunner",
"intellij.platform.dependenciesToolwindow",
"intellij.platform.rd.community",
"intellij.remoteDev.util",
"intellij.platform.feedback",
"intellij.platform.warmup",
"intellij.idea.community.build.dependencies",
"intellij.platform.usageView.impl",
"intellij.platform.ml.impl",
"intellij.platform.bootstrap",
"intellij.relaxng",
"intellij.json",
"intellij.spellchecker",
"intellij.platform.webSymbols",
"intellij.xml.dom.impl",
"intellij.platform.vcs.dvcs.impl",
"intellij.platform.vcs.log.graph.impl",
"intellij.platform.vcs.log.impl",
"intellij.smart.update",
"intellij.platform.collaborationTools",
"intellij.platform.collaborationTools.auth",
"intellij.platform.markdown.utils",
)
internal val PLATFORM_CUSTOM_PACK_MODE: Map<String, LibraryPackMode> = persistentMapOf(
"jetbrains-annotations-java5" to LibraryPackMode.STANDALONE_SEPARATE_WITHOUT_VERSION_NAME,
"intellij-coverage" to LibraryPackMode.STANDALONE_SEPARATE,
)
internal fun collectPlatformModules(to: MutableCollection<String>) {
to.addAll(PLATFORM_API_MODULES)
to.addAll(PLATFORM_IMPLEMENTATION_MODULES)
}
internal fun hasPlatformCoverage(productLayout: ProductModulesLayout, enabledPluginModules: Set<String>, context: BuildContext): Boolean {
val modules = HashSet<String>()
collectIncludedPluginModules(enabledPluginModules = enabledPluginModules, product = productLayout, result = modules)
modules.addAll(PLATFORM_API_MODULES)
modules.addAll(PLATFORM_IMPLEMENTATION_MODULES)
modules.addAll(productLayout.productApiModules)
modules.addAll(productLayout.productImplementationModules)
val coverageModuleName = "intellij.platform.coverage"
if (modules.contains(coverageModuleName)) {
return true
}
val javaExtensionService = JpsJavaExtensionService.getInstance()
for (moduleName in modules) {
for (element in context.findRequiredModule(moduleName).dependenciesList.dependencies) {
if (element !is JpsModuleDependency ||
javaExtensionService.getDependencyExtension(element)?.scope?.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME) != true) {
continue
}
if (element.moduleReference.moduleName == coverageModuleName) {
return true
}
}
}
return false
}
private fun addModule(relativeJarPath: String,
moduleNames: Collection<String>,
productLayout: ProductModulesLayout,
layout: PlatformLayout) {
layout.withModules(moduleNames.asSequence()
.filter { !productLayout.excludedModuleNames.contains(it) }
.map { ModuleItem(moduleName = it, relativeOutputFile = relativeJarPath, reason = "addModule") }.toList())
}
suspend fun createPlatformLayout(pluginsToPublish: Set<PluginLayout>, context: BuildContext): PlatformLayout {
val enabledPluginModules = getEnabledPluginModules(pluginsToPublish = pluginsToPublish, productProperties = context.productProperties)
val productLayout = context.productProperties.productLayout
return createPlatformLayout(
addPlatformCoverage = !productLayout.excludedModuleNames.contains("intellij.platform.coverage") &&
hasPlatformCoverage(productLayout = productLayout,
enabledPluginModules = enabledPluginModules,
context = context),
projectLibrariesUsedByPlugins = computeProjectLibsUsedByPlugins(enabledPluginModules = enabledPluginModules, context = context),
context = context,
)
}
internal suspend fun createPlatformLayout(addPlatformCoverage: Boolean,
projectLibrariesUsedByPlugins: SortedSet<ProjectLibraryData>,
context: BuildContext): PlatformLayout {
val jetBrainsClientModuleFilter = context.jetBrainsClientModuleFilter
val productLayout = context.productProperties.productLayout
val layout = PlatformLayout()
// used only in modules that packed into Java
layout.withoutProjectLibrary("jps-javac-extension")
layout.withoutProjectLibrary("Eclipse")
for (customizer in productLayout.platformLayoutSpec) {
customizer(layout, context)
}
for ((module, patterns) in productLayout.moduleExcludes) {
layout.excludeFromModule(module, patterns)
}
addModule(UTIL_RT_JAR, listOf(
"intellij.platform.util.rt",
"intellij.platform.util.trove",
), productLayout = productLayout, layout = layout)
layout.withProjectLibrary(libraryName = "ion", jarName = UTIL_RT_JAR)
// JDOM is used by maven in an external process
addModule(UTIL_8_JAR, listOf(
"intellij.platform.util.jdom",
"intellij.platform.util.xmlDom",
"intellij.platform.tracing.rt",
"intellij.platform.util.base",
"intellij.platform.diagnostic",
"intellij.platform.util",
"intellij.platform.core",
), productLayout = productLayout, layout = layout)
// used by jdom - pack to the same JAR
layout.withProjectLibrary(libraryName = "aalto-xml", jarName = UTIL_8_JAR)
// Space plugin uses it and bundles into IntelliJ IDEA, but not bundles into DataGrip, so, or Space plugin should bundle this lib,
// or IJ Platform. As it is a small library and consistency is important across other coroutine libs, bundle to IJ Platform.
layout.withProjectLibrary(libraryName = "kotlinx-coroutines-slf4j", jarName = APP_JAR)
// used by intellij.database.jdbcConsole -
// cannot be in 3rd-party-rt.jar, because this JAR must contain classes for java versions <= 7 only
layout.withProjectLibrary(libraryName = "jbr-api", jarName = UTIL_JAR)
// boot.jar is loaded by JVM classloader as part of loading our custom PathClassLoader class - reduce file size
addModule(PLATFORM_LOADER_JAR, listOf(
"intellij.platform.util.rt.java8",
"intellij.platform.util.classLoader",
"intellij.platform.util.zip",
"intellij.platform.boot",
"intellij.platform.runtime.repository",
"intellij.platform.runtime.loader",
), productLayout = productLayout, layout = layout)
addModule(UTIL_JAR, listOf(
// Scala uses GeneralCommandLine in JPS plugin
"intellij.platform.ide.util.io",
"intellij.platform.extensions",
), productLayout = productLayout, layout = layout)
addModule("externalProcess-rt.jar", listOf(
"intellij.platform.externalProcessAuthHelper.rt"
), productLayout = productLayout, layout = layout)
addModule("stats.jar", listOf(
"intellij.platform.statistics",
"intellij.platform.statistics.uploader",
"intellij.platform.statistics.config",
), productLayout = productLayout, layout = layout)
if (!productLayout.excludedModuleNames.contains("intellij.java.guiForms.rt")) {
layout.withModule("intellij.java.guiForms.rt", "forms_rt.jar")
}
addModule("jps-model.jar", listOf(
"intellij.platform.jps.model",
"intellij.platform.jps.model.serialization",
"intellij.platform.jps.model.impl"
), productLayout = productLayout, layout = layout)
addModule("external-system-rt.jar", listOf(
"intellij.platform.externalSystem.rt",
"intellij.platform.objectSerializer.annotations"
), productLayout = productLayout, layout = layout)
addModule("cds/classesLogAgent.jar", listOf("intellij.platform.cdsAgent"), productLayout = productLayout, layout = layout)
val productPluginSourceModuleName = context.productProperties.productPluginSourceModuleName
?: context.productProperties.applicationInfoModule
val productPluginContentModules = getProductPluginContentModules(context = context,
productPluginSourceModuleName = productPluginSourceModuleName)
val explicit = mutableListOf<ModuleItem>()
for (moduleName in productLayout.productImplementationModules) {
if (productLayout.excludedModuleNames.contains(moduleName)) {
continue
}
explicit.add(ModuleItem(moduleName = moduleName,
relativeOutputFile = when {
isModuleCloseSource(moduleName, context = context) -> {
if (jetBrainsClientModuleFilter.isModuleIncluded(moduleName)) PRODUCT_CLIENT_JAR else PRODUCT_JAR
}
else -> PlatformJarNames.getPlatformModuleJarName(moduleName, context)
},
reason = "productImplementationModules"))
}
explicit.addAll(toModuleItemSequence(PLATFORM_API_MODULES, productLayout = productLayout, reason = "PLATFORM_API_MODULES", context))
explicit.addAll(toModuleItemSequence(PLATFORM_IMPLEMENTATION_MODULES, productLayout = productLayout, reason = "PLATFORM_IMPLEMENTATION_MODULES",
context))
explicit.addAll(toModuleItemSequence(productLayout.productApiModules, productLayout = productLayout, reason = "productApiModules",
context))
if (addPlatformCoverage) {
explicit.add(ModuleItem(moduleName = "intellij.platform.coverage", relativeOutputFile = APP_JAR, reason = "coverage"))
}
val implicit = computeImplicitRequiredModules(
explicit = explicit.map { it.moduleName }.toList(),
layout = layout,
productPluginContentModules = productPluginContentModules.mapTo(HashSet()) { it.moduleName },
productLayout = productLayout,
context = context,
)
layout.withModules((explicit +
productPluginContentModules +
implicit.asSequence().map {
ModuleItem(moduleName = it.first,
relativeOutputFile = PlatformJarNames.getPlatformModuleJarName(it.first, context),
reason = "<- " + it.second.asReversed().joinToString(separator = " <- "))
}).sortedBy { it.moduleName }.toList())
for (item in projectLibrariesUsedByPlugins) {
if (!layout.excludedProjectLibraries.contains(item.libraryName)) {
layout.includedProjectLibraries.add(item)
}
}
// as a separate step, not a part of computing implicitModules, as we should collect libraries from a such implicitly included modules
layout.collectProjectLibrariesFromIncludedModules(context = context) { lib, module ->
val name = lib.name
// this module is used only when running IDE from sources, no need to include its dependencies, see IJPL-125
if (module.name == "intellij.platform.buildScripts.downloader" && (name == "zstd-jni" || name == "zstd-jni-windows-aarch64")) {
return@collectProjectLibrariesFromIncludedModules
}
layout.includedProjectLibraries
.addOrGet(ProjectLibraryData(libraryName = name,
packMode = PLATFORM_CUSTOM_PACK_MODE.getOrDefault(name, LibraryPackMode.MERGED),
reason = "<- ${module.name}"))
.dependentModules.computeIfAbsent("core") { mutableListOf() }.add(module.name)
}
return layout
}
internal fun computeProjectLibsUsedByPlugins(enabledPluginModules: Set<String>, context: BuildContext): SortedSet<ProjectLibraryData> {
val result = ObjectLinkedOpenHashSet<ProjectLibraryData>()
val jpsJavaExtensionService = JpsJavaExtensionService.getInstance()
val pluginLayoutsByJpsModuleNames = getPluginLayoutsByJpsModuleNames(modules = enabledPluginModules,
productLayout = context.productProperties.productLayout)
for (plugin in pluginLayoutsByJpsModuleNames) {
if (plugin.auto) {
continue
}
for (moduleName in plugin.includedModules.asSequence().map { it.moduleName }.distinct()) {
for (element in context.findRequiredModule(moduleName).dependenciesList.dependencies) {
val libraryReference = (element as? JpsLibraryDependency)?.libraryReference ?: continue
if (libraryReference.parentReference is JpsModuleReference) {
continue
}
if (jpsJavaExtensionService.getDependencyExtension(element)?.scope?.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME) != true) {
continue
}
val libraryName = element.libraryReference.libraryName
if (plugin.hasLibrary(libraryName)) {
continue
}
val packMode = PLATFORM_CUSTOM_PACK_MODE.getOrDefault(libraryName, LibraryPackMode.MERGED)
result.addOrGet(ProjectLibraryData(libraryName, packMode, reason = "<- $moduleName"))
.dependentModules
.computeIfAbsent(plugin.directoryName) { mutableListOf() }
.add(moduleName)
}
}
}
return result
}
internal fun getEnabledPluginModules(pluginsToPublish: Set<PluginLayout>, productProperties: ProductProperties): Set<String> {
val result = LinkedHashSet<String>()
result.addAll(productProperties.productLayout.bundledPluginModules)
pluginsToPublish.mapTo(result) { it.mainModule }
return result
}
private fun isModuleCloseSource(moduleName: String, context: BuildContext): Boolean {
if (moduleName.endsWith(".resources") || moduleName.endsWith(".icons")) {
return false
}
val sourceRoots = context.findRequiredModule(moduleName).sourceRoots.filter { it.rootType == JavaSourceRootType.SOURCE }
if (sourceRoots.isEmpty()) {
return false
}
return sourceRoots.any { moduleSourceRoot ->
!moduleSourceRoot.path.startsWith(context.paths.communityHomeDir)
}
}
private fun toModuleItemSequence(list: Collection<String>,
productLayout: ProductModulesLayout,
reason: String,
context: BuildContext): Sequence<ModuleItem> {
return list.asSequence()
.filter { !productLayout.excludedModuleNames.contains(it) }
.map { ModuleItem(moduleName = it, relativeOutputFile = PlatformJarNames.getPlatformModuleJarName(it, context), reason = reason) }
}
private suspend fun computeImplicitRequiredModules(explicit: List<String>,
layout: PlatformLayout,
productPluginContentModules: Set<String>,
productLayout: ProductModulesLayout,
context: BuildContext): List<Pair<String, PersistentList<String>>> {
val rootChain = persistentListOf<String>()
val rootList = layout.filteredIncludedModuleNames(TEST_FRAMEWORK_JAR)
.plus(explicit)
.filter {
!productLayout.excludedModuleNames.contains(it) &&
!productPluginContentModules.contains(it) &&
!it.startsWith("intellij.pycharm.") &&
!it.startsWith("intellij.python.") &&
!it.startsWith("intellij.codeServer.") &&
!it.startsWith("intellij.clion.") &&
!it.startsWith("intellij.cidr.") &&
!it.startsWith("intellij.appcode.") &&
it != "fleet.backend" &&
it != "intellij.codeServer" &&
it != "intellij.goland"
}
.distinct()
.sorted()
.map { it to rootChain }
.toList()
val unique = HashSet<String>()
layout.includedModules.mapTo(unique) { it.moduleName }
unique.addAll(explicit)
unique.addAll(productPluginContentModules)
unique.addAll(productLayout.excludedModuleNames)
unique.add("fleet.backend")
// Module intellij.featuresTrainer contains, so it is a plugin, but plugin must be not included in a platform
// (chain: [intellij.pycharm.community, intellij.python.featuresTrainer])
unique.add("intellij.pycharm.community")
unique.add("intellij.python.featuresTrainer")
unique.add("intellij.pycharm.ds")
val result = mutableListOf<Pair<String, PersistentList<String>>>()
compute(list = rootList, context = context, unique = unique, result = result)
if (context.options.validateImplicitPlatformModule) {
withContext(Dispatchers.IO) {
for ((name, chain) in result) {
launch {
val file = context.findFileInModuleSources(name, "META-INF/plugin.xml")
require(file == null) {
"Module $name contains $file, so it is a plugin, but plugin must be not included in a platform (chain: $chain)"
}
}
}
}
}
return result
}
private fun compute(list: List<Pair<String, PersistentList<String>>>,
context: BuildContext,
unique: HashSet<String>,
result: MutableList<Pair<String, PersistentList<String>>>) {
val oldSize = result.size
for ((dependentName, dependentChain) in list) {
val dependentModule = context.findRequiredModule(dependentName)
val chain = dependentChain.add(dependentName)
JpsJavaExtensionService.dependencies(dependentModule).includedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME).processModules { module ->
val name = module.name
if (unique.add(name)) {
result.add(name to chain)
}
}
}
if (oldSize != result.size) {
compute(list = result.subList(oldSize, result.size).sortedBy { it.first },
context = context,
unique = unique,
result = result)
}
}
// result _must be_ consistent, do not use Set.of or HashSet here
private suspend fun getProductPluginContentModules(context: BuildContext, productPluginSourceModuleName: String): Set<ModuleItem> {
val content = withContext(Dispatchers.IO) {
var file = context.findFileInModuleSources(productPluginSourceModuleName, "META-INF/plugin.xml")
if (file == null) {
file = context.findFileInModuleSources(productPluginSourceModuleName,
"META-INF/${context.productProperties.platformPrefix}Plugin.xml")
if (file == null) {
context.messages.warning("Cannot find product plugin descriptor in '$productPluginSourceModuleName' module")
return@withContext null
}
}
readXmlAsModel(file).getChild("content")
} ?: return emptySet()
val modules = content.children("module")
val result = LinkedHashSet<ModuleItem>()
for (module in modules) {
result.add(ModuleItem(moduleName = module.attributes.get("name") ?: continue, relativeOutputFile = "modules.jar", reason = "productModule"))
}
return result
} | 7 | null | 5079 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 21,094 | intellij-community | Apache License 2.0 |
notion-console/src/jvmMain/kotlin/io/ashdavies/notion/Main.kt | ashdavies | 36,688,248 | false | null | package io.ashdavies.notion
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.jakewharton.mosaic.Text
import com.jakewharton.mosaic.runMosaic
import kotlinx.coroutines.delay
public fun main(args: Array<String>): Unit = runMosaic {
setContent {
var elapsed by remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
while (true) {
delay(1_000)
elapsed++
}
}
NotionConsole(args)
Text("Time: $elapsed")
}
}
| 11 | Kotlin | 33 | 107 | 2c50c7fe47463c1863462e35a88dc2cf1550a59c | 689 | playground | Apache License 2.0 |
app/src/main/java/com/example/expensetracker/data/currencyFormat/CurrencyFormatsRepository.kt | seyone22 | 719,374,552 | false | {"Kotlin": 288946} | package com.example.expensetracker.data.currencyFormat
import com.example.expensetracker.model.CurrencyFormat
import kotlinx.coroutines.flow.Flow
interface CurrencyFormatsRepository {
fun getAllCurrencyFormatsStream(): Flow<List<CurrencyFormat>>
fun getCurrencyFormatStream(currencyId: Int): Flow<CurrencyFormat?>
fun getCurrencyFormatsFromTypeStream(currencyId: Int): Flow<List<CurrencyFormat>>
suspend fun insertCurrencyFormat(currency: CurrencyFormat)
suspend fun deleteCurrencyFormat(currency: CurrencyFormat)
suspend fun updateCurrencyFormat(currency: CurrencyFormat)
} | 17 | Kotlin | 0 | 0 | a5969f7a30d0384125ec3fdce71eb6890b327d19 | 601 | Expense_Tracker | MIT License |
bitcoincore/src/main/kotlin/io/horizontalsystems/bitcoincore/models/SentTransaction.kt | horizontalsystems | 147,199,533 | false | null | package io.horizontalsystems.bitcoincore.models
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity
class SentTransaction() {
@PrimaryKey
var hash = byteArrayOf()
var firstSendTime: Long = System.currentTimeMillis()
var lastSendTime: Long = System.currentTimeMillis()
var retriesCount: Int = 0
var sendSuccess: Boolean = false
constructor(hash: ByteArray) : this() {
this.hash = hash
}
}
| 20 | null | 55 | 96 | 110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167 | 480 | bitcoin-kit-android | MIT License |
bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/dto/LegalEntityGateOutput.kt | eclipse-tractusx | 526,621,398 | false | {"Kotlin": 1712199, "Smarty": 133187, "Dockerfile": 3902, "Java": 2019, "Shell": 1221} | /*******************************************************************************
* Copyright (c) 2021,2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.eclipse.tractusx.bpdm.gate.api.model.request
import com.fasterxml.jackson.annotation.JsonUnwrapped
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import io.swagger.v3.oas.annotations.media.Schema
import org.eclipse.tractusx.bpdm.common.dto.openapidescription.CommonDescription
import org.eclipse.tractusx.bpdm.common.dto.openapidescription.SiteDescription
import org.eclipse.tractusx.bpdm.common.service.DataClassUnwrappedJsonDeserializer
import org.eclipse.tractusx.bpdm.gate.api.model.LogisticAddressDto
import org.eclipse.tractusx.bpdm.gate.api.model.SiteGateDto
@JsonDeserialize(using = DataClassUnwrappedJsonDeserializer::class)
@Schema(description = SiteDescription.headerUpsertRequest)
data class SiteGateInputRequest(
@field:JsonUnwrapped
val site: SiteGateDto,
// TODO OpenAPI description for complex field does not work!!
@get:Schema(description = SiteDescription.mainAddress)
val mainAddress: LogisticAddressDto,
@get:Schema(description = CommonDescription.externalId)
val externalId: String,
@get:Schema(description = SiteDescription.legalEntityExternalId)
val legalEntityExternalId: String,
)
| 73 | Kotlin | 7 | 6 | c0c0ccfb385772381a06068d648327291d6ff194 | 2,083 | product-bpdm | Apache License 2.0 |
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/actionmodecallback/TextActionModeCallback.android.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ui.core.texttoolbar.actionmodecallback
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.ui.core.texttoolbar.ActionCallback
internal const val MENU_ITEM_COPY = 0
internal const val MENU_ITEM_PASTE = 1
internal const val MENU_ITEM_CUT = 2
internal class TextActionModeCallback(
private val view: View,
private val onCopyRequested: ActionCallback? = null,
private val onPasteRequested: ActionCallback? = null,
private val onCutRequested: ActionCallback? = null
) : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
requireNotNull(menu)
requireNotNull(mode)
onCopyRequested?.let {
menu.add(0, MENU_ITEM_COPY, 0, android.R.string.copy)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
onPasteRequested?.let {
menu.add(0, MENU_ITEM_PASTE, 1, android.R.string.paste)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
onCutRequested?.let {
menu.add(0, MENU_ITEM_CUT, 2, android.R.string.cut)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
when (item!!.itemId) {
MENU_ITEM_COPY -> onCopyRequested?.invoke()
MENU_ITEM_PASTE -> onPasteRequested?.invoke()
MENU_ITEM_CUT -> onCutRequested?.invoke()
else -> return false
}
mode?.finish()
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {}
}
| 0 | null | 0 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 2,445 | androidx | Apache License 2.0 |
data/src/test/java/com/jbkalit/data/source/PostRemoteDataSourceTest.kt | jbkalit | 366,999,274 | false | null | package com.jbkalit.data.source
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.jbkalit.data.scheduler.BaseSchedulerProvider
import com.jbkalit.data.scheduler.SchedulerProvider
import com.jbkalit.data.service.PostService
import com.jbkalit.data.source.post.remote.PostRemoteDataSource
import com.jbkalit.data.source.post.remote.PostRemoteDataSourceContract
import com.jbkalit.data.mock.post
import io.reactivex.Single
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class PostRemoteDataSourceTest {
@get:Rule
var rule = InstantTaskExecutorRule()
@Mock private lateinit var postService: PostService
private lateinit var schedulerProvider: BaseSchedulerProvider
private lateinit var postRemoteDataSource: PostRemoteDataSourceContract
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
schedulerProvider = SchedulerProvider.getInstance()
postRemoteDataSource = PostRemoteDataSource(
postService,
schedulerProvider
)
}
@Test
fun getFeed_Success_Test() {
Mockito.`when`(postService.getAllPosts())
.thenReturn(Single.just(listOf(post)))
postRemoteDataSource.getAllPosts()
Mockito.verify(postService, Mockito.times(1)).getAllPosts()
Assert.assertNotNull("Feed not empty", postRemoteDataSource.getAllPosts())
}
@Test
fun getPostById_Success_Test() {
Mockito.`when`(postService.getPostById(1))
.thenReturn(Single.just(post))
postRemoteDataSource.getPostById(1)
Mockito.verify(postService, Mockito.times(1)).getPostById(1)
Assert.assertNotNull("Post not empty", postRemoteDataSource.getPostById(1))
}
}
| 0 | Kotlin | 0 | 1 | fbf808718f0648b7bf9046ede6a6c3c60463a1e7 | 1,877 | PostApp | Apache License 2.0 |
Chapter3/favedish-ui/src/main/java/com/favedish/ui/restaurantdetails/mapper/RestaurantDetailsNotificationPresentationToUiMapper.kt | bpbpublications | 533,628,168 | false | null | package com.favedish.ui.restaurantdetails.mapper
import com.favedish.ui.architecture.mapper.NotificationPresentationToUiMapper
import com.favedish.ui.architecture.model.NotificationUiModel
class RestaurantDetailsNotificationPresentationToUiMapper :
NotificationPresentationToUiMapper<Unit> {
override fun toUi(presentationNotification: Unit): NotificationUiModel {
TODO("No notifications implemented for the restaurant details screen.")
}
}
| 0 | Kotlin | 5 | 7 | cd85b9fb89e307ad4977bcdb63121aa906f19427 | 463 | Clean-Architecture-for-Android | MIT License |
ProductsList/app/src/main/java/br/com/productslist/presentation/products/ProductScreen.kt | gitdaniellopes | 504,232,611 | false | {"Kotlin": 32927} | package br.com.productslist.presentation.products
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import br.com.productslist.presentation.products.components.*
import br.com.productslist.ui.theme.ProductsListTheme
import br.com.productslist.util.toCurrency
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
@RootNavGraph(start = true)
@Destination
@Composable
fun ProductScreen(
modifier: Modifier = Modifier,
viewModel: ProductViewModel = hiltViewModel(),
navigator: DestinationsNavigator
) {
LaunchedEffect(Unit) {
viewModel.getProducts()
viewModel.getShoppingCart()
}
Scaffold(
topBar = {
ProductsTopBar()
},
floatingActionButton = {
ProductsFab()
}
) { paddingValues ->
Column(modifier = modifier) {
ShoppingCart(
totalCard = viewModel.shoppingCart.toCurrency()
)
ProductsContent(
paddingValues = paddingValues,
navigator = navigator
)
}
}
if (viewModel.openDialog) {
AddProductAlertDialog()
}
}
//@Preview(showBackground = true, backgroundColor = 0xFFF0EAE2)
//@Composable
//fun ProductScreenPreview() {
// ProductsListTheme {
// ProductScreen()
// }
//} | 0 | Kotlin | 0 | 0 | de23caa291295d79e896163cd5ed21e43322f48c | 1,733 | ProductsListApp | MIT License |
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/checker/CheckListener.kt | JetBrains | 43,696,115 | false | {"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71} | package com.jetbrains.edu.learning.checker
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.jetbrains.edu.learning.courseFormat.CheckResult
import com.jetbrains.edu.learning.courseFormat.tasks.Task
interface CheckListener {
fun beforeCheck(project: Project, task: Task) {}
fun afterCheck(project: Project, task: Task, result: CheckResult) {}
companion object {
val EP_NAME: ExtensionPointName<CheckListener> = ExtensionPointName.create("Educational.checkListener")
}
}
| 7 | Kotlin | 49 | 150 | 9cec6c97d896f4485e76cf9a2a95f8a8dd21c982 | 548 | educational-plugin | Apache License 2.0 |
test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt | JetBrains | 278,369,660 | false | null | // 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.test
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.daemon.impl.EditorTracker
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.fileEditor.impl.text.TextEditorPsiDataProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.LoggedErrorProcessor
import com.intellij.testFramework.RunAll
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.formatter.KotlinLanguageCodeStyleSettingsProvider
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.API_VERSION_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.COMPILER_ARGUMENTS_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.JVM_TARGET_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.LANGUAGE_VERSION_DIRECTIVE
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinRoot
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestMetadataUtil
import org.jetbrains.kotlin.test.util.slashedPath
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.rethrow
import java.io.File
import java.io.IOException
import java.nio.file.Path
abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFixtureTestCaseBase() {
private val exceptions = ArrayList<Throwable>()
protected open val captureExceptions = false
protected fun testDataFile(fileName: String): File = File(testDataDirectory, fileName)
protected fun testDataFile(): File = testDataFile(fileName())
protected fun testDataFilePath(): Path = testDataFile().toPath()
protected fun testPath(fileName: String = fileName()): String = testDataFile(fileName).toString()
protected fun testPath(): String = testPath(fileName())
protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt")
@Deprecated("Migrate to 'testDataDirectory'.", ReplaceWith("testDataDirectory"))
final override fun getTestDataPath(): String = testDataDirectory.slashedPath
open val testDataDirectory: File by lazy {
File(TestMetadataUtil.getTestDataPath(javaClass))
}
override fun setUp() {
super.setUp()
enableKotlinOfficialCodeStyle(project)
if (!isFirPlugin) {
// We do it here to avoid possible initialization problems
// UnusedSymbolInspection() calls IDEA UnusedDeclarationInspection() in static initializer,
// which in turn registers some extensions provoking "modifications aren't allowed during highlighting"
// when done lazily
UnusedSymbolInspection()
}
VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path)
EditorTracker.getInstance(project)
if (!isFirPlugin) {
invalidateLibraryCache(project)
}
if (captureExceptions) {
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(category: String, message: String?, t: Throwable?, details: Array<out String>): Boolean {
exceptions.addIfNotNull(t)
return super.processError(category, message, t, details)
}
})
}
}
override fun tearDown() {
runAll(
ThrowableRunnable { LoggedErrorProcessor.restoreDefaultProcessor() },
ThrowableRunnable { disableKotlinOfficialCodeStyle(project) },
ThrowableRunnable { super.tearDown() },
)
if (exceptions.isNotEmpty()) {
exceptions.forEach { it.printStackTrace() }
throw AssertionError("Exceptions in other threads happened")
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective()
protected fun getProjectDescriptorFromAnnotation(): LightProjectDescriptor {
val testMethod = this::class.java.getDeclaredMethod(name)
return when (testMethod.getAnnotation(ProjectDescriptorKind::class.java)?.value) {
JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES -> KotlinJdkAndMultiplatformStdlibDescriptor.JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES
KOTLIN_JVM_WITH_STDLIB_SOURCES -> ProjectDescriptorWithStdlibSources.INSTANCE
KOTLIN_JAVASCRIPT -> KotlinStdJSProjectDescriptor
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS,
mainModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE,
additionalModuleDescriptor = KotlinStdJSProjectDescriptor
)
}
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB,
mainModuleDescriptor = KotlinStdJSProjectDescriptor,
additionalModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
)
}
else -> throw IllegalStateException("Unknown value for project descriptor kind")
}
}
protected fun getProjectDescriptorFromTestName(): LightProjectDescriptor {
val testName = StringUtil.toLowerCase(getTestName(false))
return when {
testName.endsWith("runtime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
testName.endsWith("stdlib") -> ProjectDescriptorWithStdlibSources.INSTANCE
else -> KotlinLightProjectDescriptor.INSTANCE
}
}
protected fun getProjectDescriptorFromFileDirective(): LightProjectDescriptor {
val file = mainFile()
if (!file.exists()) {
return KotlinLightProjectDescriptor.INSTANCE
}
try {
val fileText = FileUtil.loadFile(file, true)
val withLibraryDirective = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "WITH_LIBRARY:")
val minJavaVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "MIN_JAVA_VERSION:")?.toInt()
if (minJavaVersion != null && !(InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_RUNTIME"))
) {
error("MIN_JAVA_VERSION so far is supported for RUNTIME/WITH_RUNTIME only")
}
return when {
withLibraryDirective.isNotEmpty() ->
SdkAndMockLibraryProjectDescriptor(IDEA_TEST_DATA_DIR.resolve(withLibraryDirective[0]).path, true)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITHOUT_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE_NO_SOURCES
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_KOTLIN_TEST") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_KOTLIN_TEST
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_FULL_JDK") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_JDK_10") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance(LanguageLevel.JDK_10)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_REFLECT") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_REFLECT
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SCRIPT_RUNTIME") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_SCRIPT_RUNTIME
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_RUNTIME") ->
if (minJavaVersion != null) {
object : KotlinWithJdkAndRuntimeLightProjectDescriptor(INSTANCE.libraryFiles, INSTANCE.librarySourceFiles) {
val sdkValue by lazy { sdk(minJavaVersion) }
override fun getSdk(): Sdk = sdkValue
}
} else {
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
InTextDirectivesUtils.isDirectiveDefined(fileText, "JS") ->
KotlinStdJSProjectDescriptor
InTextDirectivesUtils.isDirectiveDefined(fileText, "ENABLE_MULTIPLATFORM") ->
KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM
else -> getDefaultProjectDescriptor()
}
} catch (e: IOException) {
throw rethrow(e)
}
}
protected open fun mainFile() = File(testDataDirectory, fileName())
private fun sdk(javaVersion: Int): Sdk = when (javaVersion) {
6 -> IdeaTestUtil.getMockJdk16()
8 -> IdeaTestUtil.getMockJdk18()
9 -> IdeaTestUtil.getMockJdk9()
11 -> {
if (SystemInfo.isJavaVersionAtLeast(javaVersion, 0, 0)) {
PluginTestCaseBase.fullJdk()
} else {
error("JAVA_HOME have to point at least to JDK 11")
}
}
else -> error("Unsupported JDK version $javaVersion")
}
protected open fun getDefaultProjectDescriptor(): KotlinLightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE
protected fun performNotWriteEditorAction(actionId: String): Boolean {
val dataContext = (myFixture.editor as EditorEx).dataContext
val managerEx = ActionManagerEx.getInstanceEx()
val action = managerEx.getAction(actionId)
val event = AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, Presentation(), managerEx, 0)
if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) {
ActionUtil.performActionDumbAwareWithCallbacks(action, event)
return true
}
return false
}
fun JavaCodeInsightTestFixture.configureByFile(file: File): PsiFile {
val relativePath = file.toRelativeString(testDataDirectory)
return configureByFile(relativePath)
}
fun JavaCodeInsightTestFixture.checkResultByFile(file: File) {
val relativePath = file.toRelativeString(testDataDirectory)
checkResultByFile(relativePath)
}
}
object CompilerTestDirectives {
const val LANGUAGE_VERSION_DIRECTIVE = "LANGUAGE_VERSION:"
const val API_VERSION_DIRECTIVE = "API_VERSION:"
const val JVM_TARGET_DIRECTIVE = "JVM_TARGET:"
const val COMPILER_ARGUMENTS_DIRECTIVE = "COMPILER_ARGUMENTS:"
val ALL_COMPILER_TEST_DIRECTIVES = listOf(LANGUAGE_VERSION_DIRECTIVE, JVM_TARGET_DIRECTIVE, COMPILER_ARGUMENTS_DIRECTIVE)
}
fun <T> withCustomCompilerOptions(fileText: String, project: Project, module: Module, body: () -> T): T {
val removeFacet = !module.hasKotlinFacet()
val configured = configureCompilerOptions(fileText, project, module)
try {
return body()
} finally {
if (configured) {
rollbackCompilerOptions(project, module, removeFacet)
}
}
}
private fun configureCompilerOptions(fileText: String, project: Project, module: Module): Boolean {
val version = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $LANGUAGE_VERSION_DIRECTIVE ")
val apiVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $API_VERSION_DIRECTIVE ")
val jvmTarget = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $JVM_TARGET_DIRECTIVE ")
// We can have several such directives in quickFixMultiFile tests
// TODO: refactor such tests or add sophisticated check for the directive
val options = InTextDirectivesUtils.findListWithPrefixes(fileText, "// $COMPILER_ARGUMENTS_DIRECTIVE ").firstOrNull()
if (version != null || apiVersion != null || jvmTarget != null || options != null) {
configureLanguageAndApiVersion(
project, module,
version ?: LanguageVersion.LATEST_STABLE.versionString,
apiVersion
)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
if (jvmTarget != null) {
val compilerArguments = facetSettings.compilerArguments
require(compilerArguments is K2JVMCompilerArguments) { "Attempt to specify `$JVM_TARGET_DIRECTIVE` for non-JVM test" }
compilerArguments.jvmTarget = jvmTarget
}
if (options != null) {
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = options
facetSettings.updateMergedArguments()
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = options }
}
return true
}
return false
}
fun configureRegistryAndRun(fileText: String, body: () -> Unit) {
val registers = InTextDirectivesUtils.findListWithPrefixes(fileText, "// REGISTRY:")
.map { it.split(' ') }
.map { Registry.get(it.first()) to it.last() }
try {
for ((register, value) in registers) {
register.setValue(value)
}
body()
} finally {
for ((register, _) in registers) {
register.resetToDefault()
}
}
}
fun configureCodeStyleAndRun(
project: Project,
configurator: (CodeStyleSettings) -> Unit = { },
body: () -> Unit
) {
val testSettings = CodeStyle.createTestSettings(CodeStyle.getSettings(project))
CodeStyle.doWithTemporarySettings(project, testSettings, Runnable {
configurator(testSettings)
body()
})
}
fun enableKotlinOfficialCodeStyle(project: Project) {
val settings = CodeStyleSettingsManager.getInstance(project).createTemporarySettings()
KotlinStyleGuideCodeStyle.apply(settings)
CodeStyle.setTemporarySettings(project, settings)
}
fun disableKotlinOfficialCodeStyle(project: Project) {
CodeStyle.dropTemporarySettings(project)
}
fun resetCodeStyle(project: Project) {
val provider = KotlinLanguageCodeStyleSettingsProvider()
CodeStyle.getSettings(project).apply {
removeCommonSettings(provider)
removeCustomSettings(provider)
clearCodeStyleSettings()
}
}
fun runAll(
vararg actions: ThrowableRunnable<Throwable>,
suppressedExceptions: List<Throwable> = emptyList()
) = RunAll(actions.toList()).run(suppressedExceptions)
private fun rollbackCompilerOptions(project: Project, module: Module, removeFacet: Boolean) {
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS }
KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = LanguageVersion.LATEST_STABLE.versionString }
if (removeFacet) {
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
return
}
configureLanguageAndApiVersion(project, module, LanguageVersion.LATEST_STABLE.versionString, ApiVersion.LATEST_STABLE.versionString)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
(facetSettings.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget = JvmTarget.DEFAULT.description
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS
facetSettings.updateMergedArguments()
}
fun withCustomLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: String,
apiVersion: String?,
body: () -> Unit
) {
val removeFacet = !module.hasKotlinFacet()
configureLanguageAndApiVersion(project, module, languageVersion, apiVersion)
try {
body()
} finally {
if (removeFacet) {
KotlinCommonCompilerArgumentsHolder.getInstance(project)
.update { this.languageVersion = LanguageVersion.LATEST_STABLE.versionString }
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
} else {
configureLanguageAndApiVersion(
project,
module,
LanguageVersion.LATEST_STABLE.versionString,
ApiVersion.LATEST_STABLE.versionString
)
}
}
}
private fun configureLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: String,
apiVersion: String?
) {
WriteAction.run<Throwable> {
val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(project)
val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = false)
val compilerArguments = facet.configuration.settings.compilerArguments
if (compilerArguments != null) {
compilerArguments.apiVersion = null
}
facet.configureFacet(languageVersion, null, modelsProvider, emptySet())
if (apiVersion != null) {
facet.configuration.settings.apiLevel = LanguageVersion.fromVersionString(apiVersion)
}
KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = languageVersion }
modelsProvider.commit()
}
}
fun Project.allKotlinFiles(): List<KtFile> {
val virtualFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<KtFile>()
}
fun Project.allJavaFiles(): List<PsiJavaFile> {
val virtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<PsiJavaFile>()
}
fun Project.findFileWithCaret(): PsiClassOwner {
return (allKotlinFiles() + allJavaFiles()).single {
"<caret>" in VfsUtilCore.loadText(it.virtualFile) && !it.virtualFile.name.endsWith(".after")
}
}
fun createTextEditorBasedDataContext(
project: Project,
editor: Editor,
caret: Caret,
additionalSteps: SimpleDataContext.Builder.() -> SimpleDataContext.Builder = { this },
): DataContext {
val textEditorPsiDataProvider = TextEditorPsiDataProvider()
val parentContext = DataContext { dataId -> textEditorPsiDataProvider.getData(dataId, editor, caret) }
return SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(CommonDataKeys.EDITOR, editor)
.additionalSteps()
.setParent(parentContext)
.build()
}
| 284 | null | 5162 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 21,752 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/oceanknight/wanandroid/base/App.kt | Zouyupeng | 795,336,315 | false | {"Kotlin": 2690} | package com.oceanknight.wanandroid.base
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App: Application() {
} | 0 | Kotlin | 0 | 0 | 800f04bfe3a0bc48d3f33d7dbf2e5e8d6fcd6381 | 160 | wan-android | MIT License |
src/main/kotlin/com.sakebook.sample.lambda_test/App.kt | sakebook | 74,758,660 | false | null | package com.sakebook.sample.lambda_test
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.LambdaLogger
/**
* Created by sakemotoshinya on 16/11/25.
*/
public class App {
public fun handler(count: Int, context: Context): String {
val lambdaLogger = context.getLogger()
lambdaLogger.log("count = " + count)
return "${count * 3}"
}
}
| 0 | Kotlin | 1 | 13 | fe87edcb427d97add55152e008fb367660222bfd | 415 | aws_lambda_gradle_kotlin | Apache License 2.0 |
compose/compose-runtime/src/test/java/androidx/compose/frames/FramesTests.kt | FYI-Google | 258,765,297 | false | null | package androidx.compose.frames
import junit.framework.TestCase
import org.junit.Assert
import java.util.ArrayDeque
import kotlin.reflect.KClass
const val OLD_STREET = "123 Any Street"
const val OLD_CITY = "AnyTown"
const val NEW_STREET = "456 New Street"
const val NEW_CITY = "AnyCity"
class FrameTest : TestCase() {
fun testCreatingAddress() {
val address = frame {
val address = Address(
OLD_STREET,
OLD_CITY
)
Assert.assertEquals(OLD_STREET, address.street)
Assert.assertEquals(OLD_CITY, address.city)
address
}
frame {
Assert.assertEquals(OLD_STREET, address.street)
Assert.assertEquals(OLD_CITY, address.city)
}
}
fun testModifyingAddress() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
frame {
address.street = NEW_STREET
}
frame {
Assert.assertEquals(NEW_STREET, address.street)
Assert.assertEquals(OLD_CITY, address.city)
}
}
fun testIsolation() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
val f = suspended {
address.street = NEW_STREET
}
frame {
Assert.assertEquals(OLD_STREET, address.street)
}
restored(f) {
Assert.assertEquals(NEW_STREET, address.street)
}
frame {
Assert.assertEquals(NEW_STREET, address.street)
}
}
fun testRecordReuse() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
Assert.assertEquals(1, address.firstFrameRecord.length)
frame { address.street = NEW_STREET }
Assert.assertEquals(2, address.firstFrameRecord.length)
frame { address.street = "other street" }
Assert.assertEquals(2, address.firstFrameRecord.length)
}
fun testAborted() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
aborted {
address.street = NEW_STREET
Assert.assertEquals(NEW_STREET, address.street)
}
frame {
Assert.assertEquals(OLD_STREET, address.street)
}
}
fun testReuseAborted() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
Assert.assertEquals(1, address.firstFrameRecord.length)
aborted { address.street = NEW_STREET }
Assert.assertEquals(2, address.firstFrameRecord.length)
frame { address.street = "other street" }
Assert.assertEquals(2, address.firstFrameRecord.length)
}
fun testSpeculation() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
speculation {
address.street = NEW_STREET
Assert.assertEquals(NEW_STREET, address.street)
}
frame {
Assert.assertEquals(OLD_STREET, address.street)
}
}
fun testSpeculationIsolation() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
speculate()
address.street = NEW_STREET
val speculation = androidx.compose.frames.suspend()
frame {
Assert.assertEquals(OLD_STREET, address.street)
}
restore(speculation)
Assert.assertEquals(NEW_STREET, address.street)
abortHandler()
frame {
Assert.assertEquals(OLD_STREET, address.street)
}
}
fun testReuseSpeculation() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
Assert.assertEquals(1, address.firstFrameRecord.length)
speculation { address.street = NEW_STREET }
Assert.assertEquals(2, address.firstFrameRecord.length)
frame { address.street = "other street" }
Assert.assertEquals(2, address.firstFrameRecord.length)
}
fun testCommitAbortInteraction() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
val frame1 = suspended {
address.street = "From frame1"
}
val frame2 = suspended {
address.street = "From frame2"
}
// New frames should see the old value
frame {
Assert.assertEquals(
OLD_STREET,
address.street
)
}
// Aborting frame2 and committing frame1 should result in frame1
abortHandler(frame2)
// New frames should still see the old value
frame {
Assert.assertEquals(
OLD_STREET,
address.street
)
}
// Commit frame1, new frames should see frame1's value
commit(frame1)
frame { Assert.assertEquals("From frame1", address.street) }
}
fun testCollisionAB() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
expectThrow(FrameAborted::class) {
val frame1 = suspended {
address.street = "From frame1"
}
val frame2 = suspended {
address.street = "From frame2"
}
commit(frame1)
// This should throw
commit(frame2)
}
// New frames should see the value from the committed frame1
frame {
Assert.assertEquals("From frame1", address.street)
}
}
fun testCollisionBA() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
expectThrow(FrameAborted::class) {
val frame1 = suspended {
address.street = "From frame1"
}
val frame2 = suspended {
address.street = "From frame2"
}
commit(frame2)
// This should throw
commit(frame1)
}
// New frames should see the value from the committed frame2
frame {
Assert.assertEquals("From frame2", address.street)
}
}
fun testManyChangesInASingleFrame() {
val changeCount = 1000
val addresses = frame {
(0..changeCount).map {
Address(
OLD_STREET,
OLD_CITY
)
}
}
val frame1 = suspended {
for (i in 0..changeCount) {
addresses[i].street = "From index $i"
}
for (i in 0..changeCount) {
Assert.assertEquals("From index $i", addresses[i].street)
}
}
frame {
for (i in 0..changeCount) {
Assert.assertEquals(OLD_STREET, addresses[i].street)
}
}
commit(frame1)
frame {
for (i in 0..changeCount) {
Assert.assertEquals("From index $i", addresses[i].street)
}
}
}
fun testManySimultaneousFrames() {
val frameCount = 1000
val frames = ArrayDeque<Frame>()
val addresses = frame {
(0..frameCount).map {
Address(
OLD_STREET,
OLD_CITY
)
}
}
for (i in 0..frameCount) {
frames.push(suspended { addresses[i].street = "From index $i" })
}
for (i in 0..frameCount) {
commit(frames.remove())
}
for (i in 0..frameCount) {
frame {
Assert.assertEquals(
"From index $i",
addresses[i].street
)
}
}
}
fun testRaw() {
val count = 1000
val addresses = (0..count).map { AddressRaw(OLD_STREET) }
for (i in 0..count) {
addresses[i].street = "From index $i"
Assert.assertEquals("From index $i", addresses[i].street)
}
for (i in 0..count) {
Assert.assertEquals("From index $i", addresses[i].street)
}
}
fun testProp() {
val count = 10000
val addresses = (0..count).map { AddressProp(OLD_STREET) }
for (i in 0..count) {
addresses[i].street = "From index $i"
Assert.assertEquals("From index $i", addresses[i].street)
}
for (i in 0..count) {
Assert.assertEquals("From index $i", addresses[i].street)
}
}
fun testFrameObserver_ObserveRead_Single() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
var read: Address? = null
observeFrame({ obj ->
read = obj as Address
}) {
Assert.assertEquals(OLD_STREET, address.street)
}
Assert.assertEquals(address, read)
}
fun testFrameObserver_addReadObserver_Single() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
var read: Address? = null
var otherRead: Address? = null
val frame = open({ obj -> read = obj as Address })
try {
frame.observeReads({ obj -> otherRead = obj as Address }) {
Assert.assertEquals(OLD_STREET, address.street)
}
Assert.assertEquals(1, frame.readObservers.size)
} finally {
commitHandler()
}
Assert.assertEquals(address, read)
Assert.assertEquals(address, otherRead)
}
fun testFrameObserver_ObserveCommit_Single() {
val address = frame {
Address(
OLD_STREET,
OLD_CITY
)
}
var committed: Set<Any>? = null
observeCommit({ framed: Set<Any> -> committed = framed }) {
frame {
address.street = NEW_STREET
}
}
Assert.assertTrue(committed?.contains(address) ?: false)
}
fun testFrameObserver_OberveRead_Multiple() {
val addressToRead = frame {
List(100) {
Address(
OLD_STREET,
OLD_CITY
)
}
}
val addressToIgnore = frame {
List(100) {
Address(
OLD_STREET,
OLD_CITY
)
}
}
val readAddresses = HashSet<Address>()
observeFrame({ obj -> readAddresses.add(obj as Address) }) {
for (address in addressToRead) {
Assert.assertEquals(OLD_STREET, address.street)
}
}
for (address in addressToRead) {
Assert.assertTrue(
"Ensure a read callback was called for the address",
readAddresses.contains(address)
)
}
for (address in addressToIgnore) {
Assert.assertFalse(
"Ensure a read callback was not called for the address",
readAddresses.contains(address)
)
}
}
fun testFrameObserver_ObserveCommit_Multiple() {
val addressToWrite = frame {
List(100) {
Address(
OLD_STREET,
OLD_CITY
)
}
}
val addressToIgnore = frame {
List(100) {
Address(
OLD_STREET,
OLD_CITY
)
}
}
var committedAddresses = null as Set<Any>?
observeCommit({ framed -> committedAddresses = framed }) {
frame {
for (address in addressToWrite) {
address.street = NEW_STREET
}
}
}
for (address in addressToWrite) {
Assert.assertTrue(
"Ensure written address is in the set of committed objects",
committedAddresses?.contains(address) ?: false
)
}
for (address in addressToIgnore) {
Assert.assertFalse(
"Ensure ignored addresses are not in the set of committed objects",
committedAddresses?.contains(address) ?: false
)
}
}
fun testModelList_Isolated() {
val addresses = frame {
modelListOf(*(Array(100) {
Address(
OLD_STREET,
OLD_CITY
)
}))
}
fun validateOriginal() {
assertFalse(wasModified(addresses))
assertEquals(100, addresses.size)
// Iterate list
for (address in addresses) {
Assert.assertEquals(OLD_STREET, address.street)
}
assertFalse(wasModified(addresses))
}
fun validateNew() {
assertEquals(101, addresses.size)
// Iterate list
for (i in 0 until 100) {
Assert.assertEquals(OLD_STREET, addresses[i].street)
}
Assert.assertEquals(NEW_STREET, addresses[100].street)
}
frame { validateOriginal() }
val frame1 = suspended {
// Insert into the list
addresses.add(
Address(
NEW_STREET,
NEW_CITY
)
)
validateNew()
}
frame { validateOriginal() }
restored(frame1) {
validateNew()
}
}
fun testModelList_ReadDoesNotModify() {
val count = 10
val addresses = frame {
modelListOf(*(Array(count) {
Address(
OLD_STREET,
OLD_CITY
)
}))
}
// size should not modify
frame {
assertEquals(count, addresses.size)
assertFalse(wasModified(addresses))
}
// get should not modify
frame {
val address = addresses[0]
assertEquals(OLD_STREET, address.street)
assertFalse(wasModified(addresses))
assertFalse(wasModified(address))
}
// Iteration should not modify
frame {
for (address in addresses) {
assertEquals(OLD_STREET, address.street)
assertFalse(wasModified(address))
}
assertFalse(wasModified(addresses))
}
// contains should not modify
frame {
val address = addresses[1]
assertTrue(addresses.contains(address))
assertFalse(wasModified(addresses))
}
// containsAll should not modify
frame {
val sublist = listOf(addresses[1], addresses[2])
assertTrue(addresses.containsAll(sublist))
assertFalse(wasModified(addresses))
}
// indexOf of should not modify
frame {
val address = addresses[5]
assertEquals(5, addresses.indexOf(address))
assertFalse(wasModified(addresses))
}
// IsEmpty should not modify
frame {
assertFalse(addresses.isEmpty())
assertTrue(addresses.isNotEmpty())
assertFalse(wasModified(addresses))
}
// lastIndexOf should not modify
frame {
val address = addresses[5]
assertEquals(5, addresses.lastIndexOf(address))
assertFalse(wasModified(addresses))
}
// listIterator should not modify
frame {
for (address in addresses.listIterator()) {
assertEquals(OLD_STREET, address.street)
}
assertFalse(wasModified(addresses))
for (address in addresses.listIterator(5)) {
assertEquals(OLD_STREET, address.street)
}
assertFalse(wasModified(addresses))
}
}
fun testModelList_MutateThrows() {
val count = 10
val addresses = frame {
modelListOf(*(Array(count) {
Address(
OLD_STREET,
OLD_CITY
)
}))
}
// Expect iterator.remove to throw
frame {
val iterator = addresses.iterator()
assertTrue(iterator.hasNext())
iterator.next()
expectError {
iterator.remove()
}
assertFalse(wasModified(addresses))
}
// Expect listIterator.remove to throw
frame {
val iterator = addresses.listIterator()
assertTrue(iterator.hasNext())
iterator.next()
expectError {
iterator.remove()
}
assertFalse(wasModified(addresses))
}
// Expect listIterator.set to throw
frame {
val iterator = addresses.listIterator()
assertTrue(iterator.hasNext())
iterator.next()
expectError {
iterator.set(
Address(
NEW_STREET,
NEW_CITY
)
)
}
assertFalse(wasModified(addresses))
}
// Expect listIterator.add to throw
frame {
val iterator = addresses.listIterator()
assertTrue(iterator.hasNext())
iterator.next()
expectError {
iterator.add(
Address(
NEW_STREET,
NEW_CITY
)
)
}
assertFalse(wasModified(addresses))
}
}
fun testModelList_MutatingModifies() {
val count = 10
val addresses = frame {
modelListOf(*(Array(count) {
Address(
OLD_STREET,
OLD_CITY
)
}))
}
fun validate(block: () -> Unit) {
aborted {
assertFalse(wasModified(addresses))
block()
assertTrue(wasModified(addresses))
}
frame {
assertEquals(addresses.size, count)
for (address in addresses) {
assertEquals(address.street, OLD_STREET)
assertEquals(address.city, OLD_CITY)
}
}
}
// Expect add to modify
validate { addresses.add(
Address(
NEW_STREET,
OLD_CITY
)
) }
validate { addresses.add(5,
Address(
NEW_STREET,
OLD_CITY
)
) }
// Expect addAll to modify
validate {
addresses.addAll(listOf(
Address(
NEW_STREET,
NEW_CITY
),
Address(
NEW_STREET,
NEW_CITY
)
))
}
validate {
addresses.addAll(
5,
listOf(
Address(
NEW_STREET,
NEW_CITY
),
Address(
NEW_STREET,
NEW_CITY
)
)
)
}
// Expect clear to modify
validate { addresses.clear() }
// Expect remove to modify
validate {
val address = addresses[5]
addresses.remove(address)
}
// Expect removeAll to modify
validate { addresses.removeAll(listOf(addresses[5], addresses[6])) }
// Expect removeAt to modify
validate { addresses.removeAt(5) }
// Expect retainAll to modify
validate { addresses.retainAll(listOf(addresses[5], addresses[6])) }
// Expect set to modify
validate { addresses[5] = Address(
NEW_STREET,
NEW_CITY
)
}
// Expect subList to modify
validate { addresses.subList(5, 6) }
// Expecte asMutable to modify
validate { addresses.asMutable() }
}
fun testModelMap_Isolated() {
val map = frame {
modelMapOf(
1 to "a",
2 to "b",
3 to "c",
4 to "d"
)
}
fun validateOld() {
assertEquals(4, map.size)
assertTrue(map.contains(1))
assertTrue(map.contains(2))
assertTrue(map.contains(3))
assertTrue(map.contains(4))
assertEquals(map[1], "a")
assertEquals(map[2], "b")
assertEquals(map[3], "c")
assertEquals(map[4], "d")
}
fun validateNew() {
assertEquals(5, map.size)
assertTrue(map.contains(1))
assertTrue(map.contains(2))
assertTrue(map.contains(3))
assertTrue(map.contains(4))
assertTrue(map.contains(5))
assertEquals(map[1], "a")
assertEquals(map[2], "b")
assertEquals(map[3], "c")
assertEquals(map[4], "d")
assertEquals(map[5], "e")
}
frame { validateOld() }
val frame1 = suspended {
validateOld()
map[5] = "e"
validateNew()
}
frame { validateOld() }
restored(frame1) { validateNew() }
frame { validateNew() }
}
@Suppress("USELESS_IS_CHECK")
fun testModelMap_ReadingDoesntModify() {
val map = frame {
modelMapOf(
1 to "a",
2 to "b",
3 to "c",
4 to "d"
)
}
fun validateOld() {
assertEquals(4, map.size)
assertTrue(map.contains(1))
assertTrue(map.contains(2))
assertTrue(map.contains(3))
assertTrue(map.contains(4))
assertEquals(map[1], "a")
assertEquals(map[2], "b")
assertEquals(map[3], "c")
assertEquals(map[4], "d")
}
fun validate(block: () -> Unit) {
frame {
validateOld()
block()
assertFalse(wasModified(map))
validateOld()
}
}
// size should not modify
validate { assertEquals(4, map.size) }
// contains should not modify
validate { assertTrue(map.contains(1)) }
// containsKey should not modify
validate { assertTrue(map.containsKey(1)) }
// containsValue should not modify
validate { assertTrue(map.containsValue("a")) }
// get should not modify
validate { assertEquals("a", map[1]) }
// isEmpty should not modify
validate { assertFalse(map.isEmpty()) }
validate { assertTrue(map.isNotEmpty()) }
// iterating entries should not modify
validate {
for (entry in map) {
assertTrue(entry.value is String)
assertTrue(entry.key is Int)
}
for (entry in map.entries) {
assertTrue(entry.value is String)
assertTrue(entry.key is Int)
}
}
// iterating keys should not modify
validate {
for (key in map.keys) {
assertTrue(key is Int)
}
}
// iterating values should not modify
validate {
for (value in map.values) {
assertTrue(value is String)
}
}
}
fun testModelMap_Mutation() {
val map = frame {
modelMapOf(
1 to "a",
2 to "b",
3 to "c",
4 to "d"
)
}
fun validateOld() {
assertEquals(4, map.size)
assertTrue(map.contains(1))
assertTrue(map.contains(2))
assertTrue(map.contains(3))
assertTrue(map.contains(4))
assertEquals(map[1], "a")
assertEquals(map[2], "b")
assertEquals(map[3], "c")
assertEquals(map[4], "d")
}
fun validate(block: () -> Unit) {
aborted {
assertFalse(wasModified(map))
validateOld()
block()
assertTrue(wasModified(map))
}
}
// clear should modify
validate { map.clear() }
// put should modify
validate { map[5] = "e" }
// putAll should modify
validate { map.putAll(mapOf(5 to "e", 6 to "f")) }
// remove should modify
validate { map.remove(3) }
}
fun testModelMap_MutateThrows() {
val map = frame {
modelMapOf(
1 to "a",
2 to "b",
3 to "c",
4 to "d"
)
}
fun validateOld() {
assertEquals(4, map.size)
assertTrue(map.contains(1))
assertTrue(map.contains(2))
assertTrue(map.contains(3))
assertTrue(map.contains(4))
assertEquals(map[1], "a")
assertEquals(map[2], "b")
assertEquals(map[3], "c")
assertEquals(map[4], "d")
}
fun validate(block: () -> Unit) {
frame {
assertFalse(wasModified(map))
validateOld()
expectError {
block()
}
assertFalse(wasModified(map))
}
}
// Expect mutating through entries to throw
validate { map.entries.add(map.entries.first()) }
validate {
map.entries.addAll(listOf(map.entries.first(), map.entries.drop(1).first()))
}
validate { map.entries.clear() }
validate { map.entries.remove(map.entries.first()) }
validate {
map.entries.removeAll(listOf(map.entries.first(), map.entries.drop(1).first()))
}
validate {
map.entries.retainAll(listOf(map.entries.first(), map.entries.drop(1).first()))
}
validate {
val iterator = map.entries.iterator()
iterator.next()
iterator.remove()
}
// Expect mutating through keys to throw
validate { map.keys.add(map.keys.first()) }
validate { map.keys.addAll(listOf(map.keys.first(), map.keys.drop(1).first())) }
validate { map.keys.clear() }
validate { map.keys.remove(map.keys.first()) }
validate { map.keys.removeAll(listOf(map.keys.first(), map.keys.drop(1).first())) }
validate { map.keys.retainAll(listOf(map.keys.first(), map.keys.drop(1).first())) }
validate {
val iterator = map.keys.iterator()
iterator.next()
iterator.remove()
}
// Expect mutating through values to throw
validate { map.values.add(map.values.first()) }
validate { map.values.addAll(listOf(map.values.first(), map.values.drop(1).first())) }
validate { map.values.clear() }
validate { map.values.remove(map.values.first()) }
validate {
map.values.removeAll(listOf(map.values.first(), map.values.drop(1).first()))
}
validate {
map.values.retainAll(listOf(map.values.first(), map.values.drop(1).first()))
}
validate {
val iterator = map.values.iterator()
iterator.next()
iterator.remove()
}
}
}
fun expectError(block: () -> Unit) {
var thrown = false
try {
block()
} catch (e: IllegalStateException) {
thrown = true
}
Assert.assertTrue(thrown)
}
// Helpers for the above tests
inline fun <T> frame(crossinline block: ()->T): T {
open(false)
try {
return block()
} catch (e: Exception) {
abortHandler()
throw e
} finally {
commitHandler()
}
}
inline fun <T> observeFrame(noinline observer: FrameReadObserver, crossinline block: () -> T): T {
open(observer)
try {
return block()
} catch (e: Exception) {
abortHandler()
throw e
} finally {
commitHandler()
}
}
inline fun <T> observeCommit(
noinline observer: FrameCommitObserver,
crossinline block: () -> T
): T {
val unregister = registerCommitObserver(observer)
try {
return block()
} finally {
unregister()
}
}
inline fun suspended(crossinline block: ()->Unit): Frame {
open(false)
try {
block()
return androidx.compose.frames.suspend()
} catch (e: Exception) {
abortHandler()
throw e
}
}
inline fun <T> restored(frame: Frame, crossinline block: ()->T): T {
restore(frame)
try {
return block()
} catch (e: Exception) {
abortHandler()
throw e
} finally {
commitHandler()
}
}
inline fun aborted(crossinline block: ()->Unit) {
open(false)
try {
block()
} finally {
abortHandler()
}
}
inline fun speculation(crossinline block: ()->Unit) {
speculate()
try {
block()
} finally {
abortHandler()
}
}
inline fun <reified T : Throwable> expectThrow(
@Suppress("UNUSED_PARAMETER") e: KClass<T>,
crossinline block: () -> Unit
) {
var thrown = false
try {
block()
} catch (e: Throwable) {
Assert.assertTrue(e is T)
thrown = true
}
Assert.assertTrue(thrown)
}
val Record.length: Int
get() {
var current: Record? = this
var len = 0
while (current != null) {
len++
current = current.next
}
return len
}
class AddressRaw(var street: String)
class AddressProp(streetValue: String) {
var _street = streetValue
var street: String
get() = _street
set(value) {_street = value }
}
| 8 | null | 0 | 6 | b9cd83371e928380610719dfbf97c87c58e80916 | 30,928 | platform_frameworks_support | Apache License 2.0 |
src/main/kotlin/github/samyycx/fisherman/modules/exception/DependencyException.kt | samyycX | 742,795,853 | false | {"Kotlin": 13135, "Java": 351} | package github.samyycx.fisherman.modules.exception
class DependencyException(private val failedMessage: String) : Exception() {
override val message: String
get() = failedMessage
} | 0 | Kotlin | 0 | 0 | 9a79fdbbc45ad5ac50c3b82255b48719e969b139 | 195 | Fisherman | MIT License |
app/src/main/java/com/ifanr/tangzhi/ext/Record.kt | cyrushine | 224,551,311 | false | {"Kotlin": 673925, "Java": 59856, "Python": 795} | package com.ifanr.tangzhi.ext
import com.google.gson.JsonObject
import com.minapp.android.sdk.database.Record
import java.lang.reflect.Constructor
private val CONSTRUCTS = mutableMapOf<Class<*>, Constructor<*>>()
@Throws(Exception::class)
private fun findSuitableConstruct(clz: Class<*>): Constructor<*> {
synchronized(CONSTRUCTS) {
return CONSTRUCTS.getOrPut(clz) {
clz.getConstructor(JsonObject::class.java)
}
}
}
fun Record.getSafeString(prop: String): String =
getString(prop) ?: ""
/**
* prop is a json string, serialize to object
*/
fun <T> Record.getSafeArray(prop: String, clz: Class<T>): List<T> =
getArray(prop, clz) ?: emptyList()
fun <T> Record.getSafeArrayByConstruct(prop: String, clz: Class<T>): List<T> {
return try {
getSafeArray(prop).map { findSuitableConstruct(clz).newInstance(it) as T }
} catch (e: Exception) { emptyList() }
}
fun Record.getSafeArray(prop: String): List<JsonObject> =
getSafeArray(prop, JsonObject::class.java)
fun Record.getSafeStringArray(prop: String): List<String> =
getSafeArray(prop, String::class.java)
fun Record.getSafeLong(prop: String): Long =
getLong(prop) ?: 0L
fun Record.getSafeFloat(prop: String): Float =
getFloat(prop) ?: 0f
fun Record.getSafeBoolean(prop: String): Boolean =
getBoolean(prop) ?: false
fun Record.getSafeId(): String = id ?: ""
fun Record.getSafeInt(prop: String): Int =
getInt(prop) ?: 0
fun Record.getSafeJson(prop: String): JsonObject =
getJsonObject(prop) ?: JsonObject() | 0 | Kotlin | 0 | 0 | ab9a7a2eba7f53eca918e084da9d9907f7997cee | 1,554 | tangzhi_android | Apache License 2.0 |
app/src/main/java/org/liuyi/mifreeformx/proxy/framework/ActivityOptionsInjector.kt | LiuYiGL | 624,455,753 | false | null | package org.liuyi.mifreeformx.proxy.framework
import org.liuyi.mifreeformx.xposed.base.annotation.ProxyField
import org.liuyi.mifreeformx.xposed.base.interfaces.ProxyInterface
/**
* @Author: Liuyi
* @Date: 2023/05/15/11:11:08
* @Description:
*/
interface ActivityOptionsInjector: ProxyInterface {
@get: ProxyField(name = "mFreeformScale")
@set: ProxyField(name = "mFreeformScale")
var mFreeformScale: Float
} | 0 | Kotlin | 2 | 34 | 5d96c5ea8dc50df85b3a74090e623b3bcb3a7ae5 | 427 | MiFreeFormX | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-tcs-android/src/main/kotlin/org/jetbrains/kotlin/gradle/android/AndroidTargetPrototype.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("DEPRECATION", "DuplicatedCode")
package org.jetbrains.kotlin.gradle.android
import com.android.build.api.attributes.AgpVersionAttr
import com.android.build.gradle.LibraryExtension
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import org.gradle.api.attributes.java.TargetJvmEnvironment
import org.gradle.api.attributes.java.TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.named
import org.jetbrains.kotlin.gradle.android.AndroidKotlinSourceSet.Companion.android
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.ide.IdeMultiplatformImport
import org.jetbrains.kotlin.gradle.plugin.mpp.external.*
import org.jetbrains.kotlin.gradle.plugin.mpp.external.ExternalKotlinTargetDescriptor.TargetFactory
fun KotlinMultiplatformExtension.androidTargetPrototype(): PrototypeAndroidTarget {
val project = this.project
val androidExtension = project.extensions.getByType<LibraryExtension>()
/*
Set a variant filter and only allow 'debug'.
Reason: This prototype will not deal w/ buildTypes or flavors.
Only 'debug' will be supported. As of agreed w/ AGP team, this is the initial goal
for the APIs.
*/
androidExtension.variantFilter { variant ->
if (variant.name != "debug") {
variant.ignore = true
}
}
/*
Create our 'AndroidTarget':
This uses the 'KotlinPlatformType.jvm' instead of androidJvm, since from the perspective of
Kotlin, this is just another 'jvm' like target (using the jvm compiler)
*/
val androidTarget = createExternalKotlinTarget<PrototypeAndroidTarget> {
targetName = "android"
platformType = KotlinPlatformType.jvm
targetFactory = TargetFactory { delegate -> PrototypeAndroidTarget(delegate, PrototypeAndroidDsl(31)) }
/*
Configure apiElements configuration attributes (project to project dependency)
In this example we hardcoded AGP version 7.4.0-beta02 as demo
*/
apiElements.configure { _, configuration ->
configuration.attributes.attribute(TARGET_JVM_ENVIRONMENT_ATTRIBUTE, project.objects.named(TargetJvmEnvironment.ANDROID))
configuration.attributes.attribute(AgpVersionAttr.ATTRIBUTE, project.objects.named("7.4.0-beta02")) /* For demo */
}
/*
Configure runtimeElements configuration attributes (project to project dependency)
In this example we hardcoded AGP version 7.4.0-beta02 as demo
*/
runtimeElements.configure { _, configuration ->
configuration.attributes.attribute(TARGET_JVM_ENVIRONMENT_ATTRIBUTE, project.objects.named(TargetJvmEnvironment.ANDROID))
configuration.attributes.attribute(AgpVersionAttr.ATTRIBUTE, project.objects.named("7.4.0-beta02")) /* For demo */
}
/*
Configure runtimeElements configuration attributes (project to project dependency)
In this example we hardcoded AGP version 7.4.0-beta02 as demo
*/
sourcesElements.configure { _, configuration ->
configuration.attributes.attribute(TARGET_JVM_ENVIRONMENT_ATTRIBUTE, project.objects.named(TargetJvmEnvironment.ANDROID))
configuration.attributes.attribute(AgpVersionAttr.ATTRIBUTE, project.objects.named("7.4.0-beta02")) /* For demo */
}
/*
Configure published configurations (maven publication):
We override KotlinPlatformType to be androidJvm for now (to be discussed w/ Google later)
*/
apiElementsPublished.configure { _, configuration ->
/* TODO w/ Google: Find a way to deprecate this attribute */
configuration.attributes.attribute(KotlinPlatformType.attribute, KotlinPlatformType.androidJvm)
configuration.attributes.attribute(TARGET_JVM_ENVIRONMENT_ATTRIBUTE, project.objects.named(TargetJvmEnvironment.ANDROID))
}
runtimeElementsPublished.configure { _, configuration ->
/* TODO w/ Google: Find a way to deprecate this attribute */
configuration.attributes.attribute(KotlinPlatformType.attribute, KotlinPlatformType.androidJvm)
configuration.attributes.attribute(TARGET_JVM_ENVIRONMENT_ATTRIBUTE, project.objects.named(TargetJvmEnvironment.ANDROID))
}
configureIdeImport {
registerDependencyResolver(
AndroidBootClasspathIdeDependencyResolver(project),
constraint = IdeMultiplatformImport.SourceSetConstraint { sourceSet -> sourceSet.android != null },
phase = IdeMultiplatformImport.DependencyResolutionPhase.BinaryDependencyResolution,
priority = IdeMultiplatformImport.Priority.normal
)
}
}
/*
Whilst using the .all hook, we only expect the single 'debug' variant to be available through this API.
*/
androidExtension.libraryVariants.all { androidVariant ->
project.logger.quiet("Setting up applicationVariant: ${androidVariant.name}")
/*
Create Compilations: main, unitTest and instrumentedTest
(as proposed in the new Multiplatform/Android SourceSetLayout v2)
*/
val mainCompilation = androidTarget.createAndroidCompilation("main")
val unitTestCompilation = androidTarget.createAndroidCompilation("unitTest")
val instrumentedTestCompilation = androidTarget.createAndroidCompilation("instrumentedTest")
/*
Associate unitTest/instrumentedTest compilations with main
*/
unitTestCompilation.associateWith(mainCompilation)
instrumentedTestCompilation.associateWith(mainCompilation)
/*
Setup dependsOn edges as in Multiplatform/Android SourceSetLayout v2:
android/main dependsOn commonMain
android/unitTest dependsOn commonTest
android/instrumentedTest *does not depend on a common SourceSet*
*/
mainCompilation.defaultSourceSet.dependsOn(sourceSets.getByName("commonMain"))
unitTestCompilation.defaultSourceSet.dependsOn(sourceSets.getByName("commonTest"))
/*
Wire the Kotlin Compilations output (.class files) into the Android artifacts
by using the 'registerPreJavacGeneratedBytecode' function
*/
androidVariant.registerPreJavacGeneratedBytecode(mainCompilation.output.classesDirs)
androidVariant.unitTestVariant.registerPreJavacGeneratedBytecode(unitTestCompilation.output.classesDirs)
androidVariant.testVariant.registerPreJavacGeneratedBytecode(instrumentedTestCompilation.output.classesDirs)
/*
Add dependencies coming from Kotlin to Android by adding all dependencies from Kotlin to the variants
compileConfiguration or runtimeConfiguration
*/
androidVariant.compileConfiguration.extendsFrom(mainCompilation.configurations.compileDependencyConfiguration)
androidVariant.runtimeConfiguration.extendsFrom(mainCompilation.configurations.runtimeDependencyConfiguration)
androidVariant.unitTestVariant.compileConfiguration.extendsFrom(unitTestCompilation.configurations.compileDependencyConfiguration)
androidVariant.unitTestVariant.runtimeConfiguration.extendsFrom(unitTestCompilation.configurations.runtimeDependencyConfiguration)
androidVariant.testVariant.compileConfiguration.extendsFrom(instrumentedTestCompilation.configurations.compileDependencyConfiguration)
androidVariant.testVariant.runtimeConfiguration.extendsFrom(instrumentedTestCompilation.configurations.runtimeDependencyConfiguration)
/*
Add the 'android boot classpath' to the compilation dependencies to compile against
*/
mainCompilation.configurations.compileDependencyConfiguration.dependencies.add(
project.dependencies.create(project.androidBootClasspath())
)
/*
Setup apiElements configuration:
variants:
- classes (provides access to the compiled .class files)
artifactType: CLASSES_JAR
*/
androidTarget.apiElementsConfiguration.outgoing.variants.create("classes").let { variant ->
variant.attributes.attribute(AndroidArtifacts.ARTIFACT_TYPE, AndroidArtifacts.ArtifactType.CLASSES_JAR.type)
variant.artifact(mainCompilation.output.classesDirs.singleFile) {
it.builtBy(mainCompilation.output.classesDirs)
}
}
/*
Setup runtimeElements configuration:
variants:
- classes (provides access to the compiled .class files)
artifactType: CLASSES_JAR
*/
androidTarget.runtimeElementsConfiguration.outgoing.variants.create("classes").let { variant ->
variant.attributes.attribute(AndroidArtifacts.ARTIFACT_TYPE, AndroidArtifacts.ArtifactType.CLASSES_JAR.type)
variant.artifact(mainCompilation.output.classesDirs.singleFile) {
it.builtBy(mainCompilation.output.classesDirs)
}
}
/*
Add .aar artifacts to publications!
*/
androidTarget.apiElementsPublishedConfiguration.outgoing.artifact(androidVariant.packageLibraryProvider)
androidTarget.runtimeElementsPublishedConfiguration.outgoing.artifact(androidVariant.packageLibraryProvider)
/*
"Disable" configurations from plain Android plugin
This hack will not be necessary in the final implementation
*/
project.configurations.findByName("${androidVariant.name}ApiElements")?.isCanBeConsumed = false
project.configurations.findByName("${androidVariant.name}RuntimeElements")?.isCanBeConsumed = false
}
return androidTarget
}
| 7 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 10,126 | kotlin | Apache License 2.0 |
components/ledger/ledger-verification/src/main/kotlin/net/corda/ledger/verification/processor/impl/VerificationRequestProcessor.kt | corda | 346,070,752 | false | null | package net.corda.ledger.verification.processor.impl
import net.corda.data.flow.event.external.ExternalEventContext
import net.corda.data.flow.event.external.ExternalEventResponseErrorType
import net.corda.flow.external.events.responses.exceptions.NotAllowedCpkException
import net.corda.flow.external.events.responses.factory.ExternalEventResponseFactory
import net.corda.ledger.utxo.verification.TransactionVerificationRequest
import net.corda.ledger.verification.processor.VerificationRequestHandler
import net.corda.ledger.verification.sandbox.VerificationSandboxService
import net.corda.messaging.api.processor.DurableProcessor
import net.corda.messaging.api.records.Record
import net.corda.flow.utils.toMap
import net.corda.utilities.MDC_CLIENT_ID
import net.corda.utilities.MDC_EXTERNAL_EVENT_ID
import net.corda.utilities.trace
import net.corda.utilities.withMDC
import net.corda.virtualnode.toCorda
import org.slf4j.LoggerFactory
import java.io.NotSerializableException
/**
* Handles incoming requests, typically from the flow worker, and sends responses.
*/
@Suppress("LongParameterList")
class VerificationRequestProcessor(
private val verificationSandboxService: VerificationSandboxService,
private val requestHandler: VerificationRequestHandler,
private val responseFactory: ExternalEventResponseFactory
) : DurableProcessor<String, TransactionVerificationRequest> {
private companion object {
val log = LoggerFactory.getLogger(this::class.java.enclosingClass)
}
override val keyClass = String::class.java
override val valueClass = TransactionVerificationRequest::class.java
override fun onNext(events: List<Record<String, TransactionVerificationRequest>>): List<Record<*, *>> {
log.trace { "onNext processing messages ${events.joinToString(",") { it.key }}" }
return events
.mapNotNull { it.value }
.map { request ->
val clientRequestId = request.flowExternalEventContext.contextProperties.toMap()[MDC_CLIENT_ID] ?: ""
withMDC(
mapOf(
MDC_CLIENT_ID to clientRequestId,
MDC_EXTERNAL_EVENT_ID to request.flowExternalEventContext.requestId
)
) {
try {
val holdingIdentity = request.holdingIdentity.toCorda()
val sandbox = verificationSandboxService.get(holdingIdentity, request.cpkMetadata)
requestHandler.handleRequest(sandbox, request)
} catch (e: Exception) {
errorResponse(request.flowExternalEventContext, e)
}
}
}
}
private fun errorResponse(externalEventContext : ExternalEventContext, exception: Exception) = when (exception) {
is NotAllowedCpkException, is NotSerializableException -> {
log.error(errorMessage(externalEventContext, ExternalEventResponseErrorType.PLATFORM), exception)
responseFactory.platformError(externalEventContext, exception)
} else -> {
log.warn(errorMessage(externalEventContext, ExternalEventResponseErrorType.TRANSIENT), exception)
responseFactory.transientError(externalEventContext, exception)
}
}
private fun errorMessage(
externalEventContext: ExternalEventContext,
errorType: ExternalEventResponseErrorType
) = "Exception occurred (type=$errorType) for flow-worker request ${externalEventContext.requestId}"
}
| 71 | Kotlin | 9 | 30 | c8f818b35b5fa27ca5fd523a416e2fd8a58b3d7d | 3,583 | corda-runtime-os | Apache License 2.0 |
sample/src/main/java/com/longquan/ui/AuthActivity.kt | 1280149014 | 341,882,911 | false | null | package com.longquan.ui
import android.content.Context
import android.net.ProxyInfo
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.provider.Settings
import android.util.Log
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.longquan.R
import kotlinx.android.synthetic.main.activity_authz2.*
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
class AuthActivity : AppCompatActivity() {
private val url = "http://g.cn/generate_204"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_authz2)
setWeb()
webView.loadUrl(url)
}
private fun setWeb() {
val webSettings: WebSettings = webView.getSettings()
webSettings.javaScriptEnabled = true
webSettings.builtInZoomControls = true
webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
webView.visibility = View.VISIBLE
webSettings.setSupportZoom(true)
webSettings.domStorageEnabled = true
webView.requestFocus()
webSettings.useWideViewPort = true
webSettings.loadWithOverviewMode = true
webSettings.setSupportZoom(true)
webSettings.javaScriptCanOpenWindowsAutomatically = true
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
Log.d("setweb", url)
return false
}
}
}
override fun onResume() {
super.onResume()
// object : Thread(){
// override fun run() {
// val isWifiSetPortal = isWifiSetPortal()
// Log.d("test","$isWifiSetPortal = as");
// }
// }.start()
}
private fun getSetting(context: Context, symbol: String, defaultValue: String): String? {
val value = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Settings.Global.getString(context.contentResolver, symbol)
} else {
TODO("VERSION.SDK_INT < JELLY_BEAN_MR1")
}
return value ?: defaultValue
}
} | 2 | null | 1 | 1 | a38c5dfcbf11e327125da32d86bac29d4bdbc3e8 | 2,390 | WifiMaster | Apache License 2.0 |
app/src/main/java/ru/resodostudios/flick/feature/movies/presentation/components/MovieCard.kt | f33lnothin9 | 565,400,839 | false | null | package ru.resodostudios.flick.feature.movies.presentation.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import ru.resodostudios.flick.core.presentation.components.AnimatedShimmer
import ru.resodostudios.flick.core.presentation.theme.Typography
import ru.resodostudios.flick.feature.movies.data.model.MovieEntry
@ExperimentalMaterial3Api
@Composable
fun MovieCard(movie: MovieEntry, onNavigate: () -> Unit) {
Card(onClick = onNavigate) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Box {
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(movie.image?.original)
.crossfade(400)
.size(175)
.build(),
contentDescription = "Image",
modifier = Modifier
.defaultMinSize(minWidth = 200.dp)
.clip(RoundedCornerShape(12.dp)),
filterQuality = FilterQuality.Low,
contentScale = ContentScale.FillWidth,
loading = { AnimatedShimmer() }
)
Surface(
modifier = Modifier
.padding(start = 8.dp, top = 8.dp)
.align(Alignment.TopStart)
.clip(RoundedCornerShape(12.dp)),
color = MaterialTheme.colorScheme.secondaryContainer
) {
Text(
text = (movie.rating?.average ?: 0.0).toString(),
modifier = Modifier
.padding(
start = 8.dp,
top = 2.dp,
end = 8.dp,
bottom = 2.dp
),
style = Typography.labelLarge,
maxLines = 1,
fontWeight = FontWeight.Bold
)
}
}
Column(
modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = movie.name.toString(),
maxLines = 2,
overflow = TextOverflow.Ellipsis,
style = Typography.titleLarge,
textAlign = TextAlign.Start,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier
)
Text(
text = movie.genres?.take(2)?.joinToString(", ") ?: "Empty",
style = Typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
} | 0 | Kotlin | 2 | 15 | a9875c075298ad915ad4f4f052c27cfc59818d53 | 4,166 | Flick | Apache License 2.0 |
domain/interactor/weather/weatherinteractor-api/src/main/kotlin/com/francescsoftware/weathersample/domain/interactor/weather/api/GetTodayWeatherInteractor.kt | fvilarino | 355,724,548 | false | {"Kotlin": 574824, "Shell": 60} | package com.francescsoftware.weathersample.domain.interactor.weather.api
import com.francescsoftware.weathersample.core.type.either.Either
import com.francescsoftware.weathersample.domain.interactor.weather.api.model.TodayWeather
/** Gets the current weather */
interface GetTodayWeatherInteractor {
/**
* Gets the current weather
*
* @param location - a [WeatherLocation] to get the weather for
* @return an [Either] with today's weather
*/
suspend operator fun invoke(location: WeatherLocation): Either<TodayWeather>
}
| 10 | Kotlin | 1 | 33 | ae2e6ad24f6dacb2f6211cdf7684928264f5ebd7 | 556 | Weather-Sample | Apache License 2.0 |
compiler/testData/codegen/box/delegatedProperty/useReflectionOnKProperty.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND: JVM_IR
// IGNORE_BACKEND: JS_IR
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(t: Any?, p: KProperty<*>): String {
p.parameters
p.returnType
p.annotations
return p.toString()
}
}
val prop: String by Delegate()
fun box() = if (prop == "val prop: kotlin.String") "OK" else "Fail: $prop"
| 34 | null | 5563 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 492 | kotlin | Apache License 2.0 |
extension-compose/src/main/java/com/mapbox/maps/extension/compose/style/layers/generated/LayerProperties.kt | mapbox | 330,365,289 | false | null | // This file is generated.
package com.mapbox.maps.extension.compose.style.layers.generated
import androidx.compose.runtime.Immutable
import com.mapbox.bindgen.Value
import com.mapbox.maps.MapboxExperimental
import com.mapbox.maps.extension.compose.style.internal.ComposeTypeUtils
import com.mapbox.maps.extension.style.expressions.generated.Expression
/**
* Controls the frame of reference for `fill-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class FillTranslateAnchorValue(public val value: Value) {
/**
* Construct the [FillTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: FillTranslateAnchorValue = FillTranslateAnchorValue(Value.valueOf("FillTranslateAnchorValue.INITIAL"))
/**
* Default value for [FillTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: FillTranslateAnchorValue = FillTranslateAnchorValue(Value.nullValue())
/**
* The fill is translated relative to the map.
*/
@JvmField
public val MAP: FillTranslateAnchorValue = FillTranslateAnchorValue(Value("map"))
/**
* The fill is translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: FillTranslateAnchorValue = FillTranslateAnchorValue(Value("viewport"))
}
}
/**
* Whether this layer is displayed.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class VisibilityValue(public val value: Value) {
/**
* Construct the [VisibilityValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: VisibilityValue = VisibilityValue(Value.valueOf("VisibilityValue.INITIAL"))
/**
* Default value for [VisibilityValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: VisibilityValue = VisibilityValue(Value.nullValue())
/**
* The layer is shown.
*/
@JvmField
public val VISIBLE: VisibilityValue = VisibilityValue(Value("visible"))
/**
* The layer is not shown.
*/
@JvmField
public val NONE: VisibilityValue = VisibilityValue(Value("none"))
}
}
/**
* The display of line endings.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class LineCapValue(public val value: Value) {
/**
* Construct the [LineCapValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: LineCapValue = LineCapValue(Value.valueOf("LineCapValue.INITIAL"))
/**
* Default value for [LineCapValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: LineCapValue = LineCapValue(Value.nullValue())
/**
* A cap with a squared-off end which is drawn to the exact endpoint of the line.
*/
@JvmField
public val BUTT: LineCapValue = LineCapValue(Value("butt"))
/**
* A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line.
*/
@JvmField
public val ROUND: LineCapValue = LineCapValue(Value("round"))
/**
* A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width.
*/
@JvmField
public val SQUARE: LineCapValue = LineCapValue(Value("square"))
}
}
/**
* The display of lines when joining.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class LineJoinValue(public val value: Value) {
/**
* Construct the [LineJoinValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: LineJoinValue = LineJoinValue(Value.valueOf("LineJoinValue.INITIAL"))
/**
* Default value for [LineJoinValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: LineJoinValue = LineJoinValue(Value.nullValue())
/**
* A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width.
*/
@JvmField
public val BEVEL: LineJoinValue = LineJoinValue(Value("bevel"))
/**
* A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line.
*/
@JvmField
public val ROUND: LineJoinValue = LineJoinValue(Value("round"))
/**
* A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet.
*/
@JvmField
public val MITER: LineJoinValue = LineJoinValue(Value("miter"))
}
}
/**
* Controls the frame of reference for `line-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class LineTranslateAnchorValue(public val value: Value) {
/**
* Construct the [LineTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: LineTranslateAnchorValue = LineTranslateAnchorValue(Value.valueOf("LineTranslateAnchorValue.INITIAL"))
/**
* Default value for [LineTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: LineTranslateAnchorValue = LineTranslateAnchorValue(Value.nullValue())
/**
* The line is translated relative to the map.
*/
@JvmField
public val MAP: LineTranslateAnchorValue = LineTranslateAnchorValue(Value("map"))
/**
* The line is translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: LineTranslateAnchorValue = LineTranslateAnchorValue(Value("viewport"))
}
}
/**
* Part of the icon placed closest to the anchor.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class IconAnchorValue(public val value: Value) {
/**
* Construct the [IconAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: IconAnchorValue = IconAnchorValue(Value.valueOf("IconAnchorValue.INITIAL"))
/**
* Default value for [IconAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: IconAnchorValue = IconAnchorValue(Value.nullValue())
/**
* The center of the icon is placed closest to the anchor.
*/
@JvmField
public val CENTER: IconAnchorValue = IconAnchorValue(Value("center"))
/**
* The left side of the icon is placed closest to the anchor.
*/
@JvmField
public val LEFT: IconAnchorValue = IconAnchorValue(Value("left"))
/**
* The right side of the icon is placed closest to the anchor.
*/
@JvmField
public val RIGHT: IconAnchorValue = IconAnchorValue(Value("right"))
/**
* The top of the icon is placed closest to the anchor.
*/
@JvmField
public val TOP: IconAnchorValue = IconAnchorValue(Value("top"))
/**
* The bottom of the icon is placed closest to the anchor.
*/
@JvmField
public val BOTTOM: IconAnchorValue = IconAnchorValue(Value("bottom"))
/**
* The top left corner of the icon is placed closest to the anchor.
*/
@JvmField
public val TOP_LEFT: IconAnchorValue = IconAnchorValue(Value("top-left"))
/**
* The top right corner of the icon is placed closest to the anchor.
*/
@JvmField
public val TOP_RIGHT: IconAnchorValue = IconAnchorValue(Value("top-right"))
/**
* The bottom left corner of the icon is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_LEFT: IconAnchorValue = IconAnchorValue(Value("bottom-left"))
/**
* The bottom right corner of the icon is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_RIGHT: IconAnchorValue = IconAnchorValue(Value("bottom-right"))
}
}
/**
* Orientation of icon when map is pitched.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class IconPitchAlignmentValue(public val value: Value) {
/**
* Construct the [IconPitchAlignmentValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: IconPitchAlignmentValue = IconPitchAlignmentValue(Value.valueOf("IconPitchAlignmentValue.INITIAL"))
/**
* Default value for [IconPitchAlignmentValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: IconPitchAlignmentValue = IconPitchAlignmentValue(Value.nullValue())
/**
* The icon is aligned to the plane of the map.
*/
@JvmField
public val MAP: IconPitchAlignmentValue = IconPitchAlignmentValue(Value("map"))
/**
* The icon is aligned to the plane of the viewport.
*/
@JvmField
public val VIEWPORT: IconPitchAlignmentValue = IconPitchAlignmentValue(Value("viewport"))
/**
* Automatically matches the value of {@link ICON_ROTATION_ALIGNMENT}.
*/
@JvmField
public val AUTO: IconPitchAlignmentValue = IconPitchAlignmentValue(Value("auto"))
}
}
/**
* In combination with `symbol-placement`, determines the rotation behavior of icons.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class IconRotationAlignmentValue(public val value: Value) {
/**
* Construct the [IconRotationAlignmentValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: IconRotationAlignmentValue = IconRotationAlignmentValue(Value.valueOf("IconRotationAlignmentValue.INITIAL"))
/**
* Default value for [IconRotationAlignmentValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: IconRotationAlignmentValue = IconRotationAlignmentValue(Value.nullValue())
/**
* When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_POINT}, aligns icons east-west. When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_LINE} or {@link Property#SYMBOL_PLACEMENT_LINE_CENTER}, aligns icon x-axes with the line.
*/
@JvmField
public val MAP: IconRotationAlignmentValue = IconRotationAlignmentValue(Value("map"))
/**
* Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of {@link SYMBOL_PLACEMENT}.
*/
@JvmField
public val VIEWPORT: IconRotationAlignmentValue = IconRotationAlignmentValue(Value("viewport"))
/**
* When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_POINT}, this is equivalent to {@link Property#ICON_ROTATION_ALIGNMENT_VIEWPORT}. When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_LINE} or {@link Property#SYMBOL_PLACEMENT_LINE_CENTER}, this is equivalent to {@link Property#ICON_ROTATION_ALIGNMENT_MAP}.
*/
@JvmField
public val AUTO: IconRotationAlignmentValue = IconRotationAlignmentValue(Value("auto"))
}
}
/**
* Scales the icon to fit around the associated text.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class IconTextFitValue(public val value: Value) {
/**
* Construct the [IconTextFitValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: IconTextFitValue = IconTextFitValue(Value.valueOf("IconTextFitValue.INITIAL"))
/**
* Default value for [IconTextFitValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: IconTextFitValue = IconTextFitValue(Value.nullValue())
/**
* The icon is displayed at its intrinsic aspect ratio.
*/
@JvmField
public val NONE: IconTextFitValue = IconTextFitValue(Value("none"))
/**
* The icon is scaled in the x-dimension to fit the width of the text.
*/
@JvmField
public val WIDTH: IconTextFitValue = IconTextFitValue(Value("width"))
/**
* The icon is scaled in the y-dimension to fit the height of the text.
*/
@JvmField
public val HEIGHT: IconTextFitValue = IconTextFitValue(Value("height"))
/**
* The icon is scaled in both x- and y-dimensions.
*/
@JvmField
public val BOTH: IconTextFitValue = IconTextFitValue(Value("both"))
}
}
/**
* Label placement relative to its geometry.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class SymbolPlacementValue(public val value: Value) {
/**
* Construct the [SymbolPlacementValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: SymbolPlacementValue = SymbolPlacementValue(Value.valueOf("SymbolPlacementValue.INITIAL"))
/**
* Default value for [SymbolPlacementValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: SymbolPlacementValue = SymbolPlacementValue(Value.nullValue())
/**
* The label is placed at the point where the geometry is located.
*/
@JvmField
public val POINT: SymbolPlacementValue = SymbolPlacementValue(Value("point"))
/**
* The label is placed along the line of the geometry. Can only be used on LineString and Polygon geometries.
*/
@JvmField
public val LINE: SymbolPlacementValue = SymbolPlacementValue(Value("line"))
/**
* The label is placed at the center of the line of the geometry. Can only be used on LineString and Polygon geometries. Note that a single feature in a vector tile may contain multiple line geometries.
*/
@JvmField
public val LINE_CENTER: SymbolPlacementValue = SymbolPlacementValue(Value("line-center"))
}
}
/**
* Determines whether overlapping symbols in the same layer are rendered in the order that they appear in the data source or by their y-position relative to the viewport. To control the order and prioritization of symbols otherwise, use `symbol-sort-key`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class SymbolZOrderValue(public val value: Value) {
/**
* Construct the [SymbolZOrderValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: SymbolZOrderValue = SymbolZOrderValue(Value.valueOf("SymbolZOrderValue.INITIAL"))
/**
* Default value for [SymbolZOrderValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: SymbolZOrderValue = SymbolZOrderValue(Value.nullValue())
/**
* Sorts symbols by symbol sort key if set. Otherwise, sorts symbols by their y-position relative to the viewport if {@link ICON_ALLOW_OVERLAP} or {@link TEXT_ALLOW_OVERLAP} is set to {@link TRUE} or {@link ICON_IGNORE_PLACEMENT} or {@link TEXT_IGNORE_PLACEMENT} is {@link FALSE}.
*/
@JvmField
public val AUTO: SymbolZOrderValue = SymbolZOrderValue(Value("auto"))
/**
* Sorts symbols by their y-position relative to the viewport if {@link ICON_ALLOW_OVERLAP} or {@link TEXT_ALLOW_OVERLAP} is set to {@link TRUE} or {@link ICON_IGNORE_PLACEMENT} or {@link TEXT_IGNORE_PLACEMENT} is {@link FALSE}.
*/
@JvmField
public val VIEWPORT_Y: SymbolZOrderValue = SymbolZOrderValue(Value("viewport-y"))
/**
* Sorts symbols by symbol sort key if set. Otherwise, no sorting is applied; symbols are rendered in the same order as the source data.
*/
@JvmField
public val SOURCE: SymbolZOrderValue = SymbolZOrderValue(Value("source"))
}
}
/**
* Part of the text placed closest to the anchor.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextAnchorValue(public val value: Value) {
/**
* Construct the [TextAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextAnchorValue = TextAnchorValue(Value.valueOf("TextAnchorValue.INITIAL"))
/**
* Default value for [TextAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextAnchorValue = TextAnchorValue(Value.nullValue())
/**
* The center of the text is placed closest to the anchor.
*/
@JvmField
public val CENTER: TextAnchorValue = TextAnchorValue(Value("center"))
/**
* The left side of the text is placed closest to the anchor.
*/
@JvmField
public val LEFT: TextAnchorValue = TextAnchorValue(Value("left"))
/**
* The right side of the text is placed closest to the anchor.
*/
@JvmField
public val RIGHT: TextAnchorValue = TextAnchorValue(Value("right"))
/**
* The top of the text is placed closest to the anchor.
*/
@JvmField
public val TOP: TextAnchorValue = TextAnchorValue(Value("top"))
/**
* The bottom of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM: TextAnchorValue = TextAnchorValue(Value("bottom"))
/**
* The top left corner of the text is placed closest to the anchor.
*/
@JvmField
public val TOP_LEFT: TextAnchorValue = TextAnchorValue(Value("top-left"))
/**
* The top right corner of the text is placed closest to the anchor.
*/
@JvmField
public val TOP_RIGHT: TextAnchorValue = TextAnchorValue(Value("top-right"))
/**
* The bottom left corner of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_LEFT: TextAnchorValue = TextAnchorValue(Value("bottom-left"))
/**
* The bottom right corner of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_RIGHT: TextAnchorValue = TextAnchorValue(Value("bottom-right"))
}
}
/**
* Text justification options.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextJustifyValue(public val value: Value) {
/**
* Construct the [TextJustifyValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextJustifyValue = TextJustifyValue(Value.valueOf("TextJustifyValue.INITIAL"))
/**
* Default value for [TextJustifyValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextJustifyValue = TextJustifyValue(Value.nullValue())
/**
* The text is aligned towards the anchor position.
*/
@JvmField
public val AUTO: TextJustifyValue = TextJustifyValue(Value("auto"))
/**
* The text is aligned to the left.
*/
@JvmField
public val LEFT: TextJustifyValue = TextJustifyValue(Value("left"))
/**
* The text is centered.
*/
@JvmField
public val CENTER: TextJustifyValue = TextJustifyValue(Value("center"))
/**
* The text is aligned to the right.
*/
@JvmField
public val RIGHT: TextJustifyValue = TextJustifyValue(Value("right"))
}
}
/**
* Orientation of text when map is pitched.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextPitchAlignmentValue(public val value: Value) {
/**
* Construct the [TextPitchAlignmentValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextPitchAlignmentValue = TextPitchAlignmentValue(Value.valueOf("TextPitchAlignmentValue.INITIAL"))
/**
* Default value for [TextPitchAlignmentValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextPitchAlignmentValue = TextPitchAlignmentValue(Value.nullValue())
/**
* The text is aligned to the plane of the map.
*/
@JvmField
public val MAP: TextPitchAlignmentValue = TextPitchAlignmentValue(Value("map"))
/**
* The text is aligned to the plane of the viewport.
*/
@JvmField
public val VIEWPORT: TextPitchAlignmentValue = TextPitchAlignmentValue(Value("viewport"))
/**
* Automatically matches the value of {@link TEXT_ROTATION_ALIGNMENT}.
*/
@JvmField
public val AUTO: TextPitchAlignmentValue = TextPitchAlignmentValue(Value("auto"))
}
}
/**
* In combination with `symbol-placement`, determines the rotation behavior of the individual glyphs forming the text.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextRotationAlignmentValue(public val value: Value) {
/**
* Construct the [TextRotationAlignmentValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextRotationAlignmentValue = TextRotationAlignmentValue(Value.valueOf("TextRotationAlignmentValue.INITIAL"))
/**
* Default value for [TextRotationAlignmentValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextRotationAlignmentValue = TextRotationAlignmentValue(Value.nullValue())
/**
* When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_POINT}, aligns text east-west. When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_LINE} or {@link Property#SYMBOL_PLACEMENT_LINE_CENTER}, aligns text x-axes with the line.
*/
@JvmField
public val MAP: TextRotationAlignmentValue = TextRotationAlignmentValue(Value("map"))
/**
* Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of {@link SYMBOL_PLACEMENT}.
*/
@JvmField
public val VIEWPORT: TextRotationAlignmentValue = TextRotationAlignmentValue(Value("viewport"))
/**
* When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_POINT}, this is equivalent to {@link Property#TEXT_ROTATION_ALIGNMENT_VIEWPORT}. When {@link SYMBOL_PLACEMENT} is set to {@link Property#SYMBOL_PLACEMENT_LINE} or {@link Property#SYMBOL_PLACEMENT_LINE_CENTER}, this is equivalent to {@link Property#TEXT_ROTATION_ALIGNMENT_MAP}.
*/
@JvmField
public val AUTO: TextRotationAlignmentValue = TextRotationAlignmentValue(Value("auto"))
}
}
/**
* Specifies how to capitalize text, similar to the CSS `text-transform` property.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextTransformValue(public val value: Value) {
/**
* Construct the [TextTransformValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextTransformValue = TextTransformValue(Value.valueOf("TextTransformValue.INITIAL"))
/**
* Default value for [TextTransformValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextTransformValue = TextTransformValue(Value.nullValue())
/**
* The text is not altered.
*/
@JvmField
public val NONE: TextTransformValue = TextTransformValue(Value("none"))
/**
* Forces all letters to be displayed in uppercase.
*/
@JvmField
public val UPPERCASE: TextTransformValue = TextTransformValue(Value("uppercase"))
/**
* Forces all letters to be displayed in lowercase.
*/
@JvmField
public val LOWERCASE: TextTransformValue = TextTransformValue(Value("lowercase"))
}
}
/**
* To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextVariableAnchorListValue(public val value: Value) {
/**
* Construct the [TextVariableAnchorListValue] with [TextVariableAnchor].
*/
public constructor(value: List<TextVariableAnchor>) : this(ComposeTypeUtils.wrapToValue(value))
/**
* Construct the [TextVariableAnchorListValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextVariableAnchorListValue = TextVariableAnchorListValue(Value.valueOf("TextVariableAnchorListValue.INITIAL"))
/**
* Default value for [TextVariableAnchorListValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextVariableAnchorListValue = TextVariableAnchorListValue(Value.nullValue())
}
}
/**
* To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextVariableAnchor internal constructor(public val value: Value) {
/**
* Public companion object.
*/
public companion object {
/**
* The center of the text is placed closest to the anchor.
*/
@JvmField
public val CENTER: TextVariableAnchor = TextVariableAnchor(Value("center"))
/**
* The left side of the text is placed closest to the anchor.
*/
@JvmField
public val LEFT: TextVariableAnchor = TextVariableAnchor(Value("left"))
/**
* The right side of the text is placed closest to the anchor.
*/
@JvmField
public val RIGHT: TextVariableAnchor = TextVariableAnchor(Value("right"))
/**
* The top of the text is placed closest to the anchor.
*/
@JvmField
public val TOP: TextVariableAnchor = TextVariableAnchor(Value("top"))
/**
* The bottom of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM: TextVariableAnchor = TextVariableAnchor(Value("bottom"))
/**
* The top left corner of the text is placed closest to the anchor.
*/
@JvmField
public val TOP_LEFT: TextVariableAnchor = TextVariableAnchor(Value("top-left"))
/**
* The top right corner of the text is placed closest to the anchor.
*/
@JvmField
public val TOP_RIGHT: TextVariableAnchor = TextVariableAnchor(Value("top-right"))
/**
* The bottom left corner of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_LEFT: TextVariableAnchor = TextVariableAnchor(Value("bottom-left"))
/**
* The bottom right corner of the text is placed closest to the anchor.
*/
@JvmField
public val BOTTOM_RIGHT: TextVariableAnchor = TextVariableAnchor(Value("bottom-right"))
}
}
/**
* The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. For symbol with point placement, the order of elements in an array define priority order for the placement of an orientation variant. For symbol with line placement, the default text writing mode is either ['horizontal', 'vertical'] or ['vertical', 'horizontal'], the order doesn't affect the placement.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextWritingModeListValue(public val value: Value) {
/**
* Construct the [TextWritingModeListValue] with [TextWritingMode].
*/
public constructor(value: List<TextWritingMode>) : this(ComposeTypeUtils.wrapToValue(value))
/**
* Construct the [TextWritingModeListValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextWritingModeListValue = TextWritingModeListValue(Value.valueOf("TextWritingModeListValue.INITIAL"))
/**
* Default value for [TextWritingModeListValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextWritingModeListValue = TextWritingModeListValue(Value.nullValue())
}
}
/**
* The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. For symbol with point placement, the order of elements in an array define priority order for the placement of an orientation variant. For symbol with line placement, the default text writing mode is either ['horizontal', 'vertical'] or ['vertical', 'horizontal'], the order doesn't affect the placement.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextWritingMode internal constructor(public val value: Value) {
/**
* Public companion object.
*/
public companion object {
/**
* If a text's language supports horizontal writing mode, symbols would be laid out horizontally.
*/
@JvmField
public val HORIZONTAL: TextWritingMode = TextWritingMode(Value("horizontal"))
/**
* If a text's language supports vertical writing mode, symbols would be laid out vertically.
*/
@JvmField
public val VERTICAL: TextWritingMode = TextWritingMode(Value("vertical"))
}
}
/**
* Controls the frame of reference for `icon-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class IconTranslateAnchorValue(public val value: Value) {
/**
* Construct the [IconTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: IconTranslateAnchorValue = IconTranslateAnchorValue(Value.valueOf("IconTranslateAnchorValue.INITIAL"))
/**
* Default value for [IconTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: IconTranslateAnchorValue = IconTranslateAnchorValue(Value.nullValue())
/**
* Icons are translated relative to the map.
*/
@JvmField
public val MAP: IconTranslateAnchorValue = IconTranslateAnchorValue(Value("map"))
/**
* Icons are translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: IconTranslateAnchorValue = IconTranslateAnchorValue(Value("viewport"))
}
}
/**
* Controls the frame of reference for `text-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class TextTranslateAnchorValue(public val value: Value) {
/**
* Construct the [TextTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: TextTranslateAnchorValue = TextTranslateAnchorValue(Value.valueOf("TextTranslateAnchorValue.INITIAL"))
/**
* Default value for [TextTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: TextTranslateAnchorValue = TextTranslateAnchorValue(Value.nullValue())
/**
* The text is translated relative to the map.
*/
@JvmField
public val MAP: TextTranslateAnchorValue = TextTranslateAnchorValue(Value("map"))
/**
* The text is translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: TextTranslateAnchorValue = TextTranslateAnchorValue(Value("viewport"))
}
}
/**
* Orientation of circle when map is pitched.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class CirclePitchAlignmentValue(public val value: Value) {
/**
* Construct the [CirclePitchAlignmentValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: CirclePitchAlignmentValue = CirclePitchAlignmentValue(Value.valueOf("CirclePitchAlignmentValue.INITIAL"))
/**
* Default value for [CirclePitchAlignmentValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: CirclePitchAlignmentValue = CirclePitchAlignmentValue(Value.nullValue())
/**
* The circle is aligned to the plane of the map.
*/
@JvmField
public val MAP: CirclePitchAlignmentValue = CirclePitchAlignmentValue(Value("map"))
/**
* The circle is aligned to the plane of the viewport.
*/
@JvmField
public val VIEWPORT: CirclePitchAlignmentValue = CirclePitchAlignmentValue(Value("viewport"))
}
}
/**
* Controls the scaling behavior of the circle when the map is pitched.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class CirclePitchScaleValue(public val value: Value) {
/**
* Construct the [CirclePitchScaleValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: CirclePitchScaleValue = CirclePitchScaleValue(Value.valueOf("CirclePitchScaleValue.INITIAL"))
/**
* Default value for [CirclePitchScaleValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: CirclePitchScaleValue = CirclePitchScaleValue(Value.nullValue())
/**
* Circles are scaled according to their apparent distance to the camera.
*/
@JvmField
public val MAP: CirclePitchScaleValue = CirclePitchScaleValue(Value("map"))
/**
* Circles are not scaled.
*/
@JvmField
public val VIEWPORT: CirclePitchScaleValue = CirclePitchScaleValue(Value("viewport"))
}
}
/**
* Controls the frame of reference for `circle-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class CircleTranslateAnchorValue(public val value: Value) {
/**
* Construct the [CircleTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: CircleTranslateAnchorValue = CircleTranslateAnchorValue(Value.valueOf("CircleTranslateAnchorValue.INITIAL"))
/**
* Default value for [CircleTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: CircleTranslateAnchorValue = CircleTranslateAnchorValue(Value.nullValue())
/**
* The circle is translated relative to the map.
*/
@JvmField
public val MAP: CircleTranslateAnchorValue = CircleTranslateAnchorValue(Value("map"))
/**
* The circle is translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: CircleTranslateAnchorValue = CircleTranslateAnchorValue(Value("viewport"))
}
}
/**
* Controls the frame of reference for `fill-extrusion-translate`.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class FillExtrusionTranslateAnchorValue(public val value: Value) {
/**
* Construct the [FillExtrusionTranslateAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: FillExtrusionTranslateAnchorValue = FillExtrusionTranslateAnchorValue(Value.valueOf("FillExtrusionTranslateAnchorValue.INITIAL"))
/**
* Default value for [FillExtrusionTranslateAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: FillExtrusionTranslateAnchorValue = FillExtrusionTranslateAnchorValue(Value.nullValue())
/**
* The fill extrusion is translated relative to the map.
*/
@JvmField
public val MAP: FillExtrusionTranslateAnchorValue = FillExtrusionTranslateAnchorValue(Value("map"))
/**
* The fill extrusion is translated relative to the viewport.
*/
@JvmField
public val VIEWPORT: FillExtrusionTranslateAnchorValue = FillExtrusionTranslateAnchorValue(Value("viewport"))
}
}
/**
* The resampling/interpolation method to use for overscaling, also known as texture magnification filter
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class RasterResamplingValue(public val value: Value) {
/**
* Construct the [RasterResamplingValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: RasterResamplingValue = RasterResamplingValue(Value.valueOf("RasterResamplingValue.INITIAL"))
/**
* Default value for [RasterResamplingValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: RasterResamplingValue = RasterResamplingValue(Value.nullValue())
/**
* (Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled
*/
@JvmField
public val LINEAR: RasterResamplingValue = RasterResamplingValue(Value("linear"))
/**
* Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled
*/
@JvmField
public val NEAREST: RasterResamplingValue = RasterResamplingValue(Value("nearest"))
}
}
/**
* Direction of light source when map is rotated.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class HillshadeIlluminationAnchorValue(public val value: Value) {
/**
* Construct the [HillshadeIlluminationAnchorValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: HillshadeIlluminationAnchorValue = HillshadeIlluminationAnchorValue(Value.valueOf("HillshadeIlluminationAnchorValue.INITIAL"))
/**
* Default value for [HillshadeIlluminationAnchorValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: HillshadeIlluminationAnchorValue = HillshadeIlluminationAnchorValue(Value.nullValue())
/**
* The hillshade illumination is relative to the north direction.
*/
@JvmField
public val MAP: HillshadeIlluminationAnchorValue = HillshadeIlluminationAnchorValue(Value("map"))
/**
* The hillshade illumination is relative to the top of the viewport.
*/
@JvmField
public val VIEWPORT: HillshadeIlluminationAnchorValue = HillshadeIlluminationAnchorValue(Value("viewport"))
}
}
/**
* Defines scaling mode. Only applies to location-indicator type layers.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class ModelScaleModeValue(public val value: Value) {
/**
* Construct the [ModelScaleModeValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: ModelScaleModeValue = ModelScaleModeValue(Value.valueOf("ModelScaleModeValue.INITIAL"))
/**
* Default value for [ModelScaleModeValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: ModelScaleModeValue = ModelScaleModeValue(Value.nullValue())
/**
* Model is scaled so that it's always the same size relative to other map features. The property model-scale specifies how many meters each unit in the model file should cover.
*/
@JvmField
public val MAP: ModelScaleModeValue = ModelScaleModeValue(Value("map"))
/**
* Model is scaled so that it's always the same size on the screen. The property model-scale specifies how many pixels each unit in model file should cover.
*/
@JvmField
public val VIEWPORT: ModelScaleModeValue = ModelScaleModeValue(Value("viewport"))
}
}
/**
* Defines rendering behavior of model in respect to other 3D scene objects.
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class ModelTypeValue(public val value: Value) {
/**
* Construct the [ModelTypeValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: ModelTypeValue = ModelTypeValue(Value.valueOf("ModelTypeValue.INITIAL"))
/**
* Default value for [ModelTypeValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: ModelTypeValue = ModelTypeValue(Value.nullValue())
/**
* Integrated to 3D scene, using depth testing, along with terrain, fill-extrusions and custom layer.
*/
@JvmField
public val COMMON_3D: ModelTypeValue = ModelTypeValue(Value("common-3d"))
/**
* Displayed over other 3D content, occluded by terrain.
*/
@JvmField
public val LOCATION_INDICATOR: ModelTypeValue = ModelTypeValue(Value("location-indicator"))
}
}
/**
* The type of the sky
*
* @param value the property wrapped in [Value] to be used with native renderer.
*/
@Immutable
@MapboxExperimental
public data class SkyTypeValue(public val value: Value) {
/**
* Construct the [SkyTypeValue] with [Mapbox Expression](https://docs.mapbox.com/style-spec/reference/expressions/).
*/
public constructor(expression: Expression) : this(expression as Value)
/**
* True if the this value is not [INITIAL]
*/
internal val notInitial: Boolean
get() = this !== INITIAL
/**
* Public companion object.
*/
public companion object {
/**
* Use this constant to signal that no property should be set to the Maps engine.
* This is needed because sending nullValue resets the value of the property to the default one
* defined by the Maps engine, which results in overriding the value from the loaded style.
* Moreover, we set a custom String to differentiate it from [DEFAULT], otherwise things
* like [kotlinx.coroutines.flow.Flow] or [androidx.compose.runtime.MutableState] won't be able
* to differentiate them because they use [equals].
*/
@JvmField
internal val INITIAL: SkyTypeValue = SkyTypeValue(Value.valueOf("SkyTypeValue.INITIAL"))
/**
* Default value for [SkyTypeValue], setting default will result in restoring the property value defined in the style.
*/
@JvmField
public val DEFAULT: SkyTypeValue = SkyTypeValue(Value.nullValue())
/**
* Renders the sky with a gradient that can be configured with {@link SKY_GRADIENT_RADIUS} and {@link SKY_GRADIENT}.
*/
@JvmField
public val GRADIENT: SkyTypeValue = SkyTypeValue(Value("gradient"))
/**
* Renders the sky with a simulated atmospheric scattering algorithm, the sun direction can be attached to the light position or explicitly set through {@link SKY_ATMOSPHERE_SUN}.
*/
@JvmField
public val ATMOSPHERE: SkyTypeValue = SkyTypeValue(Value("atmosphere"))
}
}
// End of generated file. | 225 | null | 127 | 454 | b5802714c91775dc9175eb1b26817dbccce4b16f | 68,733 | mapbox-maps-android | Apache License 2.0 |
js/js.translator/testData/box/expression/misc/intRange.kt | JakeWharton | 99,388,807 | false | null | // EXPECTED_REACHABLE_NODES: 1121
package foo
class RangeIterator(val start: Int, var count: Int, val reversed: Boolean) {
var i = start
operator fun next(): Int {
--count
if (reversed) {
i--
return i + 1
}
else {
i++
return i - 1
}
}
operator fun hasNext() = (count > 0);
}
class NumberRange(val start: Int, val size: Int, val reversed: Boolean) {
val end: Int
get() = if (reversed) start - size + 1 else start + size - 1
fun contains(number: Int): Boolean {
if (reversed) {
return (number <= start) && (number > start - size);
}
else {
return (number >= start) && (number < start + size);
}
}
operator fun iterator() = RangeIterator(start, size, reversed);
}
fun box(): String {
return if (testRange() && testReversedRange()) "OK" else "fail"
}
fun testRange(): Boolean {
val oneToFive = NumberRange(1, 4, false);
if (oneToFive.contains(5)) return false;
if (oneToFive.contains(0)) return false;
if (oneToFive.contains(-100)) return false;
if (oneToFive.contains(10)) return false;
if (!oneToFive.contains(1)) return false;
if (!oneToFive.contains(2)) return false;
if (!oneToFive.contains(3)) return false;
if (!oneToFive.contains(4)) return false;
if (!(oneToFive.start == 1)) return false;
if (!(oneToFive.size == 4)) return false;
if (!(oneToFive.end == 4)) return false;
var sum = 0;
for (i in oneToFive) {
sum += i;
}
if (sum != 10) return false;
return true;
}
fun testReversedRange(): Boolean {
val tenToFive = NumberRange(10, 5, true);
if (tenToFive.contains(5)) return false;
if (tenToFive.contains(11)) return false;
if (tenToFive.contains(-100)) return false;
if (tenToFive.contains(1000)) return false;
if (!tenToFive.contains(6)) return false;
if (!tenToFive.contains(7)) return false;
if (!tenToFive.contains(8)) return false;
if (!tenToFive.contains(9)) return false;
if (!tenToFive.contains(10)) return false;
if (!(tenToFive.start == 10)) return false;
if (!(tenToFive.size == 5)) return false;
if (!(tenToFive.end == 6)) return false;
var sum = 0;
for (i in tenToFive) {
sum += i;
}
if (sum != 40) {
return false;
}
return true;
}
| 184 | null | 5691 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 2,432 | kotlin | Apache License 2.0 |
apps/toi-livshendelse/src/test/kotlin/HåndterPersonhendelserTest.kt | navikt | 379,186,604 | false | {"Kotlin": 464916, "Dockerfile": 1380} | import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import no.nav.arbeidsgiver.toi.livshendelser.AccessTokenClient
import no.nav.arbeidsgiver.toi.livshendelser.PdlKlient
import no.nav.arbeidsgiver.toi.livshendelser.PersonhendelseService
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import no.nav.person.pdl.leesah.Endringstype
import no.nav.person.pdl.leesah.Personhendelse
import no.nav.person.pdl.leesah.adressebeskyttelse.Adressebeskyttelse
import no.nav.person.pdl.leesah.adressebeskyttelse.Gradering
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.*
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
class HåndterPersonhendelserTest {
companion object {
private val wiremock = WireMockServer(8083).also(WireMockServer::start)
private val mockOAuth2Server = WireMockServer(18301).also(WireMockServer::start)
val testRapid = TestRapid()
val envs = mapOf(
"AZURE_OPENID_CONFIG_TOKEN_ENDPOINT" to "http://localhost:18301/isso-idtoken/token",
"AZURE_APP_CLIENT_SECRET" to "test1",
"AZURE_APP_CLIENT_ID" to "test2",
"PDL_SCOPE" to "test3",
)
val personhendelseService =
PersonhendelseService(testRapid, PdlKlient("http://localhost:8083/graphql", AccessTokenClient(envs)))
@AfterAll
fun shutdown() {
mockOAuth2Server.stop()
wiremock.stop()
}
}
@BeforeEach
fun setUp() {
testRapid.reset()
}
@AfterEach
fun tearDown() {
wiremock.resetAll()
}
@Test
fun `sjekk at gradering er sendt for en hendelse med en ident`() {
stubOAtuh()
stubPdl()
val personHendelse = personhendelse()
personhendelseService.håndter(
listOf(personHendelse)
)
val inspektør = testRapid.inspektør
assertThat(inspektør.size).isEqualTo(1)
val melding = inspektør.message(0)
assertThat(melding["@event_name"].asText()).isEqualTo("adressebeskyttelse")
assertThat(melding["aktørId"].asText()).isEqualTo("987654321")
assertThat(melding["gradering"].asText()).isEqualTo(Gradering.STRENGT_FORTROLIG.toString())
}
@Test
fun `sjekk at gradering sendes per ident for en person med flere aktørider`() {
stubOAtuh()
stubPdl(
identSvar = """
{
"ident" : "987654321"
},
{
"ident" : "987654322"
}
""".trimIndent()
)
val personHendelse = personhendelse()
personhendelseService.håndter(
listOf(personHendelse)
)
val inspektør = testRapid.inspektør
assertThat(inspektør.size).isEqualTo(2)
val meldinger = listOf(0, 1).map(inspektør::message)
val keys = listOf(0, 1).map(inspektør::key)
assertThat(keys).containsExactlyInAnyOrder("987654321", "987654322")
meldinger.map { assertThat(it["@event_name"].asText()).isEqualTo("adressebeskyttelse") }
meldinger.map { assertThat(it["gradering"].asText()).isEqualTo(Gradering.STRENGT_FORTROLIG.toString()) }
assertThat(meldinger.map { it["aktørId"].asText() }).containsExactlyInAnyOrder("987654321", "987654322")
}
@Test
fun `sjekk at gradering håndterer feil`() {
stubOAtuh()
stubPdlFeil()
val personHendelse = personhendelse()
assertThat(assertThrows<RuntimeException> {
personhendelseService.håndter(
listOf(personHendelse)
)
}).hasMessage("Noe feil skjedde ved henting av diskresjonskode: ")
val inspektør = testRapid.inspektør
assertThat(inspektør.size).isEqualTo(0)
}
private fun stubPdl(
identSvar: String = """
{
"ident" : "987654321"
}
""".trimIndent()
) {
val pesostegn = "$"
wiremock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.withHeader("Authorization", WireMock.equalTo("Bearer mockedAccessToken"))
.withRequestBody(
WireMock.equalToJson(
"""
{
"query": "query( ${pesostegn}ident: ID!) { hentPerson(ident: ${pesostegn}ident) { adressebeskyttelse(historikk: false) { gradering }} hentIdenter(ident: ${pesostegn}ident, grupper: [AKTORID], historikk: false) { identer { ident }} }",
"variables":{"ident":"12312312312"}
}
""".trimIndent()
)
)
.willReturn(
WireMock.aResponse()
.withStatus(200)
.withBody(
"""
{
"data": {
"hentPerson": {
"adressebeskyttelse": [
{
"gradering" : "STRENGT_FORTROLIG"
}
]
},
"hentIdenter": {
"identer": [
$identSvar
]
}
}
}
""".trimIndent()
)
)
)
}
private fun stubPdlFeil() {
val pesostegn = "$"
wiremock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.withHeader("Authorization", WireMock.equalTo("Bearer mockedAccessToken"))
.willReturn(
WireMock.aResponse()
.withStatus(200)
.withBody(
"""
{
"errors": [ "feil1", "feil2" ]
}
""".trimIndent()
)
)
)
}
private fun stubOAtuh() {
val mockedAccessToken = """
{
"access_token": "mockedAccessToken",
"expires_in": 36000
}
""".trimIndent()
mockOAuth2Server.stubFor(
WireMock.post(WireMock.urlEqualTo("/isso-idtoken/token")).willReturn(
WireMock.aResponse()
.withStatus(200)
.withBody(mockedAccessToken)
)
)
}
}
fun personhendelse(
hendelseId: String = "id1",
personidenter: List<String> = listOf("12312312312"),
master: String = "testMaster",
opprettet: Instant = LocalDateTime.of(2023, 1, 1, 0, 0).toInstant(ZoneOffset.UTC),
opplysningstype: String = "ADRESSEBESKYTTELSE_V1",
endringstype: Endringstype = Endringstype.OPPRETTET,
tidligereHendelseId: String = "123",
adressebeskyttelse: Adressebeskyttelse = Adressebeskyttelse(Gradering.STRENGT_FORTROLIG)
) = Personhendelse(
hendelseId,
personidenter,
master,
opprettet,
opplysningstype,
endringstype,
tidligereHendelseId,
adressebeskyttelse
)
| 2 | Kotlin | 1 | 0 | d467c77adaf719550efaa23d804211a190ae0e73 | 7,598 | toi-rapids-and-rivers | MIT License |
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/LambdaHandlerIndex.kt | mithilarao | 176,211,165 | false | null | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.lambda
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.DataIndexer
import com.intellij.util.indexing.DefaultFileTypeSpecificInputFilter
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileContent
import com.intellij.util.indexing.ID
import com.intellij.util.indexing.ScalarIndexExtension
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
class LambdaHandlerIndex : ScalarIndexExtension<String>() {
private val fileFilter by lazy {
val supportedFiles = LambdaHandlerResolver.supportedLanguages
.mapNotNull { it.associatedFileType }
.toTypedArray()
object : DefaultFileTypeSpecificInputFilter(*supportedFiles) {
override fun acceptInput(file: VirtualFile): Boolean = file.isInLocalFileSystem
}
}
override fun getName() = NAME
override fun getVersion() = 1
override fun dependsOnFileContent() = true
override fun getIndexer(): DataIndexer<String, Void?, FileContent> = DataIndexer { fileContent ->
val handlerIdentifier = fileContent.psiFile.language.runtimeGroup?.let { runtimeGroup ->
LambdaHandlerResolver.getInstance(runtimeGroup)
} ?: return@DataIndexer emptyMap<String, Void?>()
val handlers = mutableMapOf<String, Void?>()
fileContent.psiFile.acceptLeafNodes(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement?) {
super.visitElement(element)
element?.run {
val handler = handlerIdentifier.determineHandler(this) ?: return@run
handlers[handler] = null
}
}
})
handlers
}
override fun getInputFilter(): FileBasedIndex.InputFilter = fileFilter
override fun getKeyDescriptor(): KeyDescriptor<String> = EnumeratorStringDescriptor.INSTANCE
companion object {
private val NAME: ID<String, Void> = ID.create("LambdaHandlerIndex")
/**
* Passes the [visitor] to the leaf-nodes in this [PsiElement]'s hierarchy.
*
* A leaf-node is a node with no children.
*/
private fun PsiElement.acceptLeafNodes(visitor: PsiElementVisitor) {
when {
children.isEmpty() -> accept(visitor)
else -> children.forEach { it.acceptLeafNodes(visitor) }
}
}
fun listHandlers(project: Project): Collection<String> {
val index = FileBasedIndex.getInstance()
return index.getAllKeys(LambdaHandlerIndex.NAME, project)
.filter {
// Filters out out-of-date data
index.getValues(LambdaHandlerIndex.NAME, it, GlobalSearchScope.projectScope(project)).isNotEmpty()
}
}
}
} | 1 | null | 1 | 1 | 961d5ab9747161f7ed9587b1db7cde63c51c395a | 3,228 | jsinbucket | Apache License 2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.