repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
saffih/ElmDroid | app/src/main/java/elmdroid/elmdroid/example5/detail/itemDetailElm.kt | 1 | 8445 | package elmdroid.elmdroid.example5.detail
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import elmdroid.elmdroid.R
import elmdroid.elmdroid.example5.ItemDetailActivity
import elmdroid.elmdroid.example5.ItemDetailFragment
import kotlinx.android.synthetic.main.activity_item_detail.*
import saffih.elmdroid.ElmBase
/**
* Copyright Joseph Hartal (Saffi)
* Created by saffi on 28/04/17.
*/
enum class ItemOption(val id: Int) {
settings(R.id.action_settings);
companion object {
val map by lazy { values().associate { it.id to it } }
fun byId(id: Int) = map.get(id)
}
}
sealed class Msg {
class Init : Msg()
sealed class Fab : Msg(){
class Clicked(val v: MFabClicked) : Fab()
}
sealed class Action:Msg(){
class DoSomething:Action()
class UIToast(val txt: String, val duration: Int = Toast.LENGTH_SHORT) : Action()
}
sealed class Option : Msg() {
// class Navigation(val item: MNavOption) : Option()
class ItemSelected(val item: MenuItem) : Option()
// class Drawer(val item: DrawerOption = DrawerOption.opened) : Option()
}
}
fun Msg.Action.UIToast.show(me: Context) {
val toast = Toast.makeText(me, txt, duration)
toast.show()
}
/**
* Model representing the state of the system
* All Model types are Prefixed with M
*/
data class Model(val activity: MActivity = MActivity(), val hadSavedState: Boolean = false)
data class MActivity (val toolbar : MToolbar= MToolbar(),
val fab: MFab = MFab(),
val options: MOptions = MOptions()
)
data class MToolbar (val show : Boolean = false)
data class MFab (val clicked: MFabClicked?=null,
val snackbar:MSnackbar= MSnackbar())
data class MFabClicked(val clicked : View)
data class MSnackbar (val txt: String="Snack bar message",
val action: MSnackbarAction= MSnackbarAction())
data class MSnackbarAction (val name : String="Action name",
val msg:Msg.Action = Msg.Action.DoSomething())
data class MOptions(val itemOption: MItemOption = MItemOption())
data class MItemOption(val handled: Boolean = true, val item: ItemOption? = null)
class ItemDetailElm(override val me: ItemDetailActivity) : ElmBase<Model, Msg>(me) {
var savedInstanceState: Bundle? = null
fun onCreate(savedInstanceState: Bundle?) {
super.onCreate()
this.savedInstanceState = savedInstanceState
}
override fun init():Model {
dispatch(Msg.Init())
return Model().copy(hadSavedState = (savedInstanceState != null))
}
override fun update(msg: Msg, model: Model):Model {
return when (msg) {
is Msg.Init -> {
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (!model.hadSavedState) { // create initial one
// Create the detail fragment and add it to the activity
// using a fragment transaction.
val arguments = Bundle()
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
me.intent.getStringExtra(ItemDetailFragment.ARG_ITEM_ID))
val fragment = ItemDetailFragment()
fragment.arguments = arguments
me.supportFragmentManager.beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit()
}
model
}
is Msg.Fab -> {
val activity = update(msg, model.activity)
model.copy(activity = activity)
}
is Msg.Action -> {
val activity = update(msg, model.activity)
model.copy(activity = activity)
}
is Msg.Option -> {
val activity = update(msg, model.activity)
model.copy(activity = activity)
}
}
}
private fun update(msg: Msg.Fab, model: MActivity):MActivity {
return when (msg) {
is Msg.Fab.Clicked -> {
val mFab = update(msg, model.fab)
model.copy(fab = mFab)
}
}
}
private fun update(msg: Msg.Action, model: MActivity):MActivity {
return when (msg) {
is Msg.Action.DoSomething -> {
model
}
is Msg.Action.UIToast -> {
msg.show(me)
model
}
}
}
private fun update(msg: Msg.Option, model: MActivity):MActivity {
return when (msg) {
is Msg.Option -> {
val m = update(msg, model.options)
model.copy(options = m)
}
}
}
fun update(msg: Msg.Option, model: MOptions):MOptions {
// return myModel)
return when (msg) {
is Msg.Option.ItemSelected -> {
val m = update(msg, model.itemOption)
model.copy(itemOption = m)
}
}
}
private fun update(msg: Msg.Option.ItemSelected, model: MItemOption):MItemOption {
// return myModel)
val itemOption = ItemOption.byId(msg.item.itemId)
return if (itemOption == null) MItemOption(handled = false)
else when (itemOption) {
ItemOption.settings -> {
dispatch(Msg.Action.UIToast("Setting was clicked"))
MItemOption(item = itemOption)}
}
}
private fun update(msg: Msg.Fab, model: MFab):MFab {
return when (msg) {
is Msg.Fab.Clicked -> {
model.copy(clicked = msg.v)
}
}
}
override fun view(model: Model, pre: Model?) {
val setup = {}
checkView(setup, model, pre) {
view(model.activity, pre?.activity)
}
}
private fun view(model: MActivity, pre: MActivity?) {
val setup = {
me.setContentView(R.layout.activity_item_detail)
// Show the Up button in the action bar.
val actionBar = me.supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
Unit
}
checkView(setup, model, pre) {
view(model.toolbar, pre?.toolbar)
view(model.fab, pre?.fab)
}
}
private fun view(model: MFab, pre: MFab?) {
val setup = {
val fab = me.fab
fab.setOnClickListener { view -> dispatch(Msg.Fab.Clicked(MFabClicked(view)))}
}
checkView(setup, model, pre){
view(model.snackbar, pre?.snackbar)
view(model.clicked, pre?.clicked)
}
}
private fun view(model: MFabClicked?, pre: MFabClicked?) {
val setup = {
}
checkView(setup, model, pre) {
if (model!=null){
Snackbar.make(model.clicked, "exit ?", Snackbar.LENGTH_LONG)
.setAction("Exit", { me.finish() }).show()
}
}
}
private fun view(model: MSnackbar, pre: MSnackbar?) {
val setup = {
}
checkView(setup, model, pre) {
// view(myModel.x, pre?.x)
}
}
private fun view(model: MToolbar, pre: MToolbar?) {
val setup = {
val toolbar = me.detail_toolbar
me.setSupportActionBar(toolbar)
}
checkView(setup, model, pre)
{
// view(myModel., pre.)
}
}
// val setup = {
// }
// checkView(setup, myModel, pre) {
// view(myModel.x, pre?.x)
// }
//
// }
// val setup = {
// }
// checkView(setup, myModel, pre){
//// view(myModel., pre.)
// }
}
| apache-2.0 | 7e8fd16ee89a84b475f82f2c8bf1f444 | 30.047794 | 91 | 0.552398 | 4.440063 | false | false | false | false |
mdanielwork/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/trace/dsl/impl/java/JavaTypes.kt | 11 | 4286 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.trace.dsl.impl.java
import com.intellij.debugger.streams.trace.dsl.Types
import com.intellij.debugger.streams.trace.impl.handler.type.*
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiType
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.TypeConversionUtil
import one.util.streamex.StreamEx
import org.jetbrains.annotations.Contract
/**
* @author Vitaliy.Bibaev
*/
object JavaTypes : Types {
override val ANY: GenericType = ClassTypeImpl("java.lang.Object", "new java.lang.Object()")
override val INT: GenericType = GenericTypeImpl("int", "java.lang.Integer", "0")
override val BOOLEAN: GenericType = GenericTypeImpl("boolean", "java.lang.Boolean", "false")
override val DOUBLE: GenericType = GenericTypeImpl("double", "java.lang.Double", "0.")
override val EXCEPTION: GenericType = ClassTypeImpl("java.lang.Throwable")
override val VOID: GenericType = GenericTypeImpl("void", "java.lang.Void", "null")
override val TIME: GenericType = ClassTypeImpl("java.util.concurrent.atomic.AtomicInteger",
"new java.util.concurrent.atomic.AtomicInteger()")
override val STRING: GenericType = ClassTypeImpl("java.lang.String", "\"\"")
override val LONG: GenericType = GenericTypeImpl("long", "java.lang.Long", "0L")
override fun array(elementType: GenericType): ArrayType =
ArrayTypeImpl(elementType, { "$it[]" }, { "new ${elementType.variableTypeName}[$it]" })
override fun map(keyType: GenericType, valueType: GenericType): MapType =
MapTypeImpl(keyType, valueType, { keys, values -> "java.util.Map<$keys, $values>" }, "new java.util.HashMap<>()")
override fun linkedMap(keyType: GenericType, valueType: GenericType): MapType =
MapTypeImpl(keyType, valueType, { keys, values -> "java.util.Map<$keys, $values>" }, "new java.util.LinkedHashMap<>()")
override fun list(elementsType: GenericType): ListType =
ListTypeImpl(elementsType, { "java.util.List<$it>" }, "new java.util.ArrayList<>()")
override fun nullable(typeSelector: Types.() -> GenericType): GenericType = this.typeSelector()
private val optional: GenericType = ClassTypeImpl("java.util.Optional")
private val optionalInt: GenericType = ClassTypeImpl("java.util.OptionalInt")
private val optionalLong: GenericType = ClassTypeImpl("java.util.OptionalLong")
private val optionalDouble: GenericType = ClassTypeImpl("java.util.OptionalDouble")
private val OPTIONAL_TYPES = StreamEx.of(optional, optionalInt, optionalLong, optionalDouble).toSet()
fun fromStreamPsiType(streamPsiType: PsiType): GenericType {
return when {
InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM) -> INT
InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM) -> LONG
InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM) -> DOUBLE
PsiType.VOID == streamPsiType -> VOID
else -> ANY
}
}
fun fromPsiClass(psiClass: PsiClass): GenericType {
return when {
InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM) -> INT
InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM) -> LONG
InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM) -> DOUBLE
else -> ANY
}
}
fun fromPsiType(type: PsiType): GenericType {
return when (type) {
PsiType.VOID -> VOID
PsiType.INT -> INT
PsiType.DOUBLE -> DOUBLE
PsiType.LONG -> LONG
PsiType.BOOLEAN -> BOOLEAN
else -> ClassTypeImpl(TypeConversionUtil.erasure(type).canonicalText)
}
}
@Contract(pure = true)
private fun isOptional(type: GenericType): Boolean {
return OPTIONAL_TYPES.contains(type)
}
fun unwrapOptional(type: GenericType): GenericType {
assert(isOptional(type))
return when (type) {
optionalInt -> INT
optionalLong -> LONG
optionalDouble -> DOUBLE
else -> ANY
}
}
} | apache-2.0 | 5b1b2062a56938c3d45f92cbd8bd77c0 | 42.744898 | 140 | 0.725385 | 4.311871 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/utils/StyledResources.kt | 1 | 2823 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.utils
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import androidx.annotation.AttrRes
import org.isoron.uhabits.R
class StyledResources(private val context: Context) {
fun getBoolean(@AttrRes attrId: Int): Boolean {
val ta = getTypedArray(attrId)
val bool = ta.getBoolean(0, false)
ta.recycle()
return bool
}
fun getDimension(@AttrRes attrId: Int): Int {
val ta = getTypedArray(attrId)
val dim = ta.getDimensionPixelSize(0, 0)
ta.recycle()
return dim
}
fun getColor(@AttrRes attrId: Int): Int {
val ta = getTypedArray(attrId)
val color = ta.getColor(0, 0)
ta.recycle()
return color
}
fun getDrawable(@AttrRes attrId: Int): Drawable? {
val ta = getTypedArray(attrId)
val drawable = ta.getDrawable(0)
ta.recycle()
return drawable
}
fun getFloat(@AttrRes attrId: Int): Float {
val ta = getTypedArray(attrId)
val f = ta.getFloat(0, 0f)
ta.recycle()
return f
}
fun getPalette(): IntArray {
val resourceId = getResource(R.attr.palette)
if (resourceId < 0) throw RuntimeException("palette resource not found")
return context.resources.getIntArray(resourceId)
}
fun getResource(@AttrRes attrId: Int): Int {
val ta = getTypedArray(attrId)
val resourceId = ta.getResourceId(0, -1)
ta.recycle()
return resourceId
}
private fun getTypedArray(@AttrRes attrId: Int): TypedArray {
val attrs = intArrayOf(attrId)
if (fixedTheme != null) {
return context.theme.obtainStyledAttributes(fixedTheme!!, attrs)
}
return context.obtainStyledAttributes(attrs)
}
companion object {
private var fixedTheme: Int? = null
@JvmStatic
fun setFixedTheme(theme: Int?) {
fixedTheme = theme
}
}
}
| gpl-3.0 | 1eb959324fd6bca8f9c67b27c16dfb2b | 29.344086 | 80 | 0.654855 | 4.288754 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/extensionComponentFun.0.kt | 8 | 453 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtFunction
// OPTIONS: usages
interface X
class Y : X
open class G<T> {
fun get(): T = TODO()
}
abstract class Z1 : List<X>
abstract class Z2 : G<X>()
operator fun X.component1(): Int = 0
operator fun X.<caret>component2(): Int = 1
fun f() = Y()
fun test() {
val (x, y) = f()
}
fun Y.ext() {
val (a, b) = this
}
fun g(z1: Z1, z2: Z2) {
val (x1, y1) = z1[0]
val (x2, y2) = z2.get()
}
| apache-2.0 | 2c8c09c6bd06590ea914c2de315800dc | 13.612903 | 51 | 0.562914 | 2.384211 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/action/Action_List.kt | 1 | 7659 | package jp.juggler.subwaytooter.action
import android.app.Dialog
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.actmain.addColumn
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.MisskeyAntenna
import jp.juggler.subwaytooter.api.entity.TimelineItem
import jp.juggler.subwaytooter.api.entity.TootList
import jp.juggler.subwaytooter.api.entity.parseItem
import jp.juggler.subwaytooter.api.runApiTask
import jp.juggler.subwaytooter.column.ColumnType
import jp.juggler.subwaytooter.column.onListListUpdated
import jp.juggler.subwaytooter.column.onListNameUpdated
import jp.juggler.subwaytooter.dialog.ActionsDialog
import jp.juggler.subwaytooter.dialog.DlgConfirm.confirm
import jp.juggler.subwaytooter.dialog.DlgTextInput
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.util.*
import okhttp3.Request
fun ActMain.clickListTl(pos: Int, accessInfo: SavedAccount, item: TimelineItem?) {
when (item) {
is TootList -> addColumn(pos, accessInfo, ColumnType.LIST_TL, item.id)
is MisskeyAntenna -> addColumn(pos, accessInfo, ColumnType.MISSKEY_ANTENNA_TL, item.id)
}
}
fun ActMain.clickListMoreButton(pos: Int, accessInfo: SavedAccount, item: TimelineItem?) {
when (item) {
is TootList -> {
ActionsDialog()
.addAction(getString(R.string.list_timeline)) {
addColumn(pos, accessInfo, ColumnType.LIST_TL, item.id)
}
.addAction(getString(R.string.list_member)) {
addColumn(
false,
pos,
accessInfo,
ColumnType.LIST_MEMBER,
item.id
)
}
.addAction(getString(R.string.rename)) {
listRename(accessInfo, item)
}
.addAction(getString(R.string.delete)) {
listDelete(accessInfo, item)
}
.show(this, item.title)
}
is MisskeyAntenna -> {
// XXX
}
}
}
fun interface ListOnCreatedCallback {
fun onCreated(list: TootList)
}
// リストを作成する
fun ActMain.listCreate(
accessInfo: SavedAccount,
title: String,
callback: ListOnCreatedCallback?,
) {
launchMain {
var resultList: TootList? = null
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/users/lists/create",
accessInfo.putMisskeyApiToken().apply {
put("title", title)
put("name", title)
}
.toPostRequestBuilder()
)
} else {
client.request(
"/api/v1/lists",
jsonObject {
put("title", title)
}
.toPostRequestBuilder()
)
}?.also { result ->
client.publishApiProgress(getString(R.string.parsing_response))
resultList = parseItem(
::TootList,
TootParser(this, accessInfo),
result.jsonObject
)
}
}?.let { result ->
when (val list = resultList) {
null -> showToast(false, result.error)
else -> {
for (column in appState.columnList) {
column.onListListUpdated(accessInfo)
}
showToast(false, R.string.list_created)
callback?.onCreated(list)
}
}
}
}
}
// リストを削除する
fun ActMain.listDelete(
accessInfo: SavedAccount,
list: TootList,
bConfirmed: Boolean = false,
) {
launchAndShowError {
if (!bConfirmed) {
confirm(R.string.list_delete_confirm, list.title)
}
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/users/lists/delete",
accessInfo.putMisskeyApiToken().apply {
put("listId", list.id)
}
.toPostRequestBuilder()
)
// 204 no content
} else {
client.request(
"/api/v1/lists/${list.id}",
Request.Builder().delete()
)
}
}?.let { result ->
when (result.jsonObject) {
null -> showToast(false, result.error)
else -> {
for (column in appState.columnList) {
column.onListListUpdated(accessInfo)
}
showToast(false, R.string.delete_succeeded)
}
}
}
}
}
fun ActMain.listRename(
accessInfo: SavedAccount,
item: TootList,
) {
DlgTextInput.show(
this,
getString(R.string.rename),
item.title,
callback = object : DlgTextInput.Callback {
override fun onEmptyError() {
showToast(false, R.string.list_name_empty)
}
override fun onOK(dialog: Dialog, text: String) {
launchMain {
var resultList: TootList? = null
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/users/lists/update",
accessInfo.putMisskeyApiToken().apply {
put("listId", item.id)
put("title", text)
}
.toPostRequestBuilder()
)
} else {
client.request(
"/api/v1/lists/${item.id}",
jsonObject {
put("title", text)
}
.toPutRequestBuilder()
)
}?.also { result ->
client.publishApiProgress(getString(R.string.parsing_response))
resultList = parseItem(
::TootList,
TootParser(this, accessInfo),
result.jsonObject
)
}
}?.let { result ->
when (val list = resultList) {
null -> showToast(false, result.error)
else -> {
for (column in appState.columnList) {
column.onListNameUpdated(accessInfo, list)
}
dialog.dismissSafe()
}
}
}
}
}
}
)
}
| apache-2.0 | 81910d3934a85cafa57f033288f6d3c7 | 33.474419 | 95 | 0.450374 | 5.352281 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/KlaxonJson.kt | 1 | 1829 | package com.beust.klaxon
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashMap
/**
* The class used to define the DSL that generates JSON documents. All the functions defined in this class
* can be used inside a `json { ... }` call.
*/
class KlaxonJson {
fun array(vararg args: Any?) : JsonArray<Any?> = JsonArray(args.map { convert(it) })
fun array(args: List<Any?>) : JsonArray<Any?> = JsonArray(args.map { convert(it) })
// we need this as now JsonArray<T> is List<T>
fun <T> array(subArray : JsonArray<T>) : JsonArray<JsonArray<T>> = JsonArray(listOf(subArray))
fun obj(args: Iterable<Pair<String, *>>): JsonObject =
JsonObject(args.toMap(LinkedHashMap()).mapValues { convert(it.value) })
fun obj(vararg args: Pair<String, *>): JsonObject =
obj(args.toList())
fun obj(key: String, init: KlaxonJson.() -> Unit): JsonObject {
stackMap.push(LinkedHashMap<String, Any?>())
theKlaxonJson.init()
val map = stackMap.pop()
val newMap = if (stackMap.isEmpty()) HashMap() else stackMap.peek()
newMap[key] = JsonObject(map.mapValues { convert(it.value) })
return JsonObject(newMap)
}
private val stackMap = Stack<HashMap<String, Any?>>()
fun put(key: String, value: Any?) {
stackMap.peek()[key] = convert(value)
}
companion object {
internal val theKlaxonJson = KlaxonJson()
private fun convert(value: Any?): Any? = when (value) {
is Float -> value.toDouble()
is Short -> value.toInt()
is Byte -> value.toInt()
null -> null
else -> value
}
}
}
/**
* Main entry point.
*/
fun <T> json(init : KlaxonJson.() -> T) : T {
return KlaxonJson.theKlaxonJson.init()
}
| apache-2.0 | 6c14c6b32536241ccce1d938a17d5f61 | 29.483333 | 106 | 0.61509 | 3.85865 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/core/model/DiagramDM.kt | 2 | 1843 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.core.model
import org.apache.causeway.client.kroviz.to.DomainType
import org.apache.causeway.client.kroviz.to.Property
import org.apache.causeway.client.kroviz.to.TransferObject
class DiagramDM(override val title: String) : BaseDisplayModel() {
val classes = mutableSetOf<DomainType>()
val properties = mutableSetOf<Property>()
var numberOfClasses = -1
private var numberOfProperties = 0
fun incNumberOfProperties(inc: Int) {
numberOfProperties += inc
}
fun decNumberOfClasses() {
numberOfClasses--
}
override fun canBeDisplayed(): Boolean {
if (isRendered) return false
return (numberOfClasses == classes.size)
//TODO && numberOfProperties == properties.size
}
override fun addData(obj: TransferObject) {
when (obj) {
is DomainType -> classes.add(obj)
is Property -> properties.add(obj)
else -> {
}
}
}
}
| apache-2.0 | ff21ae9f29009b9b5d18ea6408c5ab44 | 31.910714 | 66 | 0.687466 | 4.296037 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClanMate.kt | 1 | 3527 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import org.objectweb.asm.Type.BOOLEAN_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.UniqueMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
@DependsOn(Buddy::class)
class ClanMate : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<Buddy>() }
.and { it.instanceFields.count { it.type == BOOLEAN_TYPE } == 0 }
@DependsOn(TriBool::class)
class isFriend0 : OrderMapper.InConstructor.Field(ClanMate::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == type<TriBool>() }
}
@DependsOn(TriBool::class)
class isIgnored0 : OrderMapper.InConstructor.Field(ClanMate::class, 1, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == type<TriBool>() }
}
@MethodParameters()
@DependsOn(isFriend0::class)
class isFriend : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<isFriend0>().id } }
}
@MethodParameters()
@DependsOn(isIgnored0::class)
class isIgnored : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<isIgnored0>().id } }
}
@MethodParameters()
@DependsOn(isFriend::class)
class fillIsFriend : UniqueMapper.InMethod.Method(isFriend::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@MethodParameters()
@DependsOn(isIgnored::class)
class fillIsIgnored : UniqueMapper.InMethod.Method(isIgnored::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@MethodParameters()
@DependsOn(isFriend0::class, Client.TriBool_unknown::class)
class clearIsFriend : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == Type.VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.opcode == PUTFIELD && it.fieldId == field<isFriend0>().id } }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<Client.TriBool_unknown>().id } }
}
@MethodParameters()
@DependsOn(isIgnored0::class, Client.TriBool_unknown::class)
class clearIsIgnored : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == Type.VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.opcode == PUTFIELD && it.fieldId == field<isIgnored0>().id } }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<Client.TriBool_unknown>().id } }
}
} | mit | 71f8dc6ef8a9e11b5974bd15bc30e43a | 47.328767 | 123 | 0.697193 | 4.072748 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt | 1 | 2636 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class IndentRawStringIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("indent.raw.string")
) {
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
if (!element.text.startsWith("\"\"\"")) return false
if (element.parents.any { it is KtAnnotationEntry || (it as? KtProperty)?.hasModifier(KtTokens.CONST_KEYWORD) == true }) return false
if (element.getQualifiedExpressionForReceiver() != null) return false
val entries = element.entries
if (entries.size <= 1 || entries.any { it.text.startsWith(" ") || it.text.startsWith("\t") }) return false
return true
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val file = element.containingKtFile
val project = file.project
val indentOptions = CodeStyle.getIndentOptions(file)
val parentIndent = CodeStyleManager.getInstance(project).getLineIndent(file, element.parent.startOffset) ?: ""
val indent = if (indentOptions.USE_TAB_CHARACTER) "$parentIndent\t" else "$parentIndent${" ".repeat(indentOptions.INDENT_SIZE)}"
val newString = buildString {
val maxIndex = element.entries.size - 1
element.entries.forEachIndexed { index, entry ->
if (index == 0) append("\n$indent")
append(entry.text)
if (entry.text == "\n") append(indent)
if (index == maxIndex) append("\n$indent")
}
}
element.replace(KtPsiFactory(project).createExpression("\"\"\"$newString\"\"\".trimIndent()"))
}
} | apache-2.0 | c4577eba69cbddc0a209cf65a7ccc63a | 50.705882 | 158 | 0.727997 | 4.792727 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/SdkIndexableFilesIteratorImpl.kt | 1 | 3876 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.indexing.roots.kind.IndexableSetOrigin
import com.intellij.util.indexing.roots.origin.SdkOriginImpl
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
class SdkIndexableFilesIteratorImpl private constructor(private val sdk: Sdk,
private val rootsToIndex: Collection<VirtualFile>) : IndexableFilesIterator {
override fun getDebugName() = "$sdkPresentableName ${sdk.name} ${sdk.homePath}"
private val sdkPresentableName: String
get() = (sdk.sdkType as? SdkType)?.presentableName.takeUnless { it.isNullOrEmpty() }
?: IndexingBundle.message("indexable.files.provider.indexing.sdk.unnamed")
override fun getIndexingProgressText() = IndexingBundle.message("indexable.files.provider.indexing.sdk", sdkPresentableName, sdk.name)
override fun getRootsScanningProgressText() = IndexingBundle.message("indexable.files.provider.scanning.sdk", sdkPresentableName,
sdk.name)
override fun getOrigin(): IndexableSetOrigin = SdkOriginImpl(sdk, rootsToIndex)
override fun iterateFiles(
project: Project,
fileIterator: ContentIterator,
fileFilter: VirtualFileFilter
): Boolean {
return IndexableFilesIterationMethods.iterateRoots(project, rootsToIndex, fileIterator, fileFilter)
}
override fun getRootUrls(project: Project): Set<String> {
return rootsToIndex.map { it.url }.toSet()
}
companion object {
fun createIterator(sdk: Sdk): SdkIndexableFilesIteratorImpl = SdkIndexableFilesIteratorImpl(sdk, getRootsToIndex(sdk))
fun getRootsToIndex(sdk: Sdk): Collection<VirtualFile> {
val rootProvider = sdk.rootProvider
return rootProvider.getFiles(OrderRootType.SOURCES).toList() + rootProvider.getFiles(OrderRootType.CLASSES)
}
fun createIterators(sdk: Sdk, listOfRootsToFilter: List<VirtualFile>): Collection<IndexableFilesIterator> {
val sdkRoots = getRootsToIndex(sdk).toMutableList()
val rootsToIndex = filterRootsToIterate(sdkRoots, listOfRootsToFilter)
val oldStyle: Collection<IndexableFilesIterator> = if (rootsToIndex.isEmpty()) {
emptyList()
}
else {
Collections.singletonList(SdkIndexableFilesIteratorImpl(sdk, rootsToIndex))
}
return oldStyle
}
fun filterRootsToIterate(initialRoots: MutableList<VirtualFile>,
listOfRootsToFilter: List<VirtualFile>): List<VirtualFile> {
val rootsToFilter = listOfRootsToFilter.toMutableList()
val rootsToIndex = mutableListOf<VirtualFile>()
val iteratorToFilter = rootsToFilter.iterator()
while (iteratorToFilter.hasNext()) {
val next = iteratorToFilter.next()
for (sdkRoot in initialRoots) {
if (VfsUtil.isAncestor(next, sdkRoot, false)) {
rootsToIndex.add(sdkRoot)
initialRoots.remove(sdkRoot)
iteratorToFilter.remove()
break
}
}
}
for (file in rootsToFilter) {
for (sdkRoot in initialRoots) {
if (VfsUtil.isAncestor(sdkRoot, file, false)) {
rootsToIndex.add(file)
}
}
}
return rootsToIndex
}
}
} | apache-2.0 | 9c968aa3414dd75f362143065bc5aab9 | 39.810526 | 136 | 0.711042 | 4.755828 | false | false | false | false |
StephaneBg/ScoreIt | data/src/main/kotlin/com/sbgapps/scoreit/data/model/Lap.kt | 1 | 1750 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.data.model
import com.squareup.moshi.JsonClass
sealed class Lap
@JsonClass(generateAdapter = true)
data class UniversalLap(
val points: List<Int>
) : Lap() {
constructor(playerCount: Int) : this(List(playerCount) { 0 })
}
@JsonClass(generateAdapter = true)
data class TarotLap(
val playerCount: Int,
val taker: PlayerPosition = PlayerPosition.ONE,
val partner: PlayerPosition = if (5 == playerCount) PlayerPosition.TWO else PlayerPosition.NONE,
val bid: TarotBidValue = TarotBidValue.SMALL,
val oudlers: List<TarotOudlerValue> = emptyList(),
val points: Int = 56,
val bonuses: List<TarotBonus> = emptyList()
) : Lap()
@JsonClass(generateAdapter = true)
data class BeloteLap(
val taker: PlayerPosition = PlayerPosition.ONE,
val points: Int = 90,
val bonuses: List<BeloteBonus> = emptyList()
) : Lap()
@JsonClass(generateAdapter = true)
data class CoincheLap(
val taker: PlayerPosition = PlayerPosition.ONE,
val bid: Int = 110,
val coinche: CoincheValue = CoincheValue.NONE,
val points: Int = 110,
val bonuses: List<BeloteBonus> = emptyList()
) : Lap()
| apache-2.0 | 66d272a0daea1d4df419a093671e4e87 | 30.8 | 100 | 0.721555 | 3.689873 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | desktop/src/main/kotlin/io/github/chrislo27/rhre3/desktop/DesktopLauncher.kt | 2 | 4773 | package io.github.chrislo27.rhre3.desktop
import com.badlogic.gdx.Files
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.glutils.HdpiMode
import com.beust.jcommander.JCommander
import com.beust.jcommander.ParameterException
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.toolboks.desktop.ToolboksDesktopLauncher3
import io.github.chrislo27.toolboks.lazysound.LazySound
import io.github.chrislo27.toolboks.logging.Logger
import java.io.File
object DesktopLauncher {
private fun printHelp(jCommander: JCommander) {
println("${RHRE3.TITLE} ${RHRE3.VERSION}\n${RHRE3.GITHUB}\n\n${StringBuilder().apply { jCommander.usage(this) }}")
}
@JvmStatic
fun main(args: Array<String>) {
// https://github.com/chrislo27/RhythmHeavenRemixEditor/issues/273
System.setProperty("jna.nosys", "true")
RHRE3.launchArguments = args.toList()
try {
// Check for bad arguments but don't cause a full crash
JCommander.newBuilder().acceptUnknownOptions(false).addObject(Arguments()).build().parse(*args)
} catch (e: ParameterException) {
println("WARNING: Failed to parse arguments. Check below for details and help documentation. You may have strange parse results from ignoring unknown options.\n")
e.printStackTrace()
println("\n\n")
printHelp(JCommander(Arguments()))
println("\n\n")
}
val arguments = Arguments()
val jcommander = JCommander.newBuilder().acceptUnknownOptions(true).addObject(arguments).build()
jcommander.parse(*args)
if (arguments.printHelp) {
printHelp(jcommander)
return
}
val logger = Logger()
val portable = arguments.portableMode
val app = RHRE3Application(logger, File(if (portable) ".rhre3/logs/" else System.getProperty("user.home") + "/.rhre3/logs/"))
ToolboksDesktopLauncher3(app)
.editConfig {
this.setAutoIconify(true)
this.setWindowedMode(app.emulatedSize.first, app.emulatedSize.second)
this.setWindowSizeLimits(RHRE3.MINIMUM_SIZE.first, RHRE3.MINIMUM_SIZE.second, -1, -1)
this.setTitle(app.getTitle())
this.setResizable(true)
this.useVsync(arguments.fps <= 60)
RHRE3.targetFramerate = arguments.fps.coerceAtLeast(30)
this.setInitialBackgroundColor(Color(0f, 0f, 0f, 1f))
this.setAudioConfig(100, 4096, 16)
this.setHdpiMode(HdpiMode.Logical)
// this.setBackBufferConfig(8, 8, 8, 8, 16, 0, 2)
if (portable) {
this.setPreferencesConfig(".rhre3/.prefs/", Files.FileType.Local)
}
RHRE3.portableMode = portable
RHRE3.skipGitScreen = arguments.skipGit
RHRE3.forceGitFetch = arguments.forceGitFetch
RHRE3.forceGitCheck = arguments.forceGitCheck
RHRE3.verifySfxDb = arguments.verifySfxdb
RHRE3.immediateEvent = when {
arguments.eventImmediateAnniversaryLikeNew -> 2
arguments.eventImmediateAnniversary -> 1
arguments.eventImmediateXmas -> 3
else -> 0
}
RHRE3.noAnalytics = arguments.noAnalytics
RHRE3.noOnlineCounter = arguments.noOnlineCounter
RHRE3.outputGeneratedDatamodels = arguments.outputGeneratedDatamodels
RHRE3.outputCustomSfx = arguments.outputCustomSfx
RHRE3.showTapalongMarkersByDefault = arguments.showTapalongMarkers
RHRE3.midiRecording = arguments.midiRecording
RHRE3.logMissingLocalizations = arguments.logMissingLocalizations
RHRE3.disableCustomSounds = arguments.disableCustomSounds
RHRE3.lc = arguments.lc
RHRE3.triggerUpdateScreen = arguments.triggerUpdateScreen
LazySound.loadLazilyWithAssetManager = !arguments.lazySoundsForceLoad
val sizes: List<Int> = listOf(256, 128, 64, 32, 24, 16)
this.setWindowIcon(Files.FileType.Internal, *sizes.map { "images/icon/$it.png" }.toTypedArray())
}
.launch()
}
}
| gpl-3.0 | 9dc51db0e93f22ee86f105bce8ee704b | 47.704082 | 174 | 0.608003 | 4.656585 | false | true | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/documentation/htl/HtlELDocumentationProvider.kt | 1 | 3154 | package com.aemtools.documentation.htl
import com.aemtools.analysis.htl.callchain
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.model.htl.HtlOption
import com.aemtools.index.model.AemComponentDefinition.Companion.generateDoc
import com.aemtools.index.search.AemComponentSearch
import com.aemtools.lang.htl.psi.mixin.PropertyAccessMixin
import com.aemtools.lang.htl.psi.mixin.VariableNameMixin
import com.aemtools.lang.htl.psi.pattern.HtlPatterns.contextOptionAssignment
import com.aemtools.lang.htl.psi.pattern.HtlPatterns.memberAccess
import com.aemtools.lang.htl.psi.pattern.HtlPatterns.optionName
import com.aemtools.lang.htl.psi.pattern.HtlPatterns.resourceTypeOptionAssignment
import com.aemtools.service.repository.inmemory.HtlAttributesRepository
import com.intellij.lang.documentation.AbstractDocumentationProvider
import com.intellij.psi.PsiElement
import generated.psi.impl.HtlStringLiteralImpl
/**
*
* @author Dmytro Troynikov.
*/
open class HtlELDocumentationProvider : AbstractDocumentationProvider() {
override fun generateDoc(element: PsiElement?, originalElement: PsiElement?): String? {
val text = originalElement?.text ?: return super.generateDoc(element, originalElement)
return when {
optionName.accepts(originalElement) -> {
HtlAttributesRepository.getHtlOptions().find {
it.name == text
}?.let(HtlOption::description)
?: super.generateDoc(element, originalElement)
}
resourceTypeOptionAssignment.accepts(originalElement) -> {
val resourceType = (originalElement.findParentByType(HtlStringLiteralImpl::class.java))?.name
?: return super.generateDoc(element, originalElement)
val component = AemComponentSearch.findByResourceType(resourceType, originalElement.project)
?: return super.generateDoc(element, originalElement)
return component.generateDoc()
}
contextOptionAssignment.accepts(originalElement) -> {
val literal = originalElement.findParentByType(HtlStringLiteralImpl::class.java)
?: return super.generateDoc(element, originalElement)
val stringValue = literal.name
HtlAttributesRepository.getContextValues().find {
it.name == stringValue
}?.let(HtlAttributesRepository.HtlContextValue::description)
?: super.generateDoc(element, originalElement)
}
memberAccess.accepts(originalElement) -> {
val propertyAccessMixin = originalElement.findParentByType(PropertyAccessMixin::class.java)
?: return super.generateDoc(element, originalElement)
val variableNameMixin = originalElement.findParentByType(VariableNameMixin::class.java)
?: return super.generateDoc(element, originalElement)
val currentChainElement = propertyAccessMixin.callchain()?.findChainElement(variableNameMixin)
?: return super.generateDoc(element, originalElement)
currentChainElement.type.documentation()
?: super.generateDoc(element, originalElement)
}
else -> super.generateDoc(element, originalElement)
}
}
}
| gpl-3.0 | fc87c752c1d29b73e3dc35a9ddd1d026 | 45.382353 | 102 | 0.7565 | 4.882353 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/internal/ml/ResourcesModelMetadataReader.kt | 3 | 1431 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.ml
open class ResourcesModelMetadataReader(protected val metadataHolder: Class<*>, private val featuresDirectory: String): ModelMetadataReader {
override fun binaryFeatures(): String = resourceContent("binary.json")
override fun floatFeatures(): String = resourceContent("float.json")
override fun categoricalFeatures(): String = resourceContent("categorical.json")
override fun allKnown(): String = resourceContent("all_features.json")
override fun featureOrderDirect(): List<String> = resourceContent("features_order.txt").lines()
override fun extractVersion(): String? {
val resource = metadataHolder.classLoader.getResource("$featuresDirectory/binary.json") ?: return null
val result = resource.file.substringBeforeLast(".jar!", "").substringAfterLast("-", "")
return if (result.isBlank()) null else result
}
private fun resourceContent(fileName: String): String {
val resource = "$featuresDirectory/$fileName"
val fileStream = metadataHolder.classLoader.getResourceAsStream(resource)
?: throw InconsistentMetadataException(
"Metadata file not found: $resource. Resources holder: ${metadataHolder.name}")
return fileStream.bufferedReader().use { it.readText() }
}
}
| apache-2.0 | 184fe9732122424cc9871e39d910e182 | 56.24 | 141 | 0.738644 | 4.900685 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/service/DataService.kt | 1 | 21663 | /*
* (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.acra.service
import com.faendir.acra.dataprovider.QueryDslDataProvider
import com.faendir.acra.model.App
import com.faendir.acra.model.Attachment
import com.faendir.acra.model.Bug
import com.faendir.acra.model.Device
import com.faendir.acra.model.MailSettings
import com.faendir.acra.model.QApp
import com.faendir.acra.model.QAttachment
import com.faendir.acra.model.QBug
import com.faendir.acra.model.QDevice
import com.faendir.acra.model.QMailSettings
import com.faendir.acra.model.QReport
import com.faendir.acra.model.QStacktrace
import com.faendir.acra.model.QVersion
import com.faendir.acra.model.Report
import com.faendir.acra.model.Stacktrace
import com.faendir.acra.model.User
import com.faendir.acra.model.Version
import com.faendir.acra.model.view.Queries
import com.faendir.acra.model.view.VApp
import com.faendir.acra.model.view.VReport
import com.faendir.acra.model.view.WhereExpressions.whereHasAppPermission
import com.faendir.acra.util.ImportResult
import com.faendir.acra.util.catching
import com.faendir.acra.util.findInt
import com.faendir.acra.util.findString
import com.faendir.acra.util.tryOrNull
import com.querydsl.core.types.Expression
import com.querydsl.core.types.Predicate
import com.querydsl.core.types.dsl.ComparableExpressionBase
import com.querydsl.core.types.dsl.Expressions
import com.querydsl.jpa.JPAExpressions
import com.querydsl.jpa.impl.JPADeleteClause
import com.querydsl.jpa.impl.JPAQuery
import com.querydsl.jpa.impl.JPAUpdateClause
import mu.KotlinLogging
import org.acra.ReportField
import org.ektorp.CouchDbConnector
import org.ektorp.http.StdHttpClient
import org.ektorp.impl.StdCouchDbConnector
import org.ektorp.impl.StdCouchDbInstance
import org.hibernate.Hibernate
import org.hibernate.engine.spi.SessionImplementor
import org.json.JSONObject
import org.springframework.context.ApplicationEventPublisher
import org.springframework.security.access.prepost.PostAuthorize
import org.springframework.security.access.prepost.PostFilter
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.io.Serializable
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import javax.persistence.EntityManager
private val logger = KotlinLogging.logger {}
/**
* @author lukas
* @since 16.05.18
*/
@Service
class DataService(
private val userService: UserService, private val entityManager: EntityManager,
private val applicationEventPublisher: ApplicationEventPublisher
) : Serializable {
private val stacktraceLock = Any()
fun getAppProvider(): QueryDslDataProvider<VApp> {
val where = whereHasAppPermission()
return QueryDslDataProvider(Queries.selectVApp(entityManager).where(where), JPAQuery<Any>(entityManager).from(QApp.app).where(where))
}
fun getAppIds(): List<Int> = JPAQuery<Any>(entityManager).from(QApp.app).where(whereHasAppPermission()).select(QApp.app.id).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getBugProvider(app: App) = QueryDslDataProvider(Queries.selectVBug(entityManager).where(QBug.bug.app.eq(app)))
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getBugIds(app: App): List<Int> = JPAQuery<Any>(entityManager).from(QBug.bug).where(QBug.bug.app.eq(app)).select(QBug.bug.id).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getStacktraceIds(bug: Bug): List<Int> =
JPAQuery<Any>(entityManager).from(QStacktrace.stacktrace1).where(QStacktrace.stacktrace1.bug.eq(bug)).select(QStacktrace.stacktrace1.id).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getReportProvider(bug: Bug) = QueryDslDataProvider(
Queries.selectVReport(entityManager, bug.app)
.where(QStacktrace.stacktrace1.bug.eq(bug))
)
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getReportProvider(app: App) = QueryDslDataProvider(
Queries.selectVReport(entityManager, app)
.join(QStacktrace.stacktrace1.version).fetchJoin()
.where(QApp.app.eq(app))
)
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#stacktrace.bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getReportIds(stacktrace: Stacktrace): List<String> =
JPAQuery<Any>(entityManager).from(QReport.report).where(QReport.report.stacktrace.eq(stacktrace)).select(QReport.report.id).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getReportIds(app: App, before: ZonedDateTime?, after: ZonedDateTime?): List<String> {
var where = QReport.report.stacktrace.bug.app.eq(app)
before?.let { where = where.and(QReport.report.date.before(it)) }
after?.let { where = where.and(QReport.report.date.after(it)) }
return JPAQuery<Any>(entityManager).from(QReport.report).where(where).select(QReport.report.id).fetch()
}
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getVersionProvider(app: App) =
QueryDslDataProvider(JPAQuery<Any>(entityManager).from(QVersion.version).fetchAll().where(QVersion.version.app.eq(app)).select(QVersion.version))
@Transactional
fun <T> store(entity: T): T = entityManager.merge(entity)
private fun delete(entity: Any) {
entityManager.remove(if (entityManager.contains(entity)) entity else entityManager.merge(entity))
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#version.app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun storeVersion(version: Version): Version = store(version)
@Transactional
fun deleteVersion(version: Version) {
JPAUpdateClause(entityManager, QBug.bug).set(QBug.bug.solvedVersion, null as Version?).where(QBug.bug.solvedVersion.eq(version))
delete(version)
applicationEventPublisher.publishEvent(ReportsDeleteEvent(this))
}
@Transactional
fun deleteReport(report: VReport) {
JPADeleteClause(entityManager, QReport.report).where(QReport.report.id.eq(report.id)).execute()
applicationEventPublisher.publishEvent(ReportsDeleteEvent(this))
}
@Transactional
fun deleteBug(bug: Bug) {
delete(bug)
}
@Transactional
fun deleteApp(app: App) {
delete(app)
}
/**
* Creates a new app
*
* @param name the name of the new app
* @return the name of the reporter user and its password (plaintext)
*/
@Transactional
@PreAuthorize("hasRole(T(com.faendir.acra.model.User\$Role).ADMIN)")
fun createNewApp(name: String): User {
val user = userService.createReporterUser()
store(App(name, user))
return user
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).ADMIN)")
fun recreateReporterUser(app: App): User {
val user = userService.createReporterUser()
app.reporter = user
store(app)
return user
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#bug.app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun unmergeBug(bug: Bug) {
getStacktraces(bug).forEach {
it.bug = Bug(bug.app, it.stacktrace)
store(it)
}
delete(bug)
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#stacktrace.bug.app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun unmergeStacktrace(stacktrace: Stacktrace) {
stacktrace.bug = Bug(stacktrace.bug.app, stacktrace.stacktrace)
store(stacktrace)
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#bug.app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun setBugSolved(bug: Bug, solved: Version?) {
bug.solvedVersion = solved
store(bug)
}
@PostAuthorize(
"returnObject == null || T(com.faendir.acra.security.SecurityUtils).hasPermission(returnObject.stacktrace.bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findReport(id: String): Report? = JPAQuery<Any>(entityManager).from(QReport.report)
.join(QReport.report.stacktrace, QStacktrace.stacktrace1)
.fetchJoin()
.join(QStacktrace.stacktrace1.version, QVersion.version)
.fetchAll()
.fetchJoin()
.join(QStacktrace.stacktrace1.bug, QBug.bug)
.fetchJoin()
.join(QBug.bug.app, QApp.app)
.fetchJoin()
.where(QReport.report.id.eq(id))
.select(QReport.report)
.fetchOne()
@PostAuthorize(
"returnObject == null || T(com.faendir.acra.security.SecurityUtils).hasPermission(returnObject.app, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findBug(id: Int): Bug? =
JPAQuery<Any>(entityManager).from(QBug.bug).join(QBug.bug.app).fetchJoin().where(QBug.bug.id.eq(id)).select(QBug.bug).fetchOne()
@PostAuthorize(
"returnObject == null || T(com.faendir.acra.security.SecurityUtils).hasPermission(returnObject, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findApp(encodedId: String): App? = tryOrNull { findApp(encodedId.toInt()) }
@PostAuthorize(
"returnObject == null || T(com.faendir.acra.security.SecurityUtils).hasPermission(returnObject, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findApp(id: Int): App? = JPAQuery<Any>(entityManager).from(QApp.app).where(QApp.app.id.eq(id)).select(QApp.app).fetchOne()
@PostFilter(
"hasRole(T(com.faendir.acra.model.User\$Role).ADMIN) || T(com.faendir.acra.security.SecurityUtils).hasPermission(filterObject, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findAllApps(): List<App> = JPAQuery<Any>(entityManager).from(QApp.app).select(QApp.app).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#report.stacktrace.bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun findAttachments(report: Report): List<Attachment> =
JPAQuery<Any>(entityManager).from(QAttachment.attachment).where(QAttachment.attachment.report.eq(report)).select(QAttachment.attachment).fetch()
@PostAuthorize(
"returnObject == null || T(com.faendir.acra.security.SecurityUtils).hasPermission(returnObject.bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)"
)
fun findStacktrace(id: Int): Stacktrace? =
JPAQuery<Any>(entityManager).from(QStacktrace.stacktrace1).where(QStacktrace.stacktrace1.id.eq(id)).select(QStacktrace.stacktrace1).fetchOne()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun findStacktrace(app: App, stacktrace: String, versionCode: Int): Stacktrace? = JPAQuery<Any>(entityManager).from(QStacktrace.stacktrace1)
.where(
QStacktrace.stacktrace1.stacktrace.eq(stacktrace)
.and(QStacktrace.stacktrace1.version.code.eq(versionCode))
.and(QStacktrace.stacktrace1.bug.app.eq(app))
)
.select(QStacktrace.stacktrace1)
.fetchOne()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun findVersion(app: App, versionCode: Int): Version? = JPAQuery<Any>(entityManager).from(QVersion.version)
.where(QVersion.version.code.eq(versionCode).and(QVersion.version.app.eq(app)))
.select(QVersion.version)
.fetchOne()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
private fun findBug(app: App, stacktrace: String): Bug? = JPAQuery<Any>(entityManager).from(QStacktrace.stacktrace1)
.join(QStacktrace.stacktrace1.bug, QBug.bug)
.leftJoin(QBug.bug.solvedVersion).fetchJoin()
.where(QBug.bug.app.eq(app).and(QStacktrace.stacktrace1.stacktrace.like(stacktrace)))
.select(QBug.bug)
.fetchFirst()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun findAllVersions(app: App): List<Version> =
JPAQuery<Any>(entityManager).from(QVersion.version).where(QVersion.version.app.eq(app)).select(QVersion.version).orderBy(QVersion.version.code.desc())
.fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun findMailSettings(app: App, user: User): MailSettings? = JPAQuery<Any>(entityManager).from(QMailSettings.mailSettings)
.where(QMailSettings.mailSettings.app.eq(app).and(QMailSettings.mailSettings.user.eq(user)))
.select(QMailSettings.mailSettings).fetchOne()
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#a, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun changeConfiguration(a: App, configuration: App.Configuration) {
var app = a
app.configuration = configuration
store(app)
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun deleteReportsOlderThanDays(app: App, days: Int) {
JPADeleteClause(entityManager, QReport.report).where(
QReport.report.stacktrace.`in`(
JPAExpressions.select(QStacktrace.stacktrace1).from(QStacktrace.stacktrace1).where(QStacktrace.stacktrace1.bug.app.eq(app))
)
.and(QReport.report.date.before(ZonedDateTime.now().minus(days.toLong(), ChronoUnit.DAYS)))
).execute()
entityManager.flush()
applicationEventPublisher.publishEvent(ReportsDeleteEvent(this))
}
@Transactional
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).EDIT)")
fun deleteReportsBeforeVersion(app: App, versionCode: Int) {
JPADeleteClause(entityManager, QReport.report).where(
QReport.report.stacktrace.`in`(
JPAExpressions.select(QStacktrace.stacktrace1).from(QStacktrace.stacktrace1).where(
QStacktrace.stacktrace1.bug.app.eq(app)
.and(QStacktrace.stacktrace1.version.code.lt(versionCode))
)
)
).execute()
entityManager.flush()
applicationEventPublisher.publishEvent(ReportsDeleteEvent(this))
}
@Transactional
@PreAuthorize("hasRole(T(com.faendir.acra.model.User\$Role).REPORTER)")
fun createNewReport(reporterUserName: String, content: String, attachments: List<MultipartFile>) {
JPAQuery<Any>(entityManager).from(QApp.app).where(QApp.app.reporter.username.eq(reporterUserName)).select(QApp.app).fetchOne()?.let { app ->
val jsonObject = JSONObject(content)
val trace = jsonObject.optString(ReportField.STACK_TRACE.name)
val version = getVersion(app, jsonObject)
val stacktrace = findStacktrace(app, trace, version.code) ?: synchronized(stacktraceLock) {
findStacktrace(app, trace, version.code) ?: store(Stacktrace(findBug(app, trace) ?: Bug(app, trace), trace, version))
}
val report = store(Report(stacktrace, content))
attachments.forEach {
try {
store(
Attachment(
report, it.originalFilename ?: it.name,
Hibernate.getLobCreator(entityManager.unwrap(SessionImplementor::class.java)).createBlob(it.inputStream, it.size)
)
)
} catch (e: IOException) {
logger.warn(e) { "Failed to load attachment with name ${it.originalFilename}" }
}
}
entityManager.flush()
applicationEventPublisher.publishEvent(NewReportEvent(this, report))
}
}
private fun getVersion(app: App, jsonObject: JSONObject): Version {
val buildConfig: JSONObject? = jsonObject.optJSONObject(ReportField.BUILD_CONFIG.name)
val versionCode: Int = buildConfig?.findInt("VERSION_CODE") ?: jsonObject.findInt(ReportField.APP_VERSION_CODE.name) ?: 0
val versionName: String = buildConfig?.findString("VERSION_NAME") ?: jsonObject.findString(ReportField.APP_VERSION_NAME.name) ?: "N/A"
return findVersion(app, versionCode) ?: (Version(app, versionCode, versionName))
}
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun <T> countReports(app: App, where: Predicate?, select: Expression<T>): Map<T, Long> {
val result = (JPAQuery<Any>(entityManager) as JPAQuery<*>).from(QReport.report)
.where(QReport.report.stacktrace.bug.app.eq(app).and(where))
.groupBy(select)
.select(select, QReport.report.id.count())
.fetch()
return result.associate { it[select]!! to (it[QReport.report.id.count()] ?: 0L) }
}
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun <T> getFromReports(app: App, select: Expression<T>, where: Predicate? = null, sorted: Boolean = true): List<T> =
(JPAQuery<Any>(entityManager) as JPAQuery<*>).from(QReport.report).where(QReport.report.stacktrace.bug.app.eq(app).and(where))
.select(select).apply { if (sorted && select is ComparableExpressionBase) orderBy(select.asc()) }.distinct().fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#bug.app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getStacktraces(bug: Bug): List<Stacktrace> =
JPAQuery<Any>(entityManager).from(QStacktrace.stacktrace1)
.join(QStacktrace.stacktrace1.version, QVersion.version).fetchAll().fetchJoin()
.join(QStacktrace.stacktrace1.bug).fetchJoin()
.where(QStacktrace.stacktrace1.bug.eq(bug)).select(QStacktrace.stacktrace1).fetch()
@PreAuthorize("T(com.faendir.acra.security.SecurityUtils).hasPermission(#app, T(com.faendir.acra.model.Permission\$Level).VIEW)")
fun getMaxVersion(app: App): Int? =
JPAQuery<Any>(entityManager).from(QVersion.version).where(QVersion.version.app.eq(app)).select(QVersion.version.code.max()).fetchOne()
@Transactional
@PreAuthorize("hasRole(T(com.faendir.acra.model.User\$Role).ADMIN)")
fun importFromAcraStorage(host: String, port: Int, ssl: Boolean, database: String): ImportResult {
val httpClient = StdHttpClient.Builder().host(host).port(port).enableSSL(ssl).build()
val db: CouchDbConnector = StdCouchDbConnector(database, StdCouchDbInstance(httpClient))
val user = createNewApp(database.replaceFirst("acra-".toRegex(), ""))
var total = 0
var success = 0
for (id in db.allDocIds) {
if (!id.startsWith("_design")) {
total++
catching {
val report = JSONObject(db.getAsStream(id).reader(Charsets.UTF_8).use { it.readText() })
fixStringIsArray(report, ReportField.STACK_TRACE)
fixStringIsArray(report, ReportField.LOGCAT)
createNewReport(user.username, report.toString(), emptyList())
success++
}
}
}
httpClient.shutdown()
return ImportResult(user, total, success)
}
private fun fixStringIsArray(report: JSONObject, reportField: ReportField) {
report.optJSONArray(reportField.name)?.let { report.put(reportField.name, it.filterIsInstance<String>().joinToString("\n")) }
}
@Transactional
fun updateDeviceTable(devices: List<Device>) {
devices.forEach { store(it) }
}
fun hasDeviceTableEntries(): Boolean {
return JPAQuery<Any>(entityManager).from(QDevice.device1).select(Expressions.ONE).fetchFirst() != null
}
} | apache-2.0 | c8050bb08747a971d9f8ea87f0feae99 | 49.264501 | 185 | 0.70692 | 3.896924 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPREditorReviewThreadsController.kt | 1 | 1596 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.comment.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
class GHPREditorReviewThreadsController(threadMap: GHPREditorReviewThreadsModel,
private val componentFactory: GHPRDiffEditorReviewComponentsFactory,
private val inlaysManager: EditorComponentInlaysManager) {
private val inlayByThread = mutableMapOf<GHPRReviewThreadModel, Disposable>()
init {
for ((line, threads) in threadMap.modelsByLine) {
for (thread in threads) {
if (insertThread(line, thread)) break
}
}
threadMap.addChangesListener(object : GHPREditorReviewThreadsModel.ChangesListener {
override fun threadsAdded(line: Int, threads: List<GHPRReviewThreadModel>) {
for (thread in threads) {
insertThread(line, thread)
}
}
override fun threadsRemoved(line: Int, threads: List<GHPRReviewThreadModel>) {
for (thread in threads) {
val inlay = inlayByThread.remove(thread) ?: continue
Disposer.dispose(inlay)
}
}
})
}
private fun insertThread(line: Int, thread: GHPRReviewThreadModel): Boolean {
val component = componentFactory.createThreadComponent(thread)
val inlay = inlaysManager.insertAfter(line, component) ?: return true
inlayByThread[thread] = inlay
return false
}
} | apache-2.0 | 9a1ee56f5b0bc5aab3822da720a7cef2 | 37.02381 | 140 | 0.690476 | 4.956522 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/nearby/type/NearbyParams.kt | 1 | 2063 | package org.mtransit.android.ui.nearby.type
import android.location.Location
import org.mtransit.android.commons.LocationUtils
import org.mtransit.android.commons.provider.POIProviderContract
import org.mtransit.android.data.AgencyBaseProperties
data class NearbyParams(
val typeId: Int? = null,
val allAgencies: List<AgencyBaseProperties>? = null,
val ad: LocationUtils.AroundDiff? = LocationUtils.getNewDefaultAroundDiff(),
val nearbyLocation: Location? = null,
val minCoverageInMeters: Float? = null,
val minSize: Int? = null,
val maxSize: Int? = null,
// TODO ? val lastEmptyAroundDiff: Double? = null,
) {
val typeAgencies: List<AgencyBaseProperties>?
get() = typeId?.let { dstId -> allAgencies?.filter { agency -> agency.type.id == dstId } }
val area: LocationUtils.Area?
get() {
return if (nearbyLocation == null || ad == null) {
null
} else {
LocationUtils.getArea(nearbyLocation.latitude, nearbyLocation.longitude, ad.aroundDiff)
}
}
val maxDistance: Float?
get() {
return if (nearbyLocation == null || ad == null) {
null
} else {
LocationUtils.getAroundCoveredDistanceInMeters(nearbyLocation.latitude, nearbyLocation.longitude, ad.aroundDiff)
}
}
val poiFilter: POIProviderContract.Filter?
get() {
return if (nearbyLocation == null || ad == null) {
null
} else {
POIProviderContract.Filter.getNewAroundFilter(nearbyLocation.latitude, nearbyLocation.longitude, ad.aroundDiff)
}
}
val isReady: Boolean
get() = typeAgencies != null && nearbyLocation != null && ad != null && minCoverageInMeters != null && maxSize != null
fun toStringS(): String {
return "NearbyParams(type=$typeId, agencies=${allAgencies?.size}, ad=$ad, nearby=$nearbyLocation, minCoverage=$minCoverageInMeters, min=$minSize, max=$maxSize)"
}
}
| apache-2.0 | fa90e1e2990119f1c506a64ba5421912 | 37.203704 | 168 | 0.634998 | 4.352321 | false | false | false | false |
leafclick/intellij-community | plugins/changeReminder/src/com/jetbrains/changeReminder/predict/PredictionService.kt | 1 | 8344 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.predict
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing.haveEqualElements
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.log.data.DataPackChangeListener
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.index.VcsLogIndex
import com.intellij.vcs.log.impl.VcsLogManager
import com.intellij.vcs.log.impl.VcsProjectLog
import com.jetbrains.changeReminder.plugin.UserSettings
import com.jetbrains.changeReminder.repository.FilesHistoryProvider
import com.jetbrains.changeReminder.stats.ChangeReminderChangeListChangedEvent
import com.jetbrains.changeReminder.stats.ChangeReminderNodeExpandedEvent
import com.jetbrains.changeReminder.stats.logEvent
import javax.swing.event.TreeExpansionEvent
import javax.swing.event.TreeExpansionListener
internal class PredictionService(val project: Project) : Disposable {
private val changesViewManager = ChangesViewManager.getInstance(project)
private val changeListManager = ChangeListManager.getInstance(project)
private data class PredictionRequirements(val dataManager: VcsLogData, val filesHistoryProvider: FilesHistoryProvider)
private var predictionRequirements: PredictionRequirements? = null
private lateinit var projectLogListenerDisposable: Disposable
private val userSettings = service<UserSettings>()
private val LOCK = Object()
private var predictionData: PredictionData = PredictionData.EmptyPrediction(PredictionData.EmptyPredictionReason.SERVICE_INIT)
val predictionDataToDisplay
get() = predictionData
val isReadyToDisplay: Boolean
get() = predictionData is PredictionData.Prediction
private val taskController = object : PredictionController(project, "ChangeReminder Calculation", this, {
synchronized(LOCK) {
setPrediction(it)
}
}) {
override fun inProgressChanged(value: Boolean) {
changesViewManager.scheduleRefresh()
}
}
val inProgress: Boolean
get() = taskController.inProgress
private val changeListsListener = object : ChangeListAdapter() {
private var lastChanges: Collection<Change> = listOf()
override fun changeListsChanged() {
val changes = changeListManager.defaultChangeList.changes
if (!haveEqualElements(changes, lastChanges)) {
if (changes.size <= Registry.intValue("vcs.changeReminder.changes.limit")) {
val prevFiles = lastChanges.map { ChangesUtil.getFilePath(it) }
val curFiles = changes.map { ChangesUtil.getFilePath(it) }
logEvent(project, ChangeReminderChangeListChangedEvent(prevFiles, predictionData, curFiles))
}
calculatePrediction()
lastChanges = changes
}
}
}
private val dataPackChangeListener = DataPackChangeListener {
synchronized(LOCK) {
predictionRequirements?.filesHistoryProvider?.clear()
setEmptyPrediction(PredictionData.EmptyPredictionReason.DATA_PACK_CHANGED)
calculatePrediction()
}
}
private val projectLogListener = object : VcsProjectLog.ProjectLogListener {
override fun logCreated(manager: VcsLogManager) = synchronized(LOCK) {
setDataManager(manager.dataManager)
}
override fun logDisposed(manager: VcsLogManager) = synchronized(LOCK) {
removeDataManager()
}
}
private val userSettingsListener = object : UserSettings.PluginStatusListener {
override fun statusChanged(isEnabled: Boolean) {
if (isEnabled) {
startService()
}
else {
shutdownService()
}
}
}
private val indexingFinishedListener = VcsLogIndex.IndexingFinishedListener { calculatePrediction() }
private val nodeExpandedListener = object : TreeExpansionListener {
private var view: ChangesListView? = null
override fun treeExpanded(event: TreeExpansionEvent?) {
if (event == null) {
return
}
val predictionData = TreeUtil.findObjectInPath(event.path, PredictionData.Prediction::class.java) ?: return
logEvent(project, ChangeReminderNodeExpandedEvent(predictionData))
}
override fun treeCollapsed(event: TreeExpansionEvent?) {}
fun tryToSubscribe() {
if (view != null) {
return
}
val changeListViewPanel =
ChangesViewContentManager.getInstance(project).getActiveComponent(ChangesViewManager.ChangesViewToolWindowPanel::class.java)
?: return
view = UIUtil.findComponentOfType(changeListViewPanel, ChangesListView::class.java)?.also {
it.addTreeExpansionListener(this)
}
}
fun unsubscribe() {
view?.removeTreeExpansionListener(this)
}
}
init {
if (userSettings.isPluginEnabled) {
startService()
}
userSettings.addPluginStatusListener(userSettingsListener, this)
}
private fun setDataManager(dataManager: VcsLogData?) {
dataManager ?: return
if (predictionRequirements?.dataManager == dataManager) return
dataManager.addDataPackChangeListener(dataPackChangeListener)
dataManager.index.addListener(indexingFinishedListener)
val filesHistoryProvider = dataManager.index.dataGetter?.let { FilesHistoryProvider(project, dataManager, it) } ?: return
predictionRequirements = PredictionRequirements(dataManager, filesHistoryProvider)
calculatePrediction()
}
private fun removeDataManager() {
setEmptyPrediction(PredictionData.EmptyPredictionReason.DATA_MANAGER_REMOVED)
val (dataManager, filesHistoryProvider) = predictionRequirements ?: return
predictionRequirements = null
filesHistoryProvider.clear()
dataManager.index.removeListener(indexingFinishedListener)
dataManager.removeDataPackChangeListener(dataPackChangeListener)
}
private fun calculatePrediction() = synchronized(LOCK) {
nodeExpandedListener.tryToSubscribe()
val changes = changeListManager.defaultChangeList.changes
if (changes.size > Registry.intValue("vcs.changeReminder.changes.limit")) {
setEmptyPrediction(PredictionData.EmptyPredictionReason.TOO_MANY_FILES)
return
}
val (dataManager, filesHistoryProvider) = predictionRequirements ?: let {
setEmptyPrediction(PredictionData.EmptyPredictionReason.REQUIREMENTS_NOT_MET)
return
}
val changeListFiles = changes.map { ChangesUtil.getFilePath(it) }
val currentPredictionData = predictionData
if (currentPredictionData is PredictionData.Prediction &&
haveEqualElements(currentPredictionData.requestedFiles, changeListFiles)) {
setPrediction(currentPredictionData)
return
}
if (dataManager.dataPack.isFull) {
taskController.request(PredictionRequest(project, dataManager, filesHistoryProvider, changeListFiles))
}
else {
setEmptyPrediction(PredictionData.EmptyPredictionReason.DATA_PACK_IS_NOT_FULL)
}
}
private fun startService() = synchronized(LOCK) {
projectLogListenerDisposable = Disposer.newDisposable()
val connection = project.messageBus.connect(projectLogListenerDisposable)
connection.subscribe(VcsProjectLog.VCS_PROJECT_LOG_CHANGED, projectLogListener)
connection.subscribe(ChangeListListener.TOPIC, changeListsListener)
setDataManager(VcsProjectLog.getInstance(project).dataManager)
}
private fun shutdownService() = synchronized(LOCK) {
nodeExpandedListener.unsubscribe()
removeDataManager()
Disposer.dispose(projectLogListenerDisposable)
}
private fun setEmptyPrediction(reason: PredictionData.EmptyPredictionReason) {
setPrediction(PredictionData.EmptyPrediction(reason))
}
private fun setPrediction(newPrediction: PredictionData) {
predictionData = newPrediction
changesViewManager.scheduleRefresh()
}
override fun dispose() {
if (userSettings.isPluginEnabled) {
shutdownService()
}
}
} | apache-2.0 | fafeb335b4567542b9135a49cf9a2062 | 36.421525 | 140 | 0.76582 | 4.948992 | false | false | false | false |
blokadaorg/blokada | android5/app/src/engine/kotlin/engine/BlockaDnsService.kt | 1 | 1301 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package newengine
import com.blocka.dns.BlockaDnsJNI
import model.BlokadaException
import model.Dns
import model.isDnsOverHttps
import utils.Logger
object BlockaDnsService {
const val PROXY_PORT: Short = 8573
private val log = Logger("BlockaDns")
private var started = false
fun startDnsProxy(dns: Dns) {
log.v("Starting DoH DNS proxy")
if (!dns.isDnsOverHttps()) throw BlokadaException("Attempted to start DoH DNS proxy for non-DoH dns entry")
val name = dns.name!!
val path = dns.path!!
BlockaDnsJNI.create_new_dns(
listen_addr = "127.0.0.1:$PROXY_PORT",
dns_ips = dns.ips.joinToString(","),
dns_name = name,
dns_path = path
)
started = true
}
fun stopDnsProxy() {
if (started) {
started = false
log.v("Stopping DoH DNS proxy")
BlockaDnsJNI.dns_close(0)
}
}
} | mpl-2.0 | cee7acd97f8e3aba177e2ff6c4f5397e | 24.509804 | 115 | 0.620769 | 3.68272 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reified/arraysReification/jaggedArrayOfNulls.kt | 2 | 595 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
inline fun <reified T> jaggedArrayOfNulls(): Array<Array<T>?> = arrayOfNulls<Array<T>>(1)
fun box(): String {
val x1 = jaggedArrayOfNulls<String>().javaClass.simpleName
if (x1 != "String[][]") return "fail1: $x1"
val x2 = jaggedArrayOfNulls<Array<String>>().javaClass.simpleName
if (x2 != "String[][][]") return "fail2: $x2"
val x3 = jaggedArrayOfNulls<IntArray>().javaClass.simpleName
if (x3 != "int[][][]") return "fail3: $x3"
return "OK"
}
| apache-2.0 | 5edf1946c49be763cce5ca9b2cc688e1 | 32.055556 | 89 | 0.655462 | 3.198925 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/inspections/DeprecatedMavenDependencyInspection.kt | 6 | 3147 | // 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.maven.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.util.text.VersionComparatorUtil
import com.intellij.util.xml.DomFileElement
import com.intellij.util.xml.highlighting.DomElementAnnotationHolder
import com.intellij.util.xml.highlighting.DomElementsInspection
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.kotlin.idea.inspections.ReplaceStringInDocumentFix
import org.jetbrains.kotlin.idea.maven.PomFile
import org.jetbrains.kotlin.idea.maven.findDependencies
import org.jetbrains.kotlin.idea.versions.DEPRECATED_LIBRARIES_INFORMATION
class DeprecatedMavenDependencyInspection :
DomElementsInspection<MavenDomProjectModel>(MavenDomProjectModel::class.java), CleanupLocalInspectionTool {
override fun checkFileElement(domFileElement: DomFileElement<MavenDomProjectModel>?, holder: DomElementAnnotationHolder?) {
if (domFileElement == null || holder == null) return
val file = domFileElement.file
val module = domFileElement.module ?: return
val manager = MavenProjectsManager.getInstance(module.project) ?: return
val mavenProject = manager.findProject(module) ?: return
val pomFile = PomFile.forFileOrNull(file) ?: return
for (libInfo in DEPRECATED_LIBRARIES_INFORMATION) {
val libMavenId = MavenId(libInfo.old.groupId, libInfo.old.name, null)
val moduleDependencies = pomFile.findDependencies(libMavenId)
.filter {
val libVersion =
mavenProject.findDependencies(libInfo.old.groupId, libInfo.old.name).map { it.version }.distinct().singleOrNull()
libVersion != null && VersionComparatorUtil.COMPARATOR.compare(libVersion, libInfo.outdatedAfterVersion) >= 0
}
val dependencyManagementDependencies = pomFile.domModel.dependencyManagement.dependencies.findDependencies(libMavenId).filter {
val version = it.version?.stringValue
version != null && VersionComparatorUtil.COMPARATOR.compare(version, libInfo.outdatedAfterVersion) >= 0
}
for (dependency in moduleDependencies + dependencyManagementDependencies) {
val xmlElement = dependency.artifactId.xmlElement
if (xmlElement != null) {
val fix = ReplaceStringInDocumentFix(xmlElement, libInfo.old.name, libInfo.new.name)
holder.createProblem(
dependency.artifactId,
ProblemHighlightType.LIKE_DEPRECATED,
libInfo.message,
null,
fix
)
}
}
}
}
} | apache-2.0 | 8859f84f6c93652375fdb13859ab0890 | 48.968254 | 158 | 0.698443 | 5.352041 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt | 1 | 25959 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult
import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter
import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl
import com.intellij.codeInspection.dataFlow.lang.DfaAnchor
import com.intellij.codeInspection.dataFlow.lang.DfaListener
import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem
import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ThreeState
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.*
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.*
import org.jetbrains.kotlin.idea.intentions.negate
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isNull
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
class KotlinConstantConditionsInspection : AbstractKotlinInspection() {
private enum class ConstantValue {
TRUE, FALSE, NULL, ZERO, UNKNOWN
}
private class KotlinDfaListener : DfaListener {
val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>()
val problems = hashMapOf<KotlinProblem, ThreeState>()
override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) {
if (anchor is KotlinAnchor) {
recordExpressionValue(anchor, state, value)
}
}
override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) {
if (problem is KotlinProblem) {
problems.merge(problem, failed, ThreeState::merge)
}
}
private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) {
val oldVal = constantConditions[anchor]
if (oldVal == ConstantValue.UNKNOWN) return
var newVal = when (val dfType = state.getDfType(value)) {
DfTypes.TRUE -> ConstantValue.TRUE
DfTypes.FALSE -> ConstantValue.FALSE
DfTypes.NULL -> ConstantValue.NULL
else -> {
val constVal: Number? = dfType.getConstantOfType(Number::class.java)
if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO
else ConstantValue.UNKNOWN
}
}
if (oldVal != null && oldVal != newVal) {
newVal = ConstantValue.UNKNOWN
}
constantConditions[anchor] = newVal
}
}
private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean {
// TODO: do something with always false branches in exhaustive when statements
// TODO: return x && y.let {return...}
var parent = expression.parent
if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) {
// Will be reported for parent qualified expression
return true
}
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if (expression is KtConstantExpression ||
// If result of initialization is constant, then the initializer will be reported
expression is KtProperty ||
// If result of assignment is constant, then the right-hand part will be reported
expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ ||
// Negation operand: negation itself will be reported
(parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL
) {
return true
}
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) {
// Left part of Elvis is Nothing?, so the right part is always executed
// Could be caused by code like return x?.let { return ... } ?: true
// While inner "return" is redundant, the "always true" warning is confusing
// probably separate inspection could report extra "return"
if (expression.left?.getKotlinType()?.isNullableNothing() == true) {
return true
}
}
if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true
when (value) {
ConstantValue.TRUE -> {
if (isSmartCastNecessary(expression, true)) return true
if (isPairingConditionInWhen(expression)) return true
if (isAssertion(parent, true)) return true
}
ConstantValue.FALSE -> {
if (isSmartCastNecessary(expression, false)) return true
if (isAssertion(parent, false)) return true
}
ConstantValue.ZERO -> {
if (expression.readWriteAccess(false).isWrite) {
// like if (x == 0) x++, warning would be somewhat annoying
return true
}
if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) {
var receiver: KtExpression? = expression.receiverExpression
if (receiver is KtQualifiedExpression) {
receiver = receiver.selectorExpression
}
if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtEnumEntry) {
// ordinal() call on explicit enum constant
return true
}
}
val bindingContext = expression.analyze()
if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true
if (expression is KtSimpleNameExpression &&
(parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression)
) {
// zero value is passed as argument to another method or used for array access. Often, such a warning is annoying
return true
}
}
ConstantValue.NULL -> {
if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) {
// initialize other variable with null to copy type, like
// var x1 : X = null
// var x2 = x1 -- let's suppress this
return true
}
if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) {
// like (null as? X)
return true
}
if (parent is KtBinaryExpression) {
val token = parent.operationToken
if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) &&
(parent.left?.isNull() == true || parent.right?.isNull() == true)
) {
// like if (x == null) when 'x' is known to be null: report 'always true' instead
return true
}
}
val kotlinType = expression.getKotlinType()
if (kotlinType.toDfType(expression) == DfTypes.NULL) {
// According to type system, nothing but null could be stored in such an expression (likely "Void?" type)
return true
}
}
else -> {}
}
if (expression is KtSimpleNameExpression) {
val target = expression.mainReference.resolve()
if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) {
// suppress warnings uses of boolean constant like 'val b = true'
return true
}
}
if (isCompilationWarning(expression)) {
return true
}
return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL))
}
private fun isUpdateChain(expression: KtExpression): Boolean {
// x = x or ..., etc.
if (expression !is KtSimpleNameExpression) return false
val binOp = expression.parent as? KtBinaryExpression ?: return false
val op = binOp.operationReference.text
if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false
val assignment = binOp.parent as? KtBinaryExpression ?: return false
if (assignment.operationToken != KtTokens.EQ) return false
val left = assignment.left
if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false
val variable = expression.mainReference.resolve() as? KtProperty ?: return false
val varParent = variable.parent as? KtBlockExpression ?: return false
var context: PsiElement = assignment
var block = context.parent
while (block is KtContainerNode ||
block is KtBlockExpression && block.statements.first() == context ||
block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable)) {
context = block
block = context.parent
}
if (block !== varParent) return false
var curExpression = variable.nextSibling
while (curExpression != context) {
if (hasWritesTo(curExpression, variable)) return false
curExpression = curExpression.nextSibling
}
return true
}
private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean {
return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref ->
val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite
!write
}
}
// Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported
private fun isAlsoChain(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
return isCallToMethod(call, "kotlin", "also")
}
// Do not report x.let { true } or x.let { false } as it's pretty evident
private fun isLetConstant(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
if (!isCallToMethod(call, "kotlin", "let")) return false
val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false
return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression
}
private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean {
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
if (descriptor.name.asString() != methodName) return false
val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return packageFragment.fqName.asString() == packageName
}
private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean {
return when (parent) {
is KtBinaryExpression ->
(parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value)
is KtParenthesizedExpression ->
isAssertion(parent.parent, value)
is KtPrefixExpression ->
parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value)
is KtValueArgument -> {
if (!value) return false
val valueArgList = parent.parent as? KtValueArgumentList ?: return false
val call = valueArgList.parent as? KtCallExpression ?: return false
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
val name = descriptor.name.asString()
if (name != "assert" && name != "require" && name != "check") return false
val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return pkg.fqName.asString() == "kotlin"
}
else -> false
}
}
/**
* Returns true if expression is part of when condition expression that looks like
* ```
* when {
* a && b -> ...
* a && !b -> ...
* }
* ```
* In this case, !b could be reported as 'always true' but such warnings are annoying
*/
private fun isPairingConditionInWhen(expression: KtExpression): Boolean {
val parent = expression.parent
if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) {
var topAnd: KtBinaryExpression = parent
while (true) {
val nextParent = topAnd.parent
if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) {
topAnd = nextParent
} else break
}
val topAndParent = topAnd.parent
if (topAndParent is KtWhenConditionWithExpression) {
val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression
if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) {
return true
}
}
}
return false
}
private fun hasOppositeCondition(whenExpression: KtWhenExpression, topAnd: KtBinaryExpression, expression: KtExpression): Boolean {
for (entry in whenExpression.entries) {
for (condition in entry.conditions) {
if (condition is KtWhenConditionWithExpression) {
val candidate = condition.expression
if (candidate === topAnd) return false
if (isOppositeCondition(candidate, topAnd, expression)) return true
}
}
}
return false
}
private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean {
if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false
val left = candidate.left
val right = candidate.right
if (left == null || right == null) return false
val templateLeft = template.left
val templateRight = template.right
if (templateLeft == null || templateRight == null) return false
if (templateRight === expression) {
return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight)
}
if (!areEquivalent(right, templateRight)) return false
if (templateLeft === expression) {
return areEquivalent(left.negate(false), templateLeft)
}
if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false
return isOppositeCondition(left, templateLeft, expression)
}
private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean {
return PsiEquivalenceUtil.areElementsEquivalent(e1, e2,
{ref1, ref2 -> ref1.element.text.compareTo(ref2.element.text)},
null, null, false)
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
// Non-JVM is not supported now
if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR
return namedFunctionVisitor(fun(function) {
val body = function.bodyExpression ?: function.bodyBlockExpression ?: return
val factory = DfaValueFactory(holder.project)
processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory)))
})
}
private fun processDataflowAnalysis(
factory: DfaValueFactory,
body: KtExpression,
holder: ProblemsHolder,
states: Collection<DfaMemoryState>
) {
val flow = KtControlFlowBuilder(factory, body).buildFlow() ?: return
val listener = KotlinDfaListener()
val interpreter = StandardDataFlowInterpreter(flow, listener)
if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return
reportProblems(listener, holder)
for ((closure, closureStates) in interpreter.closures.entrySet()) {
if (closure is KtExpression) {
processDataflowAnalysis(factory, closure, holder, closureStates)
}
}
}
private fun reportProblems(
listener: KotlinDfaListener,
holder: ProblemsHolder
) {
listener.constantConditions.forEach { (anchor, cv) ->
if (cv != ConstantValue.UNKNOWN) {
when (anchor) {
is KotlinExpressionAnchor -> {
val expr = anchor.expression
if (!shouldSuppress(cv, expr)) {
val key = when (cv) {
ConstantValue.TRUE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.true"
else if (logicalChain(expr))
"inspection.message.condition.always.true.when.reached"
else
"inspection.message.condition.always.true"
ConstantValue.FALSE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.false"
else if (logicalChain(expr))
"inspection.message.condition.always.false.when.reached"
else
"inspection.message.condition.always.false"
ConstantValue.NULL -> "inspection.message.value.always.null"
ConstantValue.ZERO -> "inspection.message.value.always.zero"
else -> throw IllegalStateException("Unexpected constant: $cv")
}
val highlightType =
if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING
else ProblemHighlightType.GENERIC_ERROR_OR_WARNING
holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType)
}
}
is KotlinWhenConditionAnchor -> {
val condition = anchor.condition
if (!shouldSuppressWhenCondition(cv, condition)) {
val key = if (cv == ConstantValue.TRUE) "inspection.message.when.condition.always.true"
else "inspection.message.when.condition.always.false"
holder.registerProblem(condition, KotlinBundle.message(key))
}
}
is KotlinForVisitedAnchor -> {
if (cv == ConstantValue.FALSE) {
val message = KotlinBundle.message("inspection.message.for.never.visited")
holder.registerProblem(anchor.forExpression.loopRange!!, message)
}
}
}
}
}
listener.problems.forEach { (problem, state) ->
if (state == ThreeState.YES) {
when (problem) {
is KotlinArrayIndexProblem ->
holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds"))
is KotlinNullCheckProblem -> {
val expr = problem.expr
if (expr.baseExpression?.isNull() != true) {
holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail"))
}
}
is KotlinCastProblem -> {
val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast
if (!isCompilationWarning(anchor)) {
holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail"))
}
}
}
}
}
}
private fun shouldReportAsValue(expr: KtExpression) =
expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression
private fun logicalChain(expr: KtExpression): Boolean {
var context = expr
var parent = context.parent
while (parent is KtParenthesizedExpression) {
context = parent
parent = context.parent
}
if (parent is KtBinaryExpression && parent.right == context) {
val token = parent.operationToken
return token == KtTokens.ANDAND || token == KtTokens.OROR
}
return false
}
private fun isCompilationWarning(anchor: KtElement): Boolean
{
val context = anchor.analyze(BodyResolveMode.FULL)
if (context.diagnostics.forElement(anchor).any
{ it.factory == Errors.CAST_NEVER_SUCCEEDS
|| it.factory == Errors.SENSELESS_COMPARISON
|| it.factory == Errors.SENSELESS_NULL_IN_WHEN
|| it.factory == Errors.USELESS_IS_CHECK
|| it.factory == Errors.DUPLICATE_LABEL_IN_WHEN }
) {
return true
}
val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache()
return suppressionCache.isSuppressed(anchor, "CAST_NEVER_SUCCEEDS", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, "SENSELESS_COMPARISON", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, "USELESS_IS_CHECK", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING)
}
private fun shouldSuppressWhenCondition(
cv: ConstantValue,
condition: KtWhenCondition
): Boolean {
if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true
if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true
if (condition.textLength == 0) return true
return isCompilationWarning(condition)
}
private fun isLastCondition(condition: KtWhenCondition): Boolean {
val entry = condition.parent as? KtWhenEntry ?: return false
val whenExpr = entry.parent as? KtWhenExpression ?: return false
if (entry.conditions.last() == condition) {
val entries = whenExpr.entries
val lastEntry = entries.last()
if (lastEntry == entry) return true
val size = entries.size
// Also, do not report the always reachable entry right before 'else',
// usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise
if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true
}
return false
}
} | apache-2.0 | 5ff7bcfb1c06e472890e038f3d5c7a22 | 50.507937 | 158 | 0.608883 | 5.634686 | false | false | false | false |
android/compose-samples | Jetcaster/app/src/main/java/com/example/jetcaster/ui/theme/Shape.kt | 1 | 961 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetcaster.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val JetcasterShapes = Shapes(
small = RoundedCornerShape(percent = 50),
medium = RoundedCornerShape(size = 8.dp),
large = RoundedCornerShape(size = 0.dp)
)
| apache-2.0 | b2a8b234b4bcb99d9fdb2acaa99b47f2 | 34.592593 | 75 | 0.754422 | 4.178261 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/util/Jarvis.kt | 1 | 1227 | package org.runestar.client.api.util
import java.awt.Point
import java.awt.Shape
import java.awt.geom.Path2D
object Jarvis {
fun convexHull(points: List<Point>): Shape {
val ch = Path2D.Float()
if (points.isEmpty()) {
return ch
}
val leftMost = checkNotNull(points.minWith(leftMostComparator))
ch.moveTo(leftMost.x.toFloat(), leftMost.y.toFloat())
var curr = leftMost
do {
var next = points[0]
for (i in 1..points.lastIndex) {
val p = points[i]
val orientation = orientation(curr, p, next)
if (orientation > 0 || (orientation == 0 && curr.distance(p) > curr.distance(next))) {
next = p
}
}
curr = next
ch.lineTo(curr.x.toFloat(), curr.y.toFloat())
} while (curr != leftMost)
ch.closePath()
return ch
}
private val leftMostComparator: Comparator<Point> = Comparator.comparingInt<Point> { it.x }
.thenComparingInt { it.y }
private fun orientation(p: Point, q: Point, r: Point): Int {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
}
} | mit | e98e9bd4f676a71cdb0f77cf2e365836 | 30.487179 | 102 | 0.536267 | 3.651786 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/ChecklistItemFormView.kt | 1 | 4135 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.OnChangeTextWatcher
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.ui.helpers.bindView
class ChecklistItemFormView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val button: ImageButton by bindView(R.id.button)
private val editText: AppCompatEditText by bindView(R.id.edit_text)
internal val dragGrip: View by bindView(R.id.drag_grip)
var item: ChecklistItem = ChecklistItem()
set(value) {
field = value
editText.setText(item.text)
}
var tintColor: Int = context.getThemeColor(R.attr.taskFormTint)
var textChangedListener: ((String) -> Unit)? = null
var animDuration = 0L
var isAddButton: Boolean = true
set(value) {
// Button is only clickable when it is *not* an add button (ie when it is a delete button),
// so make screenreaders skip it when it is an add button.
button.importantForAccessibility =
if (value) View.IMPORTANT_FOR_ACCESSIBILITY_NO
else View.IMPORTANT_FOR_ACCESSIBILITY_YES
if (field == value) {
return
}
field = value
editText.hint = context.getString(if (value) R.string.new_checklist_item else R.string.checklist_text)
val rotate = if (value) {
dragGrip.visibility = View.GONE
RotateAnimation(135f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
} else {
dragGrip.visibility = View.VISIBLE
RotateAnimation(0f, 135f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
}
rotate.duration = animDuration
rotate.interpolator = LinearInterpolator()
rotate.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) { /* no-on */ }
override fun onAnimationEnd(animation: Animation?) {
button.rotation = if (value) {
0f
} else {
135f
}
}
override fun onAnimationStart(animation: Animation?) { /* no-on */ }
})
button.startAnimation(rotate)
}
init {
minimumHeight = 38.dpToPx(context)
inflate(R.layout.task_form_checklist_item, true)
background = context.getDrawable(R.drawable.layout_rounded_bg_task_form)
background.mutate().setTint(ContextCompat.getColor(context, R.color.taskform_gray))
gravity = Gravity.CENTER_VERTICAL
button.setOnClickListener {
if (!isAddButton) {
(parent as? ViewGroup)?.removeView(this)
}
}
// It's ok to make the description always be 'Delete ..' because when this button is
// a plus button we set it as 'unimportant for accessibility' so it can't be focused.
button.contentDescription = context.getString(R.string.delete_checklist_entry)
button.drawable.mutate().setTint(tintColor)
editText.addTextChangedListener(OnChangeTextWatcher { s, _, _, _ ->
item.text = s.toString()
textChangedListener?.let { it(s.toString()) }
})
editText.labelFor = button.id
}
} | gpl-3.0 | 37b2b884773938110ba4e3f158b3e0bf | 39.54902 | 110 | 0.677146 | 4.451023 | false | false | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/roots/AutomaticModuleUnloaderTest.kt | 1 | 7566 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.roots
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.UsefulTestCase.assertSameElements
import com.intellij.util.io.systemIndependentPath
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
@RunsInEdt
class AutomaticModuleUnloaderTest {
@Rule
@JvmField
val tempDir = TemporaryDirectory()
@JvmField
@Rule
val disposableRule = DisposableRule()
@Test
fun `unload simple module`() {
val project = createProject()
createModule(project, "a")
createModule(project, "b")
val moduleManager = ModuleManager.getInstance(project)
moduleManager.setUnloadedModules(listOf("a"))
createModule(project, "c")
val moduleFiles = createNewModuleFiles(listOf("d")) {}
val newProject = reloadProjectWithNewModules(project, moduleFiles)
assertSameElements(ModuleManager.getInstance(newProject).unloadedModuleDescriptions.map { it.name }, "a", "d")
}
@Test
fun `unload modules with dependencies between them`() {
val project = createProject()
createModule(project, "a")
createModule(project, "b")
doTest(project, "a", listOf("c", "d"), { modules ->
ModuleRootModificationUtil.updateModel(modules.getValue("c")) {
it.addModuleOrderEntry(modules.getValue("d"))
}
}, "a", "c", "d")
}
@Test
fun `do not unload module if loaded module depends on it`() {
val project = createProject()
createModule(project, "a")
val b = createModule(project, "b")
ModuleRootModificationUtil.updateModel(b) {
it.addInvalidModuleEntry("d")
}
doTest(project, "a", listOf("d"), {}, "a")
}
@Test
fun `unload module if only unloaded module depends on it`() {
val project = createProject()
val a = createModule(project, "a")
createModule(project, "b")
ModuleRootModificationUtil.updateModel(a) {
it.addInvalidModuleEntry("d")
}
doTest(project, "a", listOf("d"), {}, "a", "d")
}
@Test
fun `do not unload modules if loaded module depends on them transitively`() {
val project = createProject()
createModule(project, "a")
val b = createModule(project, "b")
ModuleRootModificationUtil.updateModel(b) {
it.addInvalidModuleEntry("d")
}
doTest(project, "a", listOf("c", "d"), { modules ->
ModuleRootModificationUtil.updateModel(modules.getValue("d")) {
it.addModuleOrderEntry(modules.getValue("c"))
}
}, "a")
}
@Test
fun `unload module if loaded module transitively depends on it via previously unloaded module`() {
val project = createProject()
val a = createModule(project, "a")
val b = createModule(project, "b")
ModuleRootModificationUtil.addDependency(a, b)
ModuleRootModificationUtil.updateModel(b) {
it.addInvalidModuleEntry("c")
}
doTest(project, "b", listOf("c"), {}, "b", "c")
}
@Test
fun `deleted iml file`() {
val project = createProject()
createModule(project, "a")
createModule(project, "b")
val deletedIml = createModule(project, "deleted")
val moduleManager = ModuleManager.getInstance(project)
moduleManager.setUnloadedModules(listOf("a"))
createModule(project, "c")
val moduleFiles = createNewModuleFiles(listOf("d")) {}
val deletedImlFile = File(deletedIml.moduleFilePath)
val newProject = reloadProjectWithNewModules(project, moduleFiles) {
deletedImlFile.delete()
}
assertSameElements(ModuleManager.getInstance(newProject).unloadedModuleDescriptions.map { it.name }, "a", "d")
}
private fun doTest(project: Project,
initiallyUnloaded: String,
newModulesName: List<String>,
setup: (Map<String, Module>) -> Unit,
vararg expectedUnloadedModules: String) {
val moduleManager = ModuleManager.getInstance(project)
moduleManager.setUnloadedModules(listOf(initiallyUnloaded))
val moduleFiles = createNewModuleFiles(newModulesName, setup)
val newProject = reloadProjectWithNewModules(project, moduleFiles)
assertSameElements(ModuleManager.getInstance(newProject).unloadedModuleDescriptions.map { it.name }, *expectedUnloadedModules)
}
private fun createProject(): Project {
return ProjectManager.getInstance().createProject(null, tempDir.newPath("automaticReloaderTest").systemIndependentPath)!!
}
private fun createModule(project: Project, moduleName: String): Module {
return runWriteAction { ModuleManager.getInstance(project).newModule("${project.basePath}/$moduleName.iml", "JAVA") }
}
private fun createNewModuleFiles(moduleNames: List<String>, setup: (Map<String, Module>) -> Unit): List<File> {
val newModulesProjectDir = tempDir.newPath("newModules").toFile()
val moduleFiles = moduleNames.map { File(newModulesProjectDir, "$it.iml") }
val project = ProjectManager.getInstance().createProject("newModules", newModulesProjectDir.absolutePath)!!
try {
runWriteAction {
moduleFiles.map {
ModuleManager.getInstance(project).newModule(it.absolutePath, StdModuleTypes.JAVA.id)
}
}
setup(ModuleManager.getInstance(project).modules.associateBy { it.name })
}
finally {
saveAndCloseProject(project)
}
return moduleFiles
}
private fun saveAndCloseProject(project: Project) {
PlatformTestUtil.saveProject(project, true)
ProjectManagerEx.getInstanceEx().forceCloseProject(project)
}
private fun reloadProjectWithNewModules(project: Project, moduleFiles: List<File>, beforeReload: () -> Unit = {}): Project {
saveAndCloseProject(project)
val modulesXmlFile = File(project.basePath, ".idea/modules.xml")
val rootElement = JDOMUtil.load(modulesXmlFile)
val moduleRootComponent = JDomSerializationUtil.findComponent(rootElement, ModuleManagerImpl.COMPONENT_NAME)
val modulesTag = moduleRootComponent!!.getChild("modules")!!
moduleFiles.forEach {
val filePath = it.systemIndependentPath
val fileUrl = VfsUtil.pathToUrl(filePath)
modulesTag.addContent(Element("module").setAttribute("fileurl", fileUrl).setAttribute("filepath", filePath))
}
JDOMUtil.write(rootElement, modulesXmlFile)
beforeReload()
val reloaded = ProjectManager.getInstance().loadAndOpenProject(project.basePath!!)!!
Disposer.register(disposableRule.disposable, Disposable { ProjectManagerEx.getInstanceEx().forceCloseProject(reloaded) })
return reloaded
}
companion object {
@ClassRule
@JvmField
val appRule = ApplicationRule()
@ClassRule
@JvmField
val edtRule = EdtRule()
}
} | apache-2.0 | 74a3714fe298c4c5eb2ca8b791baa8b1 | 35.379808 | 140 | 0.722178 | 4.560579 | false | true | false | false |
JetBrains/xodus | crypto/src/main/kotlin/jetbrains/exodus/crypto/convert/ArchiveEncryptListenerFactory.kt | 1 | 2893 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 jetbrains.exodus.crypto.convert
import mu.KLogging
import org.apache.commons.compress.archivers.ArchiveOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import java.io.IOException
object ArchiveEncryptListenerFactory : KLogging() {
fun newListener(archive: ArchiveOutputStream): EncryptListener {
return when (archive) {
is TarArchiveOutputStream -> {
object : EncryptListener {
override fun onFile(header: FileHeader) {
logger.debug { "Start file $header" }
val entry = TarArchiveEntry(header.path + header.name)
entry.size = header.size
entry.setModTime(header.timestamp)
archive.putArchiveEntry(entry)
}
override fun onFileEnd(header: FileHeader) {
archive.closeArchiveEntry()
}
override fun onData(header: FileHeader, size: Int, data: ByteArray) {
archive.write(data, 0, size)
}
}
}
is ZipArchiveOutputStream -> {
object : EncryptListener {
override fun onFile(header: FileHeader) {
logger.debug { "Start file $header" }
val entry = ZipArchiveEntry(header.path + header.name)
entry.size = header.size
entry.time = header.timestamp
archive.putArchiveEntry(entry)
}
override fun onFileEnd(header: FileHeader) {
archive.closeArchiveEntry()
}
override fun onData(header: FileHeader, size: Int, data: ByteArray) {
archive.write(data, 0, size)
}
}
}
else -> throw IOException("Unknown archive output stream")
}
}
}
| apache-2.0 | 19fd1c6afc93122233de404c7da37bba | 40.328571 | 89 | 0.583823 | 5.269581 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/ParagraphIntegrationLineHeightStyleTest.kt | 3 | 38843 | /*
* 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.compose.ui.text
import android.graphics.Paint.FontMetricsInt
import androidx.compose.ui.text.android.style.lineHeight
import androidx.compose.ui.text.font.toFontFamily
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.LineHeightStyle.Trim
import androidx.compose.ui.text.style.LineHeightStyle.Alignment
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.sp
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlin.math.abs
import kotlin.math.ceil
@RunWith(AndroidJUnit4::class)
@SmallTest
@OptIn(ExperimentalTextApi::class)
class ParagraphIntegrationLineHeightStyleTest {
private val fontFamilyMeasureFont = FontTestData.BASIC_MEASURE_FONT.toFontFamily()
private val context = InstrumentationRegistry.getInstrumentation().context
private val defaultDensity = Density(density = 1f)
private val fontSize = 10.sp
private val lineHeight = 20.sp
private val fontSizeInPx = with(defaultDensity) { fontSize.toPx() }
private val lineHeightInPx = with(defaultDensity) { lineHeight.toPx() }
/* single line even */
@Test
fun singleLine_even_trim_None() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_even_trim_LastLineBottom() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_even_trim_FirstLineTop() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_even_trim_Both() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(defaultFontMetrics.lineHeight())
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
/* single line top */
@Test
fun singleLine_top_trim_None() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_top_trim_LastLineBottom() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(defaultFontMetrics.descent)
}
}
@Test
fun singleLine_top_trim_FirstLineTop() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_top_trim_Both() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(defaultFontMetrics.lineHeight())
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
/* single line bottom */
@Test
fun singleLine_bottom_trim_None() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_bottom_trim_LastLineBottom() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent - diff)
assertThat(getLineDescent(0)).isEqualTo(defaultFontMetrics.descent)
}
}
@Test
fun singleLine_bottom_trim_FirstLineTop() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_bottom_trim_Both() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(defaultFontMetrics.lineHeight())
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
/* single line proportional */
@Test
fun singleLine_proportional_trim_None() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_proportional_trim_LastLineBottom() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - descentDiff)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_proportional_trim_FirstLineTop() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - ascentDiff)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
@Test
fun singleLine_proportional_trim_Both() {
val paragraph = singleLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(defaultFontMetrics.lineHeight())
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
}
}
/* multi line even */
@Test
fun multiLine_even_trim_None() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
for (line in 0 until lineCount) {
assertThat(getLineHeight(line)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(line)).isEqualTo(expectedAscent)
assertThat(getLineDescent(line)).isEqualTo(expectedDescent)
}
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_even_trim_LastLineBottom() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_even_trim_FirstLineTop() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_even_trim_Both() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Center
)
val defaultFontMetrics = defaultFontMetrics()
val diff = (lineHeightInPx - defaultFontMetrics.lineHeight()) / 2
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
/* multi line top */
@Test
fun multiLine_top_trim_None() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_top_trim_LastLineBottom() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_top_trim_FirstLineTop() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_top_trim_Both() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Top
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent
val expectedDescent = defaultFontMetrics.descent + diff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
/* multi line bottom */
@Test
fun multiLine_bottom_trim_None() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_bottom_trim_LastLineBottom() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_bottom_trim_FirstLineTop() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_bottom_trim_Both() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Bottom
)
val defaultFontMetrics = defaultFontMetrics()
val diff = lineHeightInPx - defaultFontMetrics.lineHeight()
val expectedAscent = defaultFontMetrics.ascent - diff
val expectedDescent = defaultFontMetrics.descent
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - diff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
/* multi line proportional */
@Test
fun multiLine_proportional_trim_None() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.None,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_proportional_trim_LastLineBottom() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.LastLineBottom,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(0)).isEqualTo(expectedAscent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - descentDiff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_proportional_trim_FirstLineTop() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.FirstLineTop,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - ascentDiff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(expectedDescent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun multiLine_proportional_trim_Both() {
val paragraph = multiLineParagraph(
lineHeightTrim = Trim.Both,
lineHeightAlignment = Alignment.Proportional
)
val defaultFontMetrics = defaultFontMetrics()
val descentDiff = proportionalDescentDiff(defaultFontMetrics)
val ascentDiff = defaultFontMetrics.lineHeight() - descentDiff
val expectedAscent = defaultFontMetrics.ascent - ascentDiff
val expectedDescent = defaultFontMetrics.descent + descentDiff
with(paragraph) {
assertThat(getLineHeight(0)).isEqualTo(lineHeightInPx - ascentDiff)
assertThat(getLineAscent(0)).isEqualTo(defaultFontMetrics.ascent)
assertThat(getLineDescent(0)).isEqualTo(expectedDescent)
assertThat(getLineHeight(1)).isEqualTo(lineHeightInPx)
assertThat(getLineAscent(1)).isEqualTo(expectedAscent)
assertThat(getLineDescent(1)).isEqualTo(expectedDescent)
assertThat(getLineHeight(2)).isEqualTo(lineHeightInPx - descentDiff)
assertThat(getLineAscent(2)).isEqualTo(expectedAscent)
assertThat(getLineDescent(2)).isEqualTo(defaultFontMetrics.descent)
assertThat(getLineBaseline(1) - getLineBaseline(0)).isEqualTo(lineHeightInPx)
assertThat(getLineBaseline(2) - getLineBaseline(1)).isEqualTo(lineHeightInPx)
}
}
@Test
fun lastLineEmptyTextHasSameLineHeightAsNonEmptyText() {
assertEmptyLineMetrics("", "a")
assertEmptyLineMetrics("\n", "a\na")
assertEmptyLineMetrics("a\n", "a\na")
assertEmptyLineMetrics("\na", "a\na")
assertEmptyLineMetrics("\na\na", "a\na\na")
assertEmptyLineMetrics("a\na\n", "a\na\na")
}
private fun assertEmptyLineMetrics(textWithEmptyLine: String, textWithoutEmptyLine: String) {
val textStyle = TextStyle(
lineHeightStyle = LineHeightStyle(
trim = Trim.None,
alignment = Alignment.Proportional
),
platformStyle = @Suppress("DEPRECATION") PlatformTextStyle(
includeFontPadding = false
)
)
val paragraphWithEmptyLastLine = simpleParagraph(
text = textWithEmptyLine,
style = textStyle
) as AndroidParagraph
val otherParagraph = simpleParagraph(
text = textWithoutEmptyLine,
style = textStyle
) as AndroidParagraph
with(paragraphWithEmptyLastLine) {
for (line in 0 until lineCount) {
assertThat(height).isEqualTo(otherParagraph.height)
assertThat(getLineTop(line)).isEqualTo(otherParagraph.getLineTop(line))
assertThat(getLineBottom(line)).isEqualTo(otherParagraph.getLineBottom(line))
assertThat(getLineHeight(line)).isEqualTo(otherParagraph.getLineHeight(line))
assertThat(getLineAscent(line)).isEqualTo(otherParagraph.getLineAscent(line))
assertThat(getLineDescent(line)).isEqualTo(otherParagraph.getLineDescent(line))
assertThat(getLineBaseline(line)).isEqualTo(otherParagraph.getLineBaseline(line))
}
}
}
private fun singleLineParagraph(
lineHeightTrim: Trim,
lineHeightAlignment: Alignment,
text: String = "AAA"
): AndroidParagraph {
val textStyle = TextStyle(
lineHeightStyle = LineHeightStyle(
trim = lineHeightTrim,
alignment = lineHeightAlignment
)
)
val paragraph = simpleParagraph(
text = text,
style = textStyle,
width = text.length * fontSizeInPx
) as AndroidParagraph
assertThat(paragraph.lineCount).isEqualTo(1)
return paragraph
}
@Suppress("DEPRECATION")
private fun multiLineParagraph(
lineHeightTrim: Trim,
lineHeightAlignment: Alignment,
): AndroidParagraph {
val lineCount = 3
val word = "AAA"
val text = "AAA".repeat(lineCount)
val textStyle = TextStyle(
lineHeightStyle = LineHeightStyle(
trim = lineHeightTrim,
alignment = lineHeightAlignment
),
platformStyle = @Suppress("DEPRECATION") PlatformTextStyle(
includeFontPadding = false
)
)
val paragraph = simpleParagraph(
text = text,
style = textStyle,
width = word.length * fontSizeInPx
) as AndroidParagraph
assertThat(paragraph.lineCount).isEqualTo(lineCount)
return paragraph
}
private fun simpleParagraph(
text: String = "",
style: TextStyle? = null,
maxLines: Int = Int.MAX_VALUE,
ellipsis: Boolean = false,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
width: Float = Float.MAX_VALUE
): Paragraph {
return Paragraph(
text = text,
spanStyles = spanStyles,
style = TextStyle(
fontFamily = fontFamilyMeasureFont,
fontSize = fontSize,
lineHeight = lineHeight,
platformStyle = @Suppress("DEPRECATION") PlatformTextStyle(
includeFontPadding = false
)
).merge(style),
maxLines = maxLines,
ellipsis = ellipsis,
constraints = Constraints(maxWidth = width.ceilToInt()),
density = defaultDensity,
fontFamilyResolver = UncachedFontFamilyResolver(context)
)
}
private fun defaultFontMetrics(): FontMetricsInt {
return (simpleParagraph() as AndroidParagraph).paragraphIntrinsics.textPaint.fontMetricsInt
}
private fun proportionalDescentDiff(fontMetrics: FontMetricsInt): Int {
val ascent = abs(fontMetrics.ascent.toFloat())
val ascentRatio = ascent / fontMetrics.lineHeight()
return ceil(fontMetrics.lineHeight() * (1f - ascentRatio)).toInt()
}
} | apache-2.0 | f67ec5f3b5ebd708d23856d34c432da9 | 38.84 | 99 | 0.672528 | 5.271851 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToStarProjectionFix.kt | 3 | 5359 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.intentions.typeArguments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.checker.SimpleClassicTypeSystemContext.isArrayOrNullableArray
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ChangeToStarProjectionFix(element: KtTypeElement) : KotlinQuickFixAction<KtTypeElement>(element) {
override fun getFamilyName() = KotlinBundle.message("fix.change.to.star.projection.family")
override fun getText(): String {
val element = this.element
return when {
element != null -> {
val type = element.typeArgumentsAsTypes.joinToString { "*" }
KotlinBundle.message("fix.change.to.star.projection.text", "<$type>")
}
else -> null
} ?: ""
}
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val star = KtPsiFactory(file).createStar()
element.typeArgumentsAsTypes.forEach { it?.replace(star) }
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val psiElement = diagnostic.psiElement
// We don't suggest this quick-fix for array instance checks because there is ConvertToIsArrayOfCallFix
if (psiElement.parent is KtIsExpression && diagnostic.isArrayInstanceCheck() && psiElement.isOnJvm()) return null
val binaryExpr = psiElement.getNonStrictParentOfType<KtBinaryExpressionWithTypeRHS>()
val typeReference = binaryExpr?.right ?: psiElement.getNonStrictParentOfType()
val typeElement = typeReference?.typeElement ?: return null
if (typeElement is KtFunctionType) return null
if (binaryExpr?.operationReference?.isAsKeyword() == true) {
val parent = binaryExpr.getParentOfTypes(
true,
KtValueArgument::class.java,
KtQualifiedExpression::class.java,
KtCallableDeclaration::class.java
)
if (parent is KtCallableDeclaration
&& parent.typeReference.typeArguments().any { it.projectionKind != KtProjectionKind.STAR }
&& typeReference.typeArguments().isNotEmpty()
&& binaryExpr.isUsedAsExpression(binaryExpr.analyze(BodyResolveMode.PARTIAL_WITH_CFA))
) return null
val type = when (parent) {
is KtValueArgument -> {
val callExpr = parent.getStrictParentOfType<KtCallExpression>()
(callExpr?.resolveToCall()?.getArgumentMapping(parent) as? ArgumentMatch)?.valueParameter?.original?.type
}
is KtQualifiedExpression ->
if (KtPsiUtil.safeDeparenthesize(parent.receiverExpression) == binaryExpr)
parent.resolveToCall()?.resultingDescriptor?.extensionReceiverParameter?.value?.original?.type
else
null
else ->
null
}
if (type?.arguments?.any { !it.isStarProjection && !it.type.isTypeParameter() } == true) return null
}
if (typeElement.typeArgumentsAsTypes.isNotEmpty()) {
return ChangeToStarProjectionFix(typeElement)
}
return null
}
private fun Diagnostic.isArrayInstanceCheck(): Boolean =
factory == Errors.CANNOT_CHECK_FOR_ERASED && Errors.CANNOT_CHECK_FOR_ERASED.cast(this).a.isArrayOrNullableArray()
private fun PsiElement.isOnJvm(): Boolean = safeAs<KtElement>()?.platform.isJvm()
private fun KtSimpleNameExpression.isAsKeyword(): Boolean {
val elementType = getReferencedNameElementType()
return elementType == KtTokens.AS_KEYWORD || elementType == KtTokens.AS_SAFE
}
}
}
| apache-2.0 | b1cc4410e9afe0a78beb969e8ba8654d | 49.084112 | 129 | 0.679231 | 5.396777 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/EdgeStorageTest.kt | 22 | 3117 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.impl
import com.intellij.vcs.log.graph.BaseTestGraphBuilder
import com.intellij.vcs.log.graph.BaseTestGraphBuilder.SimpleEdge
import com.intellij.vcs.log.graph.api.EdgeFilter
import com.intellij.vcs.log.graph.api.elements.GraphEdgeType
import com.intellij.vcs.log.graph.asString
import com.intellij.vcs.log.graph.collapsing.EdgeStorage
import com.intellij.vcs.log.graph.collapsing.EdgeStorageWrapper
import com.intellij.vcs.log.graph.utils.sortR
import org.junit.Assert.assertEquals
import org.junit.Test
class EdgeStorageTest : BaseTestGraphBuilder {
private val nodeIdByIndex: (Int) -> Int = { it - 10 }
private val nodeIndexById: (Int) -> Int = { it + 10 }
fun create() = EdgeStorage()
infix fun Int.to(edge: SimpleEdge) = FullEdge(this, edge.toNode, edge.type)
infix fun Int.to(node: Int) = to(node.u)
class FullEdge(val mainId: Int, val additionId: Int?, val edgeType: GraphEdgeType)
operator fun EdgeStorage.plus(edge: FullEdge): EdgeStorage {
createEdge(edge.mainId, edge.additionId ?: EdgeStorage.NULL_ID, edge.edgeType)
return this
}
fun EdgeStorage.remove(edge: FullEdge): EdgeStorage {
removeEdge(edge.mainId, edge.additionId ?: EdgeStorage.NULL_ID, edge.edgeType)
return this
}
infix fun EdgeStorage.assert(s: String) = assertEquals(s, asString())
fun EdgeStorage.asString(): String = knownIds.sortR().map {
adapter.getAdjacentEdges(nodeIndexById(it), EdgeFilter.ALL).map { it.asString() }.joinToString(",")
}.joinToString("|-")
val EdgeStorage.adapter: EdgeStorageWrapper get() = EdgeStorageWrapper(this, nodeIndexById, nodeIdByIndex)
@Test
fun simple() = create() + (1 to 2) assert "11:12:n_U|-11:12:n_U"
@Test
fun dotted() = create() + (1 to 3.dot) assert "11:13:n_D|-11:13:n_D"
@Test
fun not_load() = create() + (1 to (-3).not_load) assert "11:n:-3_N"
@Test
fun not_load_null() = create() + (1 to null.not_load) assert "11:n:n_N"
@Test
fun down_dot() = create() + (1 to 3.down_dot) assert "11:n:3_O"
@Test
fun up_dot() = create() + (1 to 3.up_dot) assert "n:11:3_P"
@Test
fun negativeId() = create() + (-2 to -3) assert "7:8:n_U|-7:8:n_U"
@Test
fun bigId() = create() + (0x7fffff0 to -0x7fffff0) assert "-134217702:134217722:n_U|--134217702:134217722:n_U"
@Test
fun twoEqualEdge() = create() + (1 to 2) + (1 to 2) assert "11:12:n_U|-11:12:n_U"
@Test
fun twoFromOneNode() = create() + (1 to 2) + (1 to 3) assert "11:12:n_U,11:13:n_U|-11:12:n_U|-11:13:n_U"
} | apache-2.0 | ddcc8a94804f5e4c055587aed94c55a8 | 34.431818 | 112 | 0.702919 | 3.092262 | false | true | false | false |
Lizhny/BigDataFortuneTelling | baseuilib/src/main/java/com/bdft/baseuilib/widget/pullrecyclerview/wrapperadapter/FixedViewInfo.kt | 1 | 570 | package com.bdft.baseuilib.widget.pullrecyclerview.wrapperadapter
import android.view.View
/**
* ${}
* Created by spark_lizhy on 2017/11/14.
*/
class FixedViewInfo {
companion object {
/**
* header:-2~-98
*/
val ITEM_VIEW_TYPE_HEADER_START = -2
/**
* footer:-99~-∞
*/
val ITEM_VIEW_TYPE_FOOTER_START = -99
}
var view: View? = null
var itemViewType: Int? = null
constructor(view: View, itemViewType: Int) {
this.view = view
this.itemViewType = itemViewType
}
} | apache-2.0 | 2aa72f4dffb0fb2112bbaca71243b279 | 16.78125 | 65 | 0.572183 | 3.617834 | false | false | false | false |
jagguli/intellij-community | plugins/settings-repository/testSrc/RespositoryHelper.kt | 2 | 2353 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.mock.MockVirtualFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.testFramework.isFile
import gnu.trove.THashSet
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jgit.lib.Constants
import java.nio.file.Files
import java.nio.file.Path
data class FileInfo(val name: String, val data: ByteArray)
fun fs() = MockVirtualFileSystem()
private fun getChildrenStream(path: Path, excludes: Array<out String>? = null) = Files.list(path)
.filter { !it.endsWith(Constants.DOT_GIT) && (excludes == null || !excludes.contains(it.fileName.toString())) }
.sorted()
internal fun compareFiles(path1: Path, path2: Path, path3: VirtualFile? = null, vararg localExcludes: String) {
assertThat(path1).isDirectory()
assertThat(path2).isDirectory()
if (path3 != null) {
assertThat(path3.isDirectory).isTrue()
}
val notFound = THashSet<Path>()
for (path in getChildrenStream(path1, localExcludes)) {
notFound.add(path)
}
for (child2 in getChildrenStream(path2)) {
val fileName = child2.fileName
val child1 = path1.resolve(fileName)
val child3 = path3?.findChild(fileName.toString())
if (child1.isFile()) {
assertThat(child2).hasSameContentAs(child1)
if (child3 != null) {
assertThat(child3.isDirectory).isFalse()
assertThat(child1).hasContent(if (child3 is LightVirtualFile) child3.content.toString() else VfsUtilCore.loadText(child3))
}
}
else {
compareFiles(child1, child2, child3, *localExcludes)
}
notFound.remove(child1)
}
assertThat(notFound).isEmpty()
} | apache-2.0 | fb655a7e511be06ffa38787af51a2578 | 34.134328 | 130 | 0.737782 | 3.876442 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/zeroLambdaParameter.kt | 4 | 257 | val p0: () -> Int = <warning descr="SSR">{ 31 }</warning>
val p1: (Int) -> Int = { x -> x }
val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning>
val p2: (Int, Int) -> Int = { x, y -> x + y }
val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z } | apache-2.0 | 118756b21e6f21618b4f63333218c8c1 | 50.6 | 61 | 0.474708 | 2.424528 | false | false | false | false |
jwren/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/SurroundWithSuggester.kt | 6 | 6803 | package training.featuresSuggester.suggesters
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.suggested.startOffset
import training.featuresSuggester.FeatureSuggesterBundle
import training.featuresSuggester.NoSuggestion
import training.featuresSuggester.SuggesterSupport
import training.featuresSuggester.Suggestion
import training.featuresSuggester.actions.*
import training.util.WeakReferenceDelegator
class SurroundWithSuggester : AbstractFeatureSuggester() {
override val id: String = "Surround with"
override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("surround.with.name")
override val message = FeatureSuggesterBundle.message("surround.with.message")
override val suggestingActionId = "SurroundWith"
override val suggestingTipFileName = "SurroundWith.html"
override val minSuggestingIntervalDays = 14
override val languages = listOf("JAVA", "kotlin")
private object State {
var surroundingStatement: PsiElement? by WeakReferenceDelegator(null)
var surroundingStatementStartOffset: Int = -1
var firstStatementInBlockText: String = ""
var isLeftBraceAdded: Boolean = false
var isRightBraceAdded: Boolean = false
var lastChangeTimeMillis: Long = 0L
var lastTextInsertedAction: EditorTextInsertedAction? by WeakReferenceDelegator(null)
fun applySurroundingStatementAddition(statement: PsiElement, timeMillis: Long) {
reset()
surroundingStatement = statement
surroundingStatementStartOffset = statement.startOffset
lastChangeTimeMillis = timeMillis
}
fun applyBraceAddition(timeMillis: Long, braceType: String) {
lastChangeTimeMillis = timeMillis
if (braceType == "{") {
isLeftBraceAdded = true
}
else {
isRightBraceAdded = true
}
}
fun isOutOfDate(newChangeTimeMillis: Long): Boolean {
return lastChangeTimeMillis != 0L &&
newChangeTimeMillis - lastChangeTimeMillis > MAX_TIME_MILLIS_BETWEEN_ACTIONS
}
fun reset() {
surroundingStatement = null
surroundingStatementStartOffset = -1
firstStatementInBlockText = ""
isLeftBraceAdded = false
isRightBraceAdded = false
lastChangeTimeMillis = 0L
lastTextInsertedAction = null
}
}
@Suppress("NestedBlockDepth")
override fun getSuggestion(action: Action): Suggestion {
val language = action.language ?: return NoSuggestion
val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion
if (action is PsiAction && State.run { surroundingStatementStartOffset != -1 && surroundingStatement?.isValid == false }) {
State.tryToUpdateSurroundingStatement(langSupport, action)
}
when (action) {
is ChildReplacedAction -> {
@Suppress("ComplexCondition")
if (langSupport.isIfStatement(action.newChild) && action.oldChild.text == "i" ||
langSupport.isForStatement(action.newChild) && action.oldChild.text == "fo" ||
langSupport.isWhileStatement(action.newChild) && action.oldChild.text == "whil"
) {
State.applySurroundingStatementAddition(action.newChild, action.timeMillis)
}
}
is ChildAddedAction -> {
if (langSupport.isSurroundingStatement(action.newChild)) {
State.applySurroundingStatementAddition(action.newChild, action.timeMillis)
}
}
is ChildrenChangedAction -> {
if (State.surroundingStatement == null) return NoSuggestion
val textInsertedAction = State.lastTextInsertedAction ?: return NoSuggestion
val text = textInsertedAction.text
if (text.contains("{") || text.contains("}")) {
val psiFile = action.parent as? PsiFile ?: return NoSuggestion
if (State.isOutOfDate(action.timeMillis) || text != "{" && text != "}") {
State.reset()
}
else if (text == "{") {
if (State.isLeftBraceAdded) {
State.reset()
}
else if (State.isBraceAddedToStatement(
langSupport,
psiFile,
textInsertedAction.caretOffset
)
) {
State.applyBraceAddition(action.timeMillis, "{")
State.saveFirstStatementInBlock(langSupport)
}
}
else {
if (State.isLeftBraceAdded &&
State.isBraceAddedToStatement(langSupport, psiFile, textInsertedAction.caretOffset)
) {
State.applyBraceAddition(action.timeMillis, "}")
if (State.isStatementsSurrounded(langSupport)) {
State.reset()
return createSuggestion()
}
}
State.reset()
}
}
}
is EditorTextInsertedAction -> {
State.lastTextInsertedAction = action
}
else -> NoSuggestion
}
return NoSuggestion
}
private fun State.tryToUpdateSurroundingStatement(langSupport: SuggesterSupport, action: PsiAction) {
val element = action.psiFile.findElementAt(surroundingStatementStartOffset) ?: return
val parent = element.parent ?: return
if (langSupport.isSurroundingStatement(parent)) {
surroundingStatement = parent
}
}
private fun State.isBraceAddedToStatement(langSupport: SuggesterSupport, psiFile: PsiFile, offset: Int): Boolean {
val curElement = psiFile.findElementAt(offset) ?: return false
return curElement.parent === langSupport.getCodeBlock(surroundingStatement!!)
}
private fun State.saveFirstStatementInBlock(langSupport: SuggesterSupport) {
val statements = langSupport.getStatementsOfBlock(surroundingStatement!!)
if (statements.isNotEmpty()) {
firstStatementInBlockText = statements.first().text
}
}
private fun State.isStatementsSurrounded(langSupport: SuggesterSupport): Boolean {
if (surroundingStatement?.isValid == false ||
!isLeftBraceAdded ||
!isRightBraceAdded
) {
return false
}
val statements = langSupport.getStatementsOfBlock(surroundingStatement!!)
return statements.isNotEmpty() &&
statements.first().text == firstStatementInBlockText
}
private fun SuggesterSupport.getStatementsOfBlock(psiElement: PsiElement): List<PsiElement> {
val codeBlock = getCodeBlock(psiElement)
return if (codeBlock != null) {
getStatements(codeBlock)
}
else {
emptyList()
}
}
private fun SuggesterSupport.isSurroundingStatement(psiElement: PsiElement): Boolean {
return isIfStatement(psiElement) || isForStatement(psiElement) || isWhileStatement(psiElement)
}
companion object {
const val MAX_TIME_MILLIS_BETWEEN_ACTIONS: Long = 8000L
}
}
| apache-2.0 | 7b5fd69cd08a88f2287d7dc280026e77 | 36.379121 | 127 | 0.687197 | 5.103526 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/StatsOutput.kt | 4 | 4556 | // 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.perf.util
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.jetbrains.kotlin.idea.performance.tests.utils.TeamCity
import org.jetbrains.kotlin.idea.performance.tests.utils.logMessage
import org.jetbrains.kotlin.idea.testFramework.Stats
import org.jetbrains.kotlin.idea.testFramework.suggestOsNeutralFileName
import org.jetbrains.kotlin.test.KotlinRoot
import java.io.BufferedWriter
import java.io.File
internal fun List<Benchmark>.writeCSV(name: String) {
val header = listOf("benchmark", "name", "measurement", "value", "buildId", "timestamp")
fun Benchmark.append(output: BufferedWriter, warmUpValues: Boolean = false) {
fun values(n: String, value: Long?): String? = value?.let {
listOf(
benchmark,
this.name,
n,
value,
buildId?.toString() ?: "",
buildTimestamp
).joinToString()
}
val s = if (warmUpValues) {
val warmUpValue = metrics.firstOrNull { it.metricName == "_value" }?.let { metric ->
metric.rawMetrics?.firstOrNull { it.warmUp == true && it.index == 0 }?.metricValue
}
values(Stats.WARM_UP + " #0", warmUpValue)
} else {
values(Stats.GEOM_MEAN, metricValue)
}
s?.let(output::appendLine)
}
val statsFile = statsFile(name, "csv")
statsFile.bufferedWriter().use { output ->
output.appendLine(header.joinToString())
for (warmUpValue in arrayOf(true, false)) {
filterNot { it.name == Stats.GEOM_MEAN }.forEach { it.append(output, warmUpValues = warmUpValue) }
}
output.flush()
}
}
internal fun Metric.writeTeamCityStats(
name: String,
rawMeasurementName: String = "rawMetrics",
rawMetrics: Boolean = false,
consumer: (String, Long) -> Unit = { propertyName, value ->
TeamCity.statValue(propertyName, value)
}
) {
fun Metric.append(prefix: String, depth: Int) {
val s = if (this.metricName.isEmpty()) {
prefix
} else {
if (depth == 0 && this.metricName != Stats.GEOM_MEAN) "$prefix: ${this.metricName}" else "$prefix ${this.metricName}"
}.trim()
if (s != prefix) {
metricValue?.let {
consumer(s, it)
}
}
metrics?.let { list ->
for (childIndex in list.withIndex()) {
if (!rawMetrics && childIndex.index > 0) break
childIndex.value.append(s, depth + 1)
}
}
}
append(name, 0)
}
internal val kotlinJsonMapper = jacksonObjectMapper()
.registerKotlinModule()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.INDENT_OUTPUT, true)
internal fun Benchmark.statsFile() = statsFile(id(), "json")
internal fun Benchmark.json(): String {
return kotlinJsonMapper.writeValueAsString(this)
}
internal fun Benchmark.writeJson() {
val json = json()
val statsFile = statsFile()
logMessage { "write $statsFile" }
statsFile.bufferedWriter().use { output ->
output.appendLine(json)
output.flush()
}
}
internal fun File.loadBenchmark(): Benchmark = kotlinJsonMapper.readValue(this, object : TypeReference<Benchmark>() {})
internal fun Benchmark.loadJson() {
val statsFile = statsFile()
if (statsFile.exists()) {
val value = kotlinJsonMapper.readValue(statsFile, object : TypeReference<Benchmark>() {})
metrics = value.metrics
}
}
private fun statsFile(name: String, extension: String) =
pathToResource("stats${statFilePrefix(name)}.$extension").absoluteFile
internal fun pathToResource(resource: String) = File(KotlinRoot.REPO, "out/$resource").canonicalFile
internal fun statFilePrefix(name: String) = if (name.isNotEmpty()) "-${plainname(name)}" else ""
internal fun plainname(name: String) = suggestOsNeutralFileName(name)
| apache-2.0 | 6670873e2f06d0e2234b3ed4901cecde | 35.741935 | 158 | 0.660009 | 4.261927 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/classic/inspections/AbstractKotlinInspection.kt | 5 | 2233 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections
import com.intellij.codeInspection.*
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.asJava.unwrapped
abstract class AbstractKotlinInspection : LocalInspectionTool() {
fun ProblemsHolder.registerProblemWithoutOfflineInformation(
element: PsiElement,
@InspectionMessage description: String,
isOnTheFly: Boolean,
highlightType: ProblemHighlightType,
vararg fixes: LocalQuickFix
) {
registerProblemWithoutOfflineInformation(element, description, isOnTheFly, highlightType, null, *fixes)
}
fun ProblemsHolder.registerProblemWithoutOfflineInformation(
element: PsiElement,
@InspectionMessage description: String,
isOnTheFly: Boolean,
highlightType: ProblemHighlightType,
range: TextRange?,
vararg fixes: LocalQuickFix
) {
if (!isOnTheFly && highlightType == ProblemHighlightType.INFORMATION) return
val problemDescriptor = manager.createProblemDescriptor(element, range, description, highlightType, isOnTheFly, *fixes)
registerProblem(problemDescriptor)
}
}
@Suppress("unused")
fun Array<ProblemDescriptor>.registerWithElementsUnwrapped(
holder: ProblemsHolder,
isOnTheFly: Boolean,
quickFixSubstitutor: ((LocalQuickFix, PsiElement) -> LocalQuickFix?)? = null
) {
forEach { problem ->
@Suppress("UNCHECKED_CAST")
val originalFixes = problem.fixes as? Array<LocalQuickFix> ?: LocalQuickFix.EMPTY_ARRAY
val newElement = problem.psiElement.unwrapped ?: return@forEach
val newFixes = quickFixSubstitutor?.let { subst ->
originalFixes.mapNotNull { subst(it, newElement) }.toTypedArray()
} ?: originalFixes
val descriptor =
holder.manager.createProblemDescriptor(newElement, problem.descriptionTemplate, isOnTheFly, newFixes, problem.highlightType)
holder.registerProblem(descriptor)
}
}
| apache-2.0 | 184d77dc6815b364faa924914f1967b2 | 41.132075 | 136 | 0.734886 | 5.367788 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-atdd/src/test/kotlin/org/craftsmenlabs/gareth/atdd/SpringApplicationWrapper.kt | 1 | 4410 | package org.craftsmenlabs.gareth.atdd
import org.craftsmenlabs.gareth.validator.rest.BasicAuthenticationRestClient
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.io.InputStreamReader
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Callable
class SpringApplicationWrapper(val managementUrl: String, val executable: String, val configuration: ConfBuilder) {
enum class Status {
IDLE, STARTING, STARTED, STOPPING, STOPPED;
fun isIdle() = this == IDLE
fun isStarting() = this == STARTING
fun isStarted() = this == STARTED
fun isStopping() = this == STOPPING
fun isStopped() = this == STOPPED
}
private var status: Status = Status.IDLE
private val waitForStartupSeconds = 15L;
private val waitForShutdownSeconds = 5L;
private val log = LoggerFactory.getLogger("SpringApplicationWrapper")
private val restClient = BasicAuthenticationRestClient("user", "secret")
private val startupMonitor = StartupMonitor()
private val shutdownMonitor = ShutDownMonitor()
fun getStatus() = status
fun start() {
if (status != Status.IDLE) {
log.info("Cannot start service. status is $status")
return;
}
status = Status.STARTING
startServer()
try {
waitUntil(waitForStartupSeconds, startupMonitor)
if (status == Status.STARTING) {
throw IllegalStateException("Could not start service within time.")
}
} catch (e: Exception) {
throw IllegalStateException("Failed to start server")
}
log.info("Server is up")
}
private fun startServer() {
val arguments: MutableList<String> = mutableListOf("java", "-jar", executable)
arguments.addAll(configuration.build())
val pBuilder = ProcessBuilder(arguments)
val process = pBuilder.start()
fun readStream(input: InputStream) {
val scanner = Scanner(InputStreamReader(input, Charset.forName("UTF-8")))
StreamMonitor(process, scanner, false).start()
}
readStream(process.inputStream)
readStream(process.errorStream)
if (!process.isAlive) {
throw IllegalStateException("Not started")
}
}
fun shutdown() {
if (status != Status.STARTED) {
log.error("Can only shut down running server, but status is $status")
}
status = Status.STOPPING
try {
waitUntil(waitForShutdownSeconds, shutdownMonitor)
if (status == Status.STOPPING) {
throw IllegalStateException("Could not stop service within time.")
}
} catch (e: Exception) {
throw IllegalStateException("Failed to close server")
}
}
private fun waitUntil(atMost: Long, condition: Callable<Boolean>) {
Thread.sleep(3000)
var counter: Int = 0
while (counter < atMost) {
if (condition.call()) {
break;
}
Thread.sleep(1000)
counter = counter + 1
}
}
inner class StartupMonitor : Callable<Boolean> {
override fun call(): Boolean {
try {
val response = restClient.getAsEntity(JSONObject::class.java, "$managementUrl/mappings")
val isStarted = response != null && response.statusCode.is2xxSuccessful
log.info("Waiting for instance to start: $isStarted")
if (isStarted) {
status = Status.STARTED
}
return isStarted
} catch(e: Exception) {
return false;
}
}
}
inner class ShutDownMonitor : Callable<Boolean> {
override fun call(): Boolean {
try {
val response = restClient.postAsEntity("", JSONObject::class.java, "$managementUrl/shutdown")
log.info("Waiting for instance to shutdown: $response")
val isStopped = response != null && response.statusCode.is2xxSuccessful
if (isStopped) {
status = Status.STOPPED
}
return isStopped
} catch(e: Exception) {
return false;
}
}
}
} | gpl-2.0 | 2bab6a73663ae36a19ddf3ae579e7de3 | 32.416667 | 115 | 0.592063 | 5.051546 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/console/PyExecuteConsoleCustomizer.kt | 9 | 2929 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.console
import com.intellij.execution.ui.ExecutionConsole
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.run.PythonRunConfiguration
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
interface PyExecuteConsoleCustomizer {
companion object {
private val EP_NAME: ExtensionPointName<PyExecuteConsoleCustomizer> =
ExtensionPointName.create("com.jetbrains.python.console.executeCustomizer")
val instance: PyExecuteConsoleCustomizer
get() = EP_NAME.extensionList.first()
}
/**
* Return true if `virtualFile` supports execution in custom run descriptor. This descriptor will be used for executing the whole file
* or a code fragment from it
*/
fun isCustomDescriptorSupported(virtualFile: VirtualFile): Boolean = false
/**
* Return type of a custom run descriptor, which will be used for executing virtualFile or a code fragment from it
*/
fun getCustomDescriptorType(virtualFile: VirtualFile): DescriptorType? = null
/**
* Return existing run descriptor, if a file's custom descriptor type is `DescriptorType.EXISTING`
*/
fun getExistingDescriptor(virtualFile: VirtualFile): RunContentDescriptor? = null
/**
* Update custom descriptor value and type for `virtualFile`
*/
fun updateDescriptor(virtualFile: VirtualFile, type: DescriptorType, descriptor: RunContentDescriptor?) {}
/**
* Notify about new name set for custom run descriptor
*/
fun descriptorNameUpdated(descriptor: RunContentDescriptor, newName: String) {
val console: ExecutionConsole = descriptor.executionConsole
if (console is PythonConsoleView) {
console.setCommandQueueTitle(newName)
}
}
/**
* Return run descriptor name
*/
fun getDescriptorName(descriptor: RunContentDescriptor): String = descriptor.displayName
/**
* Return a run configuration created from the context
*/
fun getContextConfig(dataContext: DataContext): PythonRunConfiguration? = null
/**
* Return true if console is starting and schedule command execution
*/
fun isConsoleStarting(virtualFile: VirtualFile?, commandText: String?): Boolean = false
/**
* Notify that runner started execution, but console process will be started later
*/
fun notifyRunnerStart(virtualFile: VirtualFile, runner: PydevConsoleRunner) {}
fun isHorizontalAndUnitedToolbar(): Boolean = false
fun notifySciCellGutterExecuted(editor: EditorImpl, actionId: String) {}
}
enum class DescriptorType {
NEW, EXISTING, STARTING, NON_INTERACTIVE
} | apache-2.0 | dd85ddaf11f16925a6791914613979ee | 35.17284 | 140 | 0.768863 | 4.930976 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/sign.kt | 1 | 13151 | // 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.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package org.jetbrains.intellij.build.tasks
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import net.schmizz.keepalive.KeepAliveProvider
import net.schmizz.sshj.DefaultConfig
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.SFTPClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.apache.commons.compress.archivers.zip.Zip64Mode
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout
import org.jetbrains.intellij.build.io.NioFileDestination
import org.jetbrains.intellij.build.io.NioFileSource
import org.jetbrains.intellij.build.io.runAsync
import org.jetbrains.intellij.build.io.writeNewFile
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.security.SecureRandom
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import java.util.zip.Deflater
private val random by lazy { SecureRandom() }
// our zip for JARs, but here we need to support file permissions - that's why apache compress is used
fun prepareMacZip(macZip: Path,
sitFile: Path,
productJson: ByteArray,
macAdditionalDir: Path?,
zipRoot: String) {
Files.newByteChannel(macZip, StandardOpenOption.READ).use { sourceFileChannel ->
ZipFile(sourceFileChannel).use { zipFile ->
writeNewFile(sitFile) { targetFileChannel ->
ZipArchiveOutputStream(targetFileChannel).use { out ->
// file is used only for transfer to mac builder
out.setLevel(Deflater.BEST_SPEED)
out.setUseZip64(Zip64Mode.Never)
// exclude existing product-info.json as a custom one will be added
val productJsonZipPath = "$zipRoot/Resources/product-info.json"
zipFile.copyRawEntries(out, ZipArchiveEntryPredicate { it.name != productJsonZipPath })
if (macAdditionalDir != null) {
out.dir(macAdditionalDir, prefix = "$zipRoot/")
}
out.entry(productJsonZipPath, productJson)
}
}
}
}
}
// 0644 octal -> 420 decimal
private const val regularFileMode = 420
// 0777 octal -> 511 decimal
private const val executableFileMode = 511
@Suppress("unused")
fun signMacApp(
host: String,
user: String,
password: String,
codesignString: String,
fullBuildNumber: String,
notarize: Boolean,
bundleIdentifier: String,
appArchiveFile: Path,
jreArchiveFile: Path?,
communityHome: Path,
artifactDir: Path,
dmgImage: Path?,
artifactBuilt: Consumer<Path>,
publishAppArchive: Boolean,
) {
executeTask(host, user, password, "intellij-builds/${fullBuildNumber}") { ssh, sftp, remoteDir ->
tracer.spanBuilder("upload file")
.setAttribute("file", appArchiveFile.toString())
.setAttribute("remoteDir", remoteDir)
.setAttribute("host", host)
.startSpan()
.use {
sftp.put(NioFileSource(appArchiveFile, filePermission = regularFileMode), "$remoteDir/${appArchiveFile.fileName}")
}
if (jreArchiveFile != null) {
tracer.spanBuilder("upload JRE archive")
.setAttribute("file", jreArchiveFile.toString())
.setAttribute("remoteDir", remoteDir)
.setAttribute("host", host)
.startSpan()
.use {
sftp.put(NioFileSource(jreArchiveFile, filePermission = regularFileMode), "$remoteDir/${jreArchiveFile.fileName}")
}
}
val scriptDir = communityHome.resolve("platform/build-scripts/tools/mac/scripts")
tracer.spanBuilder("upload scripts")
.setAttribute("scriptDir", scriptDir.toString())
.setAttribute("remoteDir", remoteDir)
.setAttribute("host", host)
.startSpan().use {
sftp.put(NioFileSource(scriptDir.resolve("entitlements.xml"), filePermission = regularFileMode), "$remoteDir/entitlements.xml")
@Suppress("SpellCheckingInspection")
for (fileName in listOf("sign.sh", "notarize.sh", "signapp.sh", "makedmg.sh", "makedmg.pl")) {
sftp.put(NioFileSource(scriptDir.resolve(fileName), filePermission = executableFileMode), "$remoteDir/$fileName")
}
if (dmgImage != null) {
sftp.put(NioFileSource(dmgImage, filePermission = regularFileMode), "$remoteDir/$fullBuildNumber.png")
}
}
val args = listOf(
appArchiveFile.fileName.toString(),
fullBuildNumber,
user,
password,
codesignString,
jreArchiveFile?.fileName?.toString() ?: "no-jdk",
if (notarize) "yes" else "no",
bundleIdentifier,
publishAppArchive.toString(),
)
val env = System.getenv("ARTIFACTORY_URL")?.takeIf { it.isNotEmpty() }?.let { "ARTIFACTORY_URL=$it " } ?: ""
@Suppress("SpellCheckingInspection")
tracer.spanBuilder("sign mac app").setAttribute("file", appArchiveFile.toString()).startSpan().useWithScope {
signFile(remoteDir = remoteDir,
commandString = "$env'$remoteDir/signapp.sh' '${args.joinToString("' '")}'",
file = appArchiveFile,
ssh = ssh,
ftpClient = sftp,
artifactDir = artifactDir,
artifactBuilt = artifactBuilt)
if (publishAppArchive) {
downloadResult(remoteFile = "$remoteDir/${appArchiveFile.fileName}",
localFile = appArchiveFile,
ftpClient = sftp,
failedToSign = null)
}
}
if (publishAppArchive) {
artifactBuilt.accept(appArchiveFile)
}
if (dmgImage != null) {
val fileNameWithoutExt = appArchiveFile.fileName.toString().removeSuffix(".sit")
val dmgFile = artifactDir.resolve("$fileNameWithoutExt.dmg")
tracer.spanBuilder("build dmg").setAttribute("file", dmgFile.toString()).startSpan().useWithScope {
@Suppress("SpellCheckingInspection")
processFile(localFile = dmgFile,
ssh = ssh,
commandString = "'$remoteDir/makedmg.sh' '${fileNameWithoutExt}' '$fullBuildNumber'",
artifactDir = artifactDir,
artifactBuilt = artifactBuilt,
taskLogClassifier = "dmg")
downloadResult(remoteFile = "$remoteDir/${dmgFile.fileName}",
localFile = dmgFile,
ftpClient = sftp,
failedToSign = null)
artifactBuilt.accept(dmgFile)
}
}
}
}
private fun signFile(remoteDir: String,
file: Path,
ssh: SSHClient,
ftpClient: SFTPClient,
commandString: String,
artifactDir: Path,
artifactBuilt: Consumer<Path>) {
ftpClient.put(NioFileSource(file), "$remoteDir/${file.fileName}")
processFile(localFile = file,
ssh = ssh,
commandString = commandString,
artifactDir = artifactDir,
artifactBuilt = artifactBuilt,
taskLogClassifier = "sign")
}
private fun processFile(localFile: Path,
ssh: SSHClient,
commandString: String,
artifactDir: Path,
artifactBuilt: Consumer<Path>,
taskLogClassifier: String) {
val fileName = localFile.fileName.toString()
val logFile = artifactDir.resolve("macos-logs").resolve("$taskLogClassifier-$fileName.log")
Files.createDirectories(logFile.parent)
ssh.startSession().use { session ->
val command = session.exec(commandString)
try {
// use CompletableFuture because get will call ForkJoinPool.helpAsyncBlocker, so, other tasks in FJP will be executed while waiting
CompletableFuture.allOf(
runAsync { command.inputStream.transferTo(System.out) },
runAsync { Files.copy(command.errorStream, logFile, StandardCopyOption.REPLACE_EXISTING) }
).get(3, TimeUnit.HOURS)
command.join(1, TimeUnit.MINUTES)
}
catch (e: Exception) {
val logFileLocation = if (Files.exists(logFile)) artifactDir.relativize(logFile) else "<internal error - log file is not created>"
throw RuntimeException("SSH command failed, details are available in $logFileLocation: ${e.message}", e)
}
finally {
if (Files.exists(logFile)) {
artifactBuilt.accept(logFile)
}
command.close()
}
if (command.exitStatus != 0) {
throw RuntimeException("SSH command failed, details are available in ${artifactDir.relativize(logFile)}" +
" (exitStatus=${command.exitStatus}, exitErrorMessage=${command.exitErrorMessage})")
}
}
}
private fun downloadResult(remoteFile: String,
localFile: Path,
ftpClient: SFTPClient,
failedToSign: MutableList<Path>?) {
tracer.spanBuilder("download file")
.setAttribute("remoteFile", remoteFile)
.setAttribute("localFile", localFile.toString())
.startSpan()
.use { span ->
val localFileParent = localFile.parent
val tempFile = localFileParent.resolve("${localFile.fileName}.download")
Files.createDirectories(localFileParent)
var attempt = 1
do {
try {
ftpClient.get(remoteFile, NioFileDestination(tempFile))
}
catch (e: Exception) {
span.addEvent("cannot download $remoteFile", Attributes.of(
AttributeKey.longKey("attemptNumber"), attempt.toLong(),
AttributeKey.stringKey("error"), e.toString(),
AttributeKey.stringKey("remoteFile"), remoteFile,
))
attempt++
if (attempt > 3) {
Files.deleteIfExists(tempFile)
if (failedToSign == null) {
throw RuntimeException("Failed to sign file: $localFile")
}
else {
failedToSign.add(localFile)
}
return
}
else {
continue
}
}
break
}
while (true)
if (attempt != 1) {
span.addEvent("file was downloaded", Attributes.of(
AttributeKey.longKey("attemptNumber"), attempt.toLong(),
))
}
Files.move(tempFile, localFile, StandardCopyOption.REPLACE_EXISTING)
}
}
private val initLog by lazy {
System.setProperty("log4j.defaultInitOverride", "true")
val root = Logger.getRootLogger()
if (!root.allAppenders.hasMoreElements()) {
root.level = Level.INFO
root.addAppender(ConsoleAppender(PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN)))
}
}
private fun generateRemoteDirName(remoteDirPrefix: String): String {
val currentDateTimeString = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replace(':', '-')
return "$remoteDirPrefix-$currentDateTimeString-${java.lang.Long.toUnsignedString(random.nextLong(), Character.MAX_RADIX)}"
}
private inline fun executeTask(host: String,
user: String,
password: String,
remoteDirPrefix: String,
task: (ssh: SSHClient, sftp: SFTPClient, remoteDir: String) -> Unit) {
initLog
val config = DefaultConfig()
config.keepAliveProvider = KeepAliveProvider.KEEP_ALIVE
SSHClient(config).use { ssh ->
ssh.addHostKeyVerifier(PromiscuousVerifier())
ssh.connect(host)
ssh.authPassword(user, password)
ssh.newSFTPClient().use { sftp ->
val remoteDir = generateRemoteDirName(remoteDirPrefix)
sftp.mkdir(remoteDir)
try {
task(ssh, sftp, remoteDir)
}
finally {
// as odd as it is, session can only be used once
// https://stackoverflow.com/a/23467751
removeDir(ssh, remoteDir)
}
}
}
}
private fun removeDir(ssh: SSHClient, remoteDir: String) {
tracer.spanBuilder("remove remote dir").setAttribute("remoteDir", remoteDir).startSpan().use {
ssh.startSession().use { session ->
val command = session.exec("rm -rf '$remoteDir'")
command.join(30, TimeUnit.SECONDS)
// must be called before checking exit code
command.close()
if (command.exitStatus != 0) {
throw RuntimeException("cannot remove remote directory (exitStatus=${command.exitStatus}, " +
"exitErrorMessage=${command.exitErrorMessage})")
}
}
}
} | apache-2.0 | c1d027840a415cef6cae362d0d46351c | 37.011561 | 158 | 0.646187 | 4.567906 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/checker/infos/multipleResolvedCalls.kt | 2 | 1109 | // FIR_COMPARISON
interface I1
interface I2
interface I3
interface I4
interface I5
<info descr="null" tooltip="null">operator</info> fun I1.component1() = 1
<info descr="null" tooltip="null">operator</info> fun I2.component2() = 2
<info descr="null" tooltip="null">operator</info> fun I3.component3() = 3
<info descr="null" tooltip="null">operator</info> fun I4.component4() = 4
<info descr="null" tooltip="null">operator</info> fun I5.component5() = 5
fun test(x: Any): Int {
if (x is I1 && x is I2 && x is I3 && x is I4 && x is I5) {
val (t1, t2, t3, t4, t5) = <info descr="Smart cast to I1 (for t1 call)" tooltip="Smart cast to I1 (for t1 call)"><info descr="Smart cast to I2 (for t2 call)" tooltip="Smart cast to I2 (for t2 call)"><info descr="Smart cast to I3 (for t3 call)" tooltip="Smart cast to I3 (for t3 call)"><info descr="Smart cast to I4 (for t4 call)" tooltip="Smart cast to I4 (for t4 call)"><info descr="Smart cast to I5 (for t5 call)" tooltip="Smart cast to I5 (for t5 call)">x</info></info></info></info></info>
return t1 + t2 + t3 + t4 + t5
}
else return 0
}
| apache-2.0 | 32cdd37ca9b3347637ae20a946de3242 | 51.809524 | 501 | 0.658251 | 2.903141 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/projectModel-api/src/com/intellij/util/containers/util.kt | 3 | 4854 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.util.containers
import com.intellij.util.SmartList
import com.intellij.util.lang.CompoundRuntimeException
import gnu.trove.THashSet
import java.util.*
import java.util.stream.Stream
fun <K, V> MutableMap<K, MutableList<V>>.remove(key: K, value: V) {
val list = get(key)
if (list != null && list.remove(value) && list.isEmpty()) {
remove(key)
}
}
fun <K, V> MutableMap<K, MutableList<V>>.putValue(key: K, value: V) {
val list = get(key)
if (list == null) {
put(key, SmartList<V>(value))
}
else {
list.add(value)
}
}
fun Collection<*>?.isNullOrEmpty() = this == null || isEmpty()
inline fun <T, R> Iterator<T>.computeIfAny(processor: (T) -> R): R? {
for (item in this) {
val result = processor(item)
if (result != null) {
return result
}
}
return null
}
inline fun <T, R> Array<T>.computeIfAny(processor: (T) -> R): R? {
for (file in this) {
val result = processor(file)
if (result != null) {
return result
}
}
return null
}
inline fun <T, R> List<T>.computeIfAny(processor: (T) -> R): R? {
for (item in this) {
val result = processor(item)
if (result != null) {
return result
}
}
return null
}
fun <T> List<T>?.nullize() = if (isNullOrEmpty()) null else this
inline fun <T> Array<out T>.forEachGuaranteed(operation: (T) -> Unit): Unit {
var errors: MutableList<Throwable>? = null
for (element in this) {
try {
operation(element)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList()
}
errors.add(e)
}
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
inline fun <T> Collection<T>.forEachGuaranteed(operation: (T) -> Unit): Unit {
var errors: MutableList<Throwable>? = null
for (element in this) {
try {
operation(element)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList()
}
errors.add(e)
}
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
fun <T> Array<T>?.stream(): Stream<T> = if (this != null) Stream.of(*this) else Stream.empty()
fun <T> Stream<T>?.isEmpty(): Boolean = this == null || !this.findAny().isPresent
fun <T> Stream<T>?.notNullize(): Stream<T> = this ?: Stream.empty()
fun <T> Stream<T>?.getIfSingle(): T? =
this?.limit(2)
?.map { Optional.ofNullable(it) }
?.reduce(Optional.empty()) { a, b -> if (a.isPresent xor b.isPresent) b else Optional.empty() }
?.orElse(null)
/**
* There probably could be some performance issues if there is lots of streams to concat. See
* http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010659.html for some details.
*
* Also see [Stream.concat] documentation for other possible issues of concatenating large number of streams.
*/
fun <T> concat(vararg streams: Stream<T>): Stream<T> = Stream.of(*streams).reduce(Stream.empty()) { a, b -> Stream.concat(a, b) }
inline fun MutableList<Throwable>.catch(runnable: () -> Unit) {
try {
runnable()
}
catch (e: Throwable) {
add(e)
}
}
inline fun <T, R> Array<out T>.mapSmart(transform: (T) -> R): List<R> {
val size = size
return when (size) {
1 -> SmartList(transform(this[0]))
0 -> SmartList()
else -> mapTo(ArrayList(size), transform)
}
}
inline fun <T, R> Collection<T>.mapSmart(transform: (T) -> R): List<R> {
val size = size
return when (size) {
1 -> SmartList(transform(first()))
0 -> emptyList()
else -> mapTo(ArrayList(size), transform)
}
}
/**
* Not mutable set will be returned.
*/
inline fun <T, R> Collection<T>.mapSmartSet(transform: (T) -> R): Set<R> {
val size = size
return when (size) {
1 -> {
val result = SmartHashSet<R>()
result.add(transform(first()))
result
}
0 -> emptySet()
else -> mapTo(THashSet(size), transform)
}
}
inline fun <T, R : Any> Collection<T>.mapSmartNotNull(transform: (T) -> R?): List<R> {
val size = size
return if (size == 1) {
transform(first())?.let { SmartList<R>(it) } ?: SmartList<R>()
}
else {
mapNotNullTo(ArrayList<R>(size), transform)
}
}
fun <T> List<T>.toMutableSmartList(): MutableList<T> {
return when (size) {
1 -> SmartList(first())
0 -> SmartList()
else -> ArrayList(this)
}
}
inline fun <T> Collection<T>.filterSmart(predicate: (T) -> Boolean): List<T> {
val result: MutableList<T> = when (size) {
1 -> SmartList()
0 -> return emptyList()
else -> ArrayList()
}
filterTo(result, predicate)
return result
}
inline fun <T> Collection<T>.filterSmartMutable(predicate: (T) -> Boolean): MutableList<T> {
return filterTo(if (size <= 1) SmartList() else ArrayList(), predicate)
} | apache-2.0 | d87a2949903ccdd42818fb9e0338097e | 24.824468 | 140 | 0.621755 | 3.373176 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/commands/PasswordCommand.kt | 1 | 3806 | package glorantq.ramszesz.commands
import glorantq.ramszesz.utils.BotUtils
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IMessage
import java.util.*
import kotlin.concurrent.thread
/**
* Created by glora on 2017. 07. 28..
*/
class PasswordCommand : ICommand {
override val commandName: String
get() = "passwordgen"
override val description: String
get() = "Generate a password"
override val permission: Permission
get() = Permission.USER
override val extendedHelp: String
get() = "Generate a password of random characters and have the bot DM it to you"
override val aliases: List<String>
get() = listOf("pass", "passgen", "pwgen")
override val usage: String
get() = "[Length]"
override val availableInDM: Boolean
get() = true
val characters: CharArray = charArrayOf(
'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'#', '$', '!', '%', '/'
)
override fun execute(event: MessageReceivedEvent, args: List<String>) {
thread(name = "PwGen-${event.author.name}-${System.nanoTime()}", isDaemon = true, start = true) {
var length: Int
if (args.isEmpty()) {
length = 16
} else {
try {
length = args[0].toInt()
} catch (e: NumberFormatException) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "`${args[0]}` is not a valid number", event.author), event.channel)
return@thread
}
}
if(length == 0) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "A zero-length password isn't that secure!", event.author), event.channel)
return@thread
}
if(length < 0) {
length *= -1
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "The number `${args[0]}` is negative, it has been changed to `$length`", event.author), event.channel)
}
if(length > 64) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "The number `${args[0]}` is too large", event.author), event.channel)
return@thread
}
val random: Random = Random((System.nanoTime() * (Math.random() * 100)).toLong())
val builder: StringBuilder = StringBuilder()
for (i: Int in 1..length * 2) {
builder.append(characters[random.nextInt(characters.size)])
}
val finalRandom: Random = Random((System.nanoTime() * (Math.random() * 100)).toLong() * length)
val finalBuilder: StringBuilder = StringBuilder()
for (i: Int in 1..length) {
finalBuilder.append(builder.toString()[finalRandom.nextInt(length * 2)])
}
val message: IMessage = event.author.orCreatePMChannel.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "Your random password is: `$finalBuilder` ($length characters long). This message will disappear in 15 seconds", event.author))
if(!event.channel.isPrivate) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Password Generator", "Alright ${event.author.mention()}, sent you a DM!", event.author), event.channel)
}
Thread.sleep(15 * 1000)
message.edit(BotUtils.createSimpleEmbed("Password Generator", "This password has disappered.", event.author))
}
}
} | gpl-3.0 | 18f073f9e4dfb053ea02eb132b8453ff | 43.788235 | 255 | 0.580399 | 4.325 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/collections/empty.kt | 1 | 1464 | package io.kotest.matchers.collections
import io.kotest.assertions.show.show
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.invokeMatcher
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
fun <T> Iterable<T>?.shouldBeEmpty(): Iterable<T> {
if (this == null) fail()
toList().shouldBeEmpty()
return this
}
fun <T> Array<T>?.shouldBeEmpty(): Array<T> {
if (this == null) fail()
asList().shouldBeEmpty()
return this
}
fun <T> Collection<T>?.shouldBeEmpty(): Collection<T> {
if (this == null) fail()
this should beEmpty()
return this
}
fun <T> Iterable<T>?.shouldNotBeEmpty(): Iterable<T> {
if (this == null) fail()
toList().shouldNotBeEmpty()
return this
}
fun <T> Array<T>?.shouldNotBeEmpty(): Array<T> {
if (this == null) fail()
asList().shouldNotBeEmpty()
return this
}
fun <T> Collection<T>?.shouldNotBeEmpty(): Collection<T> {
if (this == null) fail()
this shouldNot beEmpty()
return this
}
fun <T> beEmpty(): Matcher<Collection<T>> = object : Matcher<Collection<T>> {
override fun test(value: Collection<T>): MatcherResult = MatcherResult(
value.isEmpty(),
{ "Collection should be empty but contained ${value.show().value}" },
{ "Collection should not be empty" }
)
}
private fun fail(): Nothing {
invokeMatcher(null, Matcher.failure("Should be empty but was null"))
throw NotImplementedError()
}
| mit | 5513a235c3d8f407b7410f5672592ed6 | 24.684211 | 77 | 0.681694 | 3.763496 | false | true | false | false |
kiuchikeisuke/Android-Studio-CleanArchitecture-template-forKotlin | CleanArchExample/domain/src/main/kotlin/com/example/domain/utils/commons/UseCase.kt | 1 | 1780 | package com.example.domain.utils.commons
import dagger.internal.Preconditions
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import timber.log.Timber
abstract class UseCase<in Q : UseCase.RequestValue, R : UseCase.ResponseValue, T : Throwable>(private val executionThreads: ExecutionThreads) {
internal abstract fun execute(requestValue: Q): Observable<R>
interface RequestValue
interface ResponseValue
enum class NoRequestValue : RequestValue {
INSTANCE
}
enum class NoResponseValue : ResponseValue {
INSTANCE
}
protected val disposable: CompositeDisposable = CompositeDisposable()
protected val defaultNext: (R) -> Unit = {}
protected val defaultError: (T) -> Unit = { Timber.e(it) }
protected val defaultComplete: () -> Unit = {}
@Suppress("UNCHECKED_CAST")
fun execute(
requestValues: Q,
next: (R) -> Unit = defaultNext,
error: (T) -> Unit = defaultError,
complete: () -> Unit = defaultComplete
): Observable<R> {
disposable.clear()
val observable = execute(requestValues)
.subscribeOn(executionThreads.io())
.observeOn(executionThreads.ui())
addDisposable(observable.subscribe(next, error as (Throwable) -> Unit, complete))
return observable
}
fun dispose() {
if (!disposable.isDisposed) {
disposable.dispose()
}
}
/**
* Dispose from current [CompositeDisposable].
*/
private fun addDisposable(disposable: Disposable) {
Preconditions.checkNotNull(disposable)
Preconditions.checkNotNull(this.disposable)
this.disposable.add(disposable)
}
}
| apache-2.0 | b5c6ec2a59b177d07c1cf186e9f204a9 | 29.169492 | 143 | 0.670225 | 4.836957 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/util/EventFlag.kt | 1 | 1425 | package com.soywiz.kpspemu.util
import com.soywiz.korio.async.*
import kotlin.reflect.*
class EventFlag<T>(val initial: T) {
var value: T = initial
set(value) {
if (field != value) {
field = value
onUpdated(Unit)
}
}
val onUpdated = Signal<Unit>()
suspend fun waitValue(expected: T) {
while (value != expected) onUpdated.waitOne()
}
operator fun getValue(obj: Any?, property: KProperty<*>): T = value
operator fun setValue(obj: Any?, property: KProperty<*>, value: T): Unit = run { this.value = value }
}
suspend fun EventFlag<Int>.waitAllBits(expected: Int) {
while ((value and expected) != expected) onUpdated.waitOne()
}
suspend fun EventFlag<Int>.waitAnyBits(expected: Int) {
while ((value and expected) == 0) onUpdated.waitOne()
}
class EventStatus(val generator: () -> Int) {
private val onUpdated = Signal<Unit>()
val v: Int get() = generator()
operator fun getValue(obj: Any?, property: KProperty<*>): Int = generator()
fun updated() = onUpdated(Unit)
suspend fun waitValue(expected: Int) {
while (v != expected) onUpdated.waitOne()
}
suspend fun waitAllBits(expected: Int) {
while ((v and expected) != expected) onUpdated.waitOne()
}
suspend fun waitAnyBits(expected: Int) {
while ((v and expected) == 0) onUpdated.waitOne()
}
}
| mit | 1216c3077fc15adcc9daa732247b371f | 27.5 | 105 | 0.619649 | 3.90411 | false | false | false | false |
TETRA2000/FloatBehindAndroid | mobile/src/main/java/jp/tetra2000/floatbehindandroid/MainActivity.kt | 1 | 1743 | package jp.tetra2000.floatbehindandroid
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.TextureView
import android.view.View
import android.view.ViewGroup
import org.xwalk.core.XWalkPreferences
import org.xwalk.core.XWalkView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, true)
val rootLayout = findViewById(R.id.container) as ViewGroup
val xWalkWebView = XWalkView(this)
xWalkWebView.setBackgroundColor(Color.TRANSPARENT)
xWalkWebView.load("https://crosswalk-project.org", null)
rootLayout.addView(xWalkWebView)
xWalkWebView.setBackgroundColor(Color.TRANSPARENT)
val tuv = findXWalkTextureView(xWalkWebView)
tuv?.setOpaque(false)
}
private fun findXWalkTextureView(group: ViewGroup): TextureView? {
val childCount = group.childCount
for (i in 0..childCount - 1) {
val child = group.getChildAt(i)
if (child is TextureView) {
val parentClassName = child.getParent().javaClass.toString()
val isRightKindOfParent = parentClassName.contains("XWalk")
if (isRightKindOfParent) {
return child
}
} else if (child is ViewGroup) {
val textureView = findXWalkTextureView(child)
if (textureView != null) {
return textureView
}
}
}
return null
}
}
| mit | 1915a41678d7c43b00e6d7f83239905a | 33.86 | 79 | 0.655192 | 4.635638 | false | false | false | false |
misty000/kotlinfx | kotlinfx-demos/src/main/kotlin/sevenguis/crud/CRUD.kt | 2 | 3431 | package demos.sevenguis.crud
import kotlinfx.properties.*
import kotlinfx.builders.*
import kotlinfx.bindings.*
import kotlinfx.abbreviations.*
import javafx.application.Application
import javafx.stage.Stage
import javafx.scene.control.SelectionMode
import javafx.collections.ObservableList
import javafx.beans.property.SimpleListProperty
import javafx.collections.FXCollections
import java.util.ArrayList
import javafx.beans.value.ChangeListener
import javafx.beans.value.ObservableValue
import javafx.geometry.Pos
import javafx.collections.ListChangeListener
import java.util.function.Predicate
fun main(args: Array<String>) {
Application.launch(javaClass<CRUD>())
}
class CRUD : Application() {
override fun start(stage: Stage?) {
val prefix = TextField { prefWidth = 60.0 }
val name = TextField { prefWidth = 100.0 }
val surname = TextField { prefWidth = 100.0 }
val create = Button("Create")
val update = Button("Update") { disable = true }
val delete = Button("Delete") { disable = true }
val entries = ListView<String>()
entries.selectionModel.selectionMode = SelectionMode.SINGLE
val externDb = arrayListOf("Emil, Hans", "Musterman, Max", "Tisch, Roman")
val db = FXCollections.observableArrayList(externDb)!!
// TODO: Why not anonymous function?
db.addListener(object : ListChangeListener<String> {
override fun onChanged(c: ListChangeListener.Change<out String>) {
while (c.next()) {
if (c.wasReplaced()) externDb.set(c.from, c.getAddedSubList().get(0))
else {
if (c.wasAdded()) externDb.add(c.getAddedSubList().get(0))
if (c.wasRemoved()) externDb.remove(c.from)
}
}
}
})
val dbView = db.filtered { true }
entries.setItems(dbView)
val fullname = surname.textp + ", " + name.textp
val selectedIndex = entries.selectionModel.selectedIndexp
prefix.textp.addListener { v, o, n -> dbView.setPredicate { t -> t.startsWith(n) } }
create.setOnAction { db.add(fullname.v) }
delete.setOnAction { db.remove(dbView.getSourceIndex(selectedIndex.v)) }
update.setOnAction { db.set(dbView.getSourceIndex(selectedIndex.v), fullname.v) }
delete.disablep bind (selectedIndex isEqualTo -1)
update.disablep bind (selectedIndex isEqualTo -1)
Stage(stage, title = "CRUD") {
scene = Scene {
root = BorderPane(padding=Insets(10.0)) {
prefWidth = 400.0
prefHeight = 400.0
top = HBox(spacing=10.0, padding=Insets(bottom=10.0)) {
alignment = Pos.BASELINE_LEFT
+ Label("Filter prefix: ") + prefix
}
center = entries
right = GridPane(padding=Insets(left=10.0)) {
hgap = 10.0
vgap = 10.0
addRow(0, Label("Name: "), name)
addRow(1, Label("Surname: "), surname)
}
bottom = HBox(spacing=10.0, padding=Insets(top=10.0)) {
+ create + update + delete
}
}
}
}.show()
}
}
| mit | bfbb92ce487ac89d3b52ce844916934d | 39.364706 | 92 | 0.579714 | 4.473272 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/notifications/call/IncomingCallNotification.kt | 1 | 3251 | package com.voipgrid.vialer.notifications.call
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.voipgrid.vialer.R.drawable
import com.voipgrid.vialer.R.string
import com.voipgrid.vialer.sip.SipService
class IncomingCallNotification(private val number : String, private val callerId : String) : AbstractCallNotification() {
override val notificationId = 333
/**
* We are creating a new notification channel for incoming calls because they
* will have a different priority to the other notifications.
*
*/
@RequiresApi(Build.VERSION_CODES.O)
override fun buildChannel(context: Context): NotificationChannel {
val channel = NotificationChannel(
CHANNEL_ID,
context.getString(string.notification_channel_incoming_calls),
NotificationManager.IMPORTANCE_HIGH
)
channel.enableVibration(false)
channel.setSound(null, null)
channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
return channel
}
/**
* Create a custom notification builder as we use a custom channel for this
* notification.
*
*/
override fun createNotificationBuilder(): NotificationCompat.Builder {
return NotificationCompat.Builder(context, CHANNEL_ID)
}
override fun applyUniqueNotificationProperties(builder: NotificationCompat.Builder): NotificationCompat.Builder {
return builder.setSmallIcon(drawable.ic_logo)
.setContentTitle(createNotificationTitle())
.setContentText(number)
.setContentIntent(createIncomingCallActivityPendingIntent(number, callerId))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setFullScreenIntent(createIncomingCallActivityPendingIntent(number, callerId), true)
.setLargeIcon(phoneNumberImageGenerator.findWithRoundedCorners(number))
.addAction(
drawable.ic_call_decline_normal,
context.getString(string.call_incoming_decline),
SipService.createSipServiceAction(SipService.Actions.DECLINE_INCOMING_CALL)
)
.addAction(
drawable.ic_call_answer_normal,
context.getString(string.call_incoming_accept),
SipService.createSipServiceAction(SipService.Actions.ANSWER_INCOMING_CALL)
)
.setSound(null)
}
private fun createNotificationTitle() : String {
val display = if (callerId.isEmpty()) number else callerId
return "${context.getString(string.call_incoming_expanded)} $display"
}
companion object {
const val CHANNEL_ID: String = "vialer_incoming_calls"
}
} | gpl-3.0 | 1d9f18b1441bdd854f5aac2561bf5ca2 | 38.180723 | 121 | 0.688096 | 5.260518 | false | false | false | false |
tmarsteel/kotlin-prolog | async/src/test/kotlin/com/github/prologdb/async/WorkableFutureTest.kt | 1 | 11335 | package com.github.prologdb.async
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.longs.beGreaterThanOrEqualTo
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import java.util.UUID
import java.util.concurrent.CompletableFuture
import kotlin.concurrent.thread
class WorkableFutureTest : FreeSpec({
"immediate return" {
val hasRun = CompletableFuture<Unit>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
hasRun.complete(Unit)
"foobar"
}
hasRun.isDone shouldBe false
future.step()
hasRun.isDone shouldBe true
future.isDone shouldBe true
future.get() shouldBe "foobar"
}
"immediate throw" {
val hasRun = CompletableFuture<Unit>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
hasRun.complete(Unit)
throw Exception("Faiiilleeeed!!!")
}
hasRun.isDone shouldBe false
future.step()
hasRun.isDone shouldBe true
shouldThrow<Exception> {
future.get()
}
}
"wait for another future step-by-step successfully" {
val hasStarted = CompletableFuture<Unit>()
val returnedAfterWait = CompletableFuture<Unit>()
val waitingOn = CompletableFuture<String>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
hasStarted.complete(Unit)
val result = await(waitingOn)
returnedAfterWait.complete(Unit)
result
}
// initial state
future.isDone shouldBe false
hasStarted.isDone shouldBe false
returnedAfterWait.isDone shouldBe false
// test that await(T) suspends
future.step()
future.isDone shouldBe false
hasStarted.isDone shouldBe true
returnedAfterWait.isDone shouldBe false
// test that step() does not resume the coroutine
// unless its completed
future.step()
future.isDone shouldBe false
returnedAfterWait.isDone shouldBe false
// test that await() correctly forwards the result
// of the awaited future
val value = "Hello World!!"
waitingOn.complete(value)
// unless step() is called again, the future should
// not move ahead
future.isDone shouldBe false
returnedAfterWait.isDone shouldBe false
future.step()
// completion
future.isDone shouldBe true
returnedAfterWait.isDone shouldBe true
future.get() shouldBe value
}
"wait for another future step-by-step exceptionally" {
val hasStarted = CompletableFuture<Unit>()
val waitingOn = CompletableFuture<String>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
hasStarted.complete(Unit)
try {
await(waitingOn)
Unit
}
catch (ex: Throwable) {
ex
}
}
future.step()
future.isDone shouldBe false
hasStarted.isDone shouldBe true
future.step()
future.isDone shouldBe false
waitingOn.isCompletedExceptionally shouldBe false
val error = Exception("faiiil!")
waitingOn.completeExceptionally(error)
future.isDone shouldBe false
future.isCancelled shouldBe false
future.step()
future.isDone shouldBe true
future.isCancelled shouldBe false
future.get() shouldBe error
}
"await exception should not complete the future" {
val waitingOn = CompletableFuture<Unit>()
val caught = CompletableFuture<Throwable>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
try {
await(waitingOn)
}
catch (ex: Throwable) {
caught.complete(ex)
}
"All fine"
}
val error = Exception("faaaaaaiiiilllllllll")
future.step()
waitingOn.completeExceptionally(error)
future.step()
caught.isDone shouldBe true
caught.get() shouldBe error
future.get() shouldBe "All fine"
}
"await completed does not suspend" {
val waitingOn = CompletableFuture<Unit>()
waitingOn.complete(Unit)
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
await(waitingOn)
"Done"
}
future.step()
future.isDone shouldBe true
future.get() shouldBe "Done"
}
"get waits on await future" {
val waitingOn = CompletableFuture<Unit>()
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
await(waitingOn)
"Done"
}
val earliestStart = System.currentTimeMillis()
thread {
Thread.sleep(200)
waitingOn.complete(Unit)
}
future.get() shouldBe "Done"
val completedAt = System.currentTimeMillis()
(completedAt - earliestStart) should beGreaterThanOrEqualTo(200L)
}
"await workable future" {
val stepOneCompleted = CompletableFuture<Unit>()
val blockerAfterStepOne = CompletableFuture<String>()
val principal = RANDOM_PRINCIPAL
val waitingOn = WorkableFutureImpl(principal) {
stepOneCompleted.complete(Unit)
await(blockerAfterStepOne)
}
val future = WorkableFutureImpl(principal) {
await(waitingOn)
}
future.isDone shouldBe false
future.step()
future.isDone shouldBe false
stepOneCompleted.isDone shouldBe false
future.step()
future.isDone shouldBe false
stepOneCompleted.isDone shouldBe true
waitingOn.isDone shouldBe false
future.step()
future.isDone shouldBe false
waitingOn.isDone shouldBe false
blockerAfterStepOne.complete("Fuzz")
future.isDone shouldBe false
waitingOn.isDone shouldBe false
future.step()
future.isDone shouldBe true
future.get() shouldBe "Fuzz"
}
"finally" - {
"on error" {
val finallyExecutions = mutableListOf<Int>()
val workableFuture = launchWorkableFuture(UUID.randomUUID()) {
val completedFuture1 = CompletableFuture<Unit>()
completedFuture1.complete(Unit)
val erroredFuture1 = CompletableFuture<Unit>()
erroredFuture1.completeExceptionally(Exception("ERROR!"))
await(completedFuture1)
finally {
finallyExecutions.add(1)
}
finally {
finallyExecutions.add(2)
}
awaitAndFinally(erroredFuture1) {
finallyExecutions.add(3)
}
finally {
finallyExecutions.add(4)
}
}
shouldThrow<Exception> {
workableFuture.get()
}
finallyExecutions shouldBe listOf(3, 2, 1)
}
"on success" {
val finallyExecutions = mutableListOf<Int>()
val workableFuture = launchWorkableFuture(UUID.randomUUID()) {
val completedFuture1 = CompletableFuture<Unit>()
completedFuture1.complete(Unit)
finally {
finallyExecutions.add(1)
}
awaitAndFinally(completedFuture1) {
finallyExecutions.add(2)
}
finally {
finallyExecutions.add(3)
}
}
workableFuture.get()
finallyExecutions shouldBe listOf(3, 2, 1)
}
"on cancel while waiting on future" {
val finallyExecutions = mutableListOf<Int>()
val workableFuture = launchWorkableFuture(UUID.randomUUID()) {
val uncompletedFuture = CompletableFuture<Unit>()
finally {
finallyExecutions.add(1)
}
awaitAndFinally(uncompletedFuture) {
finallyExecutions.add(2)
}
}
workableFuture.step() shouldBe false
workableFuture.cancel(true) shouldBe true
finallyExecutions shouldBe listOf(2, 1)
}
"on cancel while folding sequence" {
val finallyExecutions = mutableListOf<Int>()
val uncompletedFuture = CompletableFuture<Unit>()
val neverEmits = buildLazySequence<Unit>(IrrelevantPrincipal) {
await(uncompletedFuture)
}
val workableFuture = launchWorkableFuture(UUID.randomUUID()) {
finally {
finallyExecutions.add(1)
}
finally {
finallyExecutions.add(2)
}
foldRemaining(neverEmits, Unit) { _, _ -> Unit }
finally {
finallyExecutions.add(3)
}
}
workableFuture.step() shouldBe false
workableFuture.cancel(true) shouldBe true
finallyExecutions shouldBe listOf(2, 1)
}
}
"folding" {
val principal = RANDOM_PRINCIPAL
val foldable = buildLazySequence<Int>(principal) {
yield(1)
yield(2)
yield(3)
yield(5)
yield(102)
null
}
val future = WorkableFutureImpl(principal) {
foldRemaining(foldable, 0, Int::plus) + 4
}
future.step() shouldBe false
future.step() shouldBe false
future.step() shouldBe false
future.step() shouldBe false
future.step() shouldBe false
future.step() shouldBe false
future.step() shouldBe true
future.get() shouldBe 1 + 2 + 3 + 5 + 102 + 4
}
"rethrow in folding" {
val ex = RuntimeException("Some fancy exception")
val future = WorkableFutureImpl(RANDOM_PRINCIPAL) {
try {
return@WorkableFutureImpl foldRemaining(
buildLazySequence<Unit>(principal) {
throw ex
},
Unit,
{ _, _ -> Unit }
)
} catch (ex: RuntimeException) {
throw RuntimeException("Rethrow", ex)
}
}
val thrown = shouldThrow<RuntimeException> {
future.get()
}
thrown.message shouldBe "Rethrow"
thrown.cause shouldBe ex
}
"recover in folding" {
val ex = RuntimeException("Some fancy exception")
val future = launchWorkableFuture(RANDOM_PRINCIPAL) {
try {
foldRemaining(
buildLazySequence<Unit>(principal) {
throw ex
},
2,
{ _, _ -> 2 }
)
} catch (ex: RuntimeException) {
1
}
}
future.get() shouldBe 1
}
})
| mit | 81d617449014c91ebdd7ea743a9609b0 | 26.313253 | 75 | 0.55333 | 5.296729 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/PrintJob.kt | 1 | 4475 | package org.cups4j
/**
* Copyright (C) 2009 Harald Weyhing
*
*
* This file is part of Cups4J. Cups4J is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
*
* Cups4J is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
*
* You should have received a copy of the GNU Lesser General Public License along with Cups4J. If
* not, see <http:></http:>//www.gnu.org/licenses/>.
*/
import java.io.ByteArrayInputStream
import java.io.InputStream
/**
* Print job class
*/
class PrintJob internal constructor(builder: Builder) {
val document: InputStream
val copies: Int
val pageRanges: String?
val userName: String?
val jobName: String?
var isDuplex = false
var attributes: MutableMap<String, String>? = null
init {
this.document = builder.document
this.jobName = builder.jobName
this.copies = builder.copies
this.pageRanges = builder.pageRanges
this.userName = builder.userName
this.isDuplex = builder.duplex
this.attributes = builder.attributes
}
/**
*
*
* Builds PrintJob objects like so:
*
*
*
* PrintJob printJob = new
* PrintJob.Builder(document).jobName("jobXY").userName
* ("harald").copies(2).build();
*
*
*
* documents are supplied as byte[] or as InputStream
*
*/
class Builder {
var document: InputStream
var copies = 1
var pageRanges: String? = null
var userName: String? = null
var jobName: String? = null
var duplex = false
var attributes: MutableMap<String, String>? = null
/**
* Constructor
*
* @param document Printed document
*/
constructor(document: ByteArray) {
this.document = ByteArrayInputStream(document)
}
/**
* Constructor
*
* @param document Printed document
*/
constructor(document: InputStream) {
this.document = document
}
/**
* @param copies Number of copies - 0 and 1 are both treated as one copy
* @return Builder
*/
fun copies(copies: Int): Builder {
this.copies = copies
return this
}
/**
* @param pageRanges Page ranges 1-3, 5, 8, 10-13
* @return Builder
*/
fun pageRanges(pageRanges: String): Builder {
this.pageRanges = pageRanges
return this
}
/**
* @param userName Requesting user name
* @return Builder
*/
fun userName(userName: String): Builder {
this.userName = userName
return this
}
/**
* @param jobName Job name
* @return Builder
*/
fun jobName(jobName: String): Builder {
this.jobName = jobName
return this
}
/**
* @param duplex Duplex mode
* @return Builder
*/
fun duplex(duplex: Boolean): Builder {
this.duplex = duplex
return this
}
/**
* Additional attributes for the print operation and the print job
*
* @param attributes provide operation attributes and/or a String of job-attributes
*
* job attributes are seperated by "#"
*
* example:
* `
* attributes.put("compression","none");
* attributes.put("job-attributes",
* "print-quality:enum:3#sheet-collate:keyword:collated#sides:keyword:two-sided-long-edge"
* );
* `
* -> take a look config/ippclient/list-of-attributes.xml for more information
*
* @return Builder
*/
fun attributes(attributes: MutableMap<String, String>): Builder {
this.attributes = attributes
return this
}
/**
* Builds the PrintJob object.
*
* @return PrintJob
*/
fun build(): PrintJob = PrintJob(this)
}
}
| lgpl-3.0 | 9e8a32deb9bef63fef64c27d6fb52b6b | 26.286585 | 99 | 0.566704 | 4.651767 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/calendar/CalendarItemViewHolder.kt | 1 | 5290 | package com.battlelancer.seriesguide.shows.calendar
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.TooltipCompat
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.settings.DisplaySettings
import com.battlelancer.seriesguide.shows.episodes.EpisodeTools
import com.battlelancer.seriesguide.util.ImageTools
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.TimeTools
import com.battlelancer.seriesguide.shows.episodes.WatchedBox
import java.util.Date
class CalendarItemViewHolder(
parent: ViewGroup,
itemClickListener: CalendarAdapter2.ItemClickListener
) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_calendar,
parent,
false
)
) {
private val headerTextView: TextView = itemView.findViewById(R.id.textViewGridHeader)
private val itemContainer: ViewGroup = itemView.findViewById(R.id.constraintLayoutCalendar)
private val showTextView: TextView = itemView.findViewById(R.id.textViewActivityShow)
private val episodeTextView: TextView = itemView.findViewById(R.id.textViewActivityEpisode)
private val collected: View = itemView.findViewById(R.id.imageViewActivityCollected)
private val watchedBox: WatchedBox = itemView.findViewById(R.id.watchedBoxActivity)
private val info: TextView = itemView.findViewById(R.id.textViewActivityInfo)
private val timestamp: TextView = itemView.findViewById(R.id.textViewActivityTimestamp)
private val poster: ImageView = itemView.findViewById(R.id.imageViewActivityPoster)
private var item: CalendarFragment2ViewModel.CalendarItem? = null
init {
itemContainer.setOnClickListener {
item?.episode?.let {
itemClickListener.onItemClick(it.id)
}
}
itemContainer.setOnLongClickListener {
item?.episode?.let {
itemClickListener.onItemLongClick(itemView, it)
}
true
}
watchedBox.setOnClickListener {
item?.episode?.let {
itemClickListener.onItemWatchBoxClick(
it,
EpisodeTools.isWatched(watchedBox.episodeFlag)
)
}
}
TooltipCompat.setTooltipText(watchedBox, watchedBox.contentDescription)
}
fun bind(
context: Context,
item: CalendarFragment2ViewModel.CalendarItem,
previousItem: CalendarFragment2ViewModel.CalendarItem?,
multiColumn: Boolean
) {
this.item = item
// optional header
val isShowingHeader = previousItem == null || previousItem.headerTime != item.headerTime
if (multiColumn) {
// in a multi-column layout it looks nicer if all items are inset by header height
headerTextView.isInvisible = !isShowingHeader
} else {
headerTextView.isGone = !isShowingHeader
}
headerTextView.text = if (isShowingHeader) {
// display headers like "Mon in 3 days", also "today" when applicable
TimeTools.formatToLocalDayAndRelativeWeek(context, Date(item.headerTime))
} else {
null
}
val episode = item.episode
// show title
showTextView.text = episode.seriestitle
// episode number and title
val hideTitle =
EpisodeTools.isUnwatched(episode.watched) && DisplaySettings.preventSpoilers(context)
episodeTextView.text = TextTools.getNextEpisodeString(
context,
episode.season,
episode.episodenumber,
if (hideTitle) null else episode.episodetitle
)
// timestamp, absolute time and network
val releaseTime = episode.episode_firstairedms
val time = if (releaseTime != -1L) {
val actualRelease = TimeTools.applyUserOffset(context, releaseTime)
// timestamp
timestamp.text = if (DisplaySettings.isDisplayExactDate(context)) {
TimeTools.formatToLocalDateShort(context, actualRelease)
} else {
TimeTools.formatToLocalRelativeTime(context, actualRelease)
}
// release time of this episode
TimeTools.formatToLocalTime(context, actualRelease)
} else {
timestamp.text = null
null
}
info.text = TextTools.dotSeparate(episode.network, time)
// watched box
val episodeFlag = episode.watched
watchedBox.episodeFlag = episodeFlag
val watched = EpisodeTools.isWatched(episodeFlag)
watchedBox.contentDescription =
context.getString(if (watched) R.string.action_unwatched else R.string.action_watched)
// collected indicator
collected.isGone = !episode.episode_collected
// set poster
ImageTools.loadShowPosterResizeSmallCrop(context, poster, episode.series_poster_small)
}
} | apache-2.0 | 6fca9771b3a797d457c81373fa37aa4d | 37.064748 | 98 | 0.684688 | 4.92093 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/episodes/EpisodesViewModel.kt | 1 | 2418 | package com.battlelancer.seriesguide.shows.episodes
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.battlelancer.seriesguide.shows.database.SgEpisode2Info
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.util.TimeTools
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class EpisodesViewModel(
application: Application,
private val seasonId: Long
) : AndroidViewModel(application) {
data class Counts(
val unwatchedEpisodes: Int,
val uncollectedEpisodes: Int
)
var showId: Long = 0
private val order = MutableLiveData<EpisodesSettings.EpisodeSorting>()
val episodes = Transformations.switchMap(order) {
SgRoomDatabase.getInstance(getApplication()).sgEpisode2Helper()
.getEpisodeInfoOfSeasonLiveData(SgEpisode2Info.buildQuery(seasonId, it))
}
val episodeCounts = MutableLiveData<Counts>()
var selectedItemId: Long = -1
init {
viewModelScope.launch(Dispatchers.IO) {
val db = SgRoomDatabase.getInstance(getApplication())
db.sgSeason2Helper().getSeasonNumbers(seasonId)?.also {
showId = it.showId
}
}
updateOrder()
}
fun updateOrder() {
order.value = EpisodesSettings.getEpisodeSortOrder(getApplication())
}
fun updateCounts() = viewModelScope.launch(Dispatchers.IO) {
val helper = SgRoomDatabase.getInstance(getApplication()).sgEpisode2Helper()
val unwatchedEpisodes = helper.countNotWatchedReleasedEpisodesOfSeason(
seasonId,
TimeTools.getCurrentTime(getApplication())
)
val uncollectedEpisodes = helper.countNotCollectedEpisodesOfSeason(seasonId)
episodeCounts.postValue(
Counts(unwatchedEpisodes, uncollectedEpisodes)
)
}
}
class EpisodesViewModelFactory(
private val application: Application,
private val seasonId: Long
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return EpisodesViewModel(application, seasonId) as T
}
}
| apache-2.0 | 44035b069bc22b452fafa92b7abe2566 | 32.583333 | 84 | 0.728701 | 5.0375 | false | false | false | false |
kunickiaj/vault-kotlin | src/main/kotlin/com/adamkunicki/vault/api/AuthToken.kt | 1 | 4002 | /*
* Copyright 2016 Adam Kunicki
*
* 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.adamkunicki.vault.api
import com.adamkunicki.vault.VaultConfiguration
import com.adamkunicki.vault.VaultError
import com.adamkunicki.vault.VaultException
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.fuel.httpPut
import com.github.salomonbrys.kotson.jsonObject
import com.google.gson.Gson
@Suppress("UNUSED_VARIABLE")
class AuthToken(private val conf: VaultConfiguration) {
@Throws(VaultException::class)
fun create(options: List<Pair<String, Any?>>): Secret {
val (request, response, result) = (conf.adddress + "/v1/auth/token/create")
.httpPost()
.body(jsonObject(*options.toTypedArray()).toString(), Charsets.UTF_8)
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
val (secret, error) = result
if (secret != null) {
return secret
}
val errorMessage = if (error != null) {
Gson().fromJson(String(error.errorData), VaultError::class.java).errors.joinToString()
} else {
""
}
throw VaultException(errorMessage)
}
@Throws(VaultException::class)
fun renew(id: String, increment: Int = 0): Secret {
val (request, response, result) = (conf.adddress + "/v1/auth/token/renew/" + id)
.httpPut()
.body(jsonObject("increment" to increment).toString(), Charsets.UTF_8)
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
val (secret, error) = result
if (secret != null) {
return secret
}
val errorMessage = if (error != null) {
Gson().fromJson(String(error.errorData), VaultError::class.java).errors.joinToString()
} else {
""
}
throw VaultException(errorMessage)
}
@Throws(VaultException::class)
fun renewSelf(increment: Int = 0): Secret {
val (request, response, result) = (conf.adddress + "/v1/auth/token/renew-self")
.httpPut()
.body(jsonObject("increment" to increment).toString(), Charsets.UTF_8)
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
val (secret, error) = result
if (secret != null) {
return secret
}
val errorMessage = if (error != null) {
Gson().fromJson(String(error.errorData), VaultError::class.java).errors.joinToString()
} else {
""
}
throw VaultException(errorMessage)
}
fun revokeSelf(): Int {
val (request, response, result) = (conf.adddress + "/v1/auth/token/revoke-self")
.httpPost()
.header(Pair("X-Vault-Token", conf.token))
.response()
return response.httpStatusCode
}
fun revokeOrphan(id: String): Boolean {
val (request, response, result) = (conf.adddress + "/v1/auth/token/revoke-orphan/" + id)
.httpPut()
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
return true
}
fun revokePrefix(prefix: String): Boolean {
val (request, response, result) = (conf.adddress + "/v1/auth/token/revoke-prefix/" + prefix)
.httpPut()
.header(Pair("X-Vault-Token", conf.token))
.response()
return true
}
fun revokeTree(id: String): Boolean {
val (request, response, result) = (conf.adddress + "/v1/auth/token/revoke/" + id)
.httpPut()
.header(Pair("X-Vault-Token", conf.token))
.response()
return true
}
} | apache-2.0 | 4dc4f8890ad4ad6c7d619db53e6f4cea | 30.273438 | 96 | 0.657921 | 3.764817 | false | false | false | false |
cashapp/turbine | src/commonMain/kotlin/app/cash/turbine/Turbine.kt | 1 | 7184 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.turbine
import kotlin.time.Duration
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.channels.ChannelResult
internal const val debug = false
/**
* A standalone [Turbine] suitable for usage in fakes or other external test components.
*/
public interface Turbine<T> : ReceiveTurbine<T> {
/**
* Returns the underlying [Channel]. The [Channel] will have a buffer size of [UNLIMITED].
*/
public override fun asChannel(): Channel<T>
/**
* Closes the underlying [Channel]. After all items have been consumed, this [Turbine] will yield
* [Event.Complete] if [cause] is null, and [Event.Error] otherwise.
*/
public fun close(cause: Throwable? = null)
/**
* Add an item to the underlying [Channel] without blocking.
*
* This method is equivalent to:
*
* ```
* if (!asChannel().trySend(item).isSuccess) error()
* ```
*/
public fun add(item: T)
/**
* Assert that the next event received was non-null and return it.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun takeEvent(): Event<T>
/**
* Assert that the next event received was an item and return it.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error, or no event.
*/
public fun takeItem(): T
/**
* Assert that the next event received is [Event.Complete].
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun takeComplete()
/**
* Assert that the next event received is [Event.Error], and return the error.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun takeError(): Throwable
}
public operator fun <T> Turbine<T>.plusAssign(value: T) { add(value) }
/**
* Construct a standalone [Turbine].
*
* @param timeout If non-null, overrides the current Turbine timeout for this [Turbine]. See also:
* [withTurbineTimeout].
* @param name If non-null, name is added to any exceptions thrown to help identify which [Turbine] failed.
*/
@Suppress("FunctionName") // Interface constructor pattern.
public fun <T> Turbine(
timeout: Duration? = null,
name: String? = null,
): Turbine<T> = ChannelTurbine(timeout = timeout, name = name)
internal class ChannelTurbine<T>(
channel: Channel<T> = Channel(UNLIMITED),
private val job: Job? = null,
private val timeout: Duration?,
private val name: String?,
) : Turbine<T> {
private suspend fun <T> withTurbineTimeout(block: suspend () -> T): T {
return if (timeout != null) {
withTurbineTimeout(timeout) { block() }
} else {
block()
}
}
private val channel = object : Channel<T> by channel {
override fun tryReceive(): ChannelResult<T> {
val result = channel.tryReceive()
val event = result.toEvent()
if (event is Event.Error || event is Event.Complete) ignoreRemainingEvents = true
return result
}
override suspend fun receive(): T = try {
channel.receive()
} catch (e: Throwable) {
ignoreRemainingEvents = true
throw e
}
}
override fun asChannel(): Channel<T> = channel
override fun add(item: T) {
if (!channel.trySend(item).isSuccess) throw IllegalStateException("Added when closed")
}
@OptIn(ExperimentalCoroutinesApi::class)
override suspend fun cancel() {
if (!channel.isClosedForSend) ignoreTerminalEvents = true
channel.cancel()
job?.cancelAndJoin()
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun close(cause: Throwable?) {
if (!channel.isClosedForSend) ignoreTerminalEvents = true
channel.close(cause)
job?.cancel()
}
override fun takeEvent(): Event<T> = channel.takeEvent(name = name)
override fun takeItem(): T = channel.takeItem(name = name)
override fun takeComplete() = channel.takeComplete(name = name)
override fun takeError(): Throwable = channel.takeError(name = name)
private var ignoreTerminalEvents = false
private var ignoreRemainingEvents = false
override suspend fun cancelAndIgnoreRemainingEvents() {
cancel()
ignoreRemainingEvents = true
}
override suspend fun cancelAndConsumeRemainingEvents(): List<Event<T>> {
val events = buildList {
while (true) {
val event = channel.takeEventUnsafe() ?: break
add(event)
if (event is Event.Error || event is Event.Complete) break
}
}
ignoreRemainingEvents = true
cancel()
return events
}
override fun expectNoEvents() {
channel.expectNoEvents(name = name)
}
override fun expectMostRecentItem(): T = channel.expectMostRecentItem(name = name)
override suspend fun awaitEvent(): Event<T> = withTurbineTimeout { channel.awaitEvent(name = name) }
override suspend fun awaitItem(): T = withTurbineTimeout { channel.awaitItem(name = name) }
override suspend fun skipItems(count: Int) = withTurbineTimeout { channel.skipItems(count, name) }
override suspend fun awaitComplete() = withTurbineTimeout { channel.awaitComplete(name = name) }
override suspend fun awaitError(): Throwable = withTurbineTimeout { channel.awaitError(name = name) }
override fun ensureAllEventsConsumed() {
if (ignoreRemainingEvents) return
val unconsumed = mutableListOf<Event<T>>()
var cause: Throwable? = null
while (true) {
val event = channel.takeEventUnsafe() ?: break
if (!(ignoreTerminalEvents && event.isTerminal)) unconsumed += event
if (event is Event.Error) {
cause = event.throwable
break
} else if (event is Event.Complete) {
break
}
}
if (unconsumed.isNotEmpty()) {
throw TurbineAssertionError(
buildString {
append("Unconsumed events found".qualifiedBy(name))
append(":")
for (event in unconsumed) {
append("\n - $event")
}
},
cause
)
}
}
}
| apache-2.0 | 8f9680c911806adce9d67041b4765a52 | 30.647577 | 117 | 0.688335 | 4.159815 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/listener/PlayerCommandPreprocessListener.kt | 1 | 2379 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.unconsciousness.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.unconsciousness.bukkit.RPKUnconsciousnessBukkit
import com.rpkit.unconsciousness.bukkit.unconsciousness.RPKUnconsciousnessService
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerCommandPreprocessEvent
class PlayerCommandPreprocessListener(private val plugin: RPKUnconsciousnessBukkit) : Listener {
@EventHandler(priority = EventPriority.HIGH)
fun onPlayerCommandPreprocess(event: PlayerCommandPreprocessEvent) {
val bukkitPlayer = event.player
if (bukkitPlayer.hasPermission("rpkit.unconsciousness.unconscious.commands")) return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val unconsciousnessService = Services[RPKUnconsciousnessService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
if (!unconsciousnessService.getPreloadedUnconsciousness(character)) return
if (plugin.config.getStringList("allowed-commands")
.map { command -> "/$command" }
.contains(event.message.split(Regex("\\s+"))[0])) return
event.isCancelled = true
bukkitPlayer.sendMessage(plugin.messages["unconscious-command-blocked"])
}
} | apache-2.0 | e3f3cb6693080c15f8f6d6550566cb59 | 47.571429 | 107 | 0.765868 | 4.514231 | false | false | false | false |
manami-project/manami | manami-app/src/test/kotlin/io/github/manamiproject/manami/app/commands/history/DefaultCommandHistoryTest.kt | 1 | 15663 | package io.github.manamiproject.manami.app.commands.history
import io.github.manamiproject.manami.app.commands.ReversibleCommand
import io.github.manamiproject.manami.app.commands.TestReversibleCommand
import io.github.manamiproject.manami.app.events.SimpleEventBus
import io.github.manamiproject.manami.app.events.Subscribe
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.lang.Thread.sleep
internal class DefaultCommandHistoryTest {
private var testEventSubscriber = TestEventSubscriber()
@BeforeEach
fun before() {
SimpleEventBus.subscribe(testEventSubscriber)
}
@AfterEach
fun afterEach() {
DefaultCommandHistory.clear()
testEventSubscriber.fileSavedEvents.clear()
testEventSubscriber.undoRedoStatusEvents.clear()
SimpleEventBus.unsubscribe(testEventSubscriber)
}
@Nested
inner class PushTests {
@Test
fun `successfully add a new command`() {
// when
DefaultCommandHistory.push(TestReversibleCommand)
// then
assertThat(DefaultCommandHistory.isUndoPossible()).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents.first()).isFalse()
assertThat(testEventSubscriber.undoRedoStatusEvents.first()).isEqualTo(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
@Nested
inner class ClearTests {
@Test
fun `successfully add a new command`() {
// given
DefaultCommandHistory.push(TestReversibleCommand)
DefaultCommandHistory.push(TestReversibleCommand)
DefaultCommandHistory.push(TestReversibleCommand)
// when
DefaultCommandHistory.clear()
// then
assertThat(DefaultCommandHistory.isUndoPossible()).isFalse()
assertThat(DefaultCommandHistory.isRedoPossible()).isFalse()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, false, false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = false),
)
}
}
@Nested
inner class IsUndoPossibleTests {
@Test
fun `returns false for empty command history`() {
// then
assertThat(DefaultCommandHistory.isUndoPossible()).isFalse()
}
@Test
fun `returns true if it's possible to undo previously executed command`() {
// given
DefaultCommandHistory.push(TestReversibleCommand)
// when
val result = DefaultCommandHistory.isUndoPossible()
// then
assertThat(result).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
@Nested
inner class IsRedoPossibleTests {
@Test
fun `returns false for empty command history`() {
// then
assertThat(DefaultCommandHistory.isRedoPossible()).isFalse()
}
@Test
fun `returns true if it's possible to redo previously undone command`() {
// given
val testReversibleCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() { }
}
DefaultCommandHistory.push(testReversibleCommand)
DefaultCommandHistory.undo()
// when
val result = DefaultCommandHistory.isRedoPossible()
// then
assertThat(result).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = true),
)
}
}
@Nested
inner class UndoTests {
@Test
fun `successfully undo command`() {
// given
var commandUndone = false
val testReversibleCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() { commandUndone = true }
}
DefaultCommandHistory.push(testReversibleCommand)
// when
DefaultCommandHistory.undo()
// then
assertThat(commandUndone).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = true),
)
}
}
@Nested
inner class RedoTests {
@Test
fun `successfully redo command`() {
// given
DefaultCommandHistory.push(TestReversibleCommand)
var commandRedone = 0
val testReversibleCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() { }
override fun execute(): Boolean {
commandRedone++
return true
}
}
DefaultCommandHistory.push(testReversibleCommand)
DefaultCommandHistory.undo()
// when
DefaultCommandHistory.redo()
// then
assertThat(commandRedone).isOne()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, false, false, false)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = true),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
@Nested
inner class IsUnsavedTests {
@Test
fun `returns false if the command history is empty`() {
// when
val result = DefaultCommandHistory.isUnsaved()
// then
assertThat(result).isFalse()
}
@Test
fun `returns true if the command history contains an element and is not saved`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand { }
DefaultCommandHistory.push(testCommand)
// when
val result = DefaultCommandHistory.isUnsaved()
// then
assertThat(result).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
@Test
fun `returns false if the first command is undone`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() {}
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
// when
val result = DefaultCommandHistory.isUnsaved()
// then
assertThat(result).isFalse()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = true),
)
}
@Test
fun `returns false if the given state has been saved`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() {}
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
DefaultCommandHistory.save()
// when
val result = DefaultCommandHistory.isUnsaved()
// then
assertThat(result).isFalse()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, false, false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = true),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
@Nested
inner class IsSavedTests {
@Test
fun `returns true if the command history is empty`() {
// when
val result = DefaultCommandHistory.isSaved()
// then
assertThat(result).isTrue()
}
@Test
fun `returns false if the command history contains an element and is not saved`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand { }
DefaultCommandHistory.push(testCommand)
// when
val result = DefaultCommandHistory.isSaved()
// then
assertThat(result).isFalse()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
@Test
fun `returns true if the first command is undone`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() {}
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
// when
val result = DefaultCommandHistory.isSaved()
// then
assertThat(result).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = true),
)
}
@Test
fun `returns true if the given state has been saved`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() {}
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
DefaultCommandHistory.save()
// when
val result = DefaultCommandHistory.isSaved()
// then
assertThat(result).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, false, false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = true),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
@Nested
inner class SaveTests {
@Test
fun `when called on initial element after undoing a command, the following commands are not cropped`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() { }
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
// when
DefaultCommandHistory.save()
// then
assertThat(DefaultCommandHistory.isRedoPossible()).isTrue()
assertThat(DefaultCommandHistory.isUndoPossible()).isFalse()
assertThat(DefaultCommandHistory.isSaved()).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = false, isRedoPossible = true),
)
}
@Test
fun `crop following commands when save is called`() {
// given
val testCommand = object: ReversibleCommand by TestReversibleCommand {
override fun undo() { }
}
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.push(testCommand)
DefaultCommandHistory.undo()
// when
DefaultCommandHistory.save()
// then
assertThat(DefaultCommandHistory.isRedoPossible()).isFalse()
assertThat(DefaultCommandHistory.isUndoPossible()).isTrue()
assertThat(DefaultCommandHistory.isSaved()).isTrue()
sleep(1000)
assertThat(testEventSubscriber.fileSavedEvents).containsExactly(false, false, false, true)
assertThat(testEventSubscriber.undoRedoStatusEvents).containsExactly(
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = true),
UndoRedoStatusEvent(isUndoPossible = true, isRedoPossible = false),
)
}
}
}
internal class TestEventSubscriber {
val fileSavedEvents = mutableListOf<Boolean>()
val undoRedoStatusEvents = mutableListOf<UndoRedoStatusEvent>()
@Subscribe(FileSavedStatusChangedEvent::class)
fun receive(event: FileSavedStatusChangedEvent) {
fileSavedEvents.add(event.isFileSaved)
}
@Subscribe(UndoRedoStatusEvent::class)
fun receive(event: UndoRedoStatusEvent) {
undoRedoStatusEvents.add(event)
}
} | agpl-3.0 | bd9fc66383777c0655ebfd2aea09ee37 | 35.092166 | 112 | 0.618911 | 5.34391 | false | true | false | false |
googlecodelabs/android-compose-codelabs | NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/theme/RallyTheme.kt | 1 | 2196 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.rally.ui.theme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Typography
import androidx.compose.material.darkColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
/**
* A [MaterialTheme] for Rally.
*/
@Composable
fun RallyTheme(content: @Composable () -> Unit) {
MaterialTheme(colors = ColorPalette, typography = Typography, content = content)
}
/**
* A theme overlay used for dialogs.
*/
@Composable
fun RallyDialogThemeOverlay(content: @Composable () -> Unit) {
// Rally is always dark themed.
val dialogColors = darkColors(
primary = Color.White,
surface = Color.White.copy(alpha = 0.12f).compositeOver(Color.Black),
onSurface = Color.White
)
// Copy the current [Typography] and replace some text styles for this theme.
val currentTypography = MaterialTheme.typography
val dialogTypography = currentTypography.copy(
body2 = currentTypography.body1.copy(
fontWeight = FontWeight.Normal,
fontSize = 20.sp,
lineHeight = 28.sp,
letterSpacing = 1.sp
),
button = currentTypography.button.copy(
fontWeight = FontWeight.Bold,
letterSpacing = 0.2.em
)
)
MaterialTheme(colors = dialogColors, typography = dialogTypography, content = content)
}
| apache-2.0 | 42e370a156f87ecef989c3c6e05e7b9d | 32.784615 | 90 | 0.714481 | 4.314342 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/ipptCalculator/ScoringUpdateTask.kt | 1 | 1169 | package com.itachi1706.cheesecakeutilities.modules.ipptCalculator
import android.app.Activity
import android.os.AsyncTask
import com.itachi1706.cheesecakeutilities.modules.ipptCalculator.helpers.JsonHelper
import java.lang.ref.WeakReference
/**
* Created by Kenneth on 31/7/2019.
* for com.itachi1706.cheesecakeutilities.modules.IPPTCalculator in CheesecakeUtilities
*/
class ScoringUpdateTask(activity: Activity, private var callback: ScoringCallback) : AsyncTask<Int, Void, Void>() {
private val activityRef = WeakReference(activity)
private var results: List<String> = ArrayList()
interface ScoringCallback {
fun updateResults(results: List<String>)
}
override fun doInBackground(vararg params: Int?): Void? {
if (params.size < 3) return null
val ageGroup = params[0]!!
val gender = params[1]!!
val exercise = params[2]!!
val activity = activityRef.get() ?: return null
results = JsonHelper.getExerciseScores(ageGroup, exercise, gender, activity.applicationContext)
activity.runOnUiThread {
callback.updateResults(results)
}
return null
}
} | mit | d26f6e9ef32be578f4bbd7dc528587cf | 32.428571 | 115 | 0.715997 | 4.42803 | false | false | false | false |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/ITaskContributor.kt | 2 | 1237 | package com.beust.kobalt.api
import com.beust.kobalt.TaskResult
import com.beust.kobalt.internal.TaskResult2
/**
* Plug-ins that need to add dynamic tasks (tasks that are not methods annotated with @Task) need
* to implement this interface.
*/
interface ITaskContributor : IContributor {
fun tasksFor(project: Project, context: KobaltContext) : List<DynamicTask>
}
class DynamicTask(override val plugin: IPlugin, override val name: String, override val doc: String,
override val group: String,
override val project: Project,
val dependsOn: List<String> = listOf<String>(),
val reverseDependsOn: List<String> = listOf<String>(),
val runBefore: List<String> = listOf<String>(),
val runAfter: List<String> = listOf<String>(),
val alwaysRunAfter: List<String> = listOf<String>(),
val closure: (Project) -> TaskResult) : ITask {
override fun call(): TaskResult2<ITask> {
val taskResult = closure.invoke(project)
return TaskResult2(taskResult.success, errorMessage = taskResult.errorMessage, value = this)
}
override fun toString() =
"[DynamicTask ${project.name}:$name dependsOn=$dependsOn reverseDependsOn=$reverseDependsOn]"
}
| apache-2.0 | be6aa989e86a19dbf4b8f0f413bcf97a | 37.65625 | 101 | 0.700081 | 4.355634 | false | false | false | false |
mpv-android/mpv-android | app/src/main/java/is/xyz/mpv/PlaylistDialog.kt | 1 | 4213 | package `is`.xyz.mpv
import `is`.xyz.mpv.databinding.DialogPlaylistBinding
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
internal class PlaylistDialog(private val player: MPVView) {
private lateinit var binding: DialogPlaylistBinding
private var playlist = listOf<MPVView.PlaylistItem>()
private var selectedIndex = -1
interface Listeners {
fun pickFile()
fun openUrl()
fun onItemPicked(item: MPVView.PlaylistItem)
}
var listeners: Listeners? = null
fun buildView(layoutInflater: LayoutInflater): View {
binding = DialogPlaylistBinding.inflate(layoutInflater)
// Set up recycler view
binding.list.adapter = CustomAdapter(this)
binding.list.setHasFixedSize(true)
refresh()
binding.fileBtn.setOnClickListener { listeners?.pickFile() }
binding.urlBtn.setOnClickListener { listeners?.openUrl() }
binding.shuffleBtn.setOnClickListener {
player.changeShuffle(true)
refresh()
}
binding.repeatBtn.setOnClickListener {
player.cycleRepeat()
refresh()
}
return binding.root
}
fun refresh() {
selectedIndex = MPVLib.getPropertyInt("playlist-pos") ?: -1
playlist = player.loadPlaylist()
Log.v(TAG, "PlaylistDialog: loaded ${playlist.size} items")
(binding.list.adapter as RecyclerView.Adapter).notifyDataSetChanged()
binding.list.scrollToPosition(playlist.indexOfFirst { it.index == selectedIndex })
val accent = ContextCompat.getColor(binding.root.context, R.color.accent)
val disabled = ContextCompat.getColor(binding.root.context, R.color.alpha_disabled)
//
val shuffleState = player.getShuffle()
binding.shuffleBtn.apply {
isEnabled = playlist.size > 1
imageTintList = if (isEnabled)
if (shuffleState) ColorStateList.valueOf(accent) else null
else
ColorStateList.valueOf(disabled)
}
val repeatState = player.getRepeat()
binding.repeatBtn.apply {
imageTintList = if (repeatState > 0) ColorStateList.valueOf(accent) else null
setImageResource(if (repeatState == 2) R.drawable.ic_repeat_one_24dp else R.drawable.ic_repeat_24dp)
}
}
private fun clickItem(position: Int) {
val item = playlist[position]
listeners?.onItemPicked(item)
}
class CustomAdapter(private val parent: PlaylistDialog) :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
class ViewHolder(private val parent: PlaylistDialog, view: View) :
RecyclerView.ViewHolder(view) {
private val textView: TextView
var selfPosition: Int = -1
init {
textView = view.findViewById(android.R.id.text1)
view.setOnClickListener {
parent.clickItem(selfPosition)
}
}
fun bind(item: MPVView.PlaylistItem, selected: Boolean) {
textView.text = item.title ?: Utils.fileBasename(item.filename)
textView.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.dialog_playlist_item, viewGroup, false)
return ViewHolder(parent, view)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.selfPosition = position
val item = parent.playlist[position]
viewHolder.bind(item, item.index == parent.selectedIndex)
}
override fun getItemCount() = parent.playlist.size
}
companion object {
private const val TAG = "mpv"
}
}
| mit | d6fda87eb8ef0c1d0ab8ef7ea2dec8fb | 33.818182 | 112 | 0.648469 | 4.848101 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/CinnamonUserCommandExecutor.kt | 1 | 5023 | package net.perfectdreams.loritta.cinnamon.discord.interactions.commands
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.Member
import dev.kord.core.entity.User
import kotlinx.datetime.Clock
import mu.KotlinLogging
import net.perfectdreams.discordinteraktions.common.commands.ApplicationCommandContext
import net.perfectdreams.discordinteraktions.common.commands.GuildApplicationCommandContext
import net.perfectdreams.discordinteraktions.common.commands.UserCommandExecutor
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.utils.metrics.InteractionsMetrics
import net.perfectdreams.loritta.common.commands.ApplicationCommandType
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext as CinnamonApplicationCommandContext
/**
* Discord InteraKTions' [UserCommandExecutor] wrapper, used to provide Cinnamon-specific features.
*/
abstract class CinnamonUserCommandExecutor(val loritta: LorittaBot) : UserCommandExecutor(), CommandExecutorWrapper {
companion object {
private val logger = KotlinLogging.logger {}
}
private val executorClazzName = this::class.simpleName ?: "UnknownExecutor"
val rest = loritta.rest
val applicationId = loritta.config.loritta.discord.applicationId
abstract suspend fun execute(context: net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext, targetUser: User, targetMember: Member?)
override suspend fun execute(
context: ApplicationCommandContext,
targetUser: User,
targetMember: Member?
) {
val rootDeclarationClazzName = (context.applicationCommandDeclaration as CinnamonUserCommandDeclaration)
.declarationWrapper::class
.simpleName ?: "UnknownCommand"
logger.info { "(${context.sender.id.value}) $this" }
val timer = InteractionsMetrics.EXECUTED_COMMAND_LATENCY_COUNT
.labels(rootDeclarationClazzName, executorClazzName)
.startTimer()
val guildId = (context as? GuildApplicationCommandContext)?.guildId
val result = executeCommand(
rootDeclarationClazzName,
executorClazzName,
context,
guildId,
targetUser,
targetMember
)
var stacktrace: String? = null
if (result is CommandExecutorWrapper.CommandExecutionFailure)
stacktrace = result.throwable.stackTraceToString()
val commandLatency = timer.observeDuration()
logger.info { "(${context.sender.id.value}) $this - OK! Result: ${result}; Took ${commandLatency * 1000}ms" }
loritta.pudding.executedInteractionsLog.insertApplicationCommandLog(
context.sender.id.value.toLong(),
guildId?.value?.toLong(),
context.channelId.value.toLong(),
Clock.System.now(),
ApplicationCommandType.MESSAGE,
rootDeclarationClazzName,
executorClazzName,
buildJsonWithArguments(emptyMap()),
stacktrace == null,
commandLatency,
stacktrace
)
}
private suspend fun executeCommand(
rootDeclarationClazzName: String,
executorClazzName: String,
context: ApplicationCommandContext,
guildId: Snowflake?,
targetUser: User,
targetMember: Member?
): CommandExecutorWrapper.CommandExecutionResult {
// These variables are used in the catch { ... } block, to make our lives easier
var i18nContext: I18nContext? = null
val cinnamonContext: CinnamonApplicationCommandContext?
try {
val serverConfig = getGuildServerConfigOrLoadDefaultConfig(loritta, guildId)
val locale = loritta.localeManager.getLocaleById(serverConfig.localeId)
i18nContext = loritta.languageManager.getI18nContextByLegacyLocaleId(serverConfig.localeId)
cinnamonContext = convertInteraKTionsContextToCinnamonContext(loritta, context, i18nContext, locale)
// Don't let users that are banned from using Loritta
if (CommandExecutorWrapper.handleIfBanned(loritta, cinnamonContext))
return CommandExecutorWrapper.CommandExecutionSuccess
launchUserInfoCacheUpdater(loritta, context, null)
execute(
cinnamonContext,
targetUser,
targetMember
)
launchAdditionalNotificationsCheckerAndSender(loritta, context, i18nContext)
return CommandExecutorWrapper.CommandExecutionSuccess
} catch (e: Throwable) {
return convertThrowableToCommandExecutionResult(
loritta,
context,
i18nContext,
rootDeclarationClazzName,
executorClazzName,
e
)
}
}
} | agpl-3.0 | 1275a792bec2701b3e9441a866c0664a | 38.873016 | 174 | 0.697193 | 5.612291 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/treatment/view/controller.kt | 1 | 10005 | package at.cpickl.gadsu.treatment.view
import at.cpickl.gadsu.client.CurrentClient
import at.cpickl.gadsu.client.ShowClientViewEvent
import at.cpickl.gadsu.service.Clock
import at.cpickl.gadsu.service.Logged
import at.cpickl.gadsu.service.minutes
import at.cpickl.gadsu.treatment.CurrentTreatment
import at.cpickl.gadsu.treatment.NextTreatmentEvent
import at.cpickl.gadsu.treatment.OpenTreatmentEvent
import at.cpickl.gadsu.treatment.PrefillByAppointmentTreatment
import at.cpickl.gadsu.treatment.PrepareNewTreatmentEvent
import at.cpickl.gadsu.treatment.PreviousTreatmentEvent
import at.cpickl.gadsu.treatment.Treatment
import at.cpickl.gadsu.treatment.TreatmentBackEvent
import at.cpickl.gadsu.treatment.TreatmentChangedEvent
import at.cpickl.gadsu.treatment.TreatmentCreatedEvent
import at.cpickl.gadsu.treatment.TreatmentSaveEvent
import at.cpickl.gadsu.treatment.TreatmentService
import at.cpickl.gadsu.treatment.TreatmentViewFactory
import at.cpickl.gadsu.treatment.dyn.DynTreatmentFactory
import at.cpickl.gadsu.view.ChangeMainContentEvent
import at.cpickl.gadsu.view.GadsuMenuBar
import at.cpickl.gadsu.view.MainContentChangedEvent
import at.cpickl.gadsu.view.MainContentType
import at.cpickl.gadsu.view.MainFrame
import at.cpickl.gadsu.view.components.DialogType
import at.cpickl.gadsu.view.components.Dialogs
import at.cpickl.gadsu.view.logic.ChangeBehaviour
import at.cpickl.gadsu.view.logic.ChangesChecker
import at.cpickl.gadsu.view.logic.ChangesCheckerCallback
import at.cpickl.gadsu.view.swing.MyKeyListener
import at.cpickl.gadsu.view.swing.RegisteredKeyListener
import at.cpickl.gadsu.view.swing.registerMyKeyListener
import com.google.common.eventbus.EventBus
import com.google.common.eventbus.Subscribe
import org.slf4j.LoggerFactory
import javax.inject.Inject
import javax.swing.JComponent
import javax.swing.JMenuItem
import javax.swing.JPopupMenu
@Logged
open class TreatmentController @Inject constructor(
private val treatmentViewFactory: TreatmentViewFactory,
private val treatmentService: TreatmentService,
private val currentClient: CurrentClient,
private val currentTreatment: CurrentTreatment,
private val bus: EventBus,
private val clock: Clock,
private val mainFrame: MainFrame, // need a proper handle to register keyboard listener
private val menuBar: GadsuMenuBar, // do it the simple way: hard wire the dependency ;) could use events instead...
private val dialogs: Dialogs
) {
private val log = LoggerFactory.getLogger(javaClass)
private var treatmentView: TreatmentView? = null
private var registeredEscapeListener: RegisteredKeyListener? = null
private val changesChecker = ChangesChecker(dialogs, object : ChangesCheckerCallback {
override fun isModified() = treatmentView?.isModified() ?: false
override fun save() = saveCurrentTreatment()
})
@Subscribe open fun onPrepareNewTreatmentEvent(event: PrepareNewTreatmentEvent) {
if (changesChecker.checkChanges() == ChangeBehaviour.ABORT) {
return
}
changeToTreatmentView(null, event.prefillByAppointment)
}
@Subscribe open fun onOpenTreatmentEvent(event: OpenTreatmentEvent) {
if (changesChecker.checkChanges() == ChangeBehaviour.ABORT) {
return
}
changeToTreatmentView(event.treatment, null)
}
@Subscribe open fun onTreatmentSaveEvent(event: TreatmentSaveEvent) {
saveCurrentTreatment()
}
@Subscribe open fun onTreatmentBackEvent(event: TreatmentBackEvent) {
if (changesChecker.checkChanges() == ChangeBehaviour.ABORT) {
return
}
currentTreatment.data = null
bus.post(ShowClientViewEvent())
}
@Subscribe open fun onMainContentChangedEvent(event: MainContentChangedEvent) {
if (event.oldContent?.type != MainContentType.TREATMENT && event.newContent.type == MainContentType.TREATMENT) {
log.trace("Navigating TO treatment view.")
registeredEscapeListener = (mainFrame.asJFrame().contentPane as JComponent).registerMyKeyListener(MyKeyListener.onEscape("abortTreatmentView", {
log.debug("Escape was hit in treatment view. Dispatching TreatmentBackEvent.")
bus.post(TreatmentBackEvent())
}))
}
val moveAway = event.oldContent?.type == MainContentType.TREATMENT && event.newContent.type != MainContentType.TREATMENT
if (moveAway) {
log.trace("Navigating AWAY from treatment view")
// check changes already covered by onTreatmentBackEvent
if (registeredEscapeListener != null) {
registeredEscapeListener!!.deregisterYourself()
registeredEscapeListener = null
}
}
if (treatmentView != null && event.oldContent?.type == MainContentType.TREATMENT) {
treatmentView!!.closePreparations()
}
if (moveAway) {
treatmentView = null
}
}
@Subscribe open fun onPreviousTreatmentEvent(event: PreviousTreatmentEvent) {
if (changesChecker.checkChanges() == ChangeBehaviour.ABORT) {
return
}
val newTreatment = treatmentService.prevAndNext(currentTreatment.data!!).first
changeToTreatmentView(newTreatment, null)
}
@Subscribe open fun onNextTreatmentEvent(event: NextTreatmentEvent) {
if (changesChecker.checkChanges() == ChangeBehaviour.ABORT) {
return
}
val newTreatment = treatmentService.prevAndNext(currentTreatment.data!!).second
changeToTreatmentView(newTreatment, null)
}
@Subscribe open fun onDynTreatmentRequestAddEvent(event: DynTreatmentRequestAddEvent) {
val existingDynTreats = treatmentView!!.getAllDynTreatmentClasses()
val dynTreatmentManagers = DynTreatmentFactory.managersForAllExcept(existingDynTreats)
if (dynTreatmentManagers.isEmpty()) {
throw IllegalStateException("Requested to add dyn treatment but none is available!")
}
val popup = JPopupMenu()
dynTreatmentManagers.forEach { manager ->
val item = JMenuItem(manager.title)
item.addActionListener {
val dynTreat = manager.create()
treatmentView!!.addDynTreatment(dynTreat)
}
popup.add(item)
}
popup.show(event.popupSpec.component, event.popupSpec.x, event.popupSpec.y)
}
@Subscribe open fun onDynTreatmentRequestDeleteEvent(event: DynTreatmentRequestDeleteEvent) {
treatmentView!!.removeDynTreatmentAt(event.tabIndex)
}
fun checkChanges(): ChangeBehaviour {
return changesChecker.checkChanges()
}
private fun saveCurrentTreatment() {
val treatmentAfterSave: Treatment
val treatmentToSave: Treatment
try {
treatmentToSave = treatmentView!!.readTreatment()
} catch (e: InvalidTreatmentInputException) {
// thrown when e.g. hara meridian connection is invalid
dialogs.show(
title = "Ungültige Eingabe",
message = e.messageI18N,
type = DialogType.WARN)
return
}
log.debug("saveCurrentTreatment() ... treatmentToSave={}", treatmentToSave)
if (!treatmentToSave.yetPersisted) {
val insertedTreatment = treatmentService.insert(treatmentToSave)
bus.post(TreatmentCreatedEvent(insertedTreatment))
treatmentAfterSave = insertedTreatment
updatePrevNextStateFor(insertedTreatment)
} else {
treatmentService.update(treatmentToSave)
bus.post(TreatmentChangedEvent(treatmentToSave))
treatmentAfterSave = treatmentToSave
}
currentTreatment.data = treatmentAfterSave
treatmentView!!.wasSaved(treatmentAfterSave)
}
private fun changeToTreatmentView(treatment: Treatment?, prefillByAppointment: PrefillByAppointmentTreatment?) {
log.debug("changeToTreatmentView(treatment={}, prefilled={})", treatment, prefillByAppointment)
val client = currentClient.data
val selectedDynTreatment = treatmentView?.selectedDynTreatmentType()
treatmentView?.closePreparations()
val nullSafeTreatment = if (treatment != null) {
treatment
} else {
val number = treatmentService.calculateNextNumber(client)
val startDate = prefillByAppointment?.start ?: clock.now()
val duration = if (prefillByAppointment == null) Treatment.DEFAULT_DURATION else minutes(prefillByAppointment.duration)
Treatment.insertPrototype(
clientId = client.id!!,
number = number,
date = startDate,
duration = duration)
}
currentTreatment.data = nullSafeTreatment
treatmentView = treatmentViewFactory.create(client, nullSafeTreatment)
selectedDynTreatment?.also { treatmentView!!.trySelectDynTreatment(selectedDynTreatment) }
if (!nullSafeTreatment.yetPersisted) {
updatePrevNextState(false, false)
} else {
updatePrevNextStateFor(nullSafeTreatment)
}
bus.post(ChangeMainContentEvent(treatmentView!!))
}
private fun updatePrevNextStateFor(treatment: Treatment) {
val prevNext = treatmentService.prevAndNext(treatment)
updatePrevNextState(prevNext.first != null, prevNext.second != null)
}
private fun updatePrevNextState(enablePrev: Boolean, enableNext: Boolean) {
treatmentView!!.enablePrev(enablePrev)
treatmentView!!.enableNext(enableNext)
menuBar.treatmentPrevious.isEnabled = enablePrev
menuBar.treatmentNext.isEnabled = enableNext
}
}
class InvalidTreatmentInputException(message: String, val messageI18N: String) : RuntimeException(message)
| apache-2.0 | 91fbda5c06df11bf23360705d199c8a3 | 41.21097 | 156 | 0.706917 | 4.76381 | false | false | false | false |
braintree/braintree-android-drop-in | Drop-In/src/androidTest/java/com/braintreepayments/api/IntegrationTestFixtures.kt | 1 | 5794 | package com.braintreepayments.api
object IntegrationTestFixtures {
// language=JSON
const val CREDIT_CARD_ERROR_RESPONSE = """
{
"error": {
"message": "Credit card is invalid"
},
"fieldErrors": [
{
"field": "creditCard",
"fieldErrors": [
{
"field": "billingAddress",
"message": "Postal code is invalid"
},
{
"field": "cvv",
"message": "CVV is invalid"
},
{
"field": "expirationMonth",
"message": "Expiration month is invalid"
},
{
"field": "expirationYear",
"message": "Expiration year is invalid"
},
{
"field": "number",
"message": "Credit card number is required"
},
{
"field": "base",
"message": "Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code"
}
]
}
]
}
"""
// language=JSON
const val ERRORS_CREDIT_CARD_DUPLICATE = """
{
"error": {
"message": "Credit card is invalid"
},
"fieldErrors": [
{
"field": "creditCard",
"fieldErrors": [
{
"field": "number",
"message": "Duplicate card exists in the vault.",
"code": "81724"
}
]
}
]
}
"""
// language=JSON
const val CREDIT_CARD_NON_NUMBER_ERROR_RESPONSE = """
{
"error": {
"message": "Credit card is invalid"
},
"fieldErrors": [
{
"field": "creditCard",
"fieldErrors": [
{
"field": "billingAddress",
"message": "Postal code is invalid"
},
{
"field": "cvv",
"message": "CVV is invalid"
},
{
"field": "expirationMonth",
"message": "Expiration month is invalid"
},
{
"field": "expirationYear",
"message": "Expiration year is invalid"
},
{
"field": "base",
"message": "Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code"
}
]
}
]
}
"""
// language=JSON
const val CREDIT_CARD_EXPIRATION_ERROR_RESPONSE = """
{
"error": {
"message": "Credit card is invalid"
},
"fieldErrors": [
{
"field": "creditCard",
"fieldErrors": [
{
"field": "expirationMonth",
"message": "Expiration month is invalid"
},
{
"field": "expirationYear",
"message": "Expiration year is invalid"
},
{
"field": "base",
"message": "Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code"
}
]
}
]
}
"""
// language=JSON
const val VISA_CREDIT_CARD_RESPONSE = """
{
"creditCards": [
{
"type": "CreditCard",
"nonce": "123456-12345-12345-a-adfa",
"description": "ending in ••11",
"default": false,
"isLocked": false,
"securityQuestions": [],
"details":
{
"cardType": "Visa",
"lastTwo": "11",
"lastFour": "1111"
}
}
]
}
"""
// language=JSON
const val PAYMENT_METHODS_VISA_CREDIT_CARD = """
{
"type": "CreditCard",
"nonce": "12345678-1234-1234-1234-123456789012",
"description": "ending in ••11",
"default": false,
"isLocked": false,
"securityQuestions": [],
"details":
{
"cardType": "Visa",
"lastTwo": "11",
"lastFour": "1111"
}
}
"""
// language=JSON
const val PAYPAL_ACCOUNT_JSON = """
{
"paypalAccounts": [
{
"type": "PayPalAccount",
"nonce": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"description": "with email [email protected]",
"default": false,
"isLocked": false,
"securityQuestions": [],
"details": {
"email": "[email protected]",
"payerInfo": {
}
}
}
]
}
"""
// language=JSON
const val PAYMENT_METHODS_VENMO_ACCOUNT_RESPONSE = """
{
"venmoAccounts": [{
"type": "VenmoAccount",
"nonce": "fake-venmo-nonce",
"description": "VenmoAccount",
"consumed": false,
"default": true,
"details": {
"cardType": "Discover",
"username": "venmojoe"
}
}]
}
"""
} | mit | 30264e94ff4ce8cb3c5f779545b4815f | 26.956522 | 118 | 0.371932 | 5.166071 | false | false | false | false |
FurhatRobotics/example-skills | Dog/src/main/kotlin/furhatos/app/dog/dog/DogEngagementPolicy.kt | 1 | 3704 | package furhatos.app.dog.dog
import furhatos.event.Event
import furhatos.event.EventSystem
import furhatos.event.senses.SenseInteractionSpaces
import furhatos.event.senses.SenseUserEnter
import furhatos.event.senses.SenseUserLeave
import furhatos.records.Ellipse
import furhatos.records.Space
import furhatos.skills.EngagementPolicy
import furhatos.skills.UserManager
class DogEngagementPolicy(private val userManager: UserManager,
innerRadiusX: Double,
innerRadiusZ: Double = innerRadiusX,
outerRadiusX: Double,
outerRadiusZ: Double = outerRadiusX,
private val maxUsers: Int) : EngagementPolicy {
private val innerSpace : Ellipse
private val outerSpace : Ellipse
private val spaces : List<Space>
init {
if (innerRadiusX > outerRadiusX || innerRadiusZ > outerRadiusZ) {
throw IllegalArgumentException("Inner space has to be fully contained by outer space")
}
innerSpace = Ellipse("inner", userManager.robotLocation, innerRadiusX, innerRadiusZ)
outerSpace = Ellipse("outer", userManager.robotLocation, outerRadiusX, outerRadiusZ)
spaces = listOf(innerSpace, outerSpace)
}
constructor(userManager: UserManager,
innerRadius: Double,
outerRadius: Double,
maxUsers: Int) : this(userManager, innerRadius, innerRadius, outerRadius, outerRadius, maxUsers)
override fun checkEngagement() {
val engagedUsers = userManager.list.map { user -> user.id }
userManager.all.forEach { user ->
if (!user.isEngaged && user.isVisible && innerSpace.contains(user.head.location)) {
// User entered
if (userManager.count < maxUsers) {
user.isEngaged = true
sendSenseEnter(user.id)
}
} else if (user.isEngaged && (!user.isVisible || !outerSpace.contains(user.head.location))) {
// User left
user.isEngaged = false
sendSenseLeave(user.id)
} else if(user.isVisible && user.data.get("isSeen") != null) {
user.data.put("isSeen", true)
sendSenseVisible(user.id)
}
}
val newEngagedUsers = userManager.list.map { user -> user.id }
if (engagedUsers != newEngagedUsers) {
userManager.sendUserStatus()
}
}
override fun requestInteractionSpaces() {
EventSystem.send(SenseInteractionSpaces.Builder().spaces(spaces).buildEvent())
}
private fun sendSenseLeave(userId: String) {
val senseUserLeave = SenseUserLeave.Builder()
.userId(userId)
EventSystem.send(senseUserLeave.buildEvent())
}
private fun sendSenseEnter(userId: String) {
val senseUserEnter = SenseUserEnter.Builder()
.userId(userId)
EventSystem.send(senseUserEnter.buildEvent())
}
private fun sendSenseVisible(userId: String) {
val senseUserVisible = SenseUserVisible.Builder()
.userId(userId)
EventSystem.send(senseUserVisible.buildEvent())
}
}
class SenseUserVisible(build: Builder) : Event(build) {
val userId: String?
class Builder : Event.Builder<SenseUserVisible>() {
var userId: String? = null
override fun buildEvent(): SenseUserVisible {
return SenseUserVisible(this)
}
fun userId(userId: String): Builder {
this.userId = userId
return this
}
}
init {
userId = build.userId
}
} | mit | fb5486b92de97fabb51eca70d90a31c8 | 33.95283 | 112 | 0.62068 | 4.62422 | false | false | false | false |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/FunctionEntity.kt | 1 | 545 | package com.jiangkang.ktools
import android.app.Activity
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import java.io.Serializable
/**
* Created by jiangkang on 2017/9/5.
* description:
*/
class FunctionEntity : Serializable {
var name: String? = null
var activity: Class<out Activity?>? = null
@IdRes
var resId = 0
constructor(name: String?, activity: Class<out Activity?>?, resId: Int) {
this.name = name
this.activity = activity
this.resId = resId
}
} | mit | 828ad52ec1234708d884b04af91ac2da | 22.652174 | 77 | 0.688766 | 4.052239 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/data/gson/FeatureCollectionTypeAdapter.kt | 1 | 1513 | package mil.nga.giat.mage.data.gson
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import mil.nga.giat.mage.data.feed.FeedItem
import java.lang.UnsupportedOperationException
import java.lang.reflect.Type
import java.util.*
class FeatureCollectionTypeAdapter : TypeAdapter<List<FeedItem>>() {
val gson: Gson = GsonBuilder()
.registerTypeAdapterFactory(GeometryTypeAdapterFactory())
.create()
override fun read(`in`: JsonReader): List<FeedItem>? {
var items = emptyList<FeedItem>()
if (`in`.peek() == JsonToken.NULL) {
`in`.nextNull()
return items
}
if (`in`.peek() != JsonToken.BEGIN_OBJECT) {
`in`.skipValue()
return items
}
`in`.beginObject()
while (`in`.hasNext()) {
when(`in`.nextName()) {
"features" -> {
val type: Type = object : TypeToken<ArrayList<FeedItem>>() {}.type
items = gson.fromJson<ArrayList<FeedItem>>(`in`, type)
}
else -> `in`.skipValue()
}
}
`in`.endObject()
return items
}
override fun write(out: JsonWriter?, value: List<FeedItem>?) {
throw UnsupportedOperationException()
}
} | apache-2.0 | 621ca890322b46dc37b0d5212d881214 | 28.115385 | 86 | 0.604098 | 4.502976 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/data/feed/FeedDao.kt | 1 | 1413 | package mil.nga.giat.mage.data.feed
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface FeedDao {
@Transaction
fun upsert(feed: Feed): Boolean {
val id = insert(feed)
if (id == -1L) {
update(feed)
}
return id != -1L;
}
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(feed: Feed): Long
@Update(onConflict = OnConflictStrategy.IGNORE)
fun update(feed: Feed)
@Query("SELECT * FROM feed WHERE event_remote_id = :eventId")
fun feeds(eventId: String): List<Feed>
@Query("SELECT * FROM feed WHERE event_remote_id = :eventId")
fun feedsLiveData(eventId: String): LiveData<List<Feed>>
@Query("SELECT * FROM feed WHERE event_remote_id = :eventId AND items_have_spatial_dimension = 1")
fun mappableFeeds(eventId: String): LiveData<List<Feed>>
@Query("SELECT * FROM feed WHERE id = :feedId")
fun feed(feedId: String): LiveData<Feed>
@Query("SELECT * FROM feed WHERE id IN(:feedIds)")
fun feeds(feedIds: List<String>): LiveData<List<Feed>>
@Transaction
@Query("SELECT * FROM feed WHERE id = :feedId")
fun feedWithItems(feedId: String): List<FeedWithItems>
@Query("DELETE FROM feed WHERE event_remote_id = :eventId AND id NOT IN (:feedIds)")
fun preserveFeeds(eventId: String, feedIds: List<String>)
@Query("DELETE FROM feed")
fun destroy()
} | apache-2.0 | dcc21d03ceb88832bf8c33df7362c452 | 28.458333 | 102 | 0.661005 | 3.818919 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-117R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_17_R1/NMSPetArmorstand.kt | 1 | 17758 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_17_R1
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent
import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy
import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
import com.github.shynixn.petblocks.api.business.service.AIService
import com.github.shynixn.petblocks.api.business.service.ConfigurationService
import com.github.shynixn.petblocks.api.business.service.LoggingService
import com.github.shynixn.petblocks.api.persistence.entity.*
import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged
import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront
import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity
import net.minecraft.nbt.MojangsonParser
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.world.entity.*
import net.minecraft.world.entity.decoration.EntityArmorStand
import net.minecraft.world.entity.player.EntityHuman
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.RayTrace
import net.minecraft.world.phys.MovingObjectPosition
import net.minecraft.world.phys.Vec3D
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_17_R1.CraftServer
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld
import org.bukkit.entity.ArmorStand
import org.bukkit.entity.LivingEntity
import org.bukkit.event.entity.CreatureSpawnEvent
import org.bukkit.util.Vector
import java.lang.reflect.Field
/**
* Created by Shynixn 2020.
*/
class NMSPetArmorstand(owner: org.bukkit.entity.Player, private val petMeta: PetMeta) :
EntityArmorStand((owner.location.world as CraftWorld).handle, owner.location.x, owner.location.y, owner.location.z),
NMSPetProxy {
private var internalProxy: PetProxy? = null
private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("bn")
private var internalHitBox: EntityInsentient? = null
private val aiService = PetBlocksApi.resolve(AIService::class.java)
private val hasFlyCollisionsEnabled = PetBlocksApi.resolve(ConfigurationService::class.java)
.findValue<Boolean>("global-configuration.fly-wall-colision")
private var flyHasTakenOffGround = false
private var flyGravity: Boolean = false
private var flyWallCollisionVector: Vector? = null
private val locField = Entity::class.java.getDeclaredField("av")
// BukkitEntity has to be self cached since 1.14.
private var entityBukkit: Any? = null
/**
* Proxy handler.
*/
override val proxy: PetProxy get() = internalProxy!!
/**
* Initializes the nms design.
*/
init {
jumpingField.isAccessible = true
locField.isAccessible = true
val location = owner.location
val mcWorld = (location.world as CraftWorld).handle
val position = PositionEntity()
position.x = location.x
position.y = location.y
position.z = location.z
position.yaw = location.yaw.toDouble()
position.pitch = location.pitch.toDouble()
position.worldName = location.world!!.name
position.relativeFront(3.0)
this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl")
.getDeclaredConstructor(
PetMeta::class.java,
ArmorStand::class.java,
org.bukkit.entity.Player::class.java
)
.newInstance(petMeta, this.bukkitEntity, owner) as PetProxy
petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true)
applyNBTTagForArmorstand()
}
/**
* Spawns a new hitbox
*/
private fun spawnHitBox() {
val shouldDeleteHitBox = shouldDeleteHitBox()
if (shouldDeleteHitBox && internalHitBox != null) {
(internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld()
internalHitBox = null
proxy.changeHitBox(internalHitBox)
}
val player = proxy.getPlayer<org.bukkit.entity.Player>()
this.applyNBTTagForArmorstand()
val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0
if (hasRidingAi) {
val armorstand = proxy.getHeadArmorstand<ArmorStand>()
if (!armorstand.passengers.contains(player)) {
armorstand.velocity = Vector(0, 1, 0)
armorstand.addPassenger(player)
}
return
} else {
for (passenger in player.passengers) {
if (passenger == this.bukkitEntity) {
player.removePassenger(passenger)
}
}
}
val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing }
if (aiWearing != null) {
this.applyNBTTagForArmorstand()
val armorstand = proxy.getHeadArmorstand<ArmorStand>()
if (!player.passengers.contains(armorstand)) {
player.addPassenger(armorstand)
}
return
}
val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying }
if (flyingAi != null) {
if (internalHitBox == null) {
internalHitBox = NMSPetBat(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetBat).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
return
}
val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping }
if (hoppingAi != null) {
if (internalHitBox == null) {
internalHitBox = NMSPetRabbit(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
return
}
if (internalHitBox == null) {
internalHitBox = NMSPetVillager(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetVillager).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
}
/**
* Disable setting slots.
*/
override fun setSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) {
}
/**
* Sets the slot securely.
*/
fun setSecureSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) {
super.setSlot(enumitemslot, itemstack)
}
/**
* Entity tick.
*/
override fun doTick() {
super.doTick()
try {
proxy.run()
if (isRemoved) {
return
}
if (this.internalHitBox != null) {
val location = internalHitBox!!.bukkitEntity.location
val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return
var y = location.y + (aiGoal as AIMovement).movementYOffSet
if (this.isSmall) {
y += 0.6
}
if (y > -100) {
this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch)
this.setMot(
this.internalHitBox!!.mot.x, this.internalHitBox!!.mot.y, this.internalHitBox!!.mot.z
)
}
}
if (proxy.teleportTarget != null) {
val location = proxy.teleportTarget!! as Location
if (this.internalHitBox != null) {
this.internalHitBox!!.setPositionRotation(
location.x,
location.y,
location.z,
location.yaw,
location.pitch
)
}
this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch)
proxy.teleportTarget = null
}
if (PetMeta::aiGoals.hasChanged(petMeta)) {
val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy)
Bukkit.getPluginManager().callEvent(event)
if (event.isCancelled) {
return
}
spawnHitBox()
proxy.aiGoals = null
}
} catch (e: Exception) {
PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e)
}
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPetArmorstand {
if (this.entityBukkit == null) {
entityBukkit = CraftPetArmorstand(Bukkit.getServer() as CraftServer, this)
val field = Entity::class.java.getDeclaredField("bukkitEntity")
field.isAccessible = true
field.set(this, entityBukkit)
}
return this.entityBukkit as CraftPetArmorstand
}
/**
* Riding function.
*/
override fun g(vec3d: Vec3D) {
val human = this.passengers.firstOrNull { p -> p is EntityHuman }
if (this.passengers == null || human == null) {
flyHasTakenOffGround = false
return
}
val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding }
if (aiFlyRiding != null) {
rideInAir(human as EntityHuman, aiFlyRiding as AIFlyRiding)
return
}
val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding }
if (aiGroundRiding != null) {
rideOnGround(human as EntityHuman, aiGroundRiding as AIGroundRiding, vec3d.y)
return
}
}
/**
* Handles the riding in air.
*/
private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) {
// Show entity and player rotation.
val sideMot: Float = human.bo * 0.5f
var forMot: Float = human.bq
yRot = human.yRot
this.x = this.yRot
this.xRot = human.xRot * 0.5f
this.setYawPitch(this.yRot, this.xRot)
this.aX = this.yRot
this.aZ = this.aX
// Calculate flying direction and fix yaw in flying direction.
val flyingVector = Vector()
val flyingLocation = Location(this.world.world, this.locX(), this.locY(), this.locZ())
if (sideMot < 0.0f) {
flyingLocation.yaw = human.yRot - 90
flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5))
} else if (sideMot > 0.0f) {
flyingLocation.yaw = human.yRot + 90
flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5))
}
if (forMot < 0.0f) {
flyingLocation.yaw = human.yRot
flyingVector.add(flyingLocation.direction.normalize().multiply(0.5))
} else if (forMot > 0.0f) {
flyingLocation.yaw = human.yRot
flyingVector.add(flyingLocation.direction.normalize().multiply(0.5))
}
// If the player has just started riding move it up.
if (!flyHasTakenOffGround) {
flyHasTakenOffGround = true
flyingVector.setY(1f)
}
if (this.isPassengerJumping()) {
flyingVector.setY(0.5f)
this.flyGravity = true
this.flyWallCollisionVector = null
} else if (this.flyGravity) {
flyingVector.setY(-0.2f)
}
// If wall collision has happened.
if (flyWallCollisionVector != null) {
this.setPosition(
this.flyWallCollisionVector!!.x,
this.flyWallCollisionVector!!.y,
this.flyWallCollisionVector!!.z
)
return
}
flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed))
this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z)
if (isCollidingWithWall()) {
// Cache current position if entity is going to collide with wall.
this.flyWallCollisionVector = flyingLocation.toVector()
}
}
/**
* Gets if this entity is going to collide with a wall.
*/
private fun isCollidingWithWall(): Boolean {
val currentLocationVector = Vec3D(this.locX(), this.locY(), this.locZ())
val directionVector =
Vec3D(this.locX() + this.mot.x * 1.5, this.locY() + this.mot.y * 1.5, this.locZ() + this.mot.z * 1.5)
val rayTrace = RayTrace(
currentLocationVector,
directionVector,
RayTrace.BlockCollisionOption.a,
RayTrace.FluidCollisionOption.a,
null
)
val movingObjectPosition = this.world.rayTrace(rayTrace)
return movingObjectPosition.type == MovingObjectPosition.EnumMovingObjectType.b && hasFlyCollisionsEnabled
}
/**
* Handles the riding on ground.
*/
private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding, f2: Double) {
val sideMot: Float = human.bo * 0.5f
var forMot: Float = human.bq
yRot = human.yRot
this.x = this.yRot
this.xRot = human.xRot * 0.5f
this.setYawPitch(this.yRot, this.xRot)
this.aX = this.yRot
this.aZ = this.aX
if (forMot <= 0.0f) {
forMot *= 0.25f
}
if (this.isOnGround && this.isPassengerJumping()) {
this.setMot(this.mot.x, 0.5, this.mot.z)
}
this.O = ai.climbingHeight.toFloat()
this.bb = this.ev() * 0.1f
if (!this.world.isClientSide) {
this.r(0.35f)
super.g(Vec3D(sideMot * ai.ridingSpeed, f2, forMot * ai.ridingSpeed))
}
}
/**
* Applies the entity NBT to the hitbox.
*/
private fun applyNBTTagToHitBox(hitBox: EntityInsentient) {
val compound = NBTTagCompound()
hitBox.saveData(compound)
applyAIEntityNbt(
compound,
this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList()
)
hitBox.loadData(compound)
// CustomNameVisible does not working via NBT Tags.
hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1
}
/**
* Applies the entity NBT to the armorstand.
*/
private fun applyNBTTagForArmorstand() {
val compound = NBTTagCompound()
this.saveData(compound)
applyAIEntityNbt(
compound,
this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList()
)
this.loadData(compound)
// CustomNameVisible does not working via NBT Tags.
this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1
}
/**
* Applies the raw NbtData to the given target.
*/
private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) {
val compoundMapField = NBTTagCompound::class.java.getDeclaredField("x")
compoundMapField.isAccessible = true
val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?>
for (rawNbtData in rawNbtDatas) {
if (rawNbtData.isEmpty()) {
continue
}
val parsedCompound = try {
MojangsonParser.parse(rawNbtData)
} catch (e: Exception) {
throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e)
}
val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *>
for (key in parsedCompoundMap.keys) {
rootCompoundMap[key] = parsedCompoundMap[key]
}
}
}
/**
* Should the hitbox of the armorstand be deleted.
*/
private fun shouldDeleteHitBox(): Boolean {
val hasEmptyHitBoxAi =
petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null
if (hasEmptyHitBoxAi) {
return true
}
if (internalHitBox != null) {
if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) {
return true
} else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) {
return true
} else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) {
return true
}
}
return false
}
/**
* Gets if a passenger of the pet is jumping.
*/
private fun isPassengerJumping(): Boolean {
return passengers != null && !this.passengers.isEmpty() && jumpingField.getBoolean(this.passengers[0])
}
}
| apache-2.0 | cfe19cee42ddcc07b489d2fe5d8770d4 | 34.587174 | 120 | 0.613414 | 4.513981 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-115R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_15_R1/NMSPetArmorstand.kt | 1 | 20004 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_15_R1
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent
import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy
import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
import com.github.shynixn.petblocks.api.business.service.AIService
import com.github.shynixn.petblocks.api.business.service.ConfigurationService
import com.github.shynixn.petblocks.api.business.service.LoggingService
import com.github.shynixn.petblocks.api.persistence.entity.*
import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged
import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront
import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity
import net.minecraft.server.v1_15_R1.*
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld
import org.bukkit.entity.ArmorStand
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.entity.CreatureSpawnEvent
import org.bukkit.util.Vector
import java.lang.reflect.Field
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class NMSPetArmorstand(owner: Player, private val petMeta: PetMeta) :
EntityArmorStand((owner.location.world as CraftWorld).handle, owner.location.x, owner.location.y, owner.location.z),
NMSPetProxy {
private var internalProxy: PetProxy? = null
private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("jumping")
private var internalHitBox: EntityInsentient? = null
private val aiService = PetBlocksApi.resolve(AIService::class.java)
private val hasFlyCollisionsEnabled = PetBlocksApi.resolve(ConfigurationService::class.java)
.findValue<Boolean>("global-configuration.fly-wall-colision")
private var flyHasTakenOffGround = false
private var flyGravity: Boolean = false
private var flyWallCollisionVector: Vector? = null
private val locFieldX = Entity::class.java.getDeclaredField("locX")
private val locFieldY = Entity::class.java.getDeclaredField("locY")
private val locFieldZ = Entity::class.java.getDeclaredField("locZ")
// BukkitEntity has to be self cached since 1.14.
private var entityBukkit: Any? = null
/**
* Proxy handler.
*/
override val proxy: PetProxy get() = internalProxy!!
/**
* Initializes the nms design.
*/
init {
jumpingField.isAccessible = true
locFieldX.isAccessible = true
locFieldY.isAccessible = true
locFieldZ.isAccessible = true
val location = owner.location
val mcWorld = (location.world as CraftWorld).handle
val position = PositionEntity()
position.x = location.x
position.y = location.y
position.z = location.z
position.yaw = location.yaw.toDouble()
position.pitch = location.pitch.toDouble()
position.worldName = location.world!!.name
position.relativeFront(3.0)
this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl")
.getDeclaredConstructor(PetMeta::class.java, ArmorStand::class.java, Player::class.java)
.newInstance(petMeta, this.bukkitEntity, owner) as PetProxy
petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true)
applyNBTTagForArmorstand()
}
/**
* Spawns a new hitbox
*/
private fun spawnHitBox() {
val shouldDeleteHitBox = shouldDeleteHitBox()
if (shouldDeleteHitBox && internalHitBox != null) {
(internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld()
internalHitBox = null
proxy.changeHitBox(internalHitBox)
}
val player = proxy.getPlayer<Player>()
this.applyNBTTagForArmorstand()
val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0
if (hasRidingAi) {
val armorstand = proxy.getHeadArmorstand<ArmorStand>()
if (!armorstand.passengers.contains(player)) {
armorstand.velocity = Vector(0, 1, 0)
armorstand.addPassenger(player)
}
return
} else {
for (passenger in player.passengers) {
if (passenger == this.bukkitEntity) {
player.removePassenger(passenger)
}
}
}
val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing }
if (aiWearing != null) {
this.applyNBTTagForArmorstand()
val armorstand = proxy.getHeadArmorstand<ArmorStand>()
if (!player.passengers.contains(armorstand)) {
player.addPassenger(armorstand)
}
return
}
val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying }
if (flyingAi != null) {
if (internalHitBox == null) {
internalHitBox = NMSPetBat(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetBat).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
return
}
val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping }
if (hoppingAi != null) {
if (internalHitBox == null) {
internalHitBox = NMSPetRabbit(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
return
}
if (internalHitBox == null) {
internalHitBox = NMSPetVillager(this, bukkitEntity.location)
proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity)
}
val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals)
(internalHitBox as NMSPetVillager).applyPathfinders(aiGoals)
applyNBTTagToHitBox(internalHitBox!!)
}
/**
* Disable setting slots.
*/
override fun setSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) {
}
/**
* Sets the slot securely.
*/
fun setSecureSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) {
super.setSlot(enumitemslot, itemstack)
}
/**
* Entity tick.
*/
override fun doTick() {
super.doTick()
try {
proxy.run()
if (dead) {
return
}
if (this.internalHitBox != null) {
val location = internalHitBox!!.bukkitEntity.location
val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return
var y = location.y + (aiGoal as AIMovement).movementYOffSet
if (this.isSmall) {
y += 0.6
}
if (y > -100) {
this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch)
this.setMot(this.internalHitBox!!.mot.x, this.internalHitBox!!.mot.y, this.internalHitBox!!.mot.z)
}
}
if (proxy.teleportTarget != null) {
val location = proxy.teleportTarget!! as Location
if (this.internalHitBox != null) {
this.internalHitBox!!.setPositionRotation(
location.x,
location.y,
location.z,
location.yaw,
location.pitch
)
}
this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch)
proxy.teleportTarget = null
}
if (PetMeta::aiGoals.hasChanged(petMeta)) {
val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy)
Bukkit.getPluginManager().callEvent(event)
if (event.isCancelled) {
return
}
spawnHitBox()
proxy.aiGoals = null
}
} catch (e: Exception) {
PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e)
}
}
/**
* Overrides the moving of the pet design.
*/
override fun move(enummovetype: EnumMoveType?, vec3d: Vec3D?) {
super.move(enummovetype, vec3d)
if (passengers == null || this.passengers.firstOrNull { p -> p is EntityHuman } == null) {
return
}
val groundAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding }
val airAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding }
var offSet = when {
groundAi != null -> (groundAi as AIGroundRiding).ridingYOffSet
airAi != null -> (airAi as AIFlyRiding).ridingYOffSet
else -> 0.0
}
if (this.isSmall) {
offSet += 0.6
}
val axisBoundingBox = this.boundingBox
// This way of setting the locations fields ensures compatibility with PaperSpigot.
this.locFieldX.set(this, (axisBoundingBox.minX + axisBoundingBox.maxX) / 2.0)
this.locFieldY.set(this, axisBoundingBox.minY + offSet)
this.locFieldZ.set(this, (axisBoundingBox.minZ + axisBoundingBox.maxZ) / 2.0)
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPetArmorstand {
if (this.entityBukkit == null) {
entityBukkit = CraftPetArmorstand(this.world.server, this)
val field = Entity::class.java.getDeclaredField("bukkitEntity")
field.isAccessible = true
field.set(this, entityBukkit)
}
return this.entityBukkit as CraftPetArmorstand
}
/**
* Riding function.
*/
override fun e(vec3d: Vec3D) {
val human = this.passengers.firstOrNull { p -> p is EntityHuman }
if (this.passengers == null || human == null) {
flyHasTakenOffGround = false
return
}
val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding }
if (aiFlyRiding != null) {
rideInAir(human as EntityHuman, aiFlyRiding as AIFlyRiding)
return
}
val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding }
if (aiGroundRiding != null) {
rideOnGround(human as EntityHuman, aiGroundRiding as AIGroundRiding, vec3d.y)
return
}
}
/**
* Handles the riding in air.
*/
private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) {
// Show entity and player rotation.
val sideMot: Float = human.aZ * 0.5f
val forMot: Float = human.bb
this.yaw = human.yaw
this.lastYaw = this.yaw
this.pitch = human.pitch * 0.5f
this.setYawPitch(this.yaw, this.pitch)
this.aI = this.yaw
this.aK = this.aI
// Calculate flying direction and fix yaw in flying direction.
val flyingVector = Vector()
val flyingLocation = Location(this.world.world, this.locX(), this.locY(), this.locZ())
if (sideMot < 0.0f) {
flyingLocation.yaw = human.yaw - 90
flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5))
} else if (sideMot > 0.0f) {
flyingLocation.yaw = human.yaw + 90
flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5))
}
if (forMot < 0.0f) {
flyingLocation.yaw = human.yaw
flyingVector.add(flyingLocation.direction.normalize().multiply(0.5))
} else if (forMot > 0.0f) {
flyingLocation.yaw = human.yaw
flyingVector.add(flyingLocation.direction.normalize().multiply(0.5))
}
// If the player has just started riding move it up.
if (!flyHasTakenOffGround) {
flyHasTakenOffGround = true
flyingVector.setY(1f)
}
if (this.isPassengerJumping()) {
flyingVector.setY(0.5f)
this.flyGravity = true
this.flyWallCollisionVector = null
} else if (this.flyGravity) {
flyingVector.setY(-0.2f)
}
// If wall collision has happened.
if (flyWallCollisionVector != null) {
this.setPosition(
this.flyWallCollisionVector!!.x,
this.flyWallCollisionVector!!.y,
this.flyWallCollisionVector!!.z
)
return
}
flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed))
this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z)
if (isCollidingWithWall()) {
// Cache current position if entity is going to collide with wall.
this.flyWallCollisionVector = flyingLocation.toVector()
}
}
/**
* Gets if this entity is going to collide with a wall.
*/
private fun isCollidingWithWall(): Boolean {
val currentLocationVector = Vec3D(this.locX(), this.locY(), this.locZ())
val directionVector =
Vec3D(this.locX() + this.mot.x * 1.5, this.locY() + this.mot.y * 1.5, this.locZ() + this.mot.z * 1.5)
val rayTrace = RayTrace(
currentLocationVector,
directionVector,
RayTrace.BlockCollisionOption.COLLIDER,
RayTrace.FluidCollisionOption.NONE,
null
)
val movingObjectPosition = this.world.rayTrace(rayTrace)
return movingObjectPosition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK && hasFlyCollisionsEnabled
}
/**
* Handles the riding on ground.
*/
private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding, f2: Double) {
val sideMot: Float = human.aZ * 0.5f
var forMot: Float = human.bb
this.yaw = human.yaw
this.lastYaw = this.yaw
this.pitch = human.pitch * 0.5f
this.setYawPitch(this.yaw, this.pitch)
this.aI = this.yaw
this.aK = this.aI
if (forMot <= 0.0f) {
forMot *= 0.25f
}
if (this.onGround && this.isPassengerJumping()) {
this.setMot(this.mot.x, 0.5, this.mot.z)
}
this.H = ai.climbingHeight.toFloat()
this.aM = this.ds() * 0.1f
if (!this.world.isClientSide) {
this.o(0.35f)
super.e(Vec3D(sideMot * ai.ridingSpeed, f2, forMot * ai.ridingSpeed))
}
this.aC = this.aD
val d0 = this.locX() - this.lastX
val d1 = this.locZ() - this.lastZ
var f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0f
if (f4 > 1.0f) {
f4 = 1.0f
}
this.aD += (f4 - this.aD) * 0.4f
this.aE += this.aD
}
/**
* Applies the entity NBT to the hitbox.
*/
private fun applyNBTTagToHitBox(hitBox: EntityInsentient) {
val compound = NBTTagCompound()
hitBox.b(compound)
applyAIEntityNbt(
compound,
this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList()
)
hitBox.a(compound)
// CustomNameVisible does not working via NBT Tags.
hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1
}
/**
* Applies the entity NBT to the armorstand.
*/
private fun applyNBTTagForArmorstand() {
val compound = NBTTagCompound()
this.b(compound)
applyAIEntityNbt(
compound,
this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList()
)
this.a(compound)
// CustomNameVisible does not working via NBT Tags.
this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1
}
/**
* Applies the raw NbtData to the given target.
*/
private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) {
val compoundMapField = NBTTagCompound::class.java.getDeclaredField("map")
compoundMapField.isAccessible = true
val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?>
for (rawNbtData in rawNbtDatas) {
if (rawNbtData.isEmpty()) {
continue
}
val parsedCompound = try {
MojangsonParser.parse(rawNbtData)
} catch (e: Exception) {
throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e)
}
val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *>
for (key in parsedCompoundMap.keys) {
rootCompoundMap[key] = parsedCompoundMap[key]
}
}
}
/**
* Should the hitbox of the armorstand be deleted.
*/
private fun shouldDeleteHitBox(): Boolean {
val hasEmptyHitBoxAi =
petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null
if (hasEmptyHitBoxAi) {
return true
}
if (internalHitBox != null) {
if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) {
return true
} else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) {
return true
} else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) {
return true
}
}
return false
}
/**
* Gets if a passenger of the pet is jumping.
*/
private fun isPassengerJumping(): Boolean {
return passengers != null && !this.passengers.isEmpty() && jumpingField.getBoolean(this.passengers[0])
}
}
| apache-2.0 | 24296f88f96779fb1d2130da51cfdb49 | 34.849462 | 120 | 0.616727 | 4.441385 | false | false | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/widget/collection/LazyCollectionChildren.kt | 1 | 3762 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.widget.collection
import com.facebook.litho.Component
/**
* A container for the children of a Lazy Collection. Manages the creation of ids, and callback
* registration.
*/
class LazyCollectionChildren {
val collectionChildren
get() = collectionChildrenBuilder.toList()
internal val effectiveIndexToId: MutableMap<Int, MutableSet<Any>> by lazy { mutableMapOf() }
internal val idToChild: MutableMap<Any, CollectionChild> by lazy { mutableMapOf() }
private val collectionChildrenBuilder = mutableListOf<CollectionChild>()
private var nextStaticId = 0
private val typeToFreq: MutableMap<Int, Int> by lazy { mutableMapOf() }
/** Prepare the final id that will be assigned to the child. */
private fun getResolvedId(id: Any?, component: Component? = null): Any {
// Generate an id that is unique to the [CollectionContainerScope] in which it was defined
// If an id has been explicitly defined on the child, use that
// If the child has a component generate an id including the type and frequency
// Otherwise the child has a null component or a lambda generator, so generate an id.
return id ?: generateIdForComponent(component) ?: generateStaticId()
}
private fun generateStaticId(): Any {
return "staticId:${nextStaticId++}"
}
/** Generate an id for a non-null Component. */
private fun generateIdForComponent(component: Component?): Any? {
val typeId = component?.typeId ?: return null
typeToFreq[typeId] = (typeToFreq[typeId] ?: 0) + 1
return "${typeId}:${typeToFreq[typeId]}"
}
private fun maybeRegisterForOnEnterOrNearCallbacks(child: CollectionChild) {
child.onNearViewport ?: return
idToChild[child.id] = child
val index = collectionChildrenBuilder.lastIndex
val effectiveIndex = index - child.onNearViewport.offset
effectiveIndexToId.getOrPut(effectiveIndex) { mutableSetOf() }.add(child.id)
}
fun add(
component: Component?,
id: Any? = null,
isSticky: Boolean = false,
isFullSpan: Boolean = false,
spanSize: Int? = null,
onNearViewport: OnNearCallback? = null,
) {
val resolvedId = getResolvedId(id, component)
component ?: return
val child =
CollectionChild(
resolvedId,
component,
null,
isSticky,
isFullSpan,
spanSize,
null,
onNearViewport,
)
collectionChildrenBuilder.add(child)
maybeRegisterForOnEnterOrNearCallbacks(child)
}
fun add(
id: Any? = null,
isSticky: Boolean = false,
isFullSpan: Boolean = false,
spanSize: Int? = null,
onNearViewport: OnNearCallback? = null,
deps: Array<Any?>,
componentFunction: () -> Component?,
) {
val child =
CollectionChild(
getResolvedId(id),
null,
{ componentFunction() },
isSticky,
isFullSpan,
spanSize,
deps,
onNearViewport,
)
collectionChildrenBuilder.add(child)
maybeRegisterForOnEnterOrNearCallbacks(child)
}
}
| apache-2.0 | 644ec7d46c299beb9fc87778a0cb19bf | 32 | 95 | 0.67411 | 4.39486 | false | false | false | false |
google/horologist | network-awareness/src/test/java/com/google/android/horologist/networks/rules/helpers/Fixtures.kt | 1 | 2016 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistNetworksApi::class)
package com.google.android.horologist.networks.rules.helpers
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.NetworkInfo
import com.google.android.horologist.networks.data.NetworkStatus
import com.google.android.horologist.networks.data.Networks
import com.google.android.horologist.networks.data.Status
object Fixtures {
fun networks(default: NetworkStatus?, vararg rest: NetworkStatus): Networks {
return Networks(default, listOfNotNull(default, *rest))
}
val wifi = NetworkStatus(
id = "wlan0",
status = Status.Available,
networkInfo = NetworkInfo.Wifi("wifi", null),
addresses = listOf(),
capabilities = null,
linkProperties = null,
bindSocket = {}
)
val bt = NetworkStatus(
id = "bt",
status = Status.Available,
networkInfo = NetworkInfo.Bluetooth("bt"),
addresses = listOf(),
capabilities = null,
linkProperties = null,
bindSocket = {}
)
val cell = NetworkStatus(
id = "cell",
status = Status.Available,
networkInfo = NetworkInfo.Cellular("cell", false),
addresses = listOf(),
capabilities = null,
linkProperties = null,
bindSocket = {}
)
}
| apache-2.0 | 2614293ac8cc03ea086958c9c7ad1cbb | 32.04918 | 81 | 0.6875 | 4.520179 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2018/Day19.kt | 1 | 705 | package com.s13g.aoc.aoc2018
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
class Day19 : Solver {
override fun solve(lines: List<String>): Result {
val ipIndex = lines[0].split(" ")[1].toInt()
val program = parseInstructions(lines)
val vmA = AocVm(ipIndex, program)
vmA.runUntilHalt()
val solutionA = vmA.getReg(0).toString()
// This would run for years.... see the go solution for an explanation
// https://github.com/shaeberling/euler/blob/master/go/src/aoc18/problems/p19/p19.go
// val vmB = AocVm(ipIndex, program)
// vmB.setReg(0, 1)
// vmB.runUntilHalt()
// val solutionB = vmB.getReg(0).toString()
return Result(solutionA, "10750428")
}
} | apache-2.0 | 7028ec5d7cd9f416bab5ff769bbbf0ba | 29.695652 | 88 | 0.678014 | 2.949791 | false | false | false | false |
HendraAnggrian/kota | kota/src/dialogs/Alerts.kt | 1 | 1705 | @file:JvmMultifileClass
@file:JvmName("DialogsKt")
@file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.app.AlertDialog
import android.app.Fragment
import android.content.Context
import android.support.annotation.StringRes
@JvmOverloads
inline fun Context.alert(
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = AlertDialog.Builder(this)
.create()
.apply { init?.invoke(this) }
@JvmOverloads
inline fun Fragment.alert(
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = activity.alert(init)
@JvmOverloads
inline fun Context.alert(
message: CharSequence,
title: CharSequence? = null,
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = AlertDialog.Builder(this)
.setMessage(message)
.apply { title?.let { setTitle(it) } }
.create()
.apply { init?.invoke(this) }
@JvmOverloads
inline fun Fragment.alert(
message: CharSequence,
title: CharSequence? = null,
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = activity.alert(message, title, init)
@JvmOverloads
inline fun Context.alert(
@StringRes message: Int,
@StringRes title: Int? = null,
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = AlertDialog.Builder(this)
.setMessage(message)
.apply { title?.let { setTitle(it) } }
.create()
.apply { init?.invoke(this) }
@JvmOverloads
inline fun Fragment.alert(
@StringRes message: Int,
@StringRes title: Int? = null,
noinline init: (AlertDialog.() -> Unit)? = null
): AlertDialog = activity.alert(message, title, init) | apache-2.0 | 2e193c941999fbffccfe6ec011dd3deb | 28.413793 | 55 | 0.651613 | 4.118357 | false | false | false | false |
QiangYoung/game-base | game-log/src/test/kotlin/com/yangqiang/log/ItemLog.kt | 1 | 1582 | /**
* 创建日期: 2017年12月14日 15:06
* 创建作者: 杨 强 <[email protected]>
*/
package com.yangqiang.log
import com.yangqiang.api.coder.Decoder
import com.yangqiang.api.coder.Encoder
import com.yangqiang.api.util.SerializeUtil
import com.yangqiang.data.annotation.Mapper
import com.yangqiang.log.annotation.Column
import com.yangqiang.log.annotation.Table
import org.slf4j.LoggerFactory
import java.sql.Timestamp
/**
* 道具日志
* @author 老 鬼
*/
@Table("item_log", primaryKeys = ["id"], charset = "utf8mb4")
class ItemLog : ILog {
override val log = LoggerFactory.getLogger("game_log")
@Column(type = "bigint", autoIncrement = true)
var id: Long = 0
@Column(type = "varchar", size = 256)
var name: String = ""
@Column(type = "datetime")
var time: Timestamp? = null
@Column(type = "int")
var itemId: Int = 0
@Column(type = "int")
var itemNum: Int = 0
@Mapper(DataDecoder::class)
@Column(type = "blob", encoder = [SerializeConverter::class])
var data: ChaosData = ChaosData()
override fun toString(): String {
return "ItemLog(log=$log, id=$id, name='$name', time=$time, itemId=$itemId, itemNum=$itemNum, data=$data)"
}
}
// 测试的时候添加相关包
class SerializeConverter : Encoder<Any, ByteArray> {
override fun encode(t: Any): ByteArray {
return SerializeUtil.encode(t)
}
}
class DataDecoder : Decoder<ByteArray, ChaosData> {
override fun decode(src: ByteArray): ChaosData {
return SerializeUtil.decode(src, ChaosData::class.java)
}
} | apache-2.0 | fd4fd0e8592d6edf9ec3d6ce91471f36 | 25.754386 | 114 | 0.674541 | 3.298701 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/model/vndb/Staff.kt | 1 | 662 | package com.booboot.vndbandroid.model.vndb
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Staff(
var id: Int = 0,
var name: String = "",
var original: String? = null,
var _gender: String? = null,
var language: String = "",
var links: Links = Links(),
var description: String? = null,
var aliases: List<Array<Any>> = emptyList(),
var main_alias: Int = 0,
var vns: List<StaffVns> = emptyList(),
var voiced: List<StaffVoiced> = emptyList(),
var note: String? = null
) {
var gender = _gender
set(gender) {
field = gender?.toUpperCase() ?: gender
}
} | gpl-3.0 | a61b767702c9b75f9f51b80bbc7afdba | 26.625 | 51 | 0.614804 | 3.637363 | false | false | false | false |
uber/RIBs | android/tooling/rib-intellij-plugin/src/main/kotlin/com/uber/intellij/plugin/android/rib/RibHierarchyUtils.kt | 1 | 6475 | /*
* Copyright (C) 2021. Uber Technologies
*
* 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.uber.intellij.plugin.android.rib
/*
* Copyright (c) 2018-2019 Uber Technologies, 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.
*/
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.ui.awt.RelativePoint
import com.uber.intellij.plugin.android.rib.io.RibNode
import com.uber.intellij.plugin.android.rib.io.RibView
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.UUID
/** Utility class used by the Rib hierarchy browser component. */
@SuppressWarnings("TooManyFunctions")
class RibHierarchyUtils {
private constructor()
companion object {
/** Constant used to represent empty UUID */
val EMPTY_UUID: UUID = UUID(0, 0)
/** Time for balloon to fade out */
private const val BALLOON_FADE_OUT_TIME: Long = 3000
/** Name of layout folder */
private const val LAYOUT_FOLDER_NAME: String = "layout"
/** Build root element, used when class is not available. */
fun buildRootElement(project: Project): PsiClass {
val psiClass: PsiClass? =
JavaPsiFacade.getInstance(project)
.findClass(Object::class.java.name, GlobalSearchScope.allScope(project))
checkNotNull(psiClass)
return psiClass!!
}
/** Return the psiClass corresponding to the given class name. */
fun getPsiClass(project: Project, name: String): PsiClass {
val psiClass: PsiClass? =
JavaPsiFacade.getInstance(project).findClass(name, GlobalSearchScope.allScope(project))
return psiClass ?: buildRootElement(project)
}
/** Check if the element supplied is a root element. */
fun isRootElement(element: PsiElement?): Boolean {
return element is PsiClass && element.qualifiedName == Object::class.java.name
}
/** Format fully qualified class name. */
fun formatQualifiedName(qualifiedName: String): String {
val index: Int = qualifiedName.lastIndexOf(".")
return if (index > 0) qualifiedName.substring(0, index) else qualifiedName
}
/** Format fully qualified class name. */
fun formatSimpleName(qualifiedName: String): String {
val index: Int = qualifiedName.lastIndexOf(".")
return if (index > 0) qualifiedName.substring(index + 1) else qualifiedName
}
/** Find node with the given ID in node hierarchy */
@SuppressWarnings("ReturnCount")
fun findRibNodeRecursive(ribNode: RibNode?, id: UUID): RibNode? {
if (ribNode == null) {
return null
}
if (ribNode.id == id.toString()) {
return ribNode
}
for (element in ribNode.children) {
val node: RibNode? = findRibNodeRecursive(element, id)
if (node != null) {
return node
}
}
return null
}
/** Find view with the given ID in view hierarchy */
@SuppressWarnings("ReturnCount")
fun findRibViewRecursive(ribView: RibView?, id: UUID): RibView? {
if (ribView == null) {
return null
}
if (ribView.id == id.toString()) {
return ribView
}
for (childView in ribView.children) {
val view: RibView? = findRibViewRecursive(childView, id)
if (view != null) {
return view
}
}
return null
}
/** Get a view tag value suffix */
fun getTagValueSuffix(value: String?): String? {
if (value == null) {
return null
}
val index = value.indexOf("/")
return if (index > 0) value.substring(index + 1) else value
}
/** Get virtual file from path */
@SuppressWarnings("MagicNumber")
fun getVirtualFile(filePath: String): VirtualFile? {
val actualPath: Path = Paths.get(filePath)
val pathFile: File = actualPath.toFile()
return LocalFileSystem.getInstance().findFileByIoFile(pathFile)
}
/** Returns whether virtual file belongs to project and appears to be a layout file */
fun isProjectLayoutFile(project: Project, file: VirtualFile): Boolean {
return ProjectRootManager.getInstance(project).fileIndex.isInContent(file) &&
file.fileType is XmlFileType &&
file.path.contains("/$LAYOUT_FOLDER_NAME/")
}
/** Display popup balloon. */
fun displayPopup(
message: String,
location: RelativePoint,
type: MessageType = MessageType.WARNING
) {
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, type, null)
.setFadeoutTime(BALLOON_FADE_OUT_TIME)
.createBalloon()
.show(location, Balloon.Position.above)
}
/** Display notification bubble. */
fun log(message: String) {
Notifications.Bus.notify(Notification("Rib", "Rib", message, NotificationType.INFORMATION))
}
}
}
| apache-2.0 | e62820851cde85a8bca9d837f51b0858 | 34 | 97 | 0.693282 | 4.375 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt | 1 | 2952 | package eu.kanade.tachiyomi.ui.library
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.signature.StringSignature
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.base.Source
import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder
import kotlinx.android.synthetic.main.item_catalogue_grid.view.*
/**
* Class used to hold the displayed data of a manga in the library, like the cover or the title.
* All the elements from the layout file "item_catalogue_grid" are available in this class.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @param listener a listener to react to single tap and long tap events.
* @constructor creates a new library holder.
*/
class LibraryHolder(private val view: View, private val adapter: LibraryCategoryAdapter, listener: FlexibleViewHolder.OnListItemClickListener) :
FlexibleViewHolder(view, adapter, listener) {
private var manga: Manga? = null
/**
* Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this
* holder with the given manga.
*
* @param manga the manga to bind.
* @param presenter the library presenter.
*/
fun onSetValues(manga: Manga, presenter: LibraryPresenter) {
this.manga = manga
// Update the title of the manga.
view.title.text = manga.title
// Update the unread count and its visibility.
with(view.unreadText) {
visibility = if (manga.unread > 0) View.VISIBLE else View.GONE
text = manga.unread.toString()
}
// Update the cover.
loadCover(manga, presenter.sourceManager.get(manga.source)!!, presenter.coverCache)
}
/**
* Load the cover of a manga in a image view.
*
* @param manga the manga to bind.
* @param source the source of the manga.
* @param coverCache the cache that stores the cover in the filesystem.
*/
private fun loadCover(manga: Manga, source: Source, coverCache: CoverCache) {
if (!manga.thumbnail_url.isNullOrEmpty()) {
coverCache.saveOrLoadFromCache(manga.thumbnail_url, source.glideHeaders) {
if (adapter.fragment.isResumed && this.manga == manga) {
Glide.with(view.context)
.load(it)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.centerCrop()
.signature(StringSignature(it.lastModified().toString()))
.placeholder(android.R.color.transparent)
.into(itemView.thumbnail)
}
}
} else {
Glide.clear(view.thumbnail)
}
}
}
| apache-2.0 | 2658831a700c987ac75eea067a080bde | 38.36 | 144 | 0.653794 | 4.569659 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/fragments/BaseFragment.kt | 1 | 3182 | package lt.vilnius.tvarkau.fragments
import android.arch.lifecycle.ViewModelProvider
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.squareup.leakcanary.RefWatcher
import dagger.android.support.DaggerFragment
import io.reactivex.Scheduler
import lt.vilnius.tvarkau.BaseActivity
import lt.vilnius.tvarkau.R
import lt.vilnius.tvarkau.analytics.Analytics
import lt.vilnius.tvarkau.dagger.IoScheduler
import lt.vilnius.tvarkau.dagger.UiScheduler
import lt.vilnius.tvarkau.extensions.emptyToNull
import lt.vilnius.tvarkau.fragments.presenters.ConnectivityProvider
import lt.vilnius.tvarkau.interfaces.OnBackPressed
import lt.vilnius.tvarkau.prefs.AppPreferences
import lt.vilnius.tvarkau.prefs.Preferences
import javax.inject.Inject
import javax.inject.Named
abstract class BaseFragment : DaggerFragment(), OnBackPressed {
protected var screen: Screen? = null
@field:[Inject Named(Preferences.MY_PROBLEMS_PREFERENCES)]
lateinit var myProblemsPreferences: SharedPreferences
@Inject
lateinit var appPreferences: AppPreferences
@Inject
lateinit var analytics: Analytics
@Inject
lateinit var refWatcher: RefWatcher
@field:[Inject IoScheduler]
lateinit var ioScheduler: Scheduler
@field:[Inject UiScheduler]
lateinit var uiScheduler: Scheduler
@Inject
lateinit var connectivityProvider: ConnectivityProvider
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
protected val baseActivity: BaseActivity?
get() = activity!! as BaseActivity?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
screen = this::class.java.annotations.find { it is Screen } as Screen?
}
override fun onResume() {
super.onResume()
screen?.run {
if (titleRes != 0) {
activity!!.setTitle(titleRes)
}
trackingScreenName.emptyToNull()?.let {
analytics.trackOpenFragment(activity!!, it)
}
(activity!! as AppCompatActivity).let { act ->
when (navigationMode) {
NavigationMode.DEFAULT ->
act.supportActionBar?.setDisplayHomeAsUpEnabled(false)
NavigationMode.CLOSE -> {
act.supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity!! as AppCompatActivity).supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close)
}
NavigationMode.BACK -> {
act.supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity!! as AppCompatActivity).supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back)
}
}
}
}
}
override fun onPause() {
screen?.trackingScreenName?.emptyToNull()?.let(analytics::trackCloseFragment)
super.onPause()
}
override fun onBackPressed(): Boolean = false
override fun onDestroy() {
super.onDestroy()
refWatcher.watch(this)
}
}
| mit | ec3c66c891d69383f93cff63e822d7d2 | 33.215054 | 117 | 0.680704 | 5.303333 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/settings/helper/PreferenceHelper.kt | 1 | 874 | package de.christinecoenen.code.zapp.app.settings.helper
import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.*
internal class PreferenceHelper(context: Context) {
companion object {
private const val SHARED_PEFERENCES_NAME = "ZAPP_SHARED_PREFERENCES"
}
private val gson = Gson()
private val preferences = context.getSharedPreferences(SHARED_PEFERENCES_NAME, Context.MODE_PRIVATE)
fun saveList(key: String, list: List<String>) {
val jsonList = gson.toJson(list)
preferences.edit()
.putString(key, jsonList)
.apply()
}
fun loadList(key: String): List<String>? {
if (!preferences.contains(key)) {
return null
}
val jsonList = preferences.getString(key, null)
val listType = object : TypeToken<ArrayList<String>?>() {}.type
return gson.fromJson(jsonList, listType)
}
}
| mit | 48ac615c59f4342dfd1fca36fc127772 | 22.621622 | 101 | 0.73913 | 3.552846 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/util/validator/MarkdownValidator.kt | 1 | 1134 | package mixit.util.validator
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* @author Dev-Mind <[email protected]>
*/
@Component
class MarkdownValidator {
private val logger = LoggerFactory.getLogger(this.javaClass)
private val escaper = StringEscapers().MARKDOWN
fun sanitize(value: String?): String {
if (value == null || value.isEmpty()) {
return ""
}
return value
.replace("&", "&")
.replace("\"", "&#${'"'.code};")
.replace("'", "&#${'\''.code};")
.replace("`", "&#${'`'.code};")
.replace("@", "&#${'@'.code};")
.replace("=", "&#${'='.code};")
.replace("+", "&#${'+'.code};")
.replace(">", ">")
.replace("<", "<")
}
fun isValid(value: String?): Boolean {
if (value == null || value.isEmpty()) {
return true
}
if (value != escaper.escape(value)) {
logger.info("$value -> ${escaper.escape(value)}")
}
return value == escaper.escape(value)
}
}
| apache-2.0 | 1fede3ac12924f98887296f3c50cd583 | 28.076923 | 64 | 0.491182 | 4.231343 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/edits/NoteEditsTable.kt | 1 | 1443 | package de.westnordost.streetcomplete.data.osmnotes.edits
object NoteEditsTable {
const val NAME = "osm_note_edits"
object Columns {
const val ID = "id"
const val NOTE_ID = "note_id"
const val LATITUDE = "latitude"
const val LONGITUDE = "longitude"
const val CREATED_TIMESTAMP = "created"
const val IS_SYNCED = "synced"
const val TYPE = "type"
const val TEXT = "text"
const val IMAGE_PATHS = "image_paths"
const val IMAGES_NEED_ACTIVATION = "images_need_activation"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Columns.NOTE_ID} int NOT NULL,
${Columns.LATITUDE} double NOT NULL,
${Columns.LONGITUDE} double NOT NULL,
${Columns.CREATED_TIMESTAMP} int NOT NULL,
${Columns.IS_SYNCED} int NOT NULL,
${Columns.TEXT} text,
${Columns.IMAGE_PATHS} text NOT NULL,
${Columns.IMAGES_NEED_ACTIVATION} int NOT NULL,
${Columns.TYPE} varchar(255)
);"""
const val SPATIAL_INDEX_CREATE = """
CREATE INDEX osm_note_edits_spatial_index ON $NAME (
${Columns.LATITUDE},
${Columns.LONGITUDE}
);
"""
const val NOTE_ID_INDEX_CREATE = """
CREATE INDEX osm_note_edits_note_index ON $NAME (${Columns.NOTE_ID});
"""
}
| gpl-3.0 | e53b49919b9a1cdab6503d4486a709e9 | 32.55814 | 77 | 0.576577 | 4.146552 | false | false | false | false |
IntershopCommunicationsAG/scmversion-gradle-plugin | src/main/kotlin/com/intershop/gradle/scm/task/PrepareRelease.kt | 1 | 2855 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.scm.task
import com.intershop.gradle.scm.extension.ScmExtension
import com.intershop.gradle.scm.utils.BranchType
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction
/**
* This is the implementation of Gradle
* task to prepare a release from the
* current SCM repository. It creates a
* task switch the repo to this tag.
*/
open class PrepareRelease: AbstractDryRunTask() {
init {
outputs.upToDateWhen { false }
description = "Prepare a release process, create branch and/or tag, moves the working copy to the tag"
}
/**
* Implementation of the task action.
*/
@Throws(GradleException::class)
@TaskAction
fun prepareReleaseAction() {
val versionConfig = project.extensions.getByType(ScmExtension::class.java).version
val versionService = versionConfig.versionService
val version = if (versionService.localService.branchType != BranchType.TAG) {
// create tag
val tv = versionService.preVersion.toString()
if (!versionService.isReleaseVersionAvailable(tv)) {
if(! dryRun) {
versionService.createTag(tv)
} else {
println("-> DryRun: Tag will be created with $tv")
}
}
if(!dryRun) {
if (versionService.moveTo(tv, BranchType.TAG) == "") {
throw GradleException("It is not possible to move the working copy to version $tv on the SCM!")
}
} else {
println("-> DryRun: Working copy will be moved to $tv")
}
tv
} else {
versionConfig.version
}
if(! dryRun) {
println("""
|----------------------------------------------
| Project version: $version
|----------------------------------------------""".trimMargin())
} else {
println("""
|----------------------------------------------
| DryRun: No changes on working copy.
|----------------------------------------------""".trimMargin())
}
}
}
| apache-2.0 | 3b3856259ccca2f7d20bd0d080058715 | 33.817073 | 115 | 0.564974 | 4.922414 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/dialog/SaveViewDialogFragment.kt | 1 | 5279 | package com.boardgamegeek.ui.dialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.boardgamegeek.R
import com.boardgamegeek.databinding.DialogSaveViewBinding
import com.boardgamegeek.extensions.CollectionView
import com.boardgamegeek.extensions.requestFocus
import com.boardgamegeek.extensions.setAndSelectExistingText
import com.boardgamegeek.extensions.toast
import com.boardgamegeek.ui.viewmodel.CollectionViewViewModel
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class SaveViewDialogFragment : DialogFragment() {
private var _binding: DialogSaveViewBinding? = null
private val binding get() = _binding!!
private var name: String = ""
private var description: String? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = DialogSaveViewBinding.inflate(layoutInflater)
val viewModel = ViewModelProvider(requireActivity())[CollectionViewViewModel::class.java]
arguments?.let {
name = it.getString(KEY_NAME).orEmpty()
description = it.getString(KEY_DESCRIPTION)
}
val firebaseAnalytics = FirebaseAnalytics.getInstance(requireContext())
val builder = AlertDialog.Builder(requireContext(), R.style.Theme_bgglight_Dialog_Alert)
.setTitle(R.string.title_save_view)
.setView(binding.root)
.setPositiveButton(R.string.save) { _, _ ->
val name = binding.nameView.text?.trim()?.toString().orEmpty()
val isDefault = binding.defaultViewCheckBox.isChecked
if (viewModel.findViewId(name) > 0L) {
AlertDialog.Builder(requireContext())
.setTitle(R.string.title_collection_view_name_in_use)
.setMessage(R.string.msg_collection_view_name_in_use)
.setPositiveButton(R.string.update) { _, _ ->
context?.let {
toast(it.getString(R.string.msg_collection_view_updated, name))
}
logAction(firebaseAnalytics, "Update", name)
viewModel.update(isDefault)
}
.setNegativeButton(R.string.create) { _, _ ->
context?.let {
toast(it.getString(R.string.msg_collection_view_inserted, name))
}
logAction(firebaseAnalytics, "Insert", name)
viewModel.insert(name, isDefault)
}
.create()
.show()
} else {
requireContext().toast(getString(R.string.msg_collection_view_inserted, name))
logAction(firebaseAnalytics, "Insert", name)
viewModel.insert(name, isDefault)
}
}
.setNegativeButton(R.string.cancel, null)
.setCancelable(true)
return builder.create().apply {
setOnShowListener {
requestFocus(binding.nameView)
getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = !binding.nameView.text.isNullOrBlank()
binding.nameView.doAfterTextChanged {
getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = !binding.nameView.text.isNullOrBlank()
}
}
}
}
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun logAction(firebaseAnalytics: FirebaseAnalytics, action: String, name: String) {
firebaseAnalytics.logEvent("DataManipulation") {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "CollectionView")
param("Action", action)
param("Name", name)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val viewModel = ViewModelProvider(requireActivity())[CollectionViewViewModel::class.java]
binding.nameView.setAndSelectExistingText(name)
binding.defaultViewCheckBox.isChecked =
viewModel.defaultViewId != CollectionView.DEFAULT_DEFAULT_ID && viewModel.findViewId(name) == viewModel.defaultViewId
binding.descriptionView.text = description
}
companion object {
private const val KEY_NAME = "title_id"
private const val KEY_DESCRIPTION = "color_count"
fun newInstance(name: String, description: String) = SaveViewDialogFragment().apply {
arguments = Bundle().apply {
putString(KEY_NAME, name)
putString(KEY_DESCRIPTION, description)
}
}
}
}
| gpl-3.0 | e33b8d23522fa79cba10b2b9b03c9abc | 42.628099 | 129 | 0.624171 | 5.237103 | false | false | false | false |
hkokocin/Atheris | library/src/main/java/com/github/hkokocin/atheris/android/ViperView.kt | 1 | 1172 | package com.github.hkokocin.atheris.android
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.hkokocin.androidkit.view.onAttachedToWindow
import com.github.hkokocin.androidkit.view.onDetachedFromWindow
import com.github.hkokocin.atheris.interactor.ViewInteractor
abstract class ViperView {
abstract val interactor: ViewInteractor
abstract val layout: Int
internal lateinit var lifecycle: ViewLifecycle
var root: View? = null
private set
@Suppress("UNCHECKED_CAST")
fun createView(inflater: LayoutInflater, parent: ViewGroup? = null, attachToParent: Boolean = false) {
if (root != null) throw IllegalStateException("View has already been inflated")
root = inflater.inflate(layout, parent, attachToParent).apply {
interactor.presenter.create(this)
onAttachedToWindow { lifecycle.onAttachedToWindow() }
onDetachedFromWindow { lifecycle.onDetachedFromWindow() }
}
onViewCreated()
}
private fun onViewCreated() {
lifecycle = interactor.router.lifecycle
lifecycle.onViewCreated()
}
} | mit | 77d7d6819518dddfc5cd3243e7266436 | 30.702703 | 106 | 0.727816 | 5.073593 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/jvmTest/src/kotlinx/serialization/protobuf/FormatConverterHelpers.kt | 1 | 2670 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf
import com.google.protobuf.*
import kotlinx.serialization.*
import java.io.*
interface IMessage {
fun toProtobufMessage(): GeneratedMessageV3
}
fun GeneratedMessageV3.toHex(): String {
val b = ByteArrayOutputStream()
this.writeTo(b)
return (HexConverter.printHexBinary(b.toByteArray(), lowerCase = true))
}
val defaultProtobuf = ProtoBuf { encodeDefaults = true }
/**
* Check serialization of [ProtoBuf].
*
* 1. Serializes the given [IMessage] into bytes using [ProtoBuf].
* 2. Parses those bytes via the `Java ProtoBuf library`.
* 3. Compares parsed `Java ProtoBuf object` to expected object ([IMessage.toProtobufMessage]).
*
* @param it The [IMessage] to check.
* @param protoBuf Provide custom [ProtoBuf] instance (default: [ProtoBuf.plain]).
*
* @return `true` if the de-serialization returns the expected object.
*/
inline fun <reified T : IMessage> dumpCompare(it: T, alwaysPrint: Boolean = false, protoBuf: BinaryFormat = defaultProtobuf): Boolean {
val msg = it.toProtobufMessage()
var parsed: GeneratedMessageV3?
val c = try {
val bytes = protoBuf.encodeToByteArray(it)
if (alwaysPrint) println("Serialized bytes: ${HexConverter.printHexBinary(bytes)}")
parsed = msg.parserForType.parseFrom(bytes)
msg == parsed
} catch (e: Exception) {
e.printStackTrace()
parsed = null
false
}
if (!c || alwaysPrint) println("Expected: $msg\nfound: $parsed")
return c
}
/**
* Check de-serialization of [ProtoBuf].
*
* 1. Converts expected `Java ProtoBuf object` ([IMessage.toProtobufMessage]) to bytes.
* 2. Parses those bytes via [ProtoBuf].
* 3. Compares parsed ProtoBuf object to given object.
*
* @param it The [IMessage] to check.
* @param alwaysPrint Set to `true` if expected/found objects should always get printed to console (default: `false`).
* @param protoBuf Provide custom [ProtoBuf] instance (default: [ProtoBuf.plain]).
*
* @return `true` if the de-serialization returns the original object.
*/
inline fun <reified T : IMessage> readCompare(it: T, alwaysPrint: Boolean = false, protoBuf: BinaryFormat = defaultProtobuf): Boolean {
var obj: T?
val c = try {
val msg = it.toProtobufMessage()
val hex = msg.toHex()
obj = protoBuf.decodeFromHexString<T>(hex)
obj == it
} catch (e: Exception) {
obj = null
e.printStackTrace()
false
}
if (!c || alwaysPrint) println("Expected: $it\nfound: $obj")
return c
}
| apache-2.0 | 3f2aff59a451ef09061749418c3608db | 32.797468 | 135 | 0.682772 | 3.991031 | false | false | false | false |
androidx/androidx-ci-action | AndroidXCI/ftlModelBuilder/src/main/kotlin/dev/androidx/ci/codegen/Dtos.kt | 1 | 1505 | /*
* 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 dev.androidx.ci.codegen
import com.squareup.moshi.Json
// see: https://developers.google.com/discovery/v1/reference/apis
/**
* The root discovery class
*/
internal class DiscoveryDto(
val schemas: Map<String, SchemaDto>
)
/**
* Represents the Schema for a single model
*/
internal data class SchemaDto(
val id: String,
/**
* https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
*/
val type: String,
val description: String? = null,
val properties: Map<String, PropertyDto>? = null
) {
fun isObject() = type == "object"
}
internal data class PropertyDto(
val description: String? = null,
val type: String?,
@Json(name = "\$ref")
val ref: String? = null,
val enum: List<String>? = null,
val enumDescriptions: List<String>? = null,
val items: PropertyDto? = null,
val format: String? = null
)
| apache-2.0 | a22164b3a4c8f2125b7a96697fa9ec19 | 27.396226 | 75 | 0.689701 | 3.7625 | false | false | false | false |
googlecodelabs/watchnext-for-movie-tv-episodes | step_4_completed/src/main/java/com/android/tv/reference/repository/FileVideoRepository.kt | 8 | 2049 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.reference.repository
import android.app.Application
import com.android.tv.reference.R
import com.android.tv.reference.parser.VideoParser
import com.android.tv.reference.shared.datamodel.Video
import com.android.tv.reference.shared.datamodel.VideoType
/**
* VideoRepository implementation to read video data from a file saved on /res/raw
*/
class FileVideoRepository(override val application: Application) : VideoRepository {
// Underscore name to allow lazy loading since "getAllVideos" matches the getter name otherwise
private val _allVideos: List<Video> by lazy {
val jsonString = readJsonFromFile()
VideoParser.loadVideosFromJson(jsonString)
}
private fun readJsonFromFile(): String {
val inputStream = application.resources.openRawResource(R.raw.api)
return inputStream.bufferedReader().use {
it.readText()
}
}
override fun getAllVideos(): List<Video> {
return _allVideos
}
override fun getVideoById(id: String): Video? {
val jsonString = readJsonFromFile()
return VideoParser.findVideoFromJson(jsonString, id)
}
override fun getVideoByVideoUri(uri: String): Video? {
return getAllVideos()
.firstOrNull { it.videoUri == uri }
}
override fun getAllVideosFromSeries(seriesUri: String): List<Video> {
return getAllVideos().filter { it.seriesUri == seriesUri }
}
}
| apache-2.0 | 20f03bb011db1c94069e43463b4de834 | 34.327586 | 99 | 0.716447 | 4.359574 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/intentions/LatexUnpackUsepackageIntention.kt | 1 | 2271 | package nl.hannahsten.texifyidea.intentions
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexRequiredParam
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.files.document
import nl.hannahsten.texifyidea.util.files.isLatexFile
import nl.hannahsten.texifyidea.util.magic.PatternMagic
/**
* @author Hannah Schellekens
*/
open class LatexUnpackUsepackageIntention : TexifyIntentionBase("Split into multiple \\usepackage commands") {
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null || !file.isLatexFile()) {
return false
}
val selected = file.findElementAt(editor.caretModel.offset) ?: return false
val command = selected.parentOfType(LatexCommands::class) ?: return false
if (command.name != "\\usepackage") {
return false
}
val required = command.requiredParameter(0)
return required != null && required.contains(",")
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null || !file.isLatexFile()) {
return
}
// Find packages.
val selected = file.findElementAt(editor.caretModel.offset) ?: return
val command = selected.parentOfType(LatexCommands::class) ?: return
val required = command.firstChildOfType(LatexRequiredParam::class) ?: return
val requiredText = required.text.trimRange(1, 1)
val packages = PatternMagic.parameterSplit.split(requiredText)
// Reorganise includes.
val document = file.document() ?: return
val offset = command.textOffset
runWriteAction {
document.deleteString(offset, command.endOffset())
for (i in packages.size - 1 downTo 0) {
val newline = if (i > 0) "\n" else ""
val pack = packages[i]
document.insertString(offset, "$newline\\usepackage{$pack}")
}
}
}
} | mit | cb52706847a10b889b3ab8e38d9c598e | 36.866667 | 110 | 0.667988 | 4.663244 | false | false | false | false |
PaulWoitaschek/Voice | playbackScreen/src/main/kotlin/voice/playbackScreen/VolumeGainDialog.kt | 1 | 919 | package voice.playbackScreen
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import voice.playback.misc.Decibel
@Composable
internal fun VolumeGainDialog(
dialogState: BookPlayDialogViewState.VolumeGainDialog,
viewModel: BookPlayViewModel,
) {
AlertDialog(
onDismissRequest = { viewModel.dismissDialog() },
confirmButton = {},
text = {
Column {
Text(stringResource(id = R.string.volume_boost) + ": " + dialogState.valueFormatted)
Slider(
valueRange = 0F..dialogState.maxGain.value,
value = dialogState.gain.value,
onValueChange = {
viewModel.onVolumeGainChanged(Decibel(it))
},
)
}
},
)
}
| gpl-3.0 | 04588f25a8cbd3654ad50fd2f22242a9 | 27.71875 | 92 | 0.709467 | 4.314554 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/view/AutoFitRecyclerView.kt | 1 | 3217 | /*
* *************************************************************************
* AutoFitRecyclerView.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.view
import android.content.Context
import android.util.AttributeSet
import android.view.WindowManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class AutoFitRecyclerView : RecyclerView {
private var gridLayoutManager: GridLayoutManager? = null
var columnWidth = -1
private var spanCount = -1
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
if (attrs != null) {
val attrsArray = intArrayOf(android.R.attr.columnWidth)
val array = context.obtainStyledAttributes(attrs, attrsArray)
columnWidth = array.getDimensionPixelSize(0, -1)
array.recycle()
}
gridLayoutManager = GridLayoutManager(getContext(), 1)
layoutManager = gridLayoutManager
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (spanCount == -1 && columnWidth > 0) {
val ratio = measuredWidth / columnWidth
val spanCount = Math.max(1, ratio)
gridLayoutManager!!.spanCount = spanCount
} else
gridLayoutManager!!.spanCount = spanCount
}
fun getPerfectColumnWidth(columnWidth: Int, margin: Int): Int {
val wm = context.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val displayWidth = display.width - margin
val remainingSpace = displayWidth % columnWidth
val ratio = displayWidth / columnWidth
val spanCount = Math.max(1, ratio)
return columnWidth + remainingSpace / spanCount
}
fun setNumColumns(spanCount: Int) {
this.spanCount = spanCount
}
}
| gpl-2.0 | 502e16cf457a51999a2b1131d35284f1 | 34.32967 | 105 | 0.639502 | 4.96142 | false | false | false | false |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/map/overlay/StrikesOverlay.kt | 1 | 7723 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.map.overlay
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Style
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.Shape
import android.text.format.DateFormat
import android.util.Log
import com.google.android.maps.ItemizedOverlay
import com.google.android.maps.MapView
import org.blitzortung.android.app.Main
import org.blitzortung.android.app.R
import org.blitzortung.android.data.Parameters
import org.blitzortung.android.data.beans.RasterParameters
import org.blitzortung.android.data.beans.Strike
import org.blitzortung.android.map.OwnMapActivity
import org.blitzortung.android.map.components.LayerOverlayComponent
import org.blitzortung.android.map.overlay.color.ColorHandler
import org.blitzortung.android.map.overlay.color.StrikeColorHandler
class StrikesOverlay(mapActivity: OwnMapActivity, private val colorHandler: StrikeColorHandler) : PopupOverlay<StrikeOverlayItem>(mapActivity, ItemizedOverlay.boundCenter(StrikesOverlay.DEFAULT_DRAWABLE)), LayerOverlay {
var strikes: List<StrikeOverlayItem>
protected set
private val layerOverlayComponent: LayerOverlayComponent
private var zoomLevel: Int = 0
var rasterParameters: RasterParameters? = null
var referenceTime: Long = 0
var parameters = Parameters()
init {
layerOverlayComponent = LayerOverlayComponent(mapActivity.resources.getString(R.string.strikes_layer))
strikes = listOf()
populate()
}
override fun createItem(index: Int): StrikeOverlayItem {
return strikes[index]
}
override fun size(): Int {
return strikes.size
}
override fun draw(canvas: Canvas?, mapView: com.google.android.maps.MapView?, shadow: Boolean) {
if (!shadow) {
super.draw(canvas, mapView, false)
if (hasRasterParameters() && canvas != null && mapView != null) {
drawDataAreaRect(canvas, mapView)
}
}
}
private fun drawDataAreaRect(canvas: Canvas, mapView: MapView) {
val paint = Paint()
paint.color = colorHandler.lineColor
paint.style = Style.STROKE
val clipBounds = canvas.clipBounds
val currentRasterParameters = rasterParameters
if (currentRasterParameters != null) {
val rect = currentRasterParameters.getRect(mapView.projection)
if (rect.left >= clipBounds.left && rect.left <= clipBounds.right) {
canvas.drawLine(rect.left, Math.max(rect.top, clipBounds.top.toFloat()), rect.left, Math.min(rect.bottom, clipBounds.bottom.toFloat()), paint)
}
if (rect.right >= clipBounds.left && rect.right <= clipBounds.right) {
canvas.drawLine(rect.right, Math.max(rect.top, clipBounds.top.toFloat()), rect.right, Math.min(rect.bottom, clipBounds.bottom.toFloat()), paint)
}
if (rect.bottom <= clipBounds.bottom && rect.bottom >= clipBounds.top) {
canvas.drawLine(Math.max(rect.left, clipBounds.left.toFloat()), rect.bottom, Math.min(rect.right, clipBounds.right.toFloat()), rect.bottom, paint)
}
if (rect.top <= clipBounds.bottom && rect.top >= clipBounds.top) {
canvas.drawLine(Math.max(rect.left, clipBounds.left.toFloat()), rect.top, Math.min(rect.right, clipBounds.right.toFloat()), rect.top, paint)
}
}
}
fun addStrikes(strikes: List<Strike>) {
Log.v(Main.LOG_TAG, "StrikesOverlay.addStrikes() #" + strikes.size)
this.strikes += strikes.map { StrikeOverlayItem(it) }
lastFocusedIndex = -1
populate()
}
fun expireStrikes() {
val expireTime = referenceTime - (parameters.intervalDuration - parameters.intervalOffset) * 60 * 1000
val sizeBefore = strikes.size
strikes = strikes.filter { it.timestamp > expireTime }
Log.v(Main.LOG_TAG, "StrikesOverlay.expireStrikes() expired ${sizeBefore - strikes.size} from $sizeBefore")
}
fun clear() {
lastFocusedIndex = -1
clearPopup()
strikes = listOf()
populate()
}
fun updateZoomLevel(zoomLevel: Int) {
if (hasRasterParameters() || zoomLevel != this.zoomLevel) {
this.zoomLevel = zoomLevel
refresh()
}
}
fun getColorHandler(): ColorHandler {
return colorHandler
}
fun refresh() {
val current_section = -1
colorHandler.updateTarget()
var drawable: Shape? = null
for (item in strikes) {
val section = colorHandler.getColorSection(
if (hasRealtimeData())
System.currentTimeMillis()
else
referenceTime,
item.timestamp, parameters)
if (hasRasterParameters() || current_section != section) {
drawable = updateAndReturnDrawable(item, section, colorHandler)
} else {
if (drawable != null) {
item.shape = drawable
}
}
}
}
// VisibleForTesting
protected fun updateAndReturnDrawable(item: StrikeOverlayItem, section: Int, colorHandler: ColorHandler): Shape {
val projection = activity.mapView.projection
val color = colorHandler.getColor(section)
val textColor = colorHandler.textColor
item.updateShape(rasterParameters, projection, color, textColor, zoomLevel)
return item.shape!!
}
fun hasRasterParameters(): Boolean {
return rasterParameters != null
}
fun hasRealtimeData(): Boolean {
return parameters.isRealtime()
}
override fun onTap(index: Int): Boolean {
val item = strikes[index]
if (item.point != null && item.timestamp > 0) {
var result = DateFormat.format("kk:mm:ss", item.timestamp) as String
if (item.shape is RasterShape) {
result += ", #%d".format(item.multiplicity)
} else if (item.shape is StrikeShape) {
result += " (%.4f %.4f)".format(item.longitude, item.latitude)
}
showPopup(item.point, result)
return true
}
return false
}
val totalNumberOfStrikes: Int
get() = strikes.fold(0, { previous, item -> previous + item.multiplicity })
override val name: String
get() = layerOverlayComponent.name
override var enabled: Boolean
get() = layerOverlayComponent.enabled
set(value) {
layerOverlayComponent.enabled = value
}
override var visible: Boolean
get() = layerOverlayComponent.visible
set(value) {
layerOverlayComponent.visible = value
}
companion object {
private val DEFAULT_DRAWABLE: Drawable
init {
val shape = StrikeShape()
shape.update(1f, 0)
DEFAULT_DRAWABLE = ShapeDrawable(shape)
}
}
} | apache-2.0 | 42ce7e7a0ab3b4f6b42b4e994f5e75d9 | 33.788288 | 220 | 0.645817 | 4.542353 | false | false | false | false |
ledao/chatbot | src/main/kotlin/com/davezhao/pattern/conll/ConllHanlp.kt | 1 | 1128 | package com.davezhao.pattern.conll
import com.davezhao.lexicons.HanlpPosToChposDict
import com.davezhao.nlp.WordBreaker
import com.davezhao.pattern.WordInfo
class ConllHanlp(val chposDict: HanlpPosToChposDict) : ConllBase {
override fun genConll(sent: String): List<WordInfo> {
val terms = WordBreaker.segmentByHanlp(sent)
var offset = 0
return terms.withIndex().map { (index, value) ->
val word = value.word
val pos = if (chposDict.dict.containsKey(value.pos)) chposDict.dict.get(value.pos)!! else value.pos
val wi = WordInfo(
index = index,
startPos = offset,
endPos = offset + value.word.length,
word = word,
pos = listOf(pos),
posConcept = emptyList(),
ner = emptyList()
)
offset += value.word.length
wi
}
}
}
fun main(args: Array<String>) {
val chposDict = HanlpPosToChposDict()
val conll = ConllHanlp(chposDict)
val sent = "这是战略的决策"
println(conll.genConll(sent))
} | gpl-3.0 | 54a2713cfd4f4b1111ddbef9fd6b4071 | 30.857143 | 111 | 0.593357 | 3.525316 | false | false | false | false |
wiltonlazary/kotlin-native | tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/model/KonanModelImpl.kt | 1 | 2965 | /*
* Copyright 2010-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin.model
import org.gradle.api.Project
import org.gradle.tooling.provider.model.ToolingModelBuilder
import org.jetbrains.kotlin.gradle.plugin.konan.konanArtifactsContainer
import org.jetbrains.kotlin.gradle.plugin.konan.konanExtension
import org.jetbrains.kotlin.gradle.plugin.konan.konanHome
import org.jetbrains.kotlin.gradle.plugin.konan.konanVersion
import org.jetbrains.kotlin.konan.CURRENT
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.target.CompilerOutputKind
import java.io.File
object KonanToolingModelBuilder : ToolingModelBuilder {
override fun canBuild(modelName: String) = KonanModel::class.java.name == modelName
private fun buildModelKonan(project: Project): KonanModel {
val artifacts = project.konanArtifactsContainer.flatten().toList().map { it.toModelArtifact() }
return KonanModelImpl(
artifacts,
project.file(project.konanHome),
project.konanVersion,
// TODO: Provide defaults for these versions.
project.konanExtension.languageVersion,
project.konanExtension.apiVersion
)
}
private val Project.hasKonanPlugin: Boolean
get() = with(pluginManager) {
hasPlugin("konan") ||
hasPlugin("org.jetbrains.kotlin.konan")
}
override fun buildAll(modelName: String, project: Project): KonanModel =
when {
project.hasKonanPlugin -> buildModelKonan(project)
else -> throw IllegalStateException("The project '${project.path}' has no Kotlin/Native plugin")
}
}
internal data class KonanModelImpl(
override val artifacts: List<KonanModelArtifact>,
override val konanHome: File,
override val konanVersion: CompilerVersion,
override val languageVersion: String?,
override val apiVersion: String?
) : KonanModel
internal data class KonanModelArtifactImpl(
override val name: String,
override val file: File,
override val type: CompilerOutputKind,
override val targetPlatform: String,
override val buildTaskName: String,
override val srcDirs: List<File>,
override val srcFiles: List<File>,
override val libraries: List<File>,
override val searchPaths: List<File>
) : KonanModelArtifact
| apache-2.0 | 633a36abed7de94d88253f040d0b0f59 | 36.531646 | 108 | 0.722428 | 4.640063 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/highlighting/HtlBlocksHighlighter.kt | 1 | 1843 | package co.nums.intellij.aem.htl.highlighting
import co.nums.intellij.aem.htl.definitions.HTL_BLOCK_PREFIX
import co.nums.intellij.aem.htl.extensions.*
import com.intellij.lang.annotation.*
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlAttribute
class HtlBlocksHighlighter : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element.containingFile.isHtl() && element is XmlAttribute && element.name.toLowerCase().startsWith(HTL_BLOCK_PREFIX)) {
holder.highlightHtlBlock(element)
}
}
private fun AnnotationHolder.highlightHtlBlock(element: XmlAttribute) {
val blockStart = element.textOffset
val blockName = element.localName
val dotOffset = blockName.indexOf('.')
val blockTypeEnd = if (dotOffset != -1) (blockStart + dotOffset) else (blockStart + blockName.length)
this.highlightText(blockStart, blockTypeEnd, HtlHighlighterColors.BLOCK_TYPE)
if (element.isHtlVariableDeclaration()) {
this.highlightBlockIdentifier(blockName, blockStart, dotOffset, HtlHighlighterColors.VARIABLE)
} else if (dotOffset != -1 && element.isHtlTemplateBlock()) {
this.highlightBlockIdentifier(blockName, blockStart, dotOffset, HtlHighlighterColors.TEMPLATE_IDENTIFIER)
}
}
private fun AnnotationHolder.highlightBlockIdentifier(blockName: String, blockStart: Int, dotOffset: Int, color: TextAttributesKey) {
val variableIdentifier = blockName.substringAfter('.', missingDelimiterValue = "")
if (variableIdentifier.isNotEmpty()) {
val blockNameEnd = blockStart + blockName.length
this.highlightText(blockStart + dotOffset + 1, blockNameEnd, color)
}
}
}
| gpl-3.0 | 78c7793cd0f0157684ddcbba310d3fe2 | 46.25641 | 137 | 0.724905 | 4.65404 | false | false | false | false |
BlurEngine/Blur | src/main/java/com/blurengine/blur/components/shared/EntityFreezer.kt | 1 | 4922 | /*
* Copyright 2017 Ali Moghnieh
*
* 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.blurengine.blur.components.shared
import com.blurengine.blur.framework.SharedComponent
import com.blurengine.blur.framework.ticking.Tick
import com.blurengine.blur.session.BlurPlayer
import com.blurengine.blur.session.BlurSession
import com.blurengine.blur.utils.getSharedComponent
import com.blurengine.blur.utils.isPositive
import com.blurengine.blur.utils.toTicks
import com.supaham.commons.bukkit.utils.LocationUtils
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerMoveEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.event.player.PlayerToggleFlightEvent
import java.time.Duration
class EntityFreezer(session: BlurSession) : SharedComponent(session) {
val NO_JUMP = BlurPotionEffects.NO_JUMP.infinite()
val potionManager: PotionEffectManager get() = session.getSharedComponent { PotionEffectManager(session) }
private val _frozenPlayers = HashMap<BlurPlayer, FreezePlayerData>()
init {
addListener(PlayerListener())
}
@Tick
fun tick() {
val it = _frozenPlayers.entries.iterator()
while (it.hasNext()) {
val (blurPlayer, data) = it.next()
if (data.done) {
unfreeze(blurPlayer, data)
it.remove()
}
}
}
fun freeze(blurPlayer: BlurPlayer, duration: Duration, turningAllowed: Boolean) {
val data = _frozenPlayers[blurPlayer]
data?.apply {
expiresTicks = duration.toTicks(session)
this.turningAllowed = turningAllowed
return
}
_frozenPlayers[blurPlayer] = FreezePlayerData(blurPlayer, duration, turningAllowed)
potionManager.apply(blurPlayer.player, NO_JUMP)
blurPlayer.player.apply {
walkSpeed = 0f
flySpeed = 0f
allowFlight = true
isFlying = true
}
}
fun unfreeze(blurPlayer: BlurPlayer, data: FreezePlayerData? = _frozenPlayers.remove(blurPlayer)): Boolean {
data?.apply {
applyDefaults()
potionManager.clear(blurPlayer.player, NO_JUMP.type)
return true
}
return false
}
operator fun contains(blurPlayer: BlurPlayer) = _frozenPlayers.contains(blurPlayer)
operator fun get(blurPlayer: BlurPlayer) = _frozenPlayers[blurPlayer]
inner class PlayerListener : Listener {
@EventHandler(ignoreCancelled = true)
fun onPlayerMove(event: PlayerMoveEvent) {
val blurPlayer = getPlayer(event.player)
if (!isSession(blurPlayer.session)) return
val data = _frozenPlayers[blurPlayer] ?: return
if (!data.turningAllowed || !LocationUtils.isSameCoordinates(event.from, event.to)) {
val tp = event.from
if (data.turningAllowed) {
tp.yaw = event.to!!.yaw
tp.pitch = event.to!!.pitch
}
event.player.teleport(tp)
}
}
@EventHandler
fun onPlayerQuit(event: PlayerQuitEvent) {
unfreeze(getPlayer(event.player))
}
@EventHandler
fun onPlayerToggleFlight(event: PlayerToggleFlightEvent) {
if (!event.isFlying) {
if(getPlayer(event.player) in this@EntityFreezer) {
event.isCancelled = true
}
}
}
}
inner class FreezePlayerData(val blurPlayer: BlurPlayer, duration: Duration, var turningAllowed: Boolean) {
val walkSpeed = blurPlayer.player.walkSpeed
val flySpeed = blurPlayer.player.flySpeed
val allowFlight = blurPlayer.player.allowFlight
val isFlying = blurPlayer.player.isFlying
var expiresTicks: Int
val done: Boolean
get() = expiresTicks <= 0
fun applyDefaults() {
blurPlayer.player.let { player ->
player.walkSpeed = walkSpeed
player.flySpeed = flySpeed
player.allowFlight = allowFlight
player.isFlying = isFlying
}
}
init {
require(duration.isPositive()) { "duration must be positive." }
expiresTicks = duration.toTicks(session)
}
}
}
| apache-2.0 | 33d0b469a4dac16139c5b5998ceb6cd8 | 33.41958 | 112 | 0.641609 | 4.54059 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/android/Transition.kt | 1 | 4925 | /**
* MIT License
*
* Copyright (c) 2018 Piruin Panichphol
*
* 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 ffc.android
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.support.annotation.TransitionRes
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.app.Fragment
import android.transition.Transition
import android.transition.TransitionInflater
import android.transition.TransitionSet
import android.view.View
import android.view.Window
import android.view.animation.Interpolator
import android.support.v4.util.Pair as AndroidSupportPair
fun Context.transition(@TransitionRes res: Int) = TransitionInflater.from(this).inflateTransition(res)
fun Fragment.transition(@TransitionRes res: Int) = context!!.transition(res)
fun View.transition(@TransitionRes res: Int) = context.transition(res)
fun Activity.sceneTransition(): Bundle? {
return if (Build.VERSION.SDK_INT < 21) null else
ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle()
}
fun Activity.sceneTransition(vararg sharedElements: Pair<View, String>?): Bundle? {
return if (Build.VERSION.SDK_INT < 21) null else
ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
*sharedElements.map { it?.toAndroidSupportPair() }.toTypedArray()
).toBundle()
}
private fun Pair<View, String>.toAndroidSupportPair() = AndroidSupportPair(first, second)
var Fragment.allowTransitionOverlap: Boolean
set(value) {
allowEnterTransitionOverlap = value
allowReturnTransitionOverlap = value
}
get() = throw IllegalAccessError()
var Window.allowTransitionOverlap: Boolean
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
set(value) {
allowEnterTransitionOverlap = value
allowReturnTransitionOverlap = value
}
get() = throw IllegalAccessError()
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Move(context: Context) = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
fun transitionSetOf(vararg transitions: Transition): TransitionSet {
return TransitionSet().apply {
transitions.forEach { this.addTransition(it) }
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Transition.excludeSystemView(): Transition {
excludeTarget(android.R.id.statusBarBackground, true)
excludeTarget(android.R.id.navigationBarBackground, true)
return this
}
val enterDuration: Long = 300
val exitDuration: Long = 250
val sharedElementDuration: Long = 250
val sharedElementEasing = android.support.v4.view.animation.FastOutSlowInInterpolator()
val enterEasing = android.support.v4.view.animation.LinearOutSlowInInterpolator()
val exitEasing = android.support.v4.view.animation.FastOutLinearInInterpolator()
fun Transition.shareElement(
time: Long = sharedElementDuration,
easing: Interpolator = sharedElementEasing
): Transition {
duration = time
interpolator = easing
return this
}
fun Transition.enter(
time: Long = enterDuration,
delay: Long = 0,
easing: Interpolator = enterEasing
): Transition {
duration = time
startDelay = delay
interpolator = easing
return this
}
fun Transition.exit(
time: Long = exitDuration,
delay: Long = 0,
easing: Interpolator = exitEasing
): Transition {
duration = time
startDelay = delay
interpolator = easing
return this
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
inline fun Activity.setTransition(action: Window.() -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.action()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
inline fun Fragment.setTransition(action: Fragment.() -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.action()
}
}
| apache-2.0 | 976bdfa3e1377980ffe7cb0c887efa2c | 32.965517 | 106 | 0.753096 | 4.327768 | false | false | false | false |
uchuhimo/kotlin-playground | konf/src/main/kotlin/com/uchuhimo/konf/source/base/MapSource.kt | 1 | 1298 | package com.uchuhimo.konf.source.base
import com.uchuhimo.konf.Path
import com.uchuhimo.konf.notEmptyOr
import com.uchuhimo.konf.source.Source
import com.uchuhimo.konf.source.toDescription
open class MapSource(
val map: Map<String, Any>,
type: String = "",
context: Map<String, String> = mapOf()
) : ValueSource(map, type.notEmptyOr("map"), context) {
override fun contains(path: Path): Boolean {
if (path.isEmpty()) {
return true
} else {
val key = path.first()
val rest = path.drop(1)
return map[key]?.castToSource(context)?.contains(rest) ?: false
}
}
override fun getOrNull(path: Path): Source? {
if (path.isEmpty()) {
return this
} else {
val key = path.first()
val rest = path.drop(1)
val result = map[key]
if (result != null) {
return result.castToSource(context).getOrNull(rest)
} else {
return null
}
}
}
override fun isMap(): Boolean = true
override fun toMap(): Map<String, Source> = map.mapValues { (_, value) ->
value.castToSource(context).apply { addInfo("inMap", [email protected]()) }
}
}
| apache-2.0 | a582b3c3b50d298c66ec7227a50b8877 | 29.186047 | 99 | 0.566256 | 4.160256 | false | false | false | false |
slartus/4pdaClient-plus | topic/topic-data/src/main/java/org/softeg/slartus/forpdaplus/topic/data/screens/users/TopicUsersRepositoryImpl.kt | 1 | 1727 | package org.softeg.slartus.forpdaplus.topic.data.screens.users
import org.softeg.slartus.forpdaplus.core.interfaces.ParseFactory
import org.softeg.slartus.forpdaplus.topic.data.screens.users.parsers.TopicReadersParser
import org.softeg.slartus.forpdaplus.topic.data.screens.users.parsers.TopicWritersParser
import org.softeg.slartus.forpdaplus.topic.data.screens.users.parsers.toTopicReaderOrNull
import org.softeg.slartus.forpdaplus.topic.data.screens.users.parsers.toTopicWriterOrNull
import ru.softeg.slartus.forum.api.TopicReaders
import ru.softeg.slartus.forum.api.TopicUsersRepository
import ru.softeg.slartus.forum.api.TopicWriters
import javax.inject.Inject
class TopicUsersRepositoryImpl @Inject constructor(
private val remoteTopicUsersDataSource: RemoteTopicUsersDataSource,
private val topicReadersParser: TopicReadersParser,
private val topicWritersParser: TopicWritersParser,
private val parseFactory: ParseFactory
): TopicUsersRepository {
override suspend fun getTopicReaders(topicId: String): TopicReaders {
val page = remoteTopicUsersDataSource.loadTopicReaders(topicId)
parseFactory.parse<Any>(
url = "",
body = page,
resultParserId = null
)
return TopicReaders(topicReadersParser.parse(page).mapNotNull { it.toTopicReaderOrNull() })
}
override suspend fun getTopicWriters(topicId: String): TopicWriters {
val page = remoteTopicUsersDataSource.loadTopicWriters(topicId)
parseFactory.parse<Any>(
url = "",
body = page,
resultParserId = null
)
return TopicWriters(topicWritersParser.parse(page).mapNotNull { it.toTopicWriterOrNull() })
}
} | apache-2.0 | 4a78981693132c9c21f622a08cd21bd7 | 44.473684 | 99 | 0.759699 | 4.339196 | false | false | false | false |
ivanTrogrlic/LeagueStats | app/src/main/java/com/ivantrogrlic/leaguestats/model/ServiceProxy.kt | 1 | 2177 | package com.ivantrogrlic.leaguestats.model
import android.content.Context
import com.ivantrogrlic.leaguestats.R
/**
* Created by ivanTrogrlic on 16/07/2017.
*/
enum class ServiceProxy {
BR {
override fun serverName(context: Context): String = context.getString(R.string.server_br)
override fun serverHost() = "https://br1.api.riotgames.com/"
},
EUNE {
override fun serverName(context: Context): String = context.getString(R.string.server_eune)
override fun serverHost() = "https://eun1.api.riotgames.com/"
},
EUW {
override fun serverName(context: Context): String = context.getString(R.string.server_euw)
override fun serverHost() = "https://euw1.api.riotgames.com/"
},
JP {
override fun serverName(context: Context): String = context.getString(R.string.server_jp)
override fun serverHost() = "https://jp1.api.riotgames.com/"
},
KR {
override fun serverName(context: Context): String = context.getString(R.string.server_kr)
override fun serverHost() = "https://kr.api.riotgames.com/"
},
LAN {
override fun serverName(context: Context): String = context.getString(R.string.server_lan)
override fun serverHost() = "https://la1.api.riotgames.com/"
},
LAS {
override fun serverName(context: Context): String = context.getString(R.string.server_las)
override fun serverHost() = "https://la2.api.riotgames.com/"
},
NA {
override fun serverName(context: Context): String = context.getString(R.string.server_na)
override fun serverHost() = "https://na1.api.riotgames.com/"
},
OCE {
override fun serverName(context: Context): String = context.getString(R.string.server_oce)
override fun serverHost() = "https://oc1.api.riotgames.com/"
},
TR {
override fun serverName(context: Context): String = context.getString(R.string.server_tr)
override fun serverHost() = "https://tr1.api.riotgames.com/"
},
RU {
override fun serverName(context: Context): String = context.getString(R.string.server_ru)
override fun serverHost() = "https://ru.api.riotgames.com/"
};
abstract fun serverName(context: Context): String
abstract fun serverHost(): String
}
| apache-2.0 | 19488ada990bbbdb62630c223f015969 | 36.534483 | 95 | 0.701883 | 3.44462 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/network/Types.kt | 1 | 48720 | package pl.wendigo.chrome.api.network
/**
* Resource type as it was perceived by the rendering engine.
*
* @link [Network#ResourceType](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ResourceType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class ResourceType {
@kotlinx.serialization.SerialName("Document")
DOCUMENT,
@kotlinx.serialization.SerialName("Stylesheet")
STYLESHEET,
@kotlinx.serialization.SerialName("Image")
IMAGE,
@kotlinx.serialization.SerialName("Media")
MEDIA,
@kotlinx.serialization.SerialName("Font")
FONT,
@kotlinx.serialization.SerialName("Script")
SCRIPT,
@kotlinx.serialization.SerialName("TextTrack")
TEXTTRACK,
@kotlinx.serialization.SerialName("XHR")
XHR,
@kotlinx.serialization.SerialName("Fetch")
FETCH,
@kotlinx.serialization.SerialName("EventSource")
EVENTSOURCE,
@kotlinx.serialization.SerialName("WebSocket")
WEBSOCKET,
@kotlinx.serialization.SerialName("Manifest")
MANIFEST,
@kotlinx.serialization.SerialName("SignedExchange")
SIGNEDEXCHANGE,
@kotlinx.serialization.SerialName("Ping")
PING,
@kotlinx.serialization.SerialName("CSPViolationReport")
CSPVIOLATIONREPORT,
@kotlinx.serialization.SerialName("Preflight")
PREFLIGHT,
@kotlinx.serialization.SerialName("Other")
OTHER;
}
/**
* Unique loader identifier.
*
* @link [Network#LoaderId](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-LoaderId) type documentation.
*/
typealias LoaderId = String
/**
* Unique request identifier.
*
* @link [Network#RequestId](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RequestId) type documentation.
*/
typealias RequestId = String
/**
* Unique intercepted request identifier.
*
* @link [Network#InterceptionId](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-InterceptionId) type documentation.
*/
typealias InterceptionId = String
/**
* Network level fetch failure reason.
*
* @link [Network#ErrorReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ErrorReason) type documentation.
*/
@kotlinx.serialization.Serializable
enum class ErrorReason {
@kotlinx.serialization.SerialName("Failed")
FAILED,
@kotlinx.serialization.SerialName("Aborted")
ABORTED,
@kotlinx.serialization.SerialName("TimedOut")
TIMEDOUT,
@kotlinx.serialization.SerialName("AccessDenied")
ACCESSDENIED,
@kotlinx.serialization.SerialName("ConnectionClosed")
CONNECTIONCLOSED,
@kotlinx.serialization.SerialName("ConnectionReset")
CONNECTIONRESET,
@kotlinx.serialization.SerialName("ConnectionRefused")
CONNECTIONREFUSED,
@kotlinx.serialization.SerialName("ConnectionAborted")
CONNECTIONABORTED,
@kotlinx.serialization.SerialName("ConnectionFailed")
CONNECTIONFAILED,
@kotlinx.serialization.SerialName("NameNotResolved")
NAMENOTRESOLVED,
@kotlinx.serialization.SerialName("InternetDisconnected")
INTERNETDISCONNECTED,
@kotlinx.serialization.SerialName("AddressUnreachable")
ADDRESSUNREACHABLE,
@kotlinx.serialization.SerialName("BlockedByClient")
BLOCKEDBYCLIENT,
@kotlinx.serialization.SerialName("BlockedByResponse")
BLOCKEDBYRESPONSE;
}
/**
* UTC time in seconds, counted from January 1, 1970.
*
* @link [Network#TimeSinceEpoch](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TimeSinceEpoch) type documentation.
*/
typealias TimeSinceEpoch = Double
/**
* Monotonically increasing time in seconds since an arbitrary point in the past.
*
* @link [Network#MonotonicTime](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-MonotonicTime) type documentation.
*/
typealias MonotonicTime = Double
/**
* Request / response headers as keys / values of JSON object.
*
* @link [Network#Headers](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Headers) type documentation.
*/
typealias Headers = Map<String, kotlinx.serialization.json.JsonElement>
/**
* The underlying connection technology that the browser is supposedly using.
*
* @link [Network#ConnectionType](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ConnectionType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class ConnectionType {
@kotlinx.serialization.SerialName("none")
NONE,
@kotlinx.serialization.SerialName("cellular2g")
CELLULAR2G,
@kotlinx.serialization.SerialName("cellular3g")
CELLULAR3G,
@kotlinx.serialization.SerialName("cellular4g")
CELLULAR4G,
@kotlinx.serialization.SerialName("bluetooth")
BLUETOOTH,
@kotlinx.serialization.SerialName("ethernet")
ETHERNET,
@kotlinx.serialization.SerialName("wifi")
WIFI,
@kotlinx.serialization.SerialName("wimax")
WIMAX,
@kotlinx.serialization.SerialName("other")
OTHER;
}
/**
* Represents the cookie's 'SameSite' status:
https://tools.ietf.org/html/draft-west-first-party-cookies
*
* @link [Network#CookieSameSite](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CookieSameSite) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CookieSameSite {
@kotlinx.serialization.SerialName("Strict")
STRICT,
@kotlinx.serialization.SerialName("Lax")
LAX,
@kotlinx.serialization.SerialName("None")
NONE;
}
/**
* Represents the cookie's 'Priority' status:
https://tools.ietf.org/html/draft-west-cookie-priority-00
*
* @link [Network#CookiePriority](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CookiePriority) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CookiePriority {
@kotlinx.serialization.SerialName("Low")
LOW,
@kotlinx.serialization.SerialName("Medium")
MEDIUM,
@kotlinx.serialization.SerialName("High")
HIGH;
}
/**
* Represents the source scheme of the origin that originally set the cookie.
A value of "Unset" allows protocol clients to emulate legacy cookie scope for the scheme.
This is a temporary ability and it will be removed in the future.
*
* @link [Network#CookieSourceScheme](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CookieSourceScheme) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CookieSourceScheme {
@kotlinx.serialization.SerialName("Unset")
UNSET,
@kotlinx.serialization.SerialName("NonSecure")
NONSECURE,
@kotlinx.serialization.SerialName("Secure")
SECURE;
}
/**
* Timing information for the request.
*
* @link [Network#ResourceTiming](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ResourceTiming) type documentation.
*/
@kotlinx.serialization.Serializable
data class ResourceTiming(
/**
* Timing's requestTime is a baseline in seconds, while the other numbers are ticks in
milliseconds relatively to this requestTime.
*/
val requestTime: Double,
/**
* Started resolving proxy.
*/
val proxyStart: Double,
/**
* Finished resolving proxy.
*/
val proxyEnd: Double,
/**
* Started DNS address resolve.
*/
val dnsStart: Double,
/**
* Finished DNS address resolve.
*/
val dnsEnd: Double,
/**
* Started connecting to the remote host.
*/
val connectStart: Double,
/**
* Connected to the remote host.
*/
val connectEnd: Double,
/**
* Started SSL handshake.
*/
val sslStart: Double,
/**
* Finished SSL handshake.
*/
val sslEnd: Double,
/**
* Started running ServiceWorker.
*/
@pl.wendigo.chrome.protocol.Experimental val workerStart: Double,
/**
* Finished Starting ServiceWorker.
*/
@pl.wendigo.chrome.protocol.Experimental val workerReady: Double,
/**
* Started fetch event.
*/
@pl.wendigo.chrome.protocol.Experimental val workerFetchStart: Double,
/**
* Settled fetch event respondWith promise.
*/
@pl.wendigo.chrome.protocol.Experimental val workerRespondWithSettled: Double,
/**
* Started sending request.
*/
val sendStart: Double,
/**
* Finished sending request.
*/
val sendEnd: Double,
/**
* Time the server started pushing request.
*/
@pl.wendigo.chrome.protocol.Experimental val pushStart: Double,
/**
* Time the server finished pushing request.
*/
@pl.wendigo.chrome.protocol.Experimental val pushEnd: Double,
/**
* Finished receiving response headers.
*/
val receiveHeadersEnd: Double
)
/**
* Loading priority of a resource request.
*
* @link [Network#ResourcePriority](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ResourcePriority) type documentation.
*/
@kotlinx.serialization.Serializable
enum class ResourcePriority {
@kotlinx.serialization.SerialName("VeryLow")
VERYLOW,
@kotlinx.serialization.SerialName("Low")
LOW,
@kotlinx.serialization.SerialName("Medium")
MEDIUM,
@kotlinx.serialization.SerialName("High")
HIGH,
@kotlinx.serialization.SerialName("VeryHigh")
VERYHIGH;
}
/**
* Post data entry for HTTP request
*
* @link [Network#PostDataEntry](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-PostDataEntry) type documentation.
*/
@kotlinx.serialization.Serializable
data class PostDataEntry(
/**
*
*/
val bytes: String? = null
)
/**
* HTTP request data.
*
* @link [Network#Request](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Request) type documentation.
*/
@kotlinx.serialization.Serializable
data class Request(
/**
* Request URL (without fragment).
*/
val url: String,
/**
* Fragment of the requested URL starting with hash, if present.
*/
val urlFragment: String? = null,
/**
* HTTP request method.
*/
val method: String,
/**
* HTTP request headers.
*/
val headers: Headers,
/**
* HTTP POST request data.
*/
val postData: String? = null,
/**
* True when the request has POST data. Note that postData might still be omitted when this flag is true when the data is too long.
*/
val hasPostData: Boolean? = null,
/**
* Request body elements. This will be converted from base64 to binary
*/
@pl.wendigo.chrome.protocol.Experimental val postDataEntries: List<PostDataEntry>? = null,
/**
* The mixed content type of the request.
*/
val mixedContentType: pl.wendigo.chrome.api.security.MixedContentType? = null,
/**
* Priority of the resource request at the time request is sent.
*/
val initialPriority: ResourcePriority,
/**
* The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/
*/
val referrerPolicy: String,
/**
* Whether is loaded via link preload.
*/
val isLinkPreload: Boolean? = null,
/**
* Set for requests when the TrustToken API is used. Contains the parameters
passed by the developer (e.g. via "fetch") as understood by the backend.
*/
@pl.wendigo.chrome.protocol.Experimental val trustTokenParams: TrustTokenParams? = null
)
/**
* Details of a signed certificate timestamp (SCT).
*
* @link [Network#SignedCertificateTimestamp](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedCertificateTimestamp) type documentation.
*/
@kotlinx.serialization.Serializable
data class SignedCertificateTimestamp(
/**
* Validation status.
*/
val status: String,
/**
* Origin.
*/
val origin: String,
/**
* Log name / description.
*/
val logDescription: String,
/**
* Log ID.
*/
val logId: String,
/**
* Issuance date.
*/
val timestamp: TimeSinceEpoch,
/**
* Hash algorithm.
*/
val hashAlgorithm: String,
/**
* Signature algorithm.
*/
val signatureAlgorithm: String,
/**
* Signature data.
*/
val signatureData: String
)
/**
* Security details about a request.
*
* @link [Network#SecurityDetails](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SecurityDetails) type documentation.
*/
@kotlinx.serialization.Serializable
data class SecurityDetails(
/**
* Protocol name (e.g. "TLS 1.2" or "QUIC").
*/
val protocol: String,
/**
* Key Exchange used by the connection, or the empty string if not applicable.
*/
val keyExchange: String,
/**
* (EC)DH group used by the connection, if applicable.
*/
val keyExchangeGroup: String? = null,
/**
* Cipher name.
*/
val cipher: String,
/**
* TLS MAC. Note that AEAD ciphers do not have separate MACs.
*/
val mac: String? = null,
/**
* Certificate ID value.
*/
val certificateId: pl.wendigo.chrome.api.security.CertificateId,
/**
* Certificate subject name.
*/
val subjectName: String,
/**
* Subject Alternative Name (SAN) DNS names and IP addresses.
*/
val sanList: List<String>,
/**
* Name of the issuing CA.
*/
val issuer: String,
/**
* Certificate valid from date.
*/
val validFrom: TimeSinceEpoch,
/**
* Certificate valid to (expiration) date
*/
val validTo: TimeSinceEpoch,
/**
* List of signed certificate timestamps (SCTs).
*/
val signedCertificateTimestampList: List<SignedCertificateTimestamp>,
/**
* Whether the request complied with Certificate Transparency policy
*/
val certificateTransparencyCompliance: CertificateTransparencyCompliance
)
/**
* Whether the request complied with Certificate Transparency policy.
*
* @link [Network#CertificateTransparencyCompliance](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CertificateTransparencyCompliance) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CertificateTransparencyCompliance {
@kotlinx.serialization.SerialName("unknown")
UNKNOWN,
@kotlinx.serialization.SerialName("not-compliant")
NOT_COMPLIANT,
@kotlinx.serialization.SerialName("compliant")
COMPLIANT;
}
/**
* The reason why request was blocked.
*
* @link [Network#BlockedReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-BlockedReason) type documentation.
*/
@kotlinx.serialization.Serializable
enum class BlockedReason {
@kotlinx.serialization.SerialName("other")
OTHER,
@kotlinx.serialization.SerialName("csp")
CSP,
@kotlinx.serialization.SerialName("mixed-content")
MIXED_CONTENT,
@kotlinx.serialization.SerialName("origin")
ORIGIN,
@kotlinx.serialization.SerialName("inspector")
INSPECTOR,
@kotlinx.serialization.SerialName("subresource-filter")
SUBRESOURCE_FILTER,
@kotlinx.serialization.SerialName("content-type")
CONTENT_TYPE,
@kotlinx.serialization.SerialName("collapsed-by-client")
COLLAPSED_BY_CLIENT,
@kotlinx.serialization.SerialName("coep-frame-resource-needs-coep-header")
COEP_FRAME_RESOURCE_NEEDS_COEP_HEADER,
@kotlinx.serialization.SerialName("coop-sandboxed-iframe-cannot-navigate-to-coop-page")
COOP_SANDBOXED_IFRAME_CANNOT_NAVIGATE_TO_COOP_PAGE,
@kotlinx.serialization.SerialName("corp-not-same-origin")
CORP_NOT_SAME_ORIGIN,
@kotlinx.serialization.SerialName("corp-not-same-origin-after-defaulted-to-same-origin-by-coep")
CORP_NOT_SAME_ORIGIN_AFTER_DEFAULTED_TO_SAME_ORIGIN_BY_COEP,
@kotlinx.serialization.SerialName("corp-not-same-site")
CORP_NOT_SAME_SITE;
}
/**
* The reason why request was blocked.
*
* @link [Network#CorsError](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CorsError) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CorsError {
@kotlinx.serialization.SerialName("DisallowedByMode")
DISALLOWEDBYMODE,
@kotlinx.serialization.SerialName("InvalidResponse")
INVALIDRESPONSE,
@kotlinx.serialization.SerialName("WildcardOriginNotAllowed")
WILDCARDORIGINNOTALLOWED,
@kotlinx.serialization.SerialName("MissingAllowOriginHeader")
MISSINGALLOWORIGINHEADER,
@kotlinx.serialization.SerialName("MultipleAllowOriginValues")
MULTIPLEALLOWORIGINVALUES,
@kotlinx.serialization.SerialName("InvalidAllowOriginValue")
INVALIDALLOWORIGINVALUE,
@kotlinx.serialization.SerialName("AllowOriginMismatch")
ALLOWORIGINMISMATCH,
@kotlinx.serialization.SerialName("InvalidAllowCredentials")
INVALIDALLOWCREDENTIALS,
@kotlinx.serialization.SerialName("CorsDisabledScheme")
CORSDISABLEDSCHEME,
@kotlinx.serialization.SerialName("PreflightInvalidStatus")
PREFLIGHTINVALIDSTATUS,
@kotlinx.serialization.SerialName("PreflightDisallowedRedirect")
PREFLIGHTDISALLOWEDREDIRECT,
@kotlinx.serialization.SerialName("PreflightWildcardOriginNotAllowed")
PREFLIGHTWILDCARDORIGINNOTALLOWED,
@kotlinx.serialization.SerialName("PreflightMissingAllowOriginHeader")
PREFLIGHTMISSINGALLOWORIGINHEADER,
@kotlinx.serialization.SerialName("PreflightMultipleAllowOriginValues")
PREFLIGHTMULTIPLEALLOWORIGINVALUES,
@kotlinx.serialization.SerialName("PreflightInvalidAllowOriginValue")
PREFLIGHTINVALIDALLOWORIGINVALUE,
@kotlinx.serialization.SerialName("PreflightAllowOriginMismatch")
PREFLIGHTALLOWORIGINMISMATCH,
@kotlinx.serialization.SerialName("PreflightInvalidAllowCredentials")
PREFLIGHTINVALIDALLOWCREDENTIALS,
@kotlinx.serialization.SerialName("PreflightMissingAllowExternal")
PREFLIGHTMISSINGALLOWEXTERNAL,
@kotlinx.serialization.SerialName("PreflightInvalidAllowExternal")
PREFLIGHTINVALIDALLOWEXTERNAL,
@kotlinx.serialization.SerialName("InvalidAllowMethodsPreflightResponse")
INVALIDALLOWMETHODSPREFLIGHTRESPONSE,
@kotlinx.serialization.SerialName("InvalidAllowHeadersPreflightResponse")
INVALIDALLOWHEADERSPREFLIGHTRESPONSE,
@kotlinx.serialization.SerialName("MethodDisallowedByPreflightResponse")
METHODDISALLOWEDBYPREFLIGHTRESPONSE,
@kotlinx.serialization.SerialName("HeaderDisallowedByPreflightResponse")
HEADERDISALLOWEDBYPREFLIGHTRESPONSE,
@kotlinx.serialization.SerialName("RedirectContainsCredentials")
REDIRECTCONTAINSCREDENTIALS,
@kotlinx.serialization.SerialName("InsecurePrivateNetwork")
INSECUREPRIVATENETWORK;
}
/**
*
*
* @link [Network#CorsErrorStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CorsErrorStatus) type documentation.
*/
@kotlinx.serialization.Serializable
data class CorsErrorStatus(
/**
*
*/
val corsError: CorsError,
/**
*
*/
val failedParameter: String
)
/**
* Source of serviceworker response.
*
* @link [Network#ServiceWorkerResponseSource](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ServiceWorkerResponseSource) type documentation.
*/
@kotlinx.serialization.Serializable
enum class ServiceWorkerResponseSource {
@kotlinx.serialization.SerialName("cache-storage")
CACHE_STORAGE,
@kotlinx.serialization.SerialName("http-cache")
HTTP_CACHE,
@kotlinx.serialization.SerialName("fallback-code")
FALLBACK_CODE,
@kotlinx.serialization.SerialName("network")
NETWORK;
}
/**
* Determines what type of Trust Token operation is executed and
depending on the type, some additional parameters. The values
are specified in third_party/blink/renderer/core/fetch/trust_token.idl.
*
* @link [Network#TrustTokenParams](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TrustTokenParams) type documentation.
*/
@kotlinx.serialization.Serializable
data class TrustTokenParams(
/**
*
*/
val type: TrustTokenOperationType,
/**
* Only set for "token-redemption" type and determine whether
to request a fresh SRR or use a still valid cached SRR.
*/
val refreshPolicy: String,
/**
* Origins of issuers from whom to request tokens or redemption
records.
*/
val issuers: List<String>? = null
)
/**
*
*
* @link [Network#TrustTokenOperationType](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TrustTokenOperationType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class TrustTokenOperationType {
@kotlinx.serialization.SerialName("Issuance")
ISSUANCE,
@kotlinx.serialization.SerialName("Redemption")
REDEMPTION,
@kotlinx.serialization.SerialName("Signing")
SIGNING;
}
/**
* HTTP response data.
*
* @link [Network#Response](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Response) type documentation.
*/
@kotlinx.serialization.Serializable
data class Response(
/**
* Response URL. This URL can be different from CachedResource.url in case of redirect.
*/
val url: String,
/**
* HTTP response status code.
*/
val status: Int,
/**
* HTTP response status text.
*/
val statusText: String,
/**
* HTTP response headers.
*/
val headers: Headers,
/**
* HTTP response headers text.
*/
val headersText: String? = null,
/**
* Resource mimeType as determined by the browser.
*/
val mimeType: String,
/**
* Refined HTTP request headers that were actually transmitted over the network.
*/
val requestHeaders: Headers? = null,
/**
* HTTP request headers text.
*/
val requestHeadersText: String? = null,
/**
* Specifies whether physical connection was actually reused for this request.
*/
val connectionReused: Boolean,
/**
* Physical connection id that was actually used for this request.
*/
val connectionId: Double,
/**
* Remote IP address.
*/
val remoteIPAddress: String? = null,
/**
* Remote port.
*/
val remotePort: Int? = null,
/**
* Specifies that the request was served from the disk cache.
*/
val fromDiskCache: Boolean? = null,
/**
* Specifies that the request was served from the ServiceWorker.
*/
val fromServiceWorker: Boolean? = null,
/**
* Specifies that the request was served from the prefetch cache.
*/
val fromPrefetchCache: Boolean? = null,
/**
* Total number of bytes received for this request so far.
*/
val encodedDataLength: Double,
/**
* Timing information for the given request.
*/
val timing: ResourceTiming? = null,
/**
* Response source of response from ServiceWorker.
*/
val serviceWorkerResponseSource: ServiceWorkerResponseSource? = null,
/**
* The time at which the returned response was generated.
*/
val responseTime: TimeSinceEpoch? = null,
/**
* Cache Storage Cache Name.
*/
val cacheStorageCacheName: String? = null,
/**
* Protocol used to fetch this request.
*/
val protocol: String? = null,
/**
* Security state of the request resource.
*/
val securityState: pl.wendigo.chrome.api.security.SecurityState,
/**
* Security details for the request.
*/
val securityDetails: SecurityDetails? = null
)
/**
* WebSocket request data.
*
* @link [Network#WebSocketRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-WebSocketRequest) type documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketRequest(
/**
* HTTP request headers.
*/
val headers: Headers
)
/**
* WebSocket response data.
*
* @link [Network#WebSocketResponse](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-WebSocketResponse) type documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketResponse(
/**
* HTTP response status code.
*/
val status: Int,
/**
* HTTP response status text.
*/
val statusText: String,
/**
* HTTP response headers.
*/
val headers: Headers,
/**
* HTTP response headers text.
*/
val headersText: String? = null,
/**
* HTTP request headers.
*/
val requestHeaders: Headers? = null,
/**
* HTTP request headers text.
*/
val requestHeadersText: String? = null
)
/**
* WebSocket message data. This represents an entire WebSocket message, not just a fragmented frame as the name suggests.
*
* @link [Network#WebSocketFrame](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-WebSocketFrame) type documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrame(
/**
* WebSocket message opcode.
*/
val opcode: Double,
/**
* WebSocket message mask.
*/
val mask: Boolean,
/**
* WebSocket message payload data.
If the opcode is 1, this is a text message and payloadData is a UTF-8 string.
If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data.
*/
val payloadData: String
)
/**
* Information about the cached resource.
*
* @link [Network#CachedResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CachedResource) type documentation.
*/
@kotlinx.serialization.Serializable
data class CachedResource(
/**
* Resource URL. This is the url of the original network request.
*/
val url: String,
/**
* Type of this resource.
*/
val type: ResourceType,
/**
* Cached response data.
*/
val response: Response? = null,
/**
* Cached response body size.
*/
val bodySize: Double
)
/**
* Information about the request initiator.
*
* @link [Network#Initiator](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Initiator) type documentation.
*/
@kotlinx.serialization.Serializable
data class Initiator(
/**
* Type of this initiator.
*/
val type: String,
/**
* Initiator JavaScript stack trace, set for Script only.
*/
val stack: pl.wendigo.chrome.api.runtime.StackTrace? = null,
/**
* Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type.
*/
val url: String? = null,
/**
* Initiator line number, set for Parser type or for Script type (when script is importing
module) (0-based).
*/
val lineNumber: Double? = null,
/**
* Initiator column number, set for Parser type or for Script type (when script is importing
module) (0-based).
*/
val columnNumber: Double? = null,
/**
* Set if another request triggered this request (e.g. preflight).
*/
val requestId: RequestId? = null
)
/**
* Cookie object
*
* @link [Network#Cookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Cookie) type documentation.
*/
@kotlinx.serialization.Serializable
data class Cookie(
/**
* Cookie name.
*/
val name: String,
/**
* Cookie value.
*/
val value: String,
/**
* Cookie domain.
*/
val domain: String,
/**
* Cookie path.
*/
val path: String,
/**
* Cookie expiration date as the number of seconds since the UNIX epoch.
*/
val expires: Double,
/**
* Cookie size.
*/
val size: Int,
/**
* True if cookie is http-only.
*/
val httpOnly: Boolean,
/**
* True if cookie is secure.
*/
val secure: Boolean,
/**
* True in case of session cookie.
*/
val session: Boolean,
/**
* Cookie SameSite type.
*/
val sameSite: CookieSameSite? = null,
/**
* Cookie Priority
*/
@pl.wendigo.chrome.protocol.Experimental val priority: CookiePriority,
/**
* True if cookie is SameParty.
*/
@pl.wendigo.chrome.protocol.Experimental val sameParty: Boolean,
/**
* Cookie source scheme type.
*/
@pl.wendigo.chrome.protocol.Experimental val sourceScheme: CookieSourceScheme,
/**
* Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port.
An unspecified port value allows protocol clients to emulate legacy cookie scope for the port.
This is a temporary ability and it will be removed in the future.
*/
@pl.wendigo.chrome.protocol.Experimental val sourcePort: Int
)
/**
* Types of reasons why a cookie may not be stored from a response.
*
* @link [Network#SetCookieBlockedReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SetCookieBlockedReason) type documentation.
*/
@kotlinx.serialization.Serializable
enum class SetCookieBlockedReason {
@kotlinx.serialization.SerialName("SecureOnly")
SECUREONLY,
@kotlinx.serialization.SerialName("SameSiteStrict")
SAMESITESTRICT,
@kotlinx.serialization.SerialName("SameSiteLax")
SAMESITELAX,
@kotlinx.serialization.SerialName("SameSiteUnspecifiedTreatedAsLax")
SAMESITEUNSPECIFIEDTREATEDASLAX,
@kotlinx.serialization.SerialName("SameSiteNoneInsecure")
SAMESITENONEINSECURE,
@kotlinx.serialization.SerialName("UserPreferences")
USERPREFERENCES,
@kotlinx.serialization.SerialName("SyntaxError")
SYNTAXERROR,
@kotlinx.serialization.SerialName("SchemeNotSupported")
SCHEMENOTSUPPORTED,
@kotlinx.serialization.SerialName("OverwriteSecure")
OVERWRITESECURE,
@kotlinx.serialization.SerialName("InvalidDomain")
INVALIDDOMAIN,
@kotlinx.serialization.SerialName("InvalidPrefix")
INVALIDPREFIX,
@kotlinx.serialization.SerialName("UnknownError")
UNKNOWNERROR,
@kotlinx.serialization.SerialName("SchemefulSameSiteStrict")
SCHEMEFULSAMESITESTRICT,
@kotlinx.serialization.SerialName("SchemefulSameSiteLax")
SCHEMEFULSAMESITELAX,
@kotlinx.serialization.SerialName("SchemefulSameSiteUnspecifiedTreatedAsLax")
SCHEMEFULSAMESITEUNSPECIFIEDTREATEDASLAX,
@kotlinx.serialization.SerialName("SamePartyFromCrossPartyContext")
SAMEPARTYFROMCROSSPARTYCONTEXT,
@kotlinx.serialization.SerialName("SamePartyConflictsWithOtherAttributes")
SAMEPARTYCONFLICTSWITHOTHERATTRIBUTES;
}
/**
* Types of reasons why a cookie may not be sent with a request.
*
* @link [Network#CookieBlockedReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CookieBlockedReason) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CookieBlockedReason {
@kotlinx.serialization.SerialName("SecureOnly")
SECUREONLY,
@kotlinx.serialization.SerialName("NotOnPath")
NOTONPATH,
@kotlinx.serialization.SerialName("DomainMismatch")
DOMAINMISMATCH,
@kotlinx.serialization.SerialName("SameSiteStrict")
SAMESITESTRICT,
@kotlinx.serialization.SerialName("SameSiteLax")
SAMESITELAX,
@kotlinx.serialization.SerialName("SameSiteUnspecifiedTreatedAsLax")
SAMESITEUNSPECIFIEDTREATEDASLAX,
@kotlinx.serialization.SerialName("SameSiteNoneInsecure")
SAMESITENONEINSECURE,
@kotlinx.serialization.SerialName("UserPreferences")
USERPREFERENCES,
@kotlinx.serialization.SerialName("UnknownError")
UNKNOWNERROR,
@kotlinx.serialization.SerialName("SchemefulSameSiteStrict")
SCHEMEFULSAMESITESTRICT,
@kotlinx.serialization.SerialName("SchemefulSameSiteLax")
SCHEMEFULSAMESITELAX,
@kotlinx.serialization.SerialName("SchemefulSameSiteUnspecifiedTreatedAsLax")
SCHEMEFULSAMESITEUNSPECIFIEDTREATEDASLAX,
@kotlinx.serialization.SerialName("SamePartyFromCrossPartyContext")
SAMEPARTYFROMCROSSPARTYCONTEXT;
}
/**
* A cookie which was not stored from a response with the corresponding reason.
*
* @link [Network#BlockedSetCookieWithReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-BlockedSetCookieWithReason) type documentation.
*/
@kotlinx.serialization.Serializable
data class BlockedSetCookieWithReason(
/**
* The reason(s) this cookie was blocked.
*/
val blockedReasons: List<SetCookieBlockedReason>,
/**
* The string representing this individual cookie as it would appear in the header.
This is not the entire "cookie" or "set-cookie" header which could have multiple cookies.
*/
val cookieLine: String,
/**
* The cookie object which represents the cookie which was not stored. It is optional because
sometimes complete cookie information is not available, such as in the case of parsing
errors.
*/
val cookie: Cookie? = null
)
/**
* A cookie with was not sent with a request with the corresponding reason.
*
* @link [Network#BlockedCookieWithReason](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-BlockedCookieWithReason) type documentation.
*/
@kotlinx.serialization.Serializable
data class BlockedCookieWithReason(
/**
* The reason(s) the cookie was blocked.
*/
val blockedReasons: List<CookieBlockedReason>,
/**
* The cookie object representing the cookie which was not sent.
*/
val cookie: Cookie
)
/**
* Cookie parameter object
*
* @link [Network#CookieParam](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CookieParam) type documentation.
*/
@kotlinx.serialization.Serializable
data class CookieParam(
/**
* Cookie name.
*/
val name: String,
/**
* Cookie value.
*/
val value: String,
/**
* The request-URI to associate with the setting of the cookie. This value can affect the
default domain, path, source port, and source scheme values of the created cookie.
*/
val url: String? = null,
/**
* Cookie domain.
*/
val domain: String? = null,
/**
* Cookie path.
*/
val path: String? = null,
/**
* True if cookie is secure.
*/
val secure: Boolean? = null,
/**
* True if cookie is http-only.
*/
val httpOnly: Boolean? = null,
/**
* Cookie SameSite type.
*/
val sameSite: CookieSameSite? = null,
/**
* Cookie expiration date, session cookie if not set
*/
val expires: TimeSinceEpoch? = null,
/**
* Cookie Priority.
*/
@pl.wendigo.chrome.protocol.Experimental val priority: CookiePriority? = null,
/**
* True if cookie is SameParty.
*/
@pl.wendigo.chrome.protocol.Experimental val sameParty: Boolean? = null,
/**
* Cookie source scheme type.
*/
@pl.wendigo.chrome.protocol.Experimental val sourceScheme: CookieSourceScheme? = null,
/**
* Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port.
An unspecified port value allows protocol clients to emulate legacy cookie scope for the port.
This is a temporary ability and it will be removed in the future.
*/
@pl.wendigo.chrome.protocol.Experimental val sourcePort: Int? = null
)
/**
* Authorization challenge for HTTP status code 401 or 407.
*
* @link [Network#AuthChallenge](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-AuthChallenge) type documentation.
*/
@kotlinx.serialization.Serializable
data class AuthChallenge(
/**
* Source of the authentication challenge.
*/
val source: String? = null,
/**
* Origin of the challenger.
*/
val origin: String,
/**
* The authentication scheme used, such as basic or digest
*/
val scheme: String,
/**
* The realm of the challenge. May be empty.
*/
val realm: String
)
/**
* Response to an AuthChallenge.
*
* @link [Network#AuthChallengeResponse](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-AuthChallengeResponse) type documentation.
*/
@kotlinx.serialization.Serializable
data class AuthChallengeResponse(
/**
* The decision on what to do in response to the authorization challenge. Default means
deferring to the default behavior of the net stack, which will likely either the Cancel
authentication or display a popup dialog box.
*/
val response: String,
/**
* The username to provide, possibly empty. Should only be set if response is
ProvideCredentials.
*/
val username: String? = null,
/**
* The password to provide, possibly empty. Should only be set if response is
ProvideCredentials.
*/
val password: String? = null
)
/**
* Stages of the interception to begin intercepting. Request will intercept before the request is
sent. Response will intercept after the response is received.
*
* @link [Network#InterceptionStage](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-InterceptionStage) type documentation.
*/
@kotlinx.serialization.Serializable
enum class InterceptionStage {
@kotlinx.serialization.SerialName("Request")
REQUEST,
@kotlinx.serialization.SerialName("HeadersReceived")
HEADERSRECEIVED;
}
/**
* Request pattern for interception.
*
* @link [Network#RequestPattern](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RequestPattern) type documentation.
*/
@kotlinx.serialization.Serializable
data class RequestPattern(
/**
* Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed. Escape character is
backslash. Omitting is equivalent to "*".
*/
val urlPattern: String? = null,
/**
* If set, only requests for matching resource types will be intercepted.
*/
val resourceType: ResourceType? = null,
/**
* Stage at wich to begin intercepting requests. Default is Request.
*/
val interceptionStage: InterceptionStage? = null
)
/**
* Information about a signed exchange signature.
https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1
*
* @link [Network#SignedExchangeSignature](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeSignature) type documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeSignature(
/**
* Signed exchange signature label.
*/
val label: String,
/**
* The hex string of signed exchange signature.
*/
val signature: String,
/**
* Signed exchange signature integrity.
*/
val integrity: String,
/**
* Signed exchange signature cert Url.
*/
val certUrl: String? = null,
/**
* The hex string of signed exchange signature cert sha256.
*/
val certSha256: String? = null,
/**
* Signed exchange signature validity Url.
*/
val validityUrl: String,
/**
* Signed exchange signature date.
*/
val date: Int,
/**
* Signed exchange signature expires.
*/
val expires: Int,
/**
* The encoded certificates.
*/
val certificates: List<String>? = null
)
/**
* Information about a signed exchange header.
https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation
*
* @link [Network#SignedExchangeHeader](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeHeader) type documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeHeader(
/**
* Signed exchange request URL.
*/
val requestUrl: String,
/**
* Signed exchange response code.
*/
val responseCode: Int,
/**
* Signed exchange response headers.
*/
val responseHeaders: Headers,
/**
* Signed exchange response signature.
*/
val signatures: List<SignedExchangeSignature>,
/**
* Signed exchange header integrity hash in the form of "sha256-<base64-hash-value>".
*/
val headerIntegrity: String
)
/**
* Field type for a signed exchange related error.
*
* @link [Network#SignedExchangeErrorField](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeErrorField) type documentation.
*/
@kotlinx.serialization.Serializable
enum class SignedExchangeErrorField {
@kotlinx.serialization.SerialName("signatureSig")
SIGNATURESIG,
@kotlinx.serialization.SerialName("signatureIntegrity")
SIGNATUREINTEGRITY,
@kotlinx.serialization.SerialName("signatureCertUrl")
SIGNATURECERTURL,
@kotlinx.serialization.SerialName("signatureCertSha256")
SIGNATURECERTSHA256,
@kotlinx.serialization.SerialName("signatureValidityUrl")
SIGNATUREVALIDITYURL,
@kotlinx.serialization.SerialName("signatureTimestamps")
SIGNATURETIMESTAMPS;
}
/**
* Information about a signed exchange response.
*
* @link [Network#SignedExchangeError](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeError) type documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeError(
/**
* Error message.
*/
val message: String,
/**
* The index of the signature which caused the error.
*/
val signatureIndex: Int? = null,
/**
* The field which caused the error.
*/
val errorField: SignedExchangeErrorField? = null
)
/**
* Information about a signed exchange response.
*
* @link [Network#SignedExchangeInfo](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeInfo) type documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeInfo(
/**
* The outer response of signed HTTP exchange which was received from network.
*/
val outerResponse: Response,
/**
* Information about the signed exchange header.
*/
val header: SignedExchangeHeader? = null,
/**
* Security details for the signed exchange header.
*/
val securityDetails: SecurityDetails? = null,
/**
* Errors occurred while handling the signed exchagne.
*/
val errors: List<SignedExchangeError>? = null
)
/**
*
*
* @link [Network#PrivateNetworkRequestPolicy](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-PrivateNetworkRequestPolicy) type documentation.
*/
@kotlinx.serialization.Serializable
enum class PrivateNetworkRequestPolicy {
@kotlinx.serialization.SerialName("Allow")
ALLOW,
@kotlinx.serialization.SerialName("BlockFromInsecureToMorePrivate")
BLOCKFROMINSECURETOMOREPRIVATE,
@kotlinx.serialization.SerialName("WarnFromInsecureToMorePrivate")
WARNFROMINSECURETOMOREPRIVATE;
}
/**
*
*
* @link [Network#IPAddressSpace](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-IPAddressSpace) type documentation.
*/
@kotlinx.serialization.Serializable
enum class IPAddressSpace {
@kotlinx.serialization.SerialName("Local")
LOCAL,
@kotlinx.serialization.SerialName("Private")
PRIVATE,
@kotlinx.serialization.SerialName("Public")
PUBLIC,
@kotlinx.serialization.SerialName("Unknown")
UNKNOWN;
}
/**
*
*
* @link [Network#ClientSecurityState](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ClientSecurityState) type documentation.
*/
@kotlinx.serialization.Serializable
data class ClientSecurityState(
/**
*
*/
val initiatorIsSecureContext: Boolean,
/**
*
*/
val initiatorIPAddressSpace: IPAddressSpace,
/**
*
*/
val privateNetworkRequestPolicy: PrivateNetworkRequestPolicy
)
/**
*
*
* @link [Network#CrossOriginOpenerPolicyValue](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginOpenerPolicyValue) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CrossOriginOpenerPolicyValue {
@kotlinx.serialization.SerialName("SameOrigin")
SAMEORIGIN,
@kotlinx.serialization.SerialName("SameOriginAllowPopups")
SAMEORIGINALLOWPOPUPS,
@kotlinx.serialization.SerialName("UnsafeNone")
UNSAFENONE,
@kotlinx.serialization.SerialName("SameOriginPlusCoep")
SAMEORIGINPLUSCOEP;
}
/**
*
*
* @link [Network#CrossOriginOpenerPolicyStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginOpenerPolicyStatus) type documentation.
*/
@kotlinx.serialization.Serializable
data class CrossOriginOpenerPolicyStatus(
/**
*
*/
val value: CrossOriginOpenerPolicyValue,
/**
*
*/
val reportOnlyValue: CrossOriginOpenerPolicyValue,
/**
*
*/
val reportingEndpoint: String? = null,
/**
*
*/
val reportOnlyReportingEndpoint: String? = null
)
/**
*
*
* @link [Network#CrossOriginEmbedderPolicyValue](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginEmbedderPolicyValue) type documentation.
*/
@kotlinx.serialization.Serializable
enum class CrossOriginEmbedderPolicyValue {
@kotlinx.serialization.SerialName("None")
NONE,
@kotlinx.serialization.SerialName("RequireCorp")
REQUIRECORP;
}
/**
*
*
* @link [Network#CrossOriginEmbedderPolicyStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginEmbedderPolicyStatus) type documentation.
*/
@kotlinx.serialization.Serializable
data class CrossOriginEmbedderPolicyStatus(
/**
*
*/
val value: CrossOriginEmbedderPolicyValue,
/**
*
*/
val reportOnlyValue: CrossOriginEmbedderPolicyValue,
/**
*
*/
val reportingEndpoint: String? = null,
/**
*
*/
val reportOnlyReportingEndpoint: String? = null
)
/**
*
*
* @link [Network#SecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SecurityIsolationStatus) type documentation.
*/
@kotlinx.serialization.Serializable
data class SecurityIsolationStatus(
/**
*
*/
val coop: CrossOriginOpenerPolicyStatus? = null,
/**
*
*/
val coep: CrossOriginEmbedderPolicyStatus? = null
)
/**
* An object providing the result of a network resource load.
*
* @link [Network#LoadNetworkResourcePageResult](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-LoadNetworkResourcePageResult) type documentation.
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourcePageResult(
/**
*
*/
val success: Boolean,
/**
* Optional values used for error reporting.
*/
val netError: Double? = null,
/**
*
*/
val netErrorName: String? = null,
/**
*
*/
val httpStatusCode: Double? = null,
/**
* If successful, one of the following two fields holds the result.
*/
val stream: pl.wendigo.chrome.api.io.StreamHandle? = null,
/**
* Response headers.
*/
val headers: pl.wendigo.chrome.api.network.Headers? = null
)
/**
* An options object that may be extended later to better support CORS,
CORB and streaming.
*
* @link [Network#LoadNetworkResourceOptions](https://chromedevtools.github.io/devtools-protocol/tot/Network#type-LoadNetworkResourceOptions) type documentation.
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourceOptions(
/**
*
*/
val disableCache: Boolean,
/**
*
*/
val includeCredentials: Boolean
)
| apache-2.0 | fd37cd767a5b8240386e9a3a983e907f | 24.791424 | 175 | 0.680932 | 4.377358 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.