content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins
import com.demonwav.mcdev.nbt.lang.psi.NbttElement
import com.demonwav.mcdev.nbt.tags.TagFloat
interface NbttFloatMixin : NbttElement {
fun getFloatTag(): TagFloat
}
| src/main/kotlin/nbt/lang/psi/mixins/NbttFloatMixin.kt | 731622055 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
/**
* This package was taken from https://github.com/go-lang-plugin-org/go-lang-idea-plugin/pull/909
*/
package com.demonwav.mcdev.errorreporter
| src/main/kotlin/errorreporter/package-info.kt | 45471056 |
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.binding.common
const val NO_VIEW1 = 0
const val NO_VIEW2 = 1
const val NO_DIMEN1 = 0
const val NO_DIMEN2 = 1
const val NO_INTEGER1 = 0
const val NO_INTEGER2 = 1
const val NO_STRING1 = 0
const val NO_STRING2 = 1 | akommons-bindings-common-test/src/main/java/com/dewarder/akommons/binding/common/Constants.kt | 807603133 |
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.filter
import org.eclipse.jgit.lib.ObjectId
import org.mapdb.DB
import org.mapdb.HTreeMap
import org.mapdb.Serializer
import svnserver.HashHelper
import svnserver.StringHelper
import svnserver.repository.git.GitObject
import java.io.IOException
import java.security.MessageDigest
/**
* Helper for common filter functionality.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object GitFilterHelper {
private const val BUFFER_SIZE: Int = 32 * 1024
@Throws(IOException::class)
fun getSize(filter: GitFilter, cacheMd5: MutableMap<String, String>, cacheSize: MutableMap<String, Long>, objectId: GitObject<out ObjectId>): Long {
val size: Long? = cacheSize[objectId.`object`.name()]
if (size != null) {
return size
}
return createMetadata(objectId, filter, cacheMd5, cacheSize).size
}
@Throws(IOException::class)
private fun createMetadata(objectId: GitObject<out ObjectId>, filter: GitFilter, cacheMd5: MutableMap<String, String>?, cacheSize: MutableMap<String, Long>?): Metadata {
val buffer = ByteArray(BUFFER_SIZE)
filter.inputStream(objectId).use { stream ->
val digest: MessageDigest? = if (cacheMd5 != null) HashHelper.md5() else null
var totalSize: Long = 0
while (true) {
val bytes: Int = stream.read(buffer)
if (bytes <= 0) break
digest?.update(buffer, 0, bytes)
totalSize += bytes.toLong()
}
val md5: String?
if ((cacheMd5 != null) && (digest != null)) {
md5 = StringHelper.toHex(digest.digest())
cacheMd5.putIfAbsent(objectId.`object`.name(), md5)
} else {
md5 = null
}
cacheSize?.putIfAbsent(objectId.`object`.name(), totalSize)
return Metadata(totalSize, md5)
}
}
@Throws(IOException::class)
fun getMd5(filter: GitFilter, cacheMd5: MutableMap<String, String>, cacheSize: MutableMap<String, Long>?, objectId: GitObject<out ObjectId>): String {
val md5: String? = cacheMd5[objectId.`object`.name()]
if (md5 != null) {
return md5
}
return (createMetadata(objectId, filter, cacheMd5, cacheSize).md5)!!
}
fun getCacheMd5(filter: GitFilter, cacheDb: DB): HTreeMap<String, String> {
return cacheDb.hashMap("cache.filter." + filter.name + ".md5", Serializer.STRING, Serializer.STRING).createOrOpen()
}
fun getCacheSize(filter: GitFilter, cacheDb: DB): HTreeMap<String, Long> {
return cacheDb.hashMap("cache.filter." + filter.name + ".size", Serializer.STRING, Serializer.LONG).createOrOpen()
}
private class Metadata(val size: Long, val md5: String?)
}
| src/main/kotlin/svnserver/repository/git/filter/GitFilterHelper.kt | 3272189859 |
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver
import org.apache.commons.io.FileUtils
import org.apache.commons.io.input.CharSequenceInputStream
import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository
import org.eclipse.jgit.lib.Repository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* Common test functions.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object TestHelper {
val logger: Logger = LoggerFactory.getLogger("test")
fun saveFile(file: Path, content: String) {
Files.write(file, content.toByteArray(StandardCharsets.UTF_8))
}
fun createTempDir(prefix: String): Path {
return Files.createTempDirectory(findGitPath().parent.resolve("build/tmp"), "$prefix-").toAbsolutePath()
}
fun findGitPath(): Path {
val root = Paths.get("").toAbsolutePath()
var path = root
while (true) {
val repo = path.resolve(".git")
if (Files.isDirectory(repo)) return repo
path = path.parent
checkNotNull(path) { "Repository not found from directory: $root" }
}
}
fun deleteDirectory(file: Path) {
FileUtils.deleteDirectory(file.toFile())
}
fun asStream(content: String): InputStream {
return CharSequenceInputStream(content, StandardCharsets.UTF_8)
}
fun emptyRepository(): Repository {
val repository: Repository = InMemoryRepository(DfsRepositoryDescription(null))
repository.create()
return repository
}
}
| src/test/kotlin/svnserver/TestHelper.kt | 3676928424 |
//
// (C) Copyright 2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.builders.objects
import i.katydid.vdom.builders.KatydidAttributesContentBuilderImpl
import i.katydid.vdom.builders.KatydidContentRestrictions
import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import i.katydid.vdom.elements.embedded.KatydidParam
import o.katydid.vdom.builders.KatydidAttributesContentBuilder
import o.katydid.vdom.builders.objects.KatydidObjectFlowContentBuilder
import o.katydid.vdom.types.EDirection
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder DSL to create the contents of an object element.
*
* @constructor Constructs a new builder for the contents of an `<object>` element.
* @param itsElement the element whose content is being built.
* @param itsContentRestrictions restrictions on content enforced at run time.
* @param itsDispatchMessages dispatcher of event handling results for when we want event handling to be reactive or Elm-like.
*/
internal class KatydidObjectFlowContentBuilderImpl<Msg>(
itsElement: KatydidHtmlElementImpl<Msg>,
itsContentRestrictions: KatydidContentRestrictions = KatydidContentRestrictions(),
itsDispatchMessages: (messages: Iterable<Msg>) -> Unit
) : KatydidFlowContentBuilderImpl<Msg>(itsElement, itsContentRestrictions, itsDispatchMessages),
KatydidObjectFlowContentBuilder<Msg> {
override fun param(
selector: String?,
key: Any?,
accesskey: Char?,
contenteditable: Boolean?,
dir: EDirection?,
draggable: Boolean?,
hidden: Boolean?,
lang: String?,
name: String?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
value: String?,
defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit
) {
contentRestrictions.confirmParamAllowed();
element.addChildNode(
KatydidParam(this, selector, key, accesskey, contenteditable, dir,
draggable, hidden, lang, name, spellcheck, style,
tabindex, title, translate, value, defineAttributes)
)
}
/**
* Creates a new attributes content builder for the given child [element]. Does not have the side effect of
* preventing further `<param>` elements.
*/
fun paramAttributesContent(element: KatydidParam<Msg>): KatydidAttributesContentBuilderImpl<Msg> {
return KatydidAttributesContentBuilderImpl(element, dispatchMessages)
}
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/builders/objects/KatydidObjectFlowContentBuilderImpl.kt | 3215722500 |
package edu.cs4730.textureviewdemo_kt
import android.graphics.Color
import android.graphics.Paint
import androidx.appcompat.app.AppCompatActivity
import android.view.TextureView.SurfaceTextureListener
import android.view.TextureView
import android.os.Bundle
import android.widget.FrameLayout
import android.view.Gravity
import android.graphics.SurfaceTexture
import kotlin.jvm.Volatile
import android.graphics.PorterDuff
/**
* original example from here: http://pastebin.com/J4uDgrZ8 with much thanks.
* Everything for the texture in in the MainActivity. And a generic textureView is used
*/
class AllinOneActivity : AppCompatActivity(), SurfaceTextureListener {
private lateinit var mTextureView: TextureView
private lateinit var mThread: RenderingThread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//get a layout, which we will use later.
val content = FrameLayout(this)
//get a TextureView and set it up with all code below
mTextureView = TextureView(this)
mTextureView.surfaceTextureListener = this
//mTextureView.setOpaque(false); //normally, yes, but we need to see the block here.
//add the TextureView to our layout from above.
content.addView(mTextureView, FrameLayout.LayoutParams(500, 500, Gravity.CENTER))
setContentView(content)
}
/**
* TextureView.SurfaceTextureListener overrides below, that start up the drawing thread.
*/
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
mThread = RenderingThread(mTextureView)
mThread.start()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
// Ignored
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
mThread.stopRendering()
return true
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
// Ignored
}
/*
* Thread to draw a green square moving around the textureView.
*/
private class RenderingThread(private val mSurface: TextureView?) : Thread() {
@Volatile
private var mRunning = true
override fun run() {
var x = 0.0f
var y = 0.0f
var speedX = 5.0f
var speedY = 3.0f
val paint = Paint()
paint.color = -0xff0100
while (mRunning && !interrupted()) {
val canvas = mSurface!!.lockCanvas(null)
try {
//canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
canvas!!.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR)
canvas.drawRect(x, y, x + 20.0f, y + 20.0f, paint)
} finally {
mSurface.unlockCanvasAndPost(canvas!!)
}
if (x + 20.0f + speedX >= mSurface.width || x + speedX <= 0.0f) {
speedX = -speedX
}
if (y + 20.0f + speedY >= mSurface.height || y + speedY <= 0.0f) {
speedY = -speedY
}
x += speedX
y += speedY
try {
sleep(15)
} catch (e: InterruptedException) {
// Interrupted
}
}
}
fun stopRendering() {
interrupt()
mRunning = false
}
}
} | TextureViewDemo_kt/app/src/main/java/edu/cs4730/textureviewdemo_kt/AllinOneActivity.kt | 2272865727 |
package me.ztiany.reflects
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KClass
import kotlin.reflect.jvm.javaField
import kotlin.reflect.jvm.javaGetter
/**
*反射:反射是这样的一组语言和库功能,它允许在运行时自省你的程序的结构。
* Kotlin 让语言中的函数和属性做为一等公民、并对其自省(即在运行时获悉一个名称或者一个属性或函数的类型)
* 与简单地使用函数式或响应式风格紧密相关。
*
* Kotlin 的反射有两套 API,因为最终都是编译为字节码,所以 Java 反射 API 通用适用于 Koitlin,另一套是 Kotlin 提供的反射 API。 kotlin的反射功能是一个独立的模块,如果需要使用则需要引入这个模块,模块中核心类包括:
*
* kotlin的反射功能是一个独立的模块,如果需要使用则需要引入这个模块,模块中核心类包括:
*
* KTypes
* KClasses
* KProperties
* KCallables:是函数和属性的超接口
*
* 内容:
*
* 1,类引用
* 2,函数引用
* 3,属性引用
* 4, 构造函数引用
* 5,与Java平台的互操作
* 6,绑定对象的函数和属性引用
*
* 另外可以参考:重新审视 Kotlin 反射,我觉得可以合理使用,https://mp.weixin.qq.com/s/ScufhaG8Pu5gk_fF3rW90g
*/
//类引用
private fun classReference() {
//类引用:该引用是 KClass 类型的值。
val strClazz = String::class
println(strClazz)
//Java类引用:Kotlin 类引用与 Java 类引用不同。要获得 Java 类引用,需要在 KClass 实例上使用 .java 属性
println(String::class)
println(String::class.java)
//绑定的类引用
//通过使用对象作为接收者,可以用相同的 ::class 语法获取指定对象的类的引用
val str = "ABC"
println(str::class)
println(str::class.java)
}
//函数引用
private fun functionReference() {
fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))//::isOdd 是函数类型 (Int) -> Boolean 的一个值
//当上下文中已知函数期望的类型时,:: 可以用于重载函数
fun isOdd(s: String) = s == "brillig" || s == "slithy" || s == "tove"
println(numbers.filter(::isOdd))//// 引用到 isOdd(x: Int)
//可以通过将方法引用存储在具有显式指定类型的变量中来提供必要的上下文
val predicate: (String) -> Boolean = ::isOdd
//如果我们需要使用类的成员函数或扩展函数,它需要是限定的
//String::toCharArray 是类型 String 提供了一个扩展函数:String.() -> CharArray。
fun toCharArray(lambda: (String) -> CharArray) {
lambda("abc")
}
toCharArray(String::toCharArray)
//示例:函数组合
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
return { x -> f(g(x)) }
}
fun length(s: String) = s.length
val oddLength = compose(::isOdd, ::length)
val strings = listOf("a", "ab", "abc")
println(strings.filter(oddLength)) // 输出 "[a, abc]"
}
//属性引用
private val number = 233
private class PropertyA(val p: Int)
private val String.lastChar: Char get() = this[length - 1]
private fun propertiesReference() {
//要把属性作为 Kotlin中 的一等对象来访问,我们也可以使用 :: 运算符
//表达式 ::x 求值为 KProperty<Int> 类型的属性对象
println(::number.get())
//属性引用可以用在不需要参数的函数处
val strList = listOf("a", "bc", "def")
println(strList.map(String::length))
//访问属于类的成员的属性
val prop = PropertyA::p
println(prop.get(PropertyA(1))) // 输出 "1"
//对于扩展属性
println(String::lastChar.get("abc")) // 输出 "c"
}
//与 Java 反射的互操作性
private fun interactJava() {
//在Java平台上,标准库包含反射类的扩展,它提供了与 Java 反射对象之间映射(kotlin.reflect.jvm)
//查找一个用作 Kotlin 属性 getter 的 幕后字段或 Java方法
println(PropertyA::p.javaGetter)
//获得对应于 Java 类的 Kotlin 类
fun getKClass(o: Any): KClass<Any> = o.javaClass.kotlin
println(getKClass("abc"))
}
//构造函数引用
private fun constructorReference() {
//构造函数可以像方法和属性那样引用。他们可以用于期待这样的函数类型对象的任何地方
//:它与该构造函数接受相同参数并且返回相应类型的对象。 通过使用 :: 操作符并添加类名来引用构造函数。
class Foo
fun function(factory: () -> Foo) {
val x: Foo = factory()
}
//::Foo引用Foo的构造函数
println(function(::Foo))
Foo::class.constructors.forEach {
println(it)
}
}
//绑定的函数与属性引用
private fun bindingFunctionAndPropertyReference() {
//可以引用特定对象的实例方法
val numberRegex = "\\d+".toRegex()
println(numberRegex.matches("29")) // 输出“true”
val isNumber: (String) -> Boolean = numberRegex::matches
println(isNumber)
println(isNumber("29"))
//属性引用也可以绑定
val lengthProp = "abc"::length
println(lengthProp.get()) // 输出“3”
//比较绑定的类型和相应的未绑定类型的引用。 绑定的可调用引用有其接收者“附加”到其上,因此接收者的类型不再是参数
/*绑定非绑定*/
val str = "ABC"
val kFunction1 = str::get
kFunction1.invoke(0)
val kFunction2 = String::get
kFunction2.invoke(str, 0)
}
class LiveData<T>
class Resource<T>
class SalesPlanModel
class A {
val pendingSalesPlanList: LiveData<Resource<List<SalesPlanModel>>> = LiveData()
}
fun main(args: Array<String>) {
println(getType(A::pendingSalesPlanList.javaField!!.genericType))
}
private fun getType(type: Type): Type {
if (type !is ParameterizedType) {
return type
}
return getType(type.actualTypeArguments[0])
}
| Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/reflects/KotlinReflect.kt | 2969472750 |
//
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.forms
import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.KatydidAttributesContentBuilder
import o.katydid.vdom.types.EDirection
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for an input type="url" element.
*/
internal class KatydidInputUrl<Msg>(
phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
autocomplete: String?,
autofocus: Boolean?,
contenteditable: Boolean?,
dir: EDirection?,
disabled: Boolean?,
draggable: Boolean?,
form: String?,
hidden: Boolean?,
lang: String?,
list: String?,
maxlength: Int?,
minlength: Int?,
name: String?,
pattern: String?,
placeholder: String?,
readonly: Boolean?,
required: Boolean?,
size: Int?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
value: String?,
defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit
) : KatydidHtmlElementImpl<Msg>(selector, key ?: name, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
init {
phrasingContent.contentRestrictions.confirmInteractiveContentAllowed()
require(maxlength == null || maxlength >= 0) { "Attribute maxlength must be non-negative." }
require(minlength == null || minlength >= 0) { "Attribute minlength must be non-negative." }
require(size == null || size >= 0) { "Attribute size must be non-negative." }
setAttribute("autocomplete", autocomplete)
setBooleanAttribute("autofocus", autofocus)
setBooleanAttribute("disabled", disabled)
setAttribute("form", form)
setAttribute("list", list)
setNumberAttribute("maxlength", maxlength)
setNumberAttribute("minlength", minlength)
setAttribute("name", name)
setAttribute("pattern", pattern)
setAttribute("placeholder", placeholder)
setBooleanAttribute("readonly", readonly)
setBooleanAttribute("required", required)
setNumberAttribute("size", size)
setAttribute("value", value)
setAttribute("type", "url")
phrasingContent.attributesContent(this).defineAttributes()
this.freeze()
}
////
override val nodeName = "INPUT"
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/forms/KatydidInputUrl.kt | 1511713573 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.css.styles.builders
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.styles.builders.clear
import o.katydid.css.styles.builders.float
import o.katydid.css.styles.makeStyle
import o.katydid.css.types.EClear
import o.katydid.css.types.EFloat
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
//---------------------------------------------------------------------------------------------------------------------
@Suppress("RemoveRedundantBackticks")
class FloatStylePropertyTests {
private fun checkStyle(
expectedCss: String,
build: KatydidStyle.() -> Unit
) {
assertEquals(expectedCss, makeStyle(build).toString())
}
@Test
fun `Clear style properties convert to correct CSS`() {
checkStyle("clear: block-end;") { clear(EClear.blockEnd) }
checkStyle("clear: block-start;") { clear(EClear.blockStart) }
checkStyle("clear: both;") { clear(EClear.both) }
checkStyle("clear: bottom;") { clear(EClear.bottom) }
checkStyle("clear: inline-end;") { clear(EClear.inlineEnd) }
checkStyle("clear: inline-start;") { clear(EClear.inlineStart) }
checkStyle("clear: left;") { clear(EClear.left) }
checkStyle("clear: none;") { clear(EClear.none) }
checkStyle("clear: right;") { clear(EClear.right) }
checkStyle("clear: top;") { clear(EClear.top) }
}
@Test
fun `Float style properties convert to correct CSS`() {
checkStyle("float: block-end;") { float(EFloat.blockEnd) }
checkStyle("float: block-start;") { float(EFloat.blockStart) }
checkStyle("float: bottom;") { float(EFloat.bottom) }
checkStyle("float: inline-end;") { float(EFloat.inlineEnd) }
checkStyle("float: inline-start;") { float(EFloat.inlineStart) }
checkStyle("float: left;") { float(EFloat.left) }
checkStyle("float: none;") { float(EFloat.none) }
checkStyle("float: right;") { float(EFloat.right) }
checkStyle("float: snap-block;") { float(EFloat.snapBlock) }
checkStyle("float: snap-inline;") { float(EFloat.snapInline) }
}
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/styles/builders/FloatStylePropertyTests.kt | 2819187350 |
package com.tamsiree.rxdemo.interfaces
import android.view.View
/**
*
* @author tamsiree
* @date 16-11-13
*/
interface ShopCartInterface {
fun add(view: View?, position: Int)
fun remove(view: View?, position: Int)
} | RxDemo/src/main/java/com/tamsiree/rxdemo/interfaces/ShopCartInterface.kt | 266993252 |
package ch.schulealtendorf.psa.dto.participation
import ch.schulealtendorf.psa.dto.status.StatusType
enum class ParticipationStatusType(
code: Int
) : StatusType {
OPEN(0),
CLOSED(1);
private val range = 2000
override val code = range + code
override val text = this.name
}
| app/dto/src/main/kotlin/ch/schulealtendorf/psa/dto/participation/ParticipationStatusType.kt | 4148082917 |
package com.sapuseven.untis.models.untis.response
import com.sapuseven.untis.models.UntisMessage
import kotlinx.serialization.Serializable
@Serializable
data class MessageResponse(
val result: MessageResult? = null
) : BaseResponse()
@Serializable
data class MessageResult(
val messages: List<UntisMessage>
)
| app/src/main/java/com/sapuseven/untis/models/untis/response/MessageResponse.kt | 2239104783 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model
import android.database.Cursor
import de.vanita5.twittnuker.provider.TwidereDataStore.Suggestions
class SuggestionItem(cursor: Cursor, indices: Indices) {
val title: String?
val summary: String?
val _id: Long
val extra_id: String?
init {
_id = if (indices._id < 0) -1 else cursor.getLong(indices._id)
title = cursor.getString(indices.title)
summary = cursor.getString(indices.summary)
extra_id = cursor.getString(indices.extra_id)
}
class Indices(cursor: Cursor) {
val _id: Int = cursor.getColumnIndex(Suggestions._ID)
val type: Int = cursor.getColumnIndex(Suggestions.TYPE)
val title: Int = cursor.getColumnIndex(Suggestions.TITLE)
val value: Int = cursor.getColumnIndex(Suggestions.VALUE)
val summary: Int = cursor.getColumnIndex(Suggestions.SUMMARY)
val icon: Int = cursor.getColumnIndex(Suggestions.ICON)
val extra_id: Int = cursor.getColumnIndex(Suggestions.EXTRA_ID)
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/SuggestionItem.kt | 3535786372 |
package com.stripe.android.identity.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.material.composethemeadapter.MdcTheme
import com.stripe.android.camera.scanui.CameraView
import com.stripe.android.identity.R
import com.stripe.android.identity.states.IdentityScanState
internal const val CONTINUE_BUTTON_TAG = "Continue"
internal const val SCAN_TITLE_TAG = "Title"
internal const val SCAN_MESSAGE_TAG = "Message"
internal const val CHECK_MARK_TAG = "CheckMark"
internal const val VIEW_FINDER_ASPECT_RATIO = 1.5f
@Composable
internal fun DocumentScanScreen(
title: String,
message: String,
newDisplayState: IdentityScanState?,
onCameraViewCreated: (CameraView) -> Unit,
onContinueClicked: () -> Unit
) {
MdcTheme {
Column(
modifier = Modifier
.fillMaxSize()
.padding(
vertical = dimensionResource(id = R.dimen.page_vertical_margin),
horizontal = dimensionResource(id = R.dimen.page_horizontal_margin)
)
) {
var loadingButtonState by remember(newDisplayState) {
mutableStateOf(
if (newDisplayState is IdentityScanState.Finished) {
LoadingButtonState.Idle
} else {
LoadingButtonState.Disabled
}
)
}
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState())
) {
Text(
text = title,
modifier = Modifier
.fillMaxWidth()
.semantics {
testTag = SCAN_TITLE_TAG
},
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
Text(
text = message,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(
top = dimensionResource(id = R.dimen.item_vertical_margin),
bottom = 48.dp
)
.semantics {
testTag = SCAN_MESSAGE_TAG
},
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
CameraViewFinder(onCameraViewCreated, newDisplayState)
}
LoadingButton(
modifier = Modifier.testTag(CONTINUE_BUTTON_TAG),
text = stringResource(id = R.string.kontinue).uppercase(),
state = loadingButtonState
) {
loadingButtonState = LoadingButtonState.Loading
onContinueClicked()
}
}
}
}
@Composable
private fun CameraViewFinder(
onCameraViewCreated: (CameraView) -> Unit,
newScanState: IdentityScanState?
) {
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(VIEW_FINDER_ASPECT_RATIO)
.clip(RoundedCornerShape(dimensionResource(id = R.dimen.view_finder_corner_radius)))
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
CameraView(
it,
CameraView.ViewFinderType.ID,
R.drawable.viewfinder_border_initial
)
},
update = {
onCameraViewCreated(it)
}
)
if (newScanState is IdentityScanState.Finished) {
Box(
modifier = Modifier
.fillMaxSize()
.background(
colorResource(id = R.color.check_mark_background)
)
.testTag(CHECK_MARK_TAG)
) {
Image(
modifier = Modifier
.fillMaxSize()
.padding(60.dp),
painter = painterResource(id = R.drawable.check_mark),
contentDescription = stringResource(id = R.string.check_mark),
colorFilter = ColorFilter.tint(MaterialTheme.colors.primary),
)
}
}
}
}
| identity/src/main/java/com/stripe/android/identity/ui/DocumenetScanScreen.kt | 3867428655 |
package com.peterlaurence.trekme.viewmodel.markermanage
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.peterlaurence.trekme.core.map.Map
class MakerManageViewModel : ViewModel() {
private val geographicCoords = MutableLiveData<GeographicCoords>()
private val projectedCoords = MutableLiveData<ProjectedCoords>()
fun getGeographicLiveData(): LiveData<GeographicCoords> = geographicCoords
fun getProjectedLiveData(): LiveData<ProjectedCoords> = projectedCoords
/**
* Called when the view had one of the geographic coordinates edited, and requires an update of
* the projected coordinates.
*/
fun onGeographicValuesChanged(map: Map, lat: Double, lon: Double) {
map.projection?.doProjection(lat, lon)?.also {
projectedCoords.postValue(ProjectedCoords(X = it[0], Y = it[1]))
}
}
/**
* Called when the view had one of the projected coordinates edited, and requires an updates of
* the geographic coordinates.
*/
fun onProjectedCoordsChanged(map: Map, X: Double, Y: Double) {
map.projection?.undoProjection(X, Y)?.also {
geographicCoords.postValue(GeographicCoords(lon = it[0], lat = it[1]))
}
}
}
data class GeographicCoords(val lon: Double, val lat: Double)
data class ProjectedCoords(val X: Double, val Y: Double) | app/src/main/java/com/peterlaurence/trekme/viewmodel/markermanage/MakerManageViewModel.kt | 3841685279 |
package com.xenoage.utils.math
/**
* 2D size in integer precision.
*/
data class Size2i(
val width: Int,
val height: Int) {
val area: Int
get() = width * height
constructor(p: Point2i) : this(p.x, p.y)
fun scale(scaling: Int) = Size2i(width * scaling, height * scaling)
fun scale(scaling: Float) = Size2f(width * scaling, height * scaling)
override fun toString() = "${width}x${height}"
}
| utils-kotlin/src/com/xenoage/utils/math/Size2i.kt | 1070199177 |
/*
* Copyright (C) 2018 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.core.content
import androidx.test.filters.SmallTest
import androidx.testutils.assertThrows
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
@SmallTest
class ContentValuesTest {
@Test fun valuesOfValid() {
val values = contentValuesOf(
"null" to null,
"string" to "string",
"byte" to 1.toByte(),
"short" to 1.toShort(),
"int" to 1,
"long" to 1L,
"float" to 1f,
"double" to 1.0,
"boolean" to true,
"byteArray" to byteArrayOf()
)
assertEquals(10, values.size())
assertNull(values.get("null"))
assertEquals("string", values.get("string"))
assertEquals(1.toByte(), values.get("byte"))
assertEquals(1.toShort(), values.get("short"))
assertEquals(1, values.get("int"))
assertEquals(1L, values.get("long"))
assertEquals(1f, values.get("float"))
assertEquals(1.0, values.get("double"))
assertEquals(true, values.get("boolean"))
assertArrayEquals(byteArrayOf(), values.get("byteArray") as ByteArray)
}
@Test fun valuesOfInvalid() {
assertThrows<IllegalArgumentException> {
contentValuesOf("nope" to AtomicInteger(1))
}.hasMessageThat().isEqualTo(
"Illegal value type java.util.concurrent.atomic.AtomicInteger for key \"nope\""
)
}
}
| core/core-ktx/src/androidTest/java/androidx/core/content/ContentValuesTest.kt | 2335299074 |
package com.vanniktech.code.quality.tools
import java.io.File
open class LintExtension {
/**
* Ability to enable or disable only lint for every subproject that is not ignored.
* @since 0.2.0
*/
var enabled: Boolean = true
/**
* Enable or disable textReport.
* @since 0.2.0
*/
var textReport: Boolean? = true
/**
* Specify the textOutput for lint. It will only be used when [textReport] is set to true.
* @since 0.2.0
*/
var textOutput: String = "stdout"
/**
* If set to false or true it overrides [CodeQualityToolsPluginExtension#failEarly].
* @since 0.2.0
*/
var abortOnError: Boolean? = null
/**
* If set to false or true it overrides [CodeQualityToolsPluginExtension#failEarly].
* @since 0.2.0
*/
var warningsAsErrors: Boolean? = null
/**
* Returns whether lint should check all warnings, including those off by default.
* @since 0.5.0
*/
var checkAllWarnings: Boolean? = null
/**
* The baseline file name (e.g. baseline.xml) which will be saved under each project.
* @since 0.5.0
*/
var baselineFileName: String? = null
/**
* Returns whether lint should use absolute paths or not.
* @since 0.9.0
*/
var absolutePaths: Boolean? = null
/**
* The lint config file (e.g. lint.xml).
* @since 0.9.0
*/
var lintConfig: File? = null
/**
* Returns whether lint should check release builds or not.
* Since this plugin hooks lint into the check task we'll assume that you're always running
* the full lint suite and hence checking release builds is not necessary.
* @since 0.10.0
*/
var checkReleaseBuilds: Boolean? = false
/**
* Returns whether lint should check test sources or not.
* @since 0.13.0
*/
var checkTestSources: Boolean? = true
/**
* Returns whether lint should check dependencies or not.
* @since 0.13.0
*/
var checkDependencies: Boolean? = null
}
| src/main/kotlin/com/vanniktech/code/quality/tools/LintExtension.kt | 1018568456 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appcompat.testutils
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
@Suppress("DEPRECATION")
class NightModeActivityTestRule<T : AppCompatActivity>(
activityClazz: Class<T>,
initialTouchMode: Boolean = false,
launchActivity: Boolean = true
) : androidx.test.rule.ActivityTestRule<T>(activityClazz, initialTouchMode, launchActivity) {
override fun beforeActivityLaunched() {
// By default we'll set the night mode to NO, which allows us to make better
// assumptions in the test below
runOnUiThread {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
override fun afterActivityFinished() {
// Reset the default night mode
runOnUiThread {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
} | appcompat/appcompat/src/androidTest/java/androidx/appcompat/testutils/NightModeActivityTestRule.kt | 3810947246 |
package solutions.day22
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
fun Direction.left() = when (this) {
Direction.UP -> Direction.LEFT
Direction.LEFT -> Direction.DOWN
Direction.RIGHT -> Direction.UP
Direction.DOWN -> Direction.RIGHT
}
fun Direction.right() = when (this) {
Direction.UP -> Direction.RIGHT
Direction.LEFT -> Direction.UP
Direction.RIGHT -> Direction.DOWN
Direction.DOWN -> Direction.LEFT
}
private fun Direction.reverse(): Direction = when (this) {
Direction.UP -> Direction.DOWN
Direction.LEFT -> Direction.RIGHT
Direction.RIGHT -> Direction.LEFT
Direction.DOWN -> Direction.UP
}
enum class NodeState {
CLEAN,
WEAKENED,
INFECTED,
FLAGGED
}
class Day22 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val grid = mutableMapOf<Coordinate, NodeState>().withDefault { NodeState.CLEAN }
val startY = (input.size / 2)
input.forEachIndexed { y, line ->
val startX = -(line.length / 2)
line.forEachIndexed { i, c ->
val coordinate = Coordinate(startX + i, startY - y)
when (c) {
'#' -> grid.put(coordinate, NodeState.INFECTED)
}
}
}
var carrier = Coordinate(0, 0)
var direction = Direction.UP
val nodeModifier: (s: NodeState) -> NodeState = if (partTwo) {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.WEAKENED
NodeState.WEAKENED -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.FLAGGED
NodeState.FLAGGED -> NodeState.CLEAN
}
}
} else {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.CLEAN
else -> throw RuntimeException("Invalid state $s")
}
}
}
val bursts = if(partTwo) {
10_000_000
} else {
10_000
}
var infectionBursts = 0
for (burst in 1..bursts) {
val state = grid.getValue(carrier)
direction = when (state) {
NodeState.CLEAN -> direction.left()
NodeState.WEAKENED -> direction
NodeState.INFECTED -> direction.right()
NodeState.FLAGGED -> direction.reverse()
}
val nextState = nodeModifier(state)
if(nextState == NodeState.INFECTED) {
infectionBursts++
}
grid.put(carrier, nextState)
carrier = carrier.step(direction)
}
return infectionBursts.toString()
}
}
| src/main/kotlin/solutions/day22/Day22.kt | 3078322232 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.lexer
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.LexerTestCase
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.annotations.NonNls
import org.rust.TestCase
import org.rust.pathToGoldTestFile
import org.rust.pathToSourceTestFile
import java.io.IOException
abstract class LexerTestCaseBase : LexerTestCase(), TestCase {
override fun getDirPath(): String = throw UnsupportedOperationException()
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val camelCase = super.getTestName(lowercaseFirstLetter)
return TestCase.camelOrWordsToSnake(camelCase)
}
// NOTE(matkad): this is basically a copy-paste of doFileTest.
// The only difference is that encoding is set to utf-8
protected fun doTest(lexer: Lexer = createLexer()) {
val filePath = pathToSourceTestFile()
var text = ""
try {
val fileText = FileUtil.loadFile(filePath.toFile(), CharsetToolkit.UTF8)
text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText)
} catch (e: IOException) {
fail("can't load file " + filePath + ": " + e.message)
}
doTest(text, null, lexer)
}
override fun doTest(@NonNls text: String, expected: String?, lexer: Lexer) {
val result = printTokens(text, 0, lexer)
if (expected != null) {
UsefulTestCase.assertSameLines(expected, result)
} else {
UsefulTestCase.assertSameLinesWithFile(pathToGoldTestFile().toFile().canonicalPath, result)
}
}
}
| src/test/kotlin/org/rust/lang/core/lexer/LexerTestCaseBase.kt | 3222691925 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
class RsWrongGenericParametersNumberInspectionTest : RsInspectionsTestBase(RsWrongGenericParametersNumberInspection::class) {
fun `test type parameters`() = checkByText("""
struct S;
trait T {
type Ty<A, B>;
fn foo<A>();
fn bar<A>();
}
impl T for S {
type Ty<error descr="Type `Ty` has 1 type parameter but its trait declaration has 2 type parameters [E0049]"><A></error> = ();
fn foo<error descr="Method `foo` has 2 type parameters but its trait declaration has 1 type parameter [E0049]"><A, B></error>() {}
fn <error descr="Method `bar` has 0 type parameters but its trait declaration has 1 type parameter [E0049]">bar</error>() {}
}
""")
fun `test const parameters`() = checkByText("""
struct S;
trait T {
type Ty<const A: usize, const B: usize>;
fn foo<const A: usize>();
}
impl T for S {
type Ty<error descr="Type `Ty` has 1 const parameter but its trait declaration has 2 const parameters [E0049]"><const A: usize></error> = ();
fn foo<error descr="Method `foo` has 2 const parameters but its trait declaration has 1 const parameter [E0049]"><const A: usize, const B: usize></error>() {}
}
""")
fun `test type and const parameters`() = checkByText("""
struct S;
trait T {
type Ty<A, B, const C: usize>;
fn foo<A, const B: usize, const C: usize>();
}
impl T for S {
type Ty<error descr="Type `Ty` has 1 type parameter but its trait declaration has 2 type parameters [E0049]"><error descr="Type `Ty` has 2 const parameters but its trait declaration has 1 const parameter [E0049]"><A, const B: usize, const C: usize></error></error> = ();
fn foo<error descr="Method `foo` has 1 const parameter but its trait declaration has 2 const parameters [E0049]"><error descr="Method `foo` has 2 type parameters but its trait declaration has 1 type parameter [E0049]"><A, B, const C: usize></error></error>() {}
}
""")
fun `test parameters naming and ordering`() = checkByText("""
struct S;
trait T {
type Ty<A1, const B1: usize>;
fn foo<const A1: usize, B1>();
}
impl T for S {
type Ty<const A2: usize, B2> = ();
fn foo<A2, const B2: usize>() {}
}
""")
}
| src/test/kotlin/org/rust/ide/inspections/RsWrongGenericParametersNumberInspectionTest.kt | 3968507488 |
package nl.brouwerijdemolen.borefts2013.gui.screens
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import arrow.core.getOrElse
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import nl.brouwerijdemolen.borefts2013.api.Beer
import nl.brouwerijdemolen.borefts2013.api.Style
import nl.brouwerijdemolen.borefts2013.gui.CoroutineScope.ui
import nl.brouwerijdemolen.borefts2013.gui.Navigator
import nl.brouwerijdemolen.borefts2013.gui.Repository
class StyleViewModel(
private val style: Style,
private val navigator: Navigator,
private val repository: Repository) : ViewModel() {
val state = MutableLiveData<StyleUiModel>()
init {
GlobalScope.launch(ui) {
state.postValue(StyleUiModel(style, repository.styleBeers(style.id)
.map { it.sortedBy { it.name } }
.getOrElse { throw IllegalStateException("StyleViewModel can only be created with cached data") }))
}
}
fun openBeer(beer: Beer) {
navigator.openBeer(beer)
}
}
data class StyleUiModel(
val style: Style,
val beers: List<Beer>)
| android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/StyleViewModel.kt | 2983610511 |
package de.blankedv.lanbahnpanel.settings
import android.content.res.Configuration
import android.os.Bundle
import android.preference.PreferenceActivity
import android.support.annotation.LayoutRes
import android.support.v7.app.ActionBar
import android.support.v7.app.AppCompatDelegate
import android.support.v7.widget.Toolbar
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
/**
* A [android.preference.PreferenceActivity] which implements and proxies the necessary calls
* to be used with AppCompat.
*/
abstract class AppCompatPreferenceActivity : PreferenceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
delegate.installViewFactory()
delegate.onCreate(savedInstanceState)
super.onCreate(savedInstanceState)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
delegate.onPostCreate(savedInstanceState)
}
val supportActionBar: ActionBar?
get() = delegate.supportActionBar
fun setSupportActionBar(toolbar: Toolbar?) {
delegate.setSupportActionBar(toolbar)
}
override fun getMenuInflater(): MenuInflater {
return delegate.menuInflater
}
override fun setContentView(@LayoutRes layoutResID: Int) {
delegate.setContentView(layoutResID)
}
override fun setContentView(view: View) {
delegate.setContentView(view)
}
override fun setContentView(view: View, params: ViewGroup.LayoutParams) {
delegate.setContentView(view, params)
}
override fun addContentView(view: View, params: ViewGroup.LayoutParams) {
delegate.addContentView(view, params)
}
override fun onPostResume() {
super.onPostResume()
delegate.onPostResume()
}
override fun onTitleChanged(title: CharSequence, color: Int) {
super.onTitleChanged(title, color)
delegate.setTitle(title)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
delegate.onConfigurationChanged(newConfig)
}
override fun onStop() {
super.onStop()
delegate.onStop()
}
override fun onDestroy() {
super.onDestroy()
delegate.onDestroy()
}
override fun invalidateOptionsMenu() {
delegate.invalidateOptionsMenu()
}
private val delegate: AppCompatDelegate by lazy {
AppCompatDelegate.create(this, null)
}
}
| app/src/main/java/de/blankedv/lanbahnpanel/settings/AppCompatPreferenceActivity.kt | 1900716499 |
package data.alarm
import android.content.Context
import dagger.Module
import dagger.Provides
import data.RootModule
import domain.alarm.AppAlarmManager
import javax.inject.Singleton
@Module(includes = [RootModule::class])
internal class AlarmModule {
@Provides
@Singleton
fun alarmManager(context: Context): AppAlarmManager = AppAlarmManagerImpl(context)
}
| data/src/main/kotlin/data/alarm/AlarmModule.kt | 2865860842 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the number of wheelchair pushes done since the last reading. Each push is only reported
* once so records shouldn't have overlapping time. The start time of each record should represent
* the start of the interval in which pushes were made.
*/
public class WheelchairPushesRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
/** Count. Required field. Valid range: 1-1000000. */
public val count: Long,
override val metadata: Metadata = Metadata.EMPTY,
) : IntervalRecord {
init {
requireNonNegative(value = count, name = "count")
count.requireNotMore(other = 1000_000, name = "count")
require(startTime.isBefore(endTime)) { "startTime must be before endTime." }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is WheelchairPushesRecord) return false
if (count != other.count) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = 0
result = 31 * result + count.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
companion object {
/**
* Metric identifier to retrieve the total wheelchair push count from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val COUNT_TOTAL: AggregateMetric<Long> =
AggregateMetric.longMetric(
"WheelchairPushes",
AggregateMetric.AggregationType.TOTAL,
"count"
)
}
}
| health/connect/connect-client/src/main/java/androidx/health/connect/client/records/WheelchairPushesRecord.kt | 617575862 |
/*
* Copyright (c) 2017 Markus Ressel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.markusressel.typedpreferencesdemo
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.support.annotation.ArrayRes
import android.support.v4.util.SparseArrayCompat
import android.support.v7.preference.Preference
import com.github.ajalt.timberkt.Timber
import de.markusressel.typedpreferences.PreferenceItem
import de.markusressel.typedpreferencesdemo.dagger.DaggerPreferenceFragment
import javax.inject.Inject
/**
* Created by Markus on 18.07.2017.
*/
class PreferencesFragment : DaggerPreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) {
val cachedValue = preferenceHandler.getValue(PreferenceHandler.BOOLEAN_SETTING)
val nonCachedValue = preferenceHandler.getValue(PreferenceHandler.BOOLEAN_SETTING, false)
Timber.d { "Cached: $cachedValue NonCached: $nonCachedValue" }
}
@Inject
lateinit var preferenceHandler: PreferenceHandler
@Inject
lateinit var appContext: Context
private lateinit var themeMap: SparseArrayCompat<String>
private lateinit var theme: IntListPreference
private lateinit var booleanPreference: Preference
private lateinit var complex: Preference
private lateinit var clearAll: Preference
private var booleanSettingListener: ((PreferenceItem<Boolean>, Boolean, Boolean) -> Unit)? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// set preferences file name
preferenceManager.sharedPreferencesName = preferenceHandler.sharedPreferencesName
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences)
initializePreferenceItems()
addListeners()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
private fun addListeners() {
val hasPreference = preferenceHandler.hasPreference(PreferenceHandler.BOOLEAN_SETTING)
Timber.d { "PreferenceHandler has boolean preference: " + hasPreference }
booleanSettingListener = preferenceHandler.addOnPreferenceChangedListener(PreferenceHandler.BOOLEAN_SETTING) { preference, old, new ->
Timber.d { "Preference '${preference.getKey(appContext)}' changed from '$old' to '$new'" }
}
preferenceHandler.addOnPreferenceChangedListener(PreferenceHandler.THEME) { preference, old, new ->
theme.summary = themeMap.get(new)
// restart activity
activity?.finish()
val intent = Intent(activity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
private fun initializePreferenceItems() {
theme = findPreference(PreferenceHandler.THEME.getKey(appContext)) as IntListPreference
theme.setDefaultValue(PreferenceHandler.THEME.defaultValue)
themeMap = getListPreferenceEntryValueMap(R.array.theme_values, R.array.theme_names)
theme.summary = themeMap.get(preferenceHandler.getValue(PreferenceHandler.THEME))
booleanPreference = findPreference(PreferenceHandler.BOOLEAN_SETTING.getKey(appContext))
complex = findPreference(PreferenceHandler.COMPLEX_SETTING.getKey(appContext))
val value = preferenceHandler.getValue(PreferenceHandler.COMPLEX_SETTING)
complex.summary = value.toString()
clearAll = findPreference(getString(R.string.key_clear_all))
clearAll.onPreferenceClickListener = Preference.OnPreferenceClickListener {
preferenceHandler.clearAll()
false
}
}
/**
* Gets a Map from two array resources
*
* @param valueRes values stored in preferences
* @param nameRes name/description of this option used in view
* @return Map from stored value -> display name
*/
private fun getListPreferenceEntryValueMap(@ArrayRes valueRes: Int, @ArrayRes nameRes: Int): SparseArrayCompat<String> {
val map = SparseArrayCompat<String>()
val values = resources.getStringArray(valueRes)
val names = resources.getStringArray(nameRes)
for (i in values.indices) {
map.put(Integer.valueOf(values[i]), names[i])
}
return map
}
override fun onPause() {
super.onPause()
// remove a single listener
booleanSettingListener?.let {
preferenceHandler.removeOnPreferenceChangedListener(it)
}
// remove all listeners of a specific preference
preferenceHandler.removeAllOnPreferenceChangedListeners(PreferenceHandler.BOOLEAN_SETTING)
// remove all listeners of the handler
preferenceHandler.removeAllOnPreferenceChangedListeners()
}
}
| app/src/main/java/de/markusressel/typedpreferencesdemo/PreferencesFragment.kt | 1607009387 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
val khr_gl_sharing = dependsOn(Binding.OPENGL) {
"KHRGLSharing".nativeClassCL("khr_gl_sharing", KHR) {
documentation = "Native bindings to the $extensionLink extension."
IntConstant(
"""
Returned by CL10#CreateContext(), CL10#CreateContextFromType(), and #GetGLContextInfoKHR() when an invalid OpenGL context or
share group object handle is specified in {@code properties}.
""",
"INVALID_GL_SHAREGROUP_REFERENCE_KHR".."-1000"
)
val INVALID_GL_SHAREGROUP_REFERENCE_KHR = "#INVALID_GL_SHAREGROUP_REFERENCE_KHR"
IntConstant(
"""
Accepted as the {@code param_name} argument of #GetGLContextInfoKHR(). Returns a list of all CL devices which may be associated with the
specified OpenGL context.
""",
"DEVICES_FOR_GL_CONTEXT_KHR"..0x2007
)
IntConstant(
"""
Accepted as the {@code param_name} argument of #GetGLContextInfoKHR(). Returns the CL device currently associated with the specified OpenGL
context.
""",
"CURRENT_DEVICE_FOR_GL_CONTEXT_KHR"..0x2006
)
IntConstant(
"Accepted as an attribute name in the {@code properties} argument of CL10#CreateContext() and CL10#CreateContextFromType().",
"GL_CONTEXT_KHR"..0x2008,
"EGL_DISPLAY_KHR"..0x2009,
"GLX_DISPLAY_KHR"..0x200A,
"WGL_HDC_KHR"..0x200B,
"CGL_SHAREGROUP_KHR"..0x200C
)
cl_int(
"GetGLContextInfoKHR",
"""
Queries the OpenCL device currently corresponding to an OpenGL context.
Such a device may not always exist (for example, if an OpenGL context is specified on a GPU not supporting OpenCL command queues, but which does support
shared CL/GL objects), and if it does exist, may change over time. When such a device does exist, acquiring and releasing shared CL/GL objects may be
faster on a command queue corresponding to this device than on command queues corresponding to other devices available to an OpenCL context.
""",
NullTerminated..const..cl_context_properties_p.IN(
"properties",
"""
points to an attribute list whose format and valid contents are identical to the {code properties} argument of CL10#CreateContext().
{@code properties} must identify a single valid GL context or GL share group object.
"""
),
cl_gl_context_info.IN(
"param_name",
"a constant that specifies the GL context information to query",
"#DEVICES_FOR_GL_CONTEXT_KHR #CURRENT_DEVICE_FOR_GL_CONTEXT_KHR"
),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_POINTER)..nullable..void_p.IN("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. If no device(s) exist corresponding to {@code param_name}, the call will not fail, but the value
of {@code param_value_size_ret} will be zero.
Returns $INVALID_GL_SHAREGROUP_REFERENCE_KHR if a context was specified by any of the following means:
${ul(
"A context was specified for an EGL-based OpenGL ES or OpenGL implementation by setting the attributes #GL_CONTEXT_KHR and #EGL_DISPLAY_KHR.",
"A context was specified for a GLX-based OpenGL implementation by setting the attributes #GL_CONTEXT_KHR and #GLX_DISPLAY_KHR.",
"A context was specified for a WGL-based OpenGL implementation by setting the attributes #GL_CONTEXT_KHR and #WGL_HDC_KHR."
)}
and any of the following conditions hold:
${ul(
"The specified display and context attributes do not identify a valid OpenGL or OpenGL ES context.",
"The specified context does not support buffer and renderbuffer objects.",
"""
The specified context is not compatible with the OpenCL context being created (for example, it exists in a physically distinct address space, such
as another hardware device; or it does not support sharing data with OpenCL due to implementation restrictions).
"""
)}
Returns $INVALID_GL_SHAREGROUP_REFERENCE_KHR if a share group was specified for a CGL-based OpenGL implementation by setting the attribute
#CGL_SHAREGROUP_KHR, and the specified share group does not identify a valid CGL share group object.
Returns $INVALID_OPERATION if a context was specified as described above and any of the following conditions hold:
${ul(
"""
A context or share group object was specified for one of CGL, EGL, GLX, or WGL and the OpenGL implementation does not support that window-system
binding API.
""",
"""
More than one of the attributes #CGL_SHAREGROUP_KHR, #EGL_DISPLAY_KHR, #GLX_DISPLAY_KHR, and
#WGL_HDC_KHR is set to a non-default value.
""",
"Both of the attributes #CGL_SHAREGROUP_KHR and #GL_CONTEXT_KHR are set to non-default values.",
"Any of the devices specified in the {@code devices} argument cannot support OpenCL objects which share the data store of an OpenGL object."
)}
Returns $INVALID_VALUE if an invalid attribute name is specified in {@code properties}.
Additionally, returns $INVALID_VALUE if {@code param_name} is invalid, or if the size in bytes specified by {@code param_value_size} is
less than the size of the return type and {@code param_value} is not a $NULL value, CL10#OUT_OF_RESOURCES if there is a failure to allocate
resources required by the OpenCL implementation on the device, or CL10#OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by
the OpenCL implementation on the host.
"""
)
}
} | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/khr_gl_sharing.kt | 862818294 |
package io.mockk.impl.stub
import io.mockk.*
import io.mockk.MockKGateway.ExclusionParameters
import io.mockk.impl.InternalPlatform
import kotlin.reflect.KClass
class ConstructorStub(
val mock: Any,
val representativeMock: Any,
val stub: Stub,
val recordPrivateCalls: Boolean
) : Stub {
private val represent = identityMapOf(mock to representativeMock)
private val revertRepresentation = identityMapOf(representativeMock to mock)
private fun <K, V> identityMapOf(vararg pairs: Pair<K, V>): Map<K, V> =
InternalPlatform.identityMap<K, V>()
.also { map -> map.putAll(pairs) }
override val name: String
get() = stub.name
override val type: KClass<*>
get() = stub.type
override fun addAnswer(matcher: InvocationMatcher, answer: Answer<*>) =
stub.addAnswer(matcher.substitute(represent), answer)
override fun answer(invocation: Invocation) = stub.answer(
invocation.substitute(represent)
).internalSubstitute(revertRepresentation)
override fun childMockK(matcher: InvocationMatcher, childType: KClass<*>) =
stub.childMockK(
matcher.substitute(represent),
childType
)
override fun recordCall(invocation: Invocation) {
val record = if (recordPrivateCalls)
true
else
!invocation.method.privateCall
if (record) {
stub.recordCall(invocation.substitute(represent))
}
}
override fun excludeRecordedCalls(params: ExclusionParameters, matcher: InvocationMatcher) {
stub.excludeRecordedCalls(
params,
matcher.substitute(represent)
)
}
override fun markCallVerified(invocation: Invocation) {
stub.markCallVerified(
invocation.substitute(represent)
)
}
override fun allRecordedCalls() = stub.allRecordedCalls()
.map {
it.substitute(revertRepresentation)
}
override fun allRecordedCalls(method: MethodDescription) =
stub.allRecordedCalls(method)
.map {
it.substitute(revertRepresentation)
}
override fun verifiedCalls() = stub.verifiedCalls()
.map {
it.substitute(revertRepresentation)
}
override fun clear(options: MockKGateway.ClearOptions) =
stub.clear(options)
override fun handleInvocation(
self: Any,
method: MethodDescription,
originalCall: () -> Any?,
args: Array<out Any?>,
fieldValueProvider: BackingFieldValueProvider
) = stub.handleInvocation(
self,
method,
originalCall,
args,
fieldValueProvider
)
override fun toStr() = stub.toStr()
override fun stdObjectAnswer(invocation: Invocation) = stub.stdObjectAnswer(invocation.substitute(represent))
override fun dispose() = stub.dispose()
} | mockk/common/src/main/kotlin/io/mockk/impl/stub/ConstructorStub.kt | 2187226147 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.openal.templates
import org.lwjgl.generator.*
import org.lwjgl.openal.*
val AL_LOKI_WAVE_format = "LOKIWAVEFormat".nativeClassAL("LOKI_WAVE_format") {
documentation = "Native bindings to the $extensionName extension."
IntConstant(
"Buffer formats.",
"FORMAT_WAVE_EXT"..0x10002
)
} | modules/templates/src/main/kotlin/org/lwjgl/openal/templates/AL_LOKI_WAVE_format.kt | 1675892038 |
package nerd.tuxmobil.fahrplan.congress.utils
import nerd.tuxmobil.fahrplan.congress.BuildConfig
import nerd.tuxmobil.fahrplan.congress.extensions.originatesFromPretalx
import nerd.tuxmobil.fahrplan.congress.extensions.originatesFromWiki
import nerd.tuxmobil.fahrplan.congress.models.Session
class FeedbackUrlComposer(
private val frabScheduleFeedbackUrlFormatString: String = BuildConfig.SCHEDULE_FEEDBACK_URL
) {
/**
* Returns the feedback URL for the [session] if it can be composed
* otherwise an empty string.
*
* The [Frab schedule feedback URL][getFrabScheduleFeedbackUrl] is
* composed from the session id.
* For sessions extracted from the wiki of the Chaos Communication Congress
* aka. "self organized sessions" an empty string is returned because
* there is no feedback system for them.
*/
fun getFeedbackUrl(session: Session): String {
if (session.originatesFromWiki) {
return NO_URL
}
return if (session.originatesFromPretalx) {
session.pretalxScheduleFeedbackUrl
} else {
getFrabScheduleFeedbackUrl(session.sessionId, frabScheduleFeedbackUrlFormatString)
}
}
private fun getFrabScheduleFeedbackUrl(sessionId: String, frabScheduleFeedbackUrlFormatString: String): String {
return if (frabScheduleFeedbackUrlFormatString.isEmpty()) {
NO_URL
} else {
String.format(frabScheduleFeedbackUrlFormatString, sessionId)
}
}
private val Session.pretalxScheduleFeedbackUrl
get() = "$url$PRETALX_SCHEDULE_FEEDBACK_URL_SUFFIX"
private companion object {
const val NO_URL = ""
const val PRETALX_SCHEDULE_FEEDBACK_URL_SUFFIX = "feedback/"
}
}
| app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FeedbackUrlComposer.kt | 1691146712 |
package util
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
/**
* Animation utils.
*/
object AnimationUtils {
fun show(view: View, alpha: Boolean = true, scale: Boolean = false, rotate: Boolean = false) {
if (view.visibility == View.VISIBLE) return
view.visibility = View.VISIBLE
val animators = ArrayList<Animator>().apply {
if (alpha) add(ObjectAnimator.ofFloat(view, "alpha", 0f, 1f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleX", 0f, 1f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f))
if (rotate) add(ObjectAnimator.ofFloat(view, "rotation", 270f, 0f))
}
AnimatorSet().apply {
playTogether(animators)
start()
}
}
fun hide(view: View, alpha: Boolean = true, scale: Boolean = false, rotate: Boolean = false) {
if (view.visibility != View.VISIBLE) return
val animators = ArrayList<Animator>().apply {
if (alpha) add(ObjectAnimator.ofFloat(view, "alpha", 0f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleX", 0f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleY", 0f))
if (rotate) add(ObjectAnimator.ofFloat(view, "rotation", 270f))
}
AnimatorSet().apply {
playTogether(animators)
onAnimationEnd({ view.visibility = View.GONE })
start()
}
}
fun showFab(view: View) {
show(view, true, true, true)
}
fun hideFab(view: View) {
hide(view, true, true, true)
}
fun slideFromRight(views: List<View>) {
var animators = ArrayList<Animator>()
for (i in views.indices) {
views[i].let {
it.translationX = 400f
val animator = ObjectAnimator.ofFloat(it, "translationX", 0f).apply {
startDelay = i * 50L
interpolator = DecelerateInterpolator()
duration = 150
}
animators.add(animator)
}
}
AnimatorSet().apply {
playTogether(animators)
start()
}
}
fun slideToRight(views: List<View>, onAnimationEnd: () -> Unit) {
var animators = ArrayList<Animator>()
for (i in views.indices) {
views[i].let {
it.translationX = 0f
val animator = ObjectAnimator.ofFloat(it, "translationX", 400f).apply {
startDelay = i * 50L
interpolator = AccelerateInterpolator()
duration = 150
}
animators.add(animator)
}
}
AnimatorSet().apply {
playTogether(animators)
onAnimationEnd { onAnimationEnd() }
start()
}
}
}
| app/src/main/java/util/AnimationUtils.kt | 4184609879 |
package com.opentok.accelerator.textchat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.opentok.accelerator.textchat.ChatMessage.MessageStatus
import io.mockk.MockKAnnotations
import io.mockk.mockk
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldNotBe
import org.amshove.kluent.shouldThrow
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.UUID
@RunWith(AndroidJUnit4::class)
class MessagesAdapterTest {
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
}
@Test
fun creating_new_instance_with_null_list_throws_exception() {
// when
val func = { MessagesAdapter(null) }
// then
func shouldThrow IllegalArgumentException::class
}
@Test
fun creating_new_instance_with_empty_list_creates_instance() {
// given
val messagesList = ArrayList<ChatMessage>()
// when
val messagesAdapter = MessagesAdapter(messagesList)
// then
messagesAdapter.itemCount shouldBeEqualTo 0
}
@Test
fun creating_new_instance_with_list_containing_one_item() {
// given
val chatMessage = mockk<ChatMessage>();
val messagesList = ArrayList<ChatMessage>()
messagesList.add(chatMessage)
// when
val messagesAdapter = MessagesAdapter(messagesList)
// then
messagesAdapter.itemCount shouldBeEqualTo 1
}
@Test
fun getting_view_type_for_existing_item_returns_view_type() {
// given
val chatMessage = ChatMessage.ChatMessageBuilder("1", UUID.randomUUID(), MessageStatus.SENT_MESSAGE)
.build()
val messagesList = ArrayList<ChatMessage>()
messagesList.add(chatMessage)
// when
val messagesAdapter = MessagesAdapter(messagesList)
// then
messagesAdapter.getItemViewType(0) shouldNotBe null
}
@Test
fun getting_view_type_for_non_existing_item_throws_exception() {
// given
val messagesList = ArrayList<ChatMessage>()
val messagesAdapter = MessagesAdapter(messagesList)
// when
val f = { messagesAdapter.getItemViewType(0) }
// then
f shouldThrow IndexOutOfBoundsException::class
}
} | accelerator-core/src/androidTest/java/com/opentok/accelerator/textchat/MessagesAdapterTest.kt | 742345291 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.reflection.reference
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.qualifiedMemberReference
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassObjectAccessExpression
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiExpressionList
import com.intellij.psi.PsiLiteral
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.ResolveResult
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.ProcessingContext
object ReflectedMethodReference : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
// The pattern for this provider should only match method params, but better be safe
if (element.parent !is PsiExpressionList) {
return arrayOf()
}
return arrayOf(Reference(element as PsiLiteral))
}
class Reference(element: PsiLiteral) : PsiReferenceBase.Poly<PsiLiteral>(element) {
val methodName
get() = element.constantStringValue ?: ""
val expressionList
get() = element.parent as PsiExpressionList
override fun getVariants(): Array<Any> {
val typeClass = findReferencedClass() ?: return arrayOf()
return typeClass.allMethods
.asSequence()
.filter { !it.hasModifier(JvmModifier.PUBLIC) }
.map { method ->
JavaLookupElementBuilder.forMethod(method, PsiSubstitutor.EMPTY).withInsertHandler { context, _ ->
val literal = context.file.findElementAt(context.startOffset)?.parent as? PsiLiteral
?: return@withInsertHandler
val params = literal.parent as? PsiExpressionList ?: return@withInsertHandler
val srgManager = literal.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val signature = method.getSignature(PsiSubstitutor.EMPTY)
val returnType = method.returnType?.let { TypeConversionUtil.erasure(it).canonicalText }
?: return@withInsertHandler
val paramTypes = MethodSignatureUtil.calcErasedParameterTypes(signature)
.map { it.canonicalText }
val memberRef = method.qualifiedMemberReference
val srgMethod = srgMap?.getSrgMethod(memberRef) ?: memberRef
context.setLaterRunnable {
// Commit changes made by code completion
context.commitDocument()
// Run command to replace PsiElement
CommandProcessor.getInstance().runUndoTransparentAction {
runWriteAction {
val elementFactory = JavaPsiFacade.getElementFactory(context.project)
val srgLiteral = elementFactory.createExpressionFromText(
"\"${srgMethod.name}\"",
params
)
if (params.expressionCount > 1) {
params.expressions[1].replace(srgLiteral)
} else {
params.add(srgLiteral)
}
if (params.expressionCount > 2) {
params.deleteChildRange(params.expressions[2], params.expressions.last())
}
val returnTypeRef = elementFactory.createExpressionFromText(
"$returnType.class",
params
)
params.add(returnTypeRef)
for (paramType in paramTypes) {
val paramTypeRef = elementFactory.createExpressionFromText(
"$paramType.class",
params
)
params.add(paramTypeRef)
}
JavaCodeStyleManager.getInstance(context.project).shortenClassReferences(params)
CodeStyleManager.getInstance(context.project).reformat(params, true)
context.editor.caretModel.moveToOffset(params.textRange.endOffset)
}
}
}
}
}
.toTypedArray()
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val typeClass = findReferencedClass() ?: return arrayOf()
val name = methodName
val srgManager = element.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val mcpName = srgMap?.mapMcpToSrgName(name) ?: name
return typeClass.allMethods.asSequence()
.filter { it.name == mcpName }
.map(::PsiElementResolveResult)
.toTypedArray()
}
private fun findReferencedClass(): PsiClass? {
val callParams = element.parent as? PsiExpressionList
val classRef = callParams?.expressions?.first() as? PsiClassObjectAccessExpression
val type = classRef?.operand?.type as? PsiClassType
return type?.resolve()
}
}
}
| src/main/kotlin/platform/forge/reflection/reference/ReflectedMethodReference.kt | 4023513217 |
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.databinding.adapters
import android.support.annotation.IntRange
import android.content.*
import android.databinding.ViewDataBinding
import android.support.annotation.AnyThread
import android.support.annotation.UiThread
import android.support.v7.widget.RecyclerView
import android.view.*
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.debug.prettyStringContent
import com.commonsense.android.kotlin.base.extensions.*
import com.commonsense.android.kotlin.base.extensions.collections.*
import com.commonsense.android.kotlin.system.datastructures.*
import com.commonsense.android.kotlin.system.logging.*
import com.commonsense.android.kotlin.views.*
import com.commonsense.android.kotlin.views.extensions.*
import java.lang.ref.*
import kotlin.reflect.*
/**
* Created by kasper on 17/05/2017.
*/
/**
* Describes the required for inflating a given ViewVBinding
* VM is the viewbinding class
*/
typealias InflatingFunction<Vm> = (inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean) -> BaseViewHolderItem<Vm>
/**
* Defines the required information for a data binding recycler adapter.
* @param T : ViewDataBinding the view to contain
* @property item T the data for the view
* @property viewBindingTypeValue Int the view type (a unique number for the view)
*/
open class BaseViewHolderItem<out T : ViewDataBinding>(val item: T) : RecyclerView.ViewHolder(item.root) {
/**
* The view's "type", which is the type of the class (which is unique, by jvm specification).
*/
val viewBindingTypeValue = item.javaClass.hashCode()
}
/**
*
* @param T : Any
* @param Vm : ViewDataBinding
*/
interface IRenderModelItem<T : Any, Vm : ViewDataBinding> :
TypeHashCodeLookupRepresent<InflatingFunction<Vm>> {
/**
* Gets the data associated with this binding
* @return T
*/
fun getValue(): T
/**
* Renders the given model to the given view, via the view holder
* @param view Vm the view to update with the model
* @param model T the model data associated with this view type
* @param viewHolder BaseViewHolderItem<Vm> the view holder containing the view and data
*/
fun renderFunction(view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>)
/**
* Binds this to the given view holder.
* @param holder BaseViewHolderItem<*>
*/
fun bindToViewHolder(holder: BaseViewHolderItem<*>)
/**
* Creates the view holder from the given (potentially newly inflated) view.
* @param inflatedView Vm the view binding
* @return BaseViewHolderItem<Vm> a valid view holder for the given view binding
*/
fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm>
/**
* Gets the inflater function to create the view for this
* @return ViewInflatingFunction<Vm> the function that can create the view;
*/
fun getInflaterFunction(): ViewInflatingFunction<Vm>
}
/**
* The Root of databinding render models (factors the most common stuff out)
* creates a renderable model that can render it self.
* @param T : Any the data associated with this render
* @param Vm : ViewDataBinding the view associated with this render
*/
abstract class BaseRenderModel<
T : Any,
Vm : ViewDataBinding>(val item: T, classType: Class<Vm>)
: IRenderModelItem<T, Vm> {
/**
* Convenience constructor, same as original but using kotlin's classes instead.
* @param item T the data to use
* @param classType KClass<Vm> the view class type
*/
constructor(item: T, classType: KClass<Vm>) : this(item, classType.java)
override fun getValue(): T = item
override fun getTypeValue() = vmTypeValue
private val vmTypeValue: Int by lazy {
classType.hashCode()
}
override fun bindToViewHolder(holder: BaseViewHolderItem<*>) {
val casted = holder.cast<BaseViewHolderItem<Vm>>()
if (casted != null) {
renderFunction(casted.item, item, casted)
//we are now "sure" that the binding class is the same as ours, thus casting "should" be "ok". (we basically introduced our own type system)
} else {
L.debug("RenderModelItem",
"unable to bind to view even though it should be correct type$vmTypeValue expected, got : ${holder.viewBindingTypeValue}")
}
}
override fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm> =
BaseViewHolderItem(inflatedView)
override fun getCreatorFunction(): InflatingFunction<Vm> {
return { inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean ->
createViewHolder(getInflaterFunction().invoke(inflater, parent, attach))
}
}
}
/**
* A simple renderable model containing all information required for a databinding recycler adapter
* @param T : Any the data associated with this render
* @param Vm : ViewDataBinding the view associated with this render
* @constructor
*/
open class RenderModel<
T : Any,
Vm : ViewDataBinding>(private val item: T,
private val vmInflater: ViewInflatingFunction<Vm>,
private val classType: Class<Vm>,
private val vmRender: (view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>) -> Unit)
: IRenderModelItem<T, Vm> {
override fun getInflaterFunction() = vmInflater
override fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm> =
BaseViewHolderItem(inflatedView)
override fun getCreatorFunction(): InflatingFunction<Vm> {
return { inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean ->
createViewHolder(vmInflater(inflater, parent, attach))
}
}
override fun getValue(): T = item
override fun getTypeValue(): Int = vmTypeValue
override fun renderFunction(view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>) = vmRender(view, model, viewHolder)
override fun bindToViewHolder(holder: BaseViewHolderItem<*>) {
val casted = holder.cast<BaseViewHolderItem<Vm>>()
if (casted != null) {
@Suppress("UNCHECKED_CAST")
renderFunction(casted.item, item, casted)
//we are now "sure" that the binding class is the same as ours, thus casting "should" be "ok". (we basically introduced our own type system)
} else {
L.debug("RenderModelItem", "unable to bind to view even though it should be correct type$vmTypeValue expected, got : ${holder.viewBindingTypeValue}")
}
}
/**
* more performance than an inline getter that retrieves it.
*/
private val vmTypeValue: Int by lazy {
classType.hashCode()
}
}
/**
* Base class for data binding recycler adapters.
* @param T the type of render models
*/
abstract class DataBindingRecyclerAdapter<T>(context: Context) :
RecyclerView.Adapter<BaseViewHolderItem<*>>() where T : IRenderModelItem<*, *> {
/**
* A simple implementation that discards / tells the underlying adapter that each item have no id.
* we are not stable so return NO_ID.
* @param position Int
* @return Long RecyclerView.NO_ID
*/
override fun getItemId(position: Int): Long = RecyclerView.NO_ID
/**
* The container for all the data via sections
*/
private val dataCollection: SectionLookupRep<T, InflatingFunction<*>> = SectionLookupRep()
/**
* A list of all attached recycler views
*/
private val listeningRecyclers = mutableSetOf<WeakReference<RecyclerView>>()
/**
* Our own layoutinflater
*/
private val inflater: LayoutInflater by lazy {
LayoutInflater.from(context)
}
/**
* The number of sections in this adapter
*/
val sectionCount: Int
get() = dataCollection.sectionCount
init {
super.setHasStableIds(false)
}
/**
* Delegates this responsibility to the data, since it knows it.
* @param parent ViewGroup
* @param viewType Int
* @return BaseViewHolderItem<*>
*/
override fun onCreateViewHolder(parent: ViewGroup, @IntRange(from = 0) viewType: Int): BaseViewHolderItem<*> {
val rep = dataCollection.getTypeRepresentativeFromTypeValue(viewType)
return rep?.invoke(inflater, parent, false)
?: throw RuntimeException("could not find item, " +
"even though we expected it, for viewType: $viewType;" +
"rep is = $rep;" +
"ViewGroup is = $parent")
}
/**
* Delegates this responsibility to the data, since it knows it.
* @param position Int
* @return Int
*/
override fun getItemViewType(@IntRange(from = 0) position: Int): Int {
val item = dataCollection[position]
?: throw RuntimeException("Could not get item, so the position is not there.;" +
" position = $position;" +
" count = ${dataCollection.size};" +
"$dataCollection")
return item.getTypeValue()
}
/**
* Delegates this responsibility to the data, since it knows it.
* and asks it to bind to the given view holder.
* @param holder BaseViewHolderItem<*>
* @param position Int
*/
override fun onBindViewHolder(holder: BaseViewHolderItem<*>, @android.support.annotation.IntRange(from = 0) position: Int) {
//lookup type to converter, then apply model on view using converter
val index = dataCollection.indexToPath(position) ?: return
val render = dataCollection[index]
render?.bindToViewHolder(holder)
}
/**
* Retrieves the number of items (total) in this adapter
* @return Int the number of items (total) in this adapter
*/
override fun getItemCount(): Int = dataCollection.size
/**
* Adds the given item to the end of the given section, or creates the section if not there
* @param newItem T the item to add/append
* @param inSection Int the section index (sparse) to add to
*/
open fun add(newItem: T, inSection: Int): Unit = updateData {
dataCollection.add(newItem, inSection)?.rawRow?.apply {
notifyItemInserted(this)
}
}
/**
* Adds all the given items to the end of the given section, or creates the section if not there
* @param items Collection<T> the items to add
* @param inSection Int the section index (sparse) to add to
*/
open fun addAll(items: Collection<T>, inSection: Int): Unit = updateData {
dataCollection.addAll(items, inSection)?.inRaw?.apply {
notifyItemRangeInserted(this.first, this.length)
}
}
/**
* Adds all the given items to the end of the given section, or creates the section if not there
* @param items Array<out T> the items to add
* @param inSection Int the section index (sparse) to add to
*/
open fun addAll(vararg items: T, inSection: Int): Unit = updateData {
dataCollection.addAll(items.asList(), inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Inserts (instead of appending /adding) to the given section, or creates the section if not there.
* @param item T the item to insert
* @param atRow Int what row to insert at (if there are data)
* @param inSection Int the section index (sparse) to insert into
*/
open fun insert(item: T, atRow: Int, inSection: Int): Unit = updateData {
dataCollection.insert(item, atRow, inSection)?.rawRow?.apply {
notifyItemInserted(this)
}
}
/**
* Inserts all the given elements at the given start position into the given section, or creates the section if not there.
* @param items Collection<T> the items to insert at the given position
* @param startPosition Int the place to perform the insert
* @param inSection Int the section index (sparse) to insert into
*/
open fun insertAll(items: Collection<T>, startPosition: Int, inSection: Int): Unit = updateData {
dataCollection.insertAll(items, startPosition, inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Inserts all the given elements at the given start position into the given section, or creates the section if not there.
* @param items Array<out T> the items to insert at the given position
* @param startPosition Int the place to perform the insert
* @param inSection Int the section index (sparse) to insert into
*/
open fun insertAll(vararg items: T, startPosition: Int, inSection: Int): Unit = updateData {
dataCollection.insertAll(items.asList(), startPosition, inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Removes the item in the section iff there
* @param newItem T the object to remove
* @param inSection Int the section index (sparse) to remove the object from
* @return Int? the raw index of the removing iff any removing was performed (if not then null is returned)
*/
open fun remove(newItem: T, inSection: Int): Int? = updateData {
return@updateData dataCollection.removeItem(newItem, inSection)?.apply {
notifyItemRemoved(rawRow)
}?.rawRow
}
/**
* Removes a given row inside of a section
* Nothing happens if the row is not there.
*
* @param row Int the row in the section to remove
* @param inSection Int the section to remove from
*/
open fun removeAt(row: Int, inSection: Int): Unit = updateData {
dataCollection.removeAt(row, inSection)?.rawRow?.apply {
notifyItemRemoved(this)
}
}
/**
* Removes all the presented items from the given list of items
* @param items List<T> the items to remove from the given section
* @param inSection Int the section index (sparse) to remove all the items from (those that are there)
*/
@UiThread
open fun removeAll(items: List<T>, inSection: Int): Unit = updateData {
items.forEach {
remove(it, inSection)
}
}
/**
* Removes all the given elements from the given section iff possible
* @param range kotlin.ranges.IntRange the range to remove from the section (rows)
* @param inSection Int the section index (sparse) to remove the elements from
*/
@UiThread
open fun removeIn(range: kotlin.ranges.IntRange, inSection: Int): Unit = updateData {
dataCollection.removeInRange(range, inSection)?.inRaw?.apply {
notifyItemRangeRemoved(start + range.first, range.length)
}
}
/**
* Gets the item at the given row in the given section iff there.
* @param atRow Int the row in the section to get
* @param inSection Int the section index (sparse) to retrieve the row from
* @return T? the potential item; if not there null is returned
*/
@AnyThread
open fun getItem(atRow: Int, inSection: Int): T? = dataCollection[atRow, inSection]
/**
* Clears all content of this adapter
*/
@UiThread
open fun clear(): Unit = updateData {
dataCollection.clear()
notifyDataSetChanged()
}
/**
* Adds the given item to the given section without calling update on the underlying adapter
* @param item T the item to append / add
* @param inSection Int the section to append to
*/
@UiThread
protected fun addNoNotify(item: T, inSection: Int): Unit = updateData {
dataCollection.add(item, inSection)?.rawRow
}
/**
* Adds the given items to the given section without calling update on the underlying adapter
* @param items List<T> the items to append / add
* @param inSection Int the section to append to
*/
@UiThread
protected fun addNoNotify(items: List<T>, inSection: Int): Unit = updateData {
dataCollection.addAll(items, inSection)?.inRaw
}
/**
* Updates the given section with the given items.
* @param items List<T> the items to set the section's content to
* @param inSection Int the section index (sparse) to update
*/
@UiThread
open fun setSection(items: List<T>, inSection: Int) = updateData {
val (changes, added, removed) = dataCollection.setSection(items, inSection)
?: return@updateData
changes?.let {
notifyItemRangeChanged(it.inRaw.first, it.inRaw.length)
}
added?.let {
notifyItemRangeInserted(it.inRaw.first, it.inRaw.length)
}
removed?.let {
notifyItemRangeRemoved(it.inRaw.first, it.inRaw.length)
}
}
/**
* Sets the content of the given section to the given item
* @param item T the item to set as the only content of the given section
* @param inSection Int the section index (Sparse) to change
*/
@UiThread
fun setSection(item: T, inSection: Int) = setSection(listOf(item), inSection)
/**
* Clears the given section (removes all elements)
* calling this on an empty section / none exising section will have no effect
* @param inSection Int the section to clear / remove
*/
@UiThread
fun clearSection(inSection: Int): Unit = updateData {
dataCollection.clearSection(inSection)?.inRaw.apply {
this?.let { notifyItemRangeRemoved(it.first, it.length) }
}
}
/**
* replaces the item at the position in the given section, with the supplied item
* @param newItem T the new item to be inserted (iff possible)
* @param position Int the position in the section to replace
* @param inSection Int the section index (sparse) to change
*/
@UiThread
open fun replace(newItem: T, position: Int, inSection: Int): Unit = updateData {
dataCollection.replace(newItem, position, inSection)?.rawRow.apply {
this?.let { notifyItemChanged(it) }
}
}
/**
*Clears and sets a given section (sparse index) without notifying the underlying adapter
* @param items List<T> the items to overwrite the given section with
* @param inSection Int the seciton to clear and set
* @param isIgnored Boolean if the section should be ignored
* @return Boolean if it is ignored or not. (true if ignored)
*/
@UiThread
protected fun clearAndSetItemsNoNotify(items: List<T>, inSection: Int, isIgnored: Boolean) = updateData {
dataCollection.setSection(items, inSection)
isIgnored.ifTrue { dataCollection.ignoreSection(inSection) }
}
/**
* Sets all sections
* @param sections List<TypeSection<T>>
*/
@UiThread
protected fun setAllSections(sections: List<TypeSection<T>>) = updateData {
dataCollection.setAllSections(sections)
super.notifyDataSetChanged()
}
/**
* Stops scroll for all RecyclerViews
*/
@UiThread
private fun stopScroll() {
listeningRecyclers.forEach { recyclerView ->
recyclerView.use { stopScroll() }
}
}
/**
* Called when we get bound to a recyclerView
* @param recyclerView RecyclerView
*/
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
listeningRecyclers.add(recyclerView.weakReference())
}
/**
* Called when a recyclerView is not going to use this adapter anymore.
* @param recyclerView RecyclerView
*/
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
listeningRecyclers.removeAll {
it.get().isNullOrEqualTo(recyclerView)
}
}
/**
* Must be called from all things that manipulate the dataCollection.
*
* @param action EmptyFunctionResult<T> the action to execute safely
* @return T the result of the action
*/
@UiThread
private inline fun <T> updateData(crossinline action: EmptyFunctionResult<T>): T {
stopScroll()
return action()
}
/**
* Gets a representor of the given type (someone who can create the view)
* @param viewHolderItem BaseViewHolderItem<*> the view holder to create it from)
* @return InflatingFunction<*>? the potential inflater function iff anyone can create the view holders view type.
* null if none can
*/
@UiThread
open fun getRepresentUsingType(viewHolderItem: BaseViewHolderItem<*>): InflatingFunction<*>? =
dataCollection.getTypeRepresentativeFromTypeValue(viewHolderItem.viewBindingTypeValue)
/**
* Tries to lookup an item from a given raw index (0 until the item count)
* @param rawIndex Int the raw index
* @return T? the item if there, null otherwise
*/
@UiThread
open fun getItemFromRawIndex(rawIndex: Int): T? {
val index = dataCollection.indexToPath(rawIndex) ?: return null
return dataCollection[index]
}
/**
* Hides the given section
* only updates anything if the section was visible beforehand
* @param sectionIndex Int the section index (sparse) to hide
*/
@UiThread
open fun hideSection(sectionIndex: Int) = updateData {
val sectionLocation = dataCollection.ignoreSection(sectionIndex)?.inRaw ?: return@updateData
notifyItemRangeRemoved(sectionLocation.first, sectionLocation.length)
}
/**
* Shows the given section iff it was invisible before.
* otherwise this have no effect
* @param sectionIndex Int the section index (sparse) to show
*/
@UiThread
open fun showSection(sectionIndex: Int) = updateData {
val sectionLocation = dataCollection.acceptSection(sectionIndex)?.inRaw ?: return@updateData
notifyItemRangeInserted(sectionLocation.first, sectionLocation.length)
}
/**
* Toggles all of the given sections visibility
* @param sectionIndexes IntArray the section indexes (sparse indexes)
*/
@UiThread
open fun toggleSectionsVisibility(vararg sectionIndexes: Int) {
sectionIndexes.forEach(this::toggleSectionVisibility)
}
/**
* Toggles the given sections visibility
* so if it was visible it becomes invisible, and vice verca
* @param sectionIndex Int the section index (sparse) to update
*/
@UiThread
open fun toggleSectionVisibility(sectionIndex: Int) {
val sectionData = dataCollection.sectionAt(sectionIndex) ?: return
if (sectionData.isIgnored) {
showSection(sectionIndex)
} else {
hideSection(sectionIndex)
}
}
/**
* Clears the underlying data without notifying the underlying adapter
*/
@AnyThread
protected fun clearNoNotify() {
dataCollection.clear()
}
/**
* Tries to find the given element in a section , and returns the path if found.
* @param item T the item to find (must be comparable to be compared, otherwise it will be per address)
* @param inSection Int the section index(sparse)
* @return IndexPath? the index where the element is, if found, null otherwise (or null also if the section is not there)
*/
@UiThread
fun getIndexFor(item: T, @android.support.annotation.IntRange(from = 0) inSection: Int): IndexPath? {
val innerIndex = dataCollection.sectionAt(inSection)?.collection?.indexOf(item)
?: return null
return IndexPath(innerIndex, inSection)
}
/**
* Retrieves the given section's size (number of elements)
* @param sectionIndex Int the section index ( sparse) to query
* @return Int? the number of item in this section (elements) , or null if the section does not exists
*/
@UiThread
fun getSectionSize(sectionIndex: Int): Int? = dataCollection.sectionAt(sectionIndex)?.size
/**
* Tells if the queried section is visible; defaults to false if the section does not exists
* @param inSection Int the section index (sparse) to query
* @return Boolean true if the section is visible, false otherwise
*/
@UiThread
fun isSectionVisible(inSection: Int): Boolean =
dataCollection.sectionAt(inSection)?.isIgnored?.not() ?: false
/**
* Changes the given section's visibility to the given visibility
* @param section Int the section index (sparse) to update
* @param isVisible Boolean if true then its visible, if false then its invisible.
*/
@UiThread
fun setSectionVisibility(section: Int, isVisible: Boolean) {
dataCollection.sectionAt(section)?.let {
if (it.isIgnored != !isVisible) {
toggleSectionVisibility(section)
}
}
}
/**
* Removes the section by index, iff it exists.
* @param sectionIndex Int the section index (sparse) to remove.
*/
@UiThread
open fun removeSection(@android.support.annotation.IntRange(from = 0) sectionIndex: Int) = clearSection(sectionIndex)
/**
* Removes a given list of sections
*
* @param sectionIndexes IntArray the sections (sparse) to remove
*/
@UiThread
fun removeSections(@android.support.annotation.IntRange(from = 0) vararg sectionIndexes: Int) {
sectionIndexes.forEach(this::removeSection)
}
/**
* Smooth scrolls to the given section start
* @param sectionIndex Int the section index (sparse)
*/
@UiThread
fun smoothScrollToSection(@android.support.annotation.IntRange(from = 0) sectionIndex: Int) {
val positionInList = dataCollection.getSectionLocation(sectionIndex)?.inRaw?.first ?: return
listeningRecyclers.forEach {
it.use { this.smoothScrollToPosition(positionInList) }
}
}
/**
* Reloads all items in this adapter
*/
@UiThread
fun reloadAll() {
notifyItemRangeChanged(0, dataCollection.size)
}
/**
* Reloads a given section's items
* @param sectionIndex Int the section index (sparse) to reload
*/
@UiThread
fun reloadSection(sectionIndex: Int) {
val location = dataCollection.getSectionLocation(sectionIndex) ?: return
notifyItemRangeChanged(location.inRaw)
}
override fun setHasStableIds(hasStableIds: Boolean) {
logClassError("Have no effect as we are effectively not stable according to the adapter implementation;" +
"We handle everything our self. Please do not call this method.")
}
//make sure we never allow transient state to be recycled.
override fun onFailedToRecycleView(holder: BaseViewHolderItem<*>): Boolean {
return false
}
override fun toString(): String {
return toPrettyString()
}
fun toPrettyString(): String {
return "Base dataBinding adapter state:" + listOf(
dataCollection.toPrettyString()
).prettyStringContent()
}
}
/**
* Hides all the given sections (by sparse index)
* calling hide on an already invisible section have no effects
* @receiver BaseDataBindingRecyclerAdapter
* @param sections IntArray the sections to hide
*/
@UiThread
fun BaseDataBindingRecyclerAdapter.hideSections(vararg sections: Int) =
sections.forEach(this::hideSection)
/**
* Shows all the given sections (by sparse index)
* calling show on an already visible section have no effects
* @receiver BaseDataBindingRecyclerAdapter
* @param sections IntArray the sections to show
*/
fun BaseDataBindingRecyclerAdapter.showSections(vararg sections: Int) =
sections.forEach(this::showSection)
open class BaseDataBindingRecyclerAdapter(context: Context) :
DataBindingRecyclerAdapter<IRenderModelItem<*, *>>(context)
class DefaultDataBindingRecyclerAdapter(context: Context) : BaseDataBindingRecyclerAdapter(context) | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/databinding/adapters/BaseDataBindingRecyclerAdapter.kt | 804854349 |
package csense.android.tools.ui
import org.junit.*
/**
*
*/
class LifeCycleTrackingKtTest {
@Ignore
@Test
fun getTimeFromStartToDisplay() {
}
@Ignore
@Test
fun getTimeForCreate() {
}
} | tools/src/test/kotlin/csense/android/tools/ui/LifeCycleTrackingKtTest.kt | 2454421728 |
/*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd
import android.app.Application
import android.test.ApplicationTestCase
/**
* [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html)
*/
class ApplicationTest : ApplicationTestCase<Application>(Application::class.java) | app/src/androidTest/kotlin/com/hpedrorodrigues/gzmd/ApplicationTest.kt | 1196903392 |
package com.vk.api.sdk.auth
import java.util.concurrent.locks.ReentrantLock
class VKAuthAnonymousTokenBarrier {
private val lock = ReentrantLock(true)
fun tryLockOrAwait(function: () -> Unit) {
try {
if (lock.tryLock()) {
function.invoke()
} else {
lock.lock()
}
} finally {
lock.unlock()
}
}
} | core/src/main/java/com/vk/api/sdk/auth/VKAuthAnonymousTokenBarrier.kt | 2948447796 |
package org.jetbrains.cabal.psi
import org.jetbrains.cabal.psi.Checkable
import com.intellij.psi.PsiElement
import org.jetbrains.cabal.highlight.ErrorMessage
public interface RangedValue: Checkable, PsiElement {
public fun getAvailableValues(): List<String> { return listOf() }
public override fun check(): List<ErrorMessage> {
if (getText()!! !in getAvailableValues()) return listOf(ErrorMessage(this, "invalid field value", "error"))
return listOf()
}
} | plugin/src/org/jetbrains/cabal/psi/RangedValue.kt | 701781107 |
package y2k.joyreactor.common
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import kotlin.reflect.KProperty
/**
* Created by y2k on 5/29/16.
*/
fun RecyclerView.ViewHolder.setOnClick(id: Int, f: (Int) -> Unit) {
itemView.find<View>(id).setOnClickListener { f(layoutPosition) }
}
fun <T : View> ViewGroup.view(): ViewGroupDelegate<T> {
return ViewGroupDelegate()
}
class ViewGroupDelegate<out T : View>() {
private var cached: T? = null
@Suppress("UNCHECKED_CAST")
operator fun getValue(group: ViewGroup, property: KProperty<*>): T {
if (cached == null) {
val context = group.context
val id = context.resources.getIdentifier(property.name, "id", context.packageName)
cached = group.findViewById(id) as T
}
return cached!!
}
}
fun <T : View> RecyclerView.ViewHolder.view(): ViewHolderDelegate<T> {
return ViewHolderDelegate()
}
class ViewHolderDelegate<out T : View>() {
private var cached: T? = null
@Suppress("UNCHECKED_CAST")
operator fun getValue(holder: RecyclerView.ViewHolder, property: KProperty<*>): T {
if (cached == null) {
val context = holder.itemView.context
val id = context.resources.getIdentifier(property.name, "id", context.packageName)
cached = holder.itemView.findViewById(id) as T
}
return cached!!
}
} | android/src/main/kotlin/y2k/joyreactor/common/ViewHolderExtensions.kt | 1994502907 |
package y2k.joyreactor.services.repository
import rx.Observable
import rx.schedulers.Schedulers
import y2k.joyreactor.common.ForegroundScheduler
import java.util.concurrent.Executors
class Entities(val factory: IDataContext) {
fun <T> useOnce(callback: DataContext.() -> T) = use(callback).toSingle()
fun <T> use(callback: DataContext.() -> T): Observable<T> {
return Observable
.fromCallable {
factory.use { callback(DataContext(it)) }
}
.subscribeOn(Schedulers.from(executor))
.observeOn(ForegroundScheduler.instance);
}
companion object {
private val executor = Executors.newSingleThreadExecutor()
}
} | core/src/main/kotlin/y2k/joyreactor/services/repository/Entities.kt | 2260389553 |
package com.eden.orchid.languages.highlighter.tags
import com.eden.orchid.api.compilers.TemplateTag
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.utilities.encodeSpaces
import org.python.util.PythonInterpreter
@Description("Add syntax highlighting using Pygments.", name = "Highlight")
class HighlightTag : TemplateTag("highlight", Type.Content, true) {
@Option
@StringDefault("java")
@Description("Your language to use for the syntax highlighting format.")
lateinit var language: String
override fun parameters() = arrayOf(::language.name)
public fun highlight(input: String): String {
try {
val interpreter = PythonInterpreter()
val pygmentsScript: OrchidResource? = context.getDefaultResourceSource(null, null).getResourceEntry(context, "scripts/pygments/pygments.py")
val pythonScript = pygmentsScript?.content ?: ""
// Set a variable with the content you want to work with
interpreter.set("code", input)
interpreter.set("codeLanguage", language)
// Simply use Pygments as you would in Python
interpreter.exec(pythonScript)
var result = interpreter.get("result", String::class.java)
// replace newlines with <br> tag, and spaces between tags with to preserve original structure
return result.encodeSpaces()
}
catch (e: Exception) {
e.printStackTrace()
}
return input
}
}
| languageExtensions/OrchidSyntaxHighlighter/src/main/kotlin/com/eden/orchid/languages/highlighter/tags/HighlightTag.kt | 3528520520 |
package sqlbuilder.impl.mappers
import sqlbuilder.mapping.BiMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import sqlbuilder.mapping.ToSQLMappingParameters
import java.sql.Types
/**
* @author Laurent Van der Linden.
*/
class IntegerMapper : BiMapper {
override fun toObject(params: ToObjectMappingParameters): Int? {
val value = params.resultSet.getInt(params.index)
return if (params.resultSet.wasNull()) {
null
} else {
value
}
}
override fun toSQL(params: ToSQLMappingParameters) {
if (params.value != null) {
params.preparedStatement.setInt(params.index, params.value as Int)
} else {
params.preparedStatement.setNull(params.index, Types.BIGINT)
}
}
override fun handles(targetType: Class<*>): Boolean {
return Int::class.java == targetType || java.lang.Integer::class.java == targetType
}
} | src/main/kotlin/sqlbuilder/impl/mappers/IntegerMapper.kt | 2737344407 |
package de.westnordost.streetcomplete.data.notifications
import de.westnordost.streetcomplete.data.ApplicationDbTestCase
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.*
class NewUserAchievementsDaoTest : ApplicationDbTestCase() {
private lateinit var dao: NewUserAchievementsDao
@Before fun createDao() {
dao = NewUserAchievementsDao(dbHelper)
}
@Test fun addPopFirst() {
val listener: NewUserAchievementsDao.UpdateListener = mock(NewUserAchievementsDao.UpdateListener::class.java)
dao.addListener(listener)
dao.push(TWO to 2)
dao.push(ONE to 1)
dao.push(TWO to 1)
dao.push(ONE to 8)
assertEquals(ONE to 1, dao.pop())
assertEquals(ONE to 8, dao.pop())
assertEquals(TWO to 1, dao.pop())
assertEquals(TWO to 2, dao.pop())
assertEquals(null, dao.pop())
verify(listener, times(8)).onNewUserAchievementsUpdated()
}
@Test fun addPop() {
val listener: NewUserAchievementsDao.UpdateListener = mock(NewUserAchievementsDao.UpdateListener::class.java)
dao.addListener(listener)
assertEquals(0, dao.getCount())
dao.push(ONE to 4)
assertEquals(1, dao.getCount())
verify(listener, times(1)).onNewUserAchievementsUpdated()
dao.push(ONE to 4)
assertEquals(1, dao.getCount())
verify(listener, times(1)).onNewUserAchievementsUpdated()
dao.push(ONE to 1)
assertEquals(2, dao.getCount())
verify(listener, times(2)).onNewUserAchievementsUpdated()
dao.pop()
assertEquals(1, dao.getCount())
verify(listener, times(3)).onNewUserAchievementsUpdated()
dao.pop()
assertEquals(0, dao.getCount())
verify(listener, times(4)).onNewUserAchievementsUpdated()
}
}
private const val ONE = "one"
private const val TWO = "two"
| app/src/androidTest/java/de/westnordost/streetcomplete/data/notifications/NewUserAchievementsDaoTest.kt | 3242674217 |
/*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.core.sequences.reverse
import uk.co.reecedunn.intellij.plugin.core.sequences.siblings
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathComment
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExpr
import xqt.platform.intellij.xpath.XPathTokenProvider
fun <T> PsiElement.filterExpressions(klass: Class<T>): Sequence<T> {
val item = children().filterIsInstance(klass)
val sequence = children().filterIsInstance<XPathExpr>().firstOrNull()
return if (sequence != null)
sequenceOf(item, sequence.children().filterIsInstance(klass)).flatten()
else
item
}
inline fun <reified T> PsiElement.filterExpressions(): Sequence<T> = filterExpressions(T::class.java)
fun Sequence<PsiElement>.filterNotWhitespace(): Sequence<PsiElement> = filterNot { e ->
e.elementType === XPathTokenProvider.S.elementType || e is XPathComment
}
val PsiElement.parenthesizedExprTextOffset: Int?
get() {
val pref = reverse(siblings()).filterNotWhitespace().firstOrNull()
return when {
pref == null -> null
pref.elementType !== XPathTokenProvider.ParenthesisOpen -> null
pref.parent !is XPathArgumentList -> pref.textOffset
pref.parent.firstChild !== pref -> pref.textOffset
else -> null
}
}
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/PsiUtils.kt | 3181820172 |
package org.mitallast.queue.rest.netty
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpServerCodec
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler
import io.netty.handler.stream.ChunkedWriteHandler
class HttpServerInitializer(
private val httpHandler: HttpServerHandler,
private val webSocketFrameHandler: WebSocketFrameHandler
) : ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel) {
val pipeline = ch.pipeline()
pipeline.addLast(HttpServerCodec(4096, 8192, 8192, false))
pipeline.addLast(HttpObjectAggregator(65536))
pipeline.addLast(ChunkedWriteHandler())
pipeline.addLast(WebSocketServerCompressionHandler())
pipeline.addLast(WebSocketServerProtocolHandler("/ws/", null, true))
pipeline.addLast(webSocketFrameHandler)
pipeline.addLast(httpHandler)
}
} | src/main/java/org/mitallast/queue/rest/netty/HttpServerInitializer.kt | 3563704919 |
package info.nightscout.androidaps.plugins.general.automation.dragHelpers
/**
* Interface to notify an item ViewHolder of relevant callbacks from [ ].
*
* @author Paul Burke (ipaulpro)
*/
interface ItemTouchHelperViewHolder {
/**
* Called when the [ItemTouchHelper] first registers an item as being moved or swiped.
* Implementations should update the item view to indicate it's active state.
*/
fun onItemSelected()
/**
* Called when the [ItemTouchHelper] has completed the move or swipe, and the active item
* state should be cleared.
*/
fun onItemClear()
} | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dragHelpers/ItemTouchHelperViewHolder.kt | 524743977 |
package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG((first as ISeq).nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| kotlin/src/mal/step8_macros.kt | 3018716089 |
/*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.project.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.xmlb.XmlSerializerUtil
import com.intellij.util.xmlb.annotations.Transient
import uk.co.reecedunn.intellij.plugin.intellij.lang.*
import java.util.concurrent.atomic.AtomicLongFieldUpdater
@State(name = "XQueryProjectSettings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class XQueryProjectSettings : PersistentStateComponent<XQueryProjectSettings>, ModificationTracker {
// region Settings
@Suppress("PrivatePropertyName")
private var PRODUCT_VERSION = VersionedProductId("w3c/spec/v1ed")
@get:Transient
val product: Product
get() = PRODUCT_VERSION.product ?: W3C.SPECIFICATIONS
@get:Transient
val productVersion: Version
get() = PRODUCT_VERSION.productVersion ?: defaultProductVersion(product)
// endregion
// region Persisted Settings
var implementationVersion: String?
get() = PRODUCT_VERSION.id
set(version) {
PRODUCT_VERSION.id = version
incrementModificationCount()
}
@Suppress("PropertyName")
var XQueryVersion: String? = "1.0"
@Suppress("PropertyName")
var XQuery10Dialect: String? = "xquery"
@Suppress("PropertyName")
var XQuery30Dialect: String? = "xquery"
@Suppress("PropertyName")
var XQuery31Dialect: String? = "xquery"
// endregion
// region PersistentStateComponent
override fun getState(): XQueryProjectSettings = this
override fun loadState(state: XQueryProjectSettings): Unit = XmlSerializerUtil.copyBean(state, this)
// endregion
// region ModificationTracker
@Volatile
private var modificationCount: Long = 0
private fun incrementModificationCount() {
UPDATER.incrementAndGet(this)
}
override fun getModificationCount(): Long = modificationCount
// endregion
companion object {
private val UPDATER = AtomicLongFieldUpdater.newUpdater(
XQueryProjectSettings::class.java,
"modificationCount"
)
fun getInstance(project: Project): XQueryProjectSettings {
return project.getService(XQueryProjectSettings::class.java)
}
}
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/project/settings/XQueryProjectSettings.kt | 1910292950 |
package org.stepik.android.view.injection.course_list
import javax.inject.Qualifier
@Qualifier
annotation class UserCoursesLoadedBus | app/src/main/java/org/stepik/android/view/injection/course_list/UserCoursesLoadedBus.kt | 606931133 |
package org.stepik.android.domain.lesson.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.android.domain.rx.maybeFirst
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.model.Lesson
interface LessonRepository {
fun getLesson(lessonId: Long, primarySourceType: DataSourceType = DataSourceType.CACHE): Maybe<Lesson> =
getLessons(lessonId, primarySourceType = primarySourceType).maybeFirst()
fun getLessons(vararg lessonIds: Long, primarySourceType: DataSourceType = DataSourceType.CACHE): Single<List<Lesson>>
fun removeCachedLessons(courseId: Long): Completable
} | app/src/main/java/org/stepik/android/domain/lesson/repository/LessonRepository.kt | 3590282827 |
package com.vmenon.mpo.my_library.data
import com.vmenon.mpo.my_library.domain.ShowModel
interface ShowPersistenceDataSource {
suspend fun insertOrUpdate(showModel: ShowModel): ShowModel
suspend fun getByName(name: String): ShowModel?
suspend fun getSubscribed(): List<ShowModel>
suspend fun getSubscribedAndLastUpdatedBefore(comparisonTime: Long): List<ShowModel>
} | my_library_data/src/main/java/com/vmenon/mpo/my_library/data/ShowPersistenceDataSource.kt | 4179791371 |
/**
* Copyright 2017 Savvas Dalkitsis
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.model
const val CURRENT_VERSION = 1
data class SaveContainer(val workspaceModel: WorkspaceModel) {
val version = CURRENT_VERSION
} | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/model/SaveContainer.kt | 971425761 |
package org.raidarar.learn
import com.sun.jna.Platform
import org.raidarar.learn.win.Windows
import java.util.*
fun processByID(processID: Int): Process? = when {
Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processID)
else -> null
}
fun processByName(processName: String): Process? = when {
Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processName)
else -> null
} | src/main/kotlin/org/raidarar/learn/ProcessBy.kt | 1805539895 |
package com.gkzxhn.mygithub.mvp.presenter
import android.util.Log
import com.gkzxhn.balabala.mvp.contract.BaseView
import com.gkzxhn.mygithub.api.OAuthApi
import com.gkzxhn.mygithub.bean.info.Owner
import com.gkzxhn.mygithub.bean.info.PostIssueResponse
import com.gkzxhn.mygithub.bean.info.SearchUserResult
import com.gkzxhn.mygithub.bean.info.User
import com.gkzxhn.mygithub.extension.toast
import com.gkzxhn.mygithub.ui.fragment.ContributorsFragment
import com.gkzxhn.mygithub.ui.fragment.IssueFragment
import com.gkzxhn.mygithub.utils.rxbus.RxBus
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
/**
* Created by 方 on 2017/10/25.
*/
class IssuePresenter @Inject constructor(private val oAuthApi: OAuthApi,
private val view: BaseView,
private val rxBus: RxBus) {
private var owner :String? = null
private var repo : String? = null
fun getIssues(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo)
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun getOpenIssues(owner: String, repo: String) {
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo, state = "open")
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun getClosedIssues(owner: String, repo: String) {
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo, state = "closed")
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun addSubscribe(){
rxBus.toFlowable(PostIssueResponse::class.java)
.bindToLifecycle(view as IssueFragment)
.subscribe(
{
t -> getOpenIssues(owner = owner!!, repo = repo!!)
},
{
e ->
Log.e(javaClass.simpleName, e.message)
}
)
}
fun getContributors(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.contributors(owner, repo)
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
lists: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(lists)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(Schedulers.io())
.subscribe {
t ->
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@subscribe
}
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.updateList(index, user)
}
}
},
{
e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
}
fun getForks(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.listForks(owner, repo, "newest")
.map {
repos ->
repos.map {
repo ->
repo.owner
}
}
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
owners: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(owners)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(Schedulers.io())
.subscribe {
t ->
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@subscribe
}
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.hideLoading()
it.updateList(index, user)
}
}
},
{
e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
}
fun searchUsers(string : String) {
view.showLoading()
oAuthApi.searchUsers(string)
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.map {
t: SearchUserResult ->
return@map t.items
}
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
owners: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(owners)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
t ->
getUserBio(t, view)
}
}
private fun getUserBio(t: ArrayList<Owner>, view: ContributorsFragment) {
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@forEachIndexed
}
if ("User" != owner.type){
return@forEachIndexed
}
checkIfFollowIng(index, owner.login)
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.hideLoading()
it.updateList(index, user)
}
}
},
{ e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
/**
* 检查是否关注该用户
*/
fun checkIfFollowIng(index: Int, username: String){
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.checkIfFollowUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
//已关注
view.updateListFollowStatus(index, 0)
}else{
view.updateListFollowStatus(index, 1)
}
},{
e ->
Log.i(javaClass.simpleName, e.message)
})
}
/**
* 关注用户
*/
fun followUser(index: Int, username: String) {
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.followUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
view.updateListFollowStatus(index, 0)
}else {
view.updateListFollowStatus(index, 1)
}
}, {
e ->
Log.e(javaClass.simpleName, e.message)
})
}
/**
* 取消关注用户
*/
fun unFollowUser(index: Int, username: String) {
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.unFollowUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
view.updateListFollowStatus(index, 1)
}else {
view.updateListFollowStatus(index, 1)
}
}, {
e ->
Log.e(javaClass.simpleName, e.message)
})
}
} | app/src/main/java/com/gkzxhn/mygithub/mvp/presenter/IssuePresenter.kt | 3363667788 |
import dev.nokee.platform.jni.JniJarBinary
import dev.nokee.platform.jni.JavaNativeInterfaceLibrary
import dev.nokee.runtime.nativebase.TargetMachine
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.CopySpec
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileTree
import org.gradle.api.provider.Provider
import org.gradle.jvm.tasks.Jar
import java.io.File
class UberJniJarPlugin : Plugin<Project> {
override fun apply(target: Project) {
target.tasks.named("jar", Jar::class.java) {
configure(this)
}
}
private fun configure(task: Jar) {
val project = task.project
val logger = task.logger
val library = project.extensions.getByType(JavaNativeInterfaceLibrary::class.java)
// Prevent variants from being published.
val targetMachines = library.targetMachines.forUseAtConfigurationTime().get()
val variantNames = targetMachines.map { "${project.name}-${it.architectureString}" }
project.configurations.forEach { config ->
config.artifacts.removeIf { it.name in variantNames }
}
logger.info("${project.name}: Merging binaries into the JVM Jar.")
library.variants.configureEach {
binaries.withType(JniJarBinary::class.java).configureEach {
jarTask.configure { enabled = false }
}
task.dependsOn(sharedLibrary.linkTask)
}
task.duplicatesStrategy = DuplicatesStrategy.EXCLUDE
targetMachines.forEach { target ->
val targetVariant = library.variants.filter { it.targetMachine == target }.map {
check(it.size == 1)
it.first()
}
if (!target.targetsHost) {
// nativeRuntimeFiles will be populated in this case due to using pre-build binaries.
task.from(targetVariant.map { it.nativeRuntimeFiles }) {
into(targetVariant.map { it.resourcePath })
renameLibrary(project, target)
}
} else {
val linkFile = targetVariant.flatMap {
it.sharedLibrary.linkTask.flatMap { linkTask -> linkTask.linkedFile }
}
task.from(linkFile) {
into(targetVariant.map { it.resourcePath })
renameLibrary(project, target)
}
}
}
}
private fun CopySpec.renameLibrary(project: Project, target: TargetMachine) {
rename {
libraryFileNameFor("${project.name}-${target.architectureString}", target.operatingSystemFamily)
}
}
private fun JniJarBinary.asZipTree(project: Project): Provider<FileTree> =
jarTask.map { project.zipTree(it.archiveFile) }
}
| buildSrc/src/main/kotlin/UberJniJarPlugin.kt | 3182492582 |
import java.io.File
import java.io.FileInputStream
import java.util.*
fun createIconAccessor(propertyFile: File, packageName : String, className: String): String {
class Property(val name: String?, val path: String)
class AccessorTreeNode(
val nodes: MutableMap<String, AccessorTreeNode>,
val properties: MutableList<Property>
)
val props = Properties().apply {
this.load(FileInputStream(propertyFile))
}
val root = AccessorTreeNode(mutableMapOf(), mutableListOf())
props.forEach { (k, value) ->
var key = k.toString()
val sepIndex = key.indexOf('|')
val name = if (sepIndex >= 0) {
val end = key.substring(sepIndex + 1)
key = key.substring(0, sepIndex)
end
} else null
val segments = key.split(".")
var node = root
for (segment in segments) {
node = node.nodes.getOrPut(segment) {
AccessorTreeNode(mutableMapOf(), mutableListOf())
}
}
node.properties.add(Property(name, value.toString()))
}
fun createAccessor(prop: Property): String =
"""
public static Icon ${prop.name ?: "get"}() {
return IconSet.iconLoader().getIcon("${prop.path}", true);
}
public static Icon ${prop.name ?: "get"}(final int width, final int height) {
return IconSet.iconLoader().getIcon("${prop.path}", width, height, true);
}
""".trimIndent()
fun createAccessorClass(name: String, node: AccessorTreeNode, topLevel: Boolean = false): String {
val properties = node.properties.sortedBy { it.name }.joinToString(separator = "\n\n") {
createAccessor(it)
}.replace("\n", "\n ")
val subNodes = node.nodes.entries.asSequence().sortedBy { it.key }.joinToString(separator = "\n\n") {
createAccessorClass(it.key, it.value)
}.replace("\n", "\n ")
return """
|@javax.annotation.Generated(value = {"GenerateIconAccessor"})
|public ${if (topLevel) "" else "static "}final class ${name.capitalize()} {
| $properties
| $subNodes
|}
""".trimMargin()
}
return """
|package $packageName;
|
|import javax.swing.Icon;
|
|${createAccessorClass(className, root, topLevel = true)}
""".trimMargin()
}
| buildSrc/src/main/kotlin/GenerateIconAccessor.kt | 3457752239 |
package eu.kanade.tachiyomi.source.model
class SMangaImpl : SManga {
override lateinit var url: String
override lateinit var title: String
override var artist: String? = null
override var author: String? = null
override var description: String? = null
override var genre: String? = null
override var status: Int = 0
override var thumbnail_url: String? = null
override var update_strategy: UpdateStrategy = UpdateStrategy.ALWAYS_UPDATE
override var initialized: Boolean = false
}
| source-api/src/main/java/eu/kanade/tachiyomi/source/model/SMangaImpl.kt | 2397094751 |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package khttp
import khttp.responses.Response
import org.awaitility.kotlin.await
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
class KHttpAsyncPutSpec : Spek({
describe("a put request") {
val url = "https://httpbin.org/put"
var error: Throwable? = null
var response: Response? = null
async.put(url, onError = { error = this }, onResponse = { response = this })
await.atMost(5, TimeUnit.SECONDS)
.until { response != null }
context("accessing the json") {
if (error != null) throw error!!
val json = response!!.jsonObject
it("should have the same url") {
assertEquals(url, json.getString("url"))
}
}
}
})
| src/test/kotlin/khttp/KHttpAsyncPutSpec.kt | 2984498198 |
package info.nightscout.androidaps.extensions
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
inline fun Any.wait() = (this as Object).wait()
/**
* Lock and wait a duration in milliseconds and nanos.
* Unlike [java.lang.Object.wait] this interprets 0 as "don't wait" instead of "wait forever".
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun Any.waitMillis(timeout: Long, nanos: Int = 0) {
if (timeout > 0L || nanos > 0) {
(this as Object).wait(timeout, nanos)
}
}
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
inline fun Any.notify() = (this as Object).notify()
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
inline fun Any.notifyAll() = (this as Object).notifyAll()
| core/src/main/java/info/nightscout/androidaps/extensions/Concurrency.kt | 2528555854 |
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
/**
* A measurement of time. Durations may be positive, zero, or negative.
*
* Positive durations are measured in seconds, with both [#getSeconds] and [#getNano] parts with
* non-negative signs.
*
* Negative durations may be surprising. The [#getSeconds] property is negative, but the [#getNano]
* property is non-negative! To represent -1.3 seconds the seconds property is -2 and the nanos
* property is 700,000,000.
*/
expect class Duration {
fun getSeconds(): Long
/** Returns a value in `[0..1,000,000,000)`. */
fun getNano(): Int
}
expect fun durationOfSeconds(seconds: Long, nano: Long): Duration
| wire-library/wire-runtime/src/commonMain/kotlin/com/squareup/wire/Duration.kt | 4012674034 |
/*
* Copyright (C) 2016 KeepSafe Software
*
* 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 au.com.timmutton.redexplugin
import java.io.File
import java.io.InputStream
object IOUtil {
@JvmStatic fun drainToFile(stream: InputStream, file: File) {
stream.use { input ->
File(file.path).outputStream().use { output ->
input.copyTo(output)
output.flush()
}
}
}
}
| src/main/kotlin/au/com/timmutton/redexplugin/IOUtil.kt | 124442807 |
package aoc2016.kot
import VM
import java.io.File
fun main(args: Array<String>) {
val s = File("./input/2016/Day25_input.txt").readLines()
var result: Long
var regA: Long = -1L
do {
regA++
val vm = VM(s, listOf("a" to regA, "lastOut" to -1L))
result = vm.run()
} while (result == -1L)
println("Part One = $regA")
}
| src/aoc2016/kot/Day25.kt | 594246363 |
// 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.plugins.github.pullrequest.ui.details
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.ide.IdeTooltip
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.CardLayoutPanel
import com.intellij.ui.components.AnActionLink
import com.intellij.ui.components.DropDownLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.CollaborationToolsIcons
import icons.DvcsImplIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.function.Consumer
import javax.swing.JComponent
import javax.swing.JLabel
internal object GHPRBranchesPanel {
fun create(model: GHPRBranchesModel): JComponent {
val from = createLabel()
val to = createLabel()
val branchActionsToolbar = BranchActionsToolbar()
Controller(model, from, to, branchActionsToolbar)
return NonOpaquePanel().apply {
layout = MigLayout(LC()
.fillX()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
add(to, CC().minWidth("${JBUIScale.scale(30)}"))
add(JLabel(" ${UIUtil.leftArrow()} ").apply {
foreground = CurrentBranchComponent.TEXT_COLOR
border = JBUI.Borders.empty(0, 5)
})
add(from, CC().minWidth("${JBUIScale.scale(30)}"))
add(branchActionsToolbar)
}
}
private fun createLabel() = JBLabel(CollaborationToolsIcons.Branch).also {
CollaborationToolsUIUtil.overrideUIDependentProperty(it) {
foreground = CurrentBranchComponent.TEXT_COLOR
background = CurrentBranchComponent.getBranchPresentationBackground(UIUtil.getListBackground())
}
}.andOpaque()
private class Controller(private val model: GHPRBranchesModel,
private val from: JBLabel,
private val to: JBLabel,
private val branchActionsToolbar: BranchActionsToolbar) {
val branchesTooltipFactory = GHPRBranchesTooltipFactory()
init {
branchesTooltipFactory.installTooltip(from)
model.addAndInvokeChangeListener {
updateBranchActionsToolbar()
updateBranchLabels()
}
}
private fun updateBranchLabels() {
val localRepository = model.localRepository
val localBranch = with(localRepository.branches) { model.localBranch?.run(::findLocalBranch) }
val remoteBranch = localBranch?.findTrackedBranch(localRepository)
val currentBranchCheckedOut = localRepository.currentBranchName == localBranch?.name
to.text = model.baseBranch
from.text = model.headBranch
from.icon = when {
currentBranchCheckedOut -> DvcsImplIcons.CurrentBranchFavoriteLabel
localBranch != null -> GithubIcons.LocalBranch
else -> CollaborationToolsIcons.Branch
}
branchesTooltipFactory.apply {
isOnCurrentBranch = currentBranchCheckedOut
prBranchName = model.headBranch
localBranchName = localBranch?.name
remoteBranchName = remoteBranch?.name
}
}
private fun updateBranchActionsToolbar() {
val prRemote = model.prRemote
if (prRemote == null) {
branchActionsToolbar.showCheckoutAction()
return
}
val localBranch = model.localBranch
val updateActionExist = localBranch != null
val multipleActionsExist = updateActionExist && model.localRepository.currentBranchName != localBranch
with(branchActionsToolbar) {
when {
multipleActionsExist -> showMultiple()
updateActionExist -> showUpdateAction()
else -> showCheckoutAction()
}
}
}
}
internal class BranchActionsToolbar : CardLayoutPanel<BranchActionsToolbar.State, BranchActionsToolbar.StateUi, JComponent>() {
companion object {
const val BRANCH_ACTIONS_TOOLBAR = "Github.PullRequest.Branch.Actions.Toolbar"
}
enum class State(private val text: String) {
CHECKOUT_ACTION(VcsBundle.message("vcs.command.name.checkout")),
UPDATE_ACTION(VcsBundle.message("vcs.command.name.update")),
MULTIPLE_ACTIONS(GithubBundle.message("pull.request.branch.action.group.name"));
override fun toString(): String = text
}
fun showCheckoutAction() {
select(State.CHECKOUT_ACTION, true)
}
fun showUpdateAction() {
select(State.UPDATE_ACTION, true)
}
fun showMultiple() {
select(State.MULTIPLE_ACTIONS, true)
}
sealed class StateUi {
abstract fun createUi(): JComponent
object CheckoutActionUi : SingleActionUi("Github.PullRequest.Branch.Create", VcsBundle.message("vcs.command.name.checkout"))
object UpdateActionUi : SingleActionUi("Github.PullRequest.Branch.Update", VcsBundle.message("vcs.command.name.update"))
abstract class SingleActionUi(private val actionId: String, @NlsContexts.LinkLabel private val actionName: String) : StateUi() {
override fun createUi(): JComponent =
AnActionLink(actionId, BRANCH_ACTIONS_TOOLBAR)
.apply {
text = actionName
border = JBUI.Borders.emptyLeft(8)
}
}
object MultipleActionUi : StateUi() {
private lateinit var dropDownLink: DropDownLink<State>
private val invokeAction: JComponent.(String) -> Unit = { actionId ->
val action = ActionManager.getInstance().getAction(actionId)
ActionUtil.invokeAction(action, this, BRANCH_ACTIONS_TOOLBAR, null, null)
}
override fun createUi(): JComponent {
dropDownLink = DropDownLink(State.MULTIPLE_ACTIONS, listOf(State.CHECKOUT_ACTION, State.UPDATE_ACTION), Consumer { state ->
when (state) {
State.CHECKOUT_ACTION -> dropDownLink.invokeAction("Github.PullRequest.Branch.Create")
State.UPDATE_ACTION -> dropDownLink.invokeAction("Github.PullRequest.Branch.Update")
State.MULTIPLE_ACTIONS -> {}
}
})
.apply { border = JBUI.Borders.emptyLeft(8) }
return dropDownLink
}
}
}
override fun prepare(state: State): StateUi =
when (state) {
State.CHECKOUT_ACTION -> StateUi.CheckoutActionUi
State.UPDATE_ACTION -> StateUi.UpdateActionUi
State.MULTIPLE_ACTIONS -> StateUi.MultipleActionUi
}
override fun create(ui: StateUi): JComponent = ui.createUi()
}
private class GHPRBranchesTooltipFactory(var isOnCurrentBranch: Boolean = false,
var prBranchName: String = "",
var localBranchName: String? = null,
var remoteBranchName: String? = null) {
fun installTooltip(label: JBLabel) {
label.addMouseMotionListener(object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent) {
showTooltip(e)
}
})
}
private fun showTooltip(e: MouseEvent) {
val point = e.point
if (IdeTooltipManager.getInstance().hasCurrent()) {
IdeTooltipManager.getInstance().hideCurrent(e)
}
val tooltip = IdeTooltip(e.component, point, Wrapper(createTooltip())).setPreferredPosition(Balloon.Position.below)
IdeTooltipManager.getInstance().show(tooltip, false)
}
private fun createTooltip(): GHPRBranchesTooltip =
GHPRBranchesTooltip(arrayListOf<BranchTooltipDescriptor>().apply {
if (isOnCurrentBranch) add(BranchTooltipDescriptor.head())
if (localBranchName != null) add(BranchTooltipDescriptor.localBranch(localBranchName!!))
if (remoteBranchName != null) {
add(BranchTooltipDescriptor.remoteBranch(remoteBranchName!!))
}
else {
add(BranchTooltipDescriptor.prBranch(prBranchName))
}
})
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRBranchesPanel.kt | 932428435 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.impl
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.intellij.codeWithMe.ClientId
import com.intellij.diagnostic.ThreadDumper
import com.intellij.icons.AllIcons
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.command.CommandEvent
import com.intellij.openapi.command.CommandListener
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.ContentInfo
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.TrackerContent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.commit.isNonModalCommit
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Future
import java.util.function.Supplier
class LineStatusTrackerManager(private val project: Project) : LineStatusTrackerManagerI, Disposable {
private val LOCK = Any()
private var isDisposed = false
private val trackers = HashMap<Document, TrackerData>()
private val forcedDocuments = HashMap<Document, Multiset<Any>>()
private val eventDispatcher = EventDispatcher.create(Listener::class.java)
private var partialChangeListsEnabled: Boolean = false
private val documentsInDefaultChangeList = HashSet<Document>()
private var clmFreezeCounter: Int = 0
private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>()
private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>()
private val loader = MyBaseRevisionLoader()
companion object {
private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java)
@JvmStatic
fun getInstance(project: Project): LineStatusTrackerManagerI = project.service()
@JvmStatic
fun getInstanceImpl(project: Project): LineStatusTrackerManager {
return getInstance(project) as LineStatusTrackerManager
}
}
internal class MyStartupActivity : VcsStartupActivity {
override fun runActivity(project: Project) {
getInstanceImpl(project).startListenForEditors()
}
override fun getOrder(): Int = VcsInitObject.OTHER_INITIALIZATION.order
}
private fun startListenForEditors() {
val busConnection = project.messageBus.connect()
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener())
busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener())
busConnection.subscribe(CommandListener.TOPIC, MyCommandListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
busConnection.subscribe(ChangeListAvailabilityListener.TOPIC, MyChangeListAvailabilityListener())
ApplicationManager.getApplication().messageBus.connect(this)
.subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener())
LocalLineStatusTrackerProvider.EP_NAME.addChangeListener(Runnable { updateTrackingSettings() }, this)
updatePartialChangeListsAvailability()
AppUIExecutor.onUiThread().expireWith(project).execute {
if (project.isDisposed) {
return@execute
}
ApplicationManager.getApplication().addApplicationListener(MyApplicationListener(), this)
FileStatusManager.getInstance(project).addFileStatusListener(MyFileStatusListener(), this)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(MyDocumentListener(), this)
MyEditorFactoryListener().install(this)
onEverythingChanged()
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
override fun dispose() {
isDisposed = true
Disposer.dispose(loader)
synchronized(LOCK) {
for ((document, multiset) in forcedDocuments) {
for (requester in multiset.elementSet()) {
warn("Tracker is being held on dispose by $requester", document)
}
}
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? {
synchronized(LOCK) {
return trackers[document]?.tracker
}
}
override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return null
return getLineStatusTracker(document)
}
@RequiresEdt
override fun requestTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) {
warn("Tracker is being requested after dispose by $requester", document)
return
}
val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() }
multiset.add(requester)
if (trackers[document] == null) {
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
switchTracker(virtualFile, document)
}
}
}
@RequiresEdt
override fun releaseTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val multiset = forcedDocuments[document]
if (multiset == null || !multiset.contains(requester)) {
warn("Tracker release underflow by $requester", document)
return
}
multiset.remove(requester)
if (multiset.isEmpty()) {
forcedDocuments.remove(document)
checkIfTrackerCanBeReleased(document)
}
}
}
override fun invokeAfterUpdate(task: Runnable) {
loader.addAfterUpdateRunnable(task)
}
fun getTrackers(): List<LineStatusTracker<*>> {
synchronized(LOCK) {
return trackers.values.map { it.tracker }
}
}
fun addTrackerListener(listener: Listener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
open class ListenerAdapter : Listener
interface Listener : EventListener {
fun onTrackerAdded(tracker: LineStatusTracker<*>) {
}
fun onTrackerRemoved(tracker: LineStatusTracker<*>) {
}
}
@RequiresEdt
private fun checkIfTrackerCanBeReleased(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
if (forcedDocuments.containsKey(document)) return
if (data.tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = data.tracker.hasPartialState()
if (hasPartialChanges) {
log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile)
return
}
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile)
if (data.tracker.hasPendingPartialState() ||
fileStatesAwaitingRefresh.containsKey(data.tracker.virtualFile)) {
log("checkIfTrackerCanBeReleased - has pending state", data.tracker.virtualFile)
return
}
}
}
releaseTracker(document)
}
}
@RequiresEdt
private fun onEverythingChanged() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) return
log("onEverythingChanged", null)
val files = HashSet<VirtualFile>()
for (data in trackers.values) {
files.add(data.tracker.virtualFile)
}
for (document in forcedDocuments.keys) {
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null) files.add(file)
}
for (file in files) {
onFileChanged(file)
}
}
}
@RequiresEdt
private fun onFileChanged(virtualFile: VirtualFile) {
val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile) ?: return
synchronized(LOCK) {
if (isDisposed) return
log("onFileChanged", virtualFile)
val tracker = trackers[document]?.tracker
if (tracker != null || forcedDocuments.containsKey(document)) {
switchTracker(virtualFile, document, refreshExisting = true)
}
}
}
private fun registerTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = VcsUtil.getFilePath(tracker.virtualFile)
if (data.clmFilePath != null) {
LOG.error("[registerTrackerInCLM] tracker already registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(filePath, tracker)
data.clmFilePath = filePath
}
private fun unregisterTrackerInCLM(data: TrackerData, wasUnbound: Boolean = false) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = data.clmFilePath
if (filePath == null) {
LOG.error("[unregisterTrackerInCLM] tracker is not registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(filePath, tracker)
data.clmFilePath = null
val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (filePath != actualFilePath && !wasUnbound) {
LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath")
}
}
private fun reregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val oldFilePath = data.clmFilePath
val newFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (oldFilePath == null) {
LOG.error("[reregisterTrackerInCLM] tracker is not registered")
return
}
if (oldFilePath != newFilePath) {
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(oldFilePath, tracker)
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(newFilePath, tracker)
data.clmFilePath = newFilePath
}
}
private fun canCreateTrackerFor(virtualFile: VirtualFile?): Boolean {
if (isDisposed) return false
if (virtualFile == null || virtualFile is LightVirtualFile) return false
if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false
return true
}
override fun arePartialChangelistsEnabled(): Boolean = partialChangeListsEnabled
override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean {
if (!partialChangeListsEnabled) return false
val vcs = VcsUtil.getVcsFor(project, virtualFile)
return vcs != null && vcs.arePartialChangelistsSupported()
}
private fun switchTracker(virtualFile: VirtualFile, document: Document,
refreshExisting: Boolean = false) {
val provider = getTrackerProvider(virtualFile)
val oldTracker = trackers[document]?.tracker
if (oldTracker != null && provider != null && provider.isMyTracker(oldTracker)) {
if (refreshExisting) {
refreshTracker(oldTracker, provider)
}
}
else {
releaseTracker(document)
if (provider != null) installTracker(virtualFile, document, provider)
}
}
private fun installTracker(virtualFile: VirtualFile, document: Document,
provider: LocalLineStatusTrackerProvider): LocalLineStatusTracker<*>? {
if (isDisposed) return null
if (trackers[document] != null) return null
val tracker = provider.createTracker(project, virtualFile) ?: return null
tracker.mode = getTrackingMode()
val data = TrackerData(tracker)
val replacedData = trackers.put(document, data)
LOG.assertTrue(replacedData == null)
registerTrackerInCLM(data)
refreshTracker(tracker, provider)
eventDispatcher.multicaster.onTrackerAdded(tracker)
if (clmFreezeCounter > 0) {
tracker.freeze()
}
log("Tracker installed", virtualFile)
return tracker
}
private fun getTrackerProvider(virtualFile: VirtualFile): LocalLineStatusTrackerProvider? {
if (!canCreateTrackerFor(virtualFile)) {
return null
}
LocalLineStatusTrackerProvider.EP_NAME.findFirstSafe { it.isTrackedFile(project, virtualFile) }?.let {
return it
}
return listOf(ChangelistsLocalStatusTrackerProvider, DefaultLocalStatusTrackerProvider).find { it.isTrackedFile(project, virtualFile) }
}
@RequiresEdt
private fun releaseTracker(document: Document, wasUnbound: Boolean = false) {
val data = trackers.remove(document) ?: return
eventDispatcher.multicaster.onTrackerRemoved(data.tracker)
unregisterTrackerInCLM(data, wasUnbound)
data.tracker.release()
log("Tracker released", data.tracker.virtualFile)
}
private fun updatePartialChangeListsAvailability() {
partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS &&
ChangeListManager.getInstance(project).areChangeListsEnabled()
}
private fun updateTrackingSettings() {
synchronized(LOCK) {
if (isDisposed) return
val mode = getTrackingMode()
for (data in trackers.values) {
data.tracker.mode = mode
}
}
onEverythingChanged()
}
private fun getTrackingMode(): LocalLineStatusTracker.Mode {
val settings = VcsApplicationSettings.getInstance()
return LocalLineStatusTracker.Mode(settings.SHOW_LST_GUTTER_MARKERS,
settings.SHOW_LST_ERROR_STRIPE_MARKERS,
settings.SHOW_WHITESPACES_IN_LST)
}
@RequiresEdt
private fun refreshTracker(tracker: LocalLineStatusTracker<*>,
provider: LocalLineStatusTrackerProvider) {
if (isDisposed) return
if (provider !is LineStatusTrackerContentLoader) return
loader.scheduleRefresh(RefreshRequest(tracker.document, provider))
log("Refresh queued", tracker.virtualFile)
}
private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() {
fun hasRequestFor(document: Document): Boolean {
return hasRequest { it.document == document }
}
override fun loadRequest(request: RefreshRequest): Result<RefreshData> {
if (isDisposed) return Result.Canceled()
val document = request.document
val virtualFile = FileDocumentManager.getInstance().getFile(document)
val loader = request.loader
log("Loading started", virtualFile)
if (virtualFile == null || !virtualFile.isValid) {
log("Loading error: virtual file is not valid", virtualFile)
return Result.Error()
}
if (!canCreateTrackerFor(virtualFile) || !loader.isTrackedFile(project, virtualFile)) {
log("Loading error: virtual file is not a tracked file", virtualFile)
return Result.Error()
}
val newContentInfo = loader.getContentInfo(project, virtualFile)
if (newContentInfo == null) {
log("Loading error: base revision not found", virtualFile)
return Result.Error()
}
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading cancelled: tracker not found", virtualFile)
return Result.Canceled()
}
if (!loader.shouldBeUpdated(data.contentInfo, newContentInfo)) {
log("Loading cancelled: no need to update", virtualFile)
return Result.Canceled()
}
}
val content = loader.loadContent(project, newContentInfo)
if (content == null) {
log("Loading error: provider failure", virtualFile)
return Result.Error()
}
log("Loading successful", virtualFile)
return Result.Success(RefreshData(content, newContentInfo))
}
@RequiresEdt
override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) {
val document = request.document
when (result) {
is Result.Canceled -> handleCanceled(document)
is Result.Error -> handleError(request, document)
is Result.Success -> handleSuccess(request, document, result.data)
}
checkIfTrackerCanBeReleased(document)
}
private fun handleCanceled(document: Document) {
restorePendingTrackerState(document)
}
private fun handleError(request: RefreshRequest, document: Document) {
synchronized(LOCK) {
val loader = request.loader
val data = trackers[document] ?: return
val tracker = data.tracker
if (loader.isMyTracker(tracker)) {
loader.handleLoadingError(tracker)
}
data.contentInfo = null
}
}
private fun handleSuccess(request: RefreshRequest, document: Document, refreshData: RefreshData) {
val virtualFile = FileDocumentManager.getInstance().getFile(document)!!
val loader = request.loader
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading finished: tracker already released", virtualFile)
return
}
if (!loader.shouldBeUpdated(data.contentInfo, refreshData.contentInfo)) {
log("Loading finished: no need to update", virtualFile)
return
}
data.contentInfo = refreshData.contentInfo
tracker = data.tracker
}
if (loader.isMyTracker(tracker)) {
loader.setLoadedContent(tracker, refreshData.content)
log("Loading finished: success", virtualFile)
}
else {
log("Loading finished: wrong tracker. tracker: $tracker, loader: $loader", virtualFile)
}
restorePendingTrackerState(document)
}
private fun restorePendingTrackerState(document: Document) {
val tracker = getLineStatusTracker(document)
if (tracker is ChangelistsLocalLineStatusTracker) {
val virtualFile = tracker.virtualFile
val state = synchronized(LOCK) {
fileStatesAwaitingRefresh.remove(virtualFile) ?: return
}
val success = tracker.restoreState(state)
log("Pending state restored. success - $success", virtualFile)
}
}
}
/**
* We can speedup initial content loading if it was already loaded by someone.
* We do not set 'contentInfo' here to ensure, that following refresh will fix potential inconsistency.
*/
@RequiresEdt
@ApiStatus.Internal
fun offerTrackerContent(document: Document, text: CharSequence) {
try {
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null || data.contentInfo != null) return
tracker = data.tracker
}
if (tracker is LocalLineStatusTrackerImpl<*>) {
ClientId.withClientId(ClientId.localId) {
tracker.setBaseRevision(text)
log("Offered content", tracker.virtualFile)
}
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
private inner class MyFileStatusListener : FileStatusListener {
override fun fileStatusesChanged() {
onEverythingChanged()
}
override fun fileStatusChanged(virtualFile: VirtualFile) {
onFileChanged(virtualFile)
}
}
private inner class MyEditorFactoryListener : EditorFactoryListener {
fun install(disposable: Disposable) {
val editorFactory = EditorFactory.getInstance()
for (editor in editorFactory.allEditors) {
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
editorFactory.addEditorFactoryListener(this, disposable)
}
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
releaseTrackerFor(editor.document, editor)
}
}
private fun isTrackedEditor(editor: Editor): Boolean {
// can't filter out "!isInLocalFileSystem" files, custom VcsBaseContentProvider can handle them
// check for isDisposed - light project in tests
return !project.isDisposed &&
(editor.project == null || editor.project == project) &&
FileDocumentManager.getInstance().getFile(editor.document) != null
}
}
private inner class MyVirtualFileListener : BulkFileListener {
override fun before(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFileDeleteEvent -> handleFileDeletion(event.file)
}
}
}
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> when {
VirtualFile.PROP_ENCODING == event.propertyName -> onFileChanged(event.file)
event.isRename -> handleFileMovement(event.file)
}
is VFileMoveEvent -> handleFileMovement(event.file)
}
}
}
private fun handleFileMovement(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
reregisterTrackerInCLM(data)
}
}
}
private fun handleFileDeletion(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
releaseTracker(data.tracker.document)
}
}
}
private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) {
if (file.isDirectory) {
val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) }
for (data in affected) {
action(data)
}
}
else {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return
val data = trackers[document] ?: return
action(data)
}
}
}
internal class MyFileDocumentManagerListener : FileDocumentManagerListener {
override fun afterDocumentUnbound(file: VirtualFile, document: Document) {
val projectManager = ProjectManager.getInstanceIfCreated() ?: return
for (project in projectManager.openProjects) {
val lstm = project.getServiceIfCreated(LineStatusTrackerManagerI::class.java) as? LineStatusTrackerManager ?: continue
lstm.releaseTracker(document, wasUnbound = true)
}
}
}
private inner class MyDocumentListener : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread
if (!partialChangeListsEnabled || project.isDisposed) return
val document = event.document
if (documentsInDefaultChangeList.contains(document)) return
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
if (getLineStatusTracker(document) != null) return
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) return
val changeList = ChangeListManager.getInstance(project).getChangeList(virtualFile)
val inAnotherChangelist = changeList != null && !ActiveChangeListTracker.getInstance(project).isActiveChangeList(changeList)
if (inAnotherChangelist) {
log("Tracker install from DocumentListener: ", virtualFile)
val tracker = synchronized(LOCK) {
installTracker(virtualFile, document, provider)
}
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.replayChangesFromDocumentEvents(listOf(event))
}
}
else {
documentsInDefaultChangeList.add(document)
}
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
documentsInDefaultChangeList.clear()
synchronized(LOCK) {
val documents = trackers.values.map { it.tracker.document }
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
}
private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener {
override fun settingsUpdated() {
updatePartialChangeListsAvailability()
updateTrackingSettings()
}
}
private inner class MyChangeListListener : ChangeListAdapter() {
override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) {
runInEdt(ModalityState.any()) {
if (project.isDisposed) return@runInEdt
expireInactiveRangesDamagedNotifications()
EditorFactory.getInstance().allEditors
.forEach { if (it is EditorEx) it.gutterComponentEx.repaint() }
}
}
}
private inner class MyChangeListAvailabilityListener : ChangeListAvailabilityListener {
override fun onBefore() {
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
val fileStates = getInstanceImpl(project).collectPartiallyChangedFilesStates()
if (fileStates.isNotEmpty()) {
PartialLineStatusTrackerManagerState.saveCurrentState(project, fileStates)
}
}
}
override fun onAfter() {
updatePartialChangeListsAvailability()
onEverythingChanged()
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
}
private inner class MyCommandListener : CommandListener {
override fun commandFinished(event: CommandEvent) {
if (!partialChangeListsEnabled) return
if (CommandProcessor.getInstance().currentCommand == null &&
!filesWithDamagedInactiveRanges.isEmpty()) {
showInactiveRangesDamagedNotification()
}
}
}
class CheckinFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
val project = panel.project
return object : CheckinHandler() {
override fun checkinSuccessful() {
resetExcludedFromCommit()
}
override fun checkinFailed(exception: MutableList<VcsException>?) {
resetExcludedFromCommit()
}
private fun resetExcludedFromCommit() {
runInEdt {
// TODO Move this to SingleChangeListCommitWorkflow
if (!project.isDisposed && !panel.isNonModalCommit) getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
}
}
}
}
private inner class MyFreezeListener : VcsFreezingProcess.Listener {
override fun onFreeze() {
runReadAction {
synchronized(LOCK) {
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.freeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
clmFreezeCounter++
}
}
}
override fun onUnfreeze() {
runInEdt(ModalityState.any()) {
synchronized(LOCK) {
clmFreezeCounter--
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.unfreeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
}
}
}
private class TrackerData(val tracker: LocalLineStatusTracker<*>,
var contentInfo: ContentInfo? = null,
var clmFilePath: FilePath? = null)
private class RefreshRequest(val document: Document, val loader: LineStatusTrackerContentLoader) {
override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document
override fun hashCode(): Int = document.hashCode()
override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown") // NON-NLS
}
private class RefreshData(val content: TrackerContent,
val contentInfo: ContentInfo)
private fun log(@NonNls message: String, file: VirtualFile?) {
if (LOG.isDebugEnabled) {
if (file != null) {
LOG.debug(message + "; file: " + file.path)
}
else {
LOG.debug(message)
}
}
}
private fun warn(@NonNls message: String, document: Document?) {
val file = document?.let { FileDocumentManager.getInstance().getFile(it) }
warn(message, file)
}
private fun warn(@NonNls message: String, file: VirtualFile?) {
if (file != null) {
LOG.warn(message + "; file: " + file.path)
}
else {
LOG.warn(message)
}
}
@RequiresEdt
fun resetExcludedFromCommitMarkers() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val documents = mutableListOf<Document>()
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.resetExcludedFromCommitMarkers()
documents.add(tracker.document)
}
}
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>()
synchronized(LOCK) {
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = tracker.affectedChangeListsIds.size > 1
if (hasPartialChanges) {
result.add(tracker.storeTrackerState())
}
}
}
}
return result
}
@RequiresEdt
internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) {
runWriteAction {
synchronized(LOCK) {
if (isDisposed) return@runWriteAction
for (state in trackerStates) {
val virtualFile = state.virtualFile
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) continue
switchTracker(virtualFile, document)
val tracker = trackers[document]?.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) continue
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("State restoration scheduled", virtualFile)
}
else {
val success = tracker.restoreState(state)
log("State restored. success - $success", virtualFile)
}
}
loader.addAfterUpdateRunnable(Runnable {
synchronized(LOCK) {
log("State restoration finished", null)
fileStatesAwaitingRefresh.clear()
}
})
}
}
onEverythingChanged()
}
@RequiresEdt
internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) {
ApplicationManager.getApplication().assertIsWriteThread()
if (filesWithDamagedInactiveRanges.contains(virtualFile) || virtualFile == FileEditorManagerEx.getInstanceEx(project).currentFile) {
return
}
filesWithDamagedInactiveRanges.add(virtualFile)
}
private fun showInactiveRangesDamagedNotification() {
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
val lastNotification = currentNotifications.lastOrNull { !it.isExpired }
if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles)
currentNotifications.forEach { it.expire() }
val files = filesWithDamagedInactiveRanges.toSet()
filesWithDamagedInactiveRanges.clear()
InactiveRangesDamagedNotification(project, files).notify(project)
}
@RequiresEdt
private fun expireInactiveRangesDamagedNotifications() {
filesWithDamagedInactiveRanges.clear()
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
currentNotifications.forEach { it.expire() }
}
private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>)
: Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId,
VcsBundle.message("lst.inactive.ranges.damaged.notification"),
NotificationType.INFORMATION) {
init {
icon = AllIcons.Toolwindows.ToolWindowChanges
setDisplayId(VcsNotificationIdsHolder.INACTIVE_RANGES_DAMAGED)
addAction(NotificationAction.createSimple(
Supplier { VcsBundle.message("action.NotificationAction.InactiveRangesDamagedNotification.text.view.changes") },
Runnable {
val defaultList = ChangeListManager.getInstance(project).defaultChangeList
val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) }
val window = getToolWindowFor(project, LOCAL_CHANGES)
window?.activate { ChangesViewManager.getInstance(project).selectChanges(changes) }
expire()
}))
}
}
@TestOnly
fun waitUntilBaseContentsLoaded() {
assert(ApplicationManager.getApplication().isUnitTestMode)
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
val semaphore = Semaphore()
semaphore.down()
loader.addAfterUpdateRunnable(Runnable {
semaphore.up()
})
val start = System.currentTimeMillis()
while (true) {
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
if (semaphore.waitFor(10)) {
return
}
if (System.currentTimeMillis() - start > 10000) {
loader.dumpInternalState()
System.err.println(ThreadDumper.dumpThreadsToString())
throw IllegalStateException("Couldn't await base contents") // NON-NLS
}
}
}
@TestOnly
fun releaseAllTrackers() {
synchronized(LOCK) {
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
}
/**
* Single threaded queue with the following properties:
* - Ignores duplicated requests (the first queued is used).
* - Allows to check whether request is scheduled or is waiting for completion.
* - Notifies callbacks when queue is exhausted.
*/
private abstract class SingleThreadLoader<Request, T> : Disposable {
companion object {
private val LOG = Logger.getInstance(SingleThreadLoader::class.java)
}
private val LOCK: Any = Any()
private val taskQueue = ArrayDeque<Request>()
private val waitingForRefresh = HashSet<Request>()
private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>()
private var isScheduled: Boolean = false
private var isDisposed: Boolean = false
private var lastFuture: Future<*>? = null
@RequiresBackgroundThread
protected abstract fun loadRequest(request: Request): Result<T>
@RequiresEdt
protected abstract fun handleResult(request: Request, result: Result<T>)
@RequiresEdt
fun scheduleRefresh(request: Request) {
if (isDisposed) return
synchronized(LOCK) {
if (taskQueue.contains(request)) return
taskQueue.add(request)
schedule()
}
}
@RequiresEdt
override fun dispose() {
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
isDisposed = true
taskQueue.clear()
waitingForRefresh.clear()
lastFuture?.cancel(true)
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
executeCallbacks(callbacksWaitingUpdateCompletion)
}
@RequiresEdt
protected fun hasRequest(condition: (Request) -> Boolean): Boolean {
synchronized(LOCK) {
return taskQueue.any(condition) ||
waitingForRefresh.any(condition)
}
}
@CalledInAny
fun addAfterUpdateRunnable(task: Runnable) {
val updateScheduled = putRunnableIfUpdateScheduled(task)
if (updateScheduled) return
runInEdt(ModalityState.any()) {
if (!putRunnableIfUpdateScheduled(task)) {
task.run()
}
}
}
private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean {
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false
callbacksWaitingUpdateCompletion.add(task)
return true
}
}
private fun schedule() {
if (isDisposed) return
synchronized(LOCK) {
if (isScheduled) return
if (taskQueue.isEmpty()) return
isScheduled = true
lastFuture = ApplicationManager.getApplication().executeOnPooledThread {
ClientId.withClientId(ClientId.localId) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable {
handleRequests()
})
}
}
}
}
private fun handleRequests() {
while (true) {
val request = synchronized(LOCK) {
val request = taskQueue.poll()
if (isDisposed || request == null) {
isScheduled = false
return
}
waitingForRefresh.add(request)
return@synchronized request
}
handleSingleRequest(request)
}
}
private fun handleSingleRequest(request: Request) {
val result: Result<T> = try {
loadRequest(request)
}
catch (e: ProcessCanceledException) {
Result.Canceled()
}
catch (e: Throwable) {
LOG.error(e)
Result.Error()
}
runInEdt(ModalityState.any()) {
try {
synchronized(LOCK) {
waitingForRefresh.remove(request)
}
handleResult(request, result)
}
finally {
notifyTrackerRefreshed()
}
}
}
@RequiresEdt
private fun notifyTrackerRefreshed() {
if (isDisposed) return
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) {
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
}
executeCallbacks(callbacks)
}
@RequiresEdt
private fun executeCallbacks(callbacks: List<Runnable>) {
for (callback in callbacks) {
try {
callback.run()
}
catch (ignore: ProcessCanceledException) {
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
@TestOnly
fun dumpInternalState() {
synchronized(LOCK) {
LOG.debug("isScheduled - $isScheduled")
LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}")
taskQueue.forEach {
LOG.debug("pending task: ${it}")
}
waitingForRefresh.forEach {
LOG.debug("waiting refresh: ${it}")
}
}
}
}
private sealed class Result<T> {
class Success<T>(val data: T) : Result<T>()
class Canceled<T> : Result<T>()
class Error<T> : Result<T>()
}
private object ChangelistsLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled(file)) return false
if (!super.isTrackedFile(project, file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status != FileStatus.MODIFIED &&
status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE &&
status != FileStatus.NOT_CHANGED) return false
val change = ChangeListManager.getInstance(project).getChange(file)
return change == null ||
change.javaClass == Change::class.java &&
(change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) &&
change.afterRevision is CurrentContentRevision
}
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is ChangelistsLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return ChangelistsLocalLineStatusTracker.createTracker(project, document, file)
}
}
private object DefaultLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is SimpleLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return SimpleLocalLineStatusTracker.createTracker(project, document, file)
}
}
private abstract class BaseRevisionStatusTrackerContentLoader : LineStatusTrackerContentLoader {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!VcsFileStatusProvider.getInstance(project).isSupported(file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status == FileStatus.ADDED ||
status == FileStatus.DELETED ||
status == FileStatus.UNKNOWN ||
status == FileStatus.IGNORED) {
return false
}
return true
}
override fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? {
val baseContent = VcsFileStatusProvider.getInstance(project).getBaseRevision(file) ?: return null
return BaseRevisionContentInfo(baseContent, file.charset)
}
override fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean {
newInfo as BaseRevisionContentInfo
return oldInfo == null ||
oldInfo !is BaseRevisionContentInfo ||
oldInfo.baseContent.revisionNumber != newInfo.baseContent.revisionNumber ||
oldInfo.baseContent.revisionNumber == VcsRevisionNumber.NULL ||
oldInfo.charset != newInfo.charset
}
override fun loadContent(project: Project, info: ContentInfo): TrackerContent? {
info as BaseRevisionContentInfo
val lastUpToDateContent = info.baseContent.loadContent() ?: return null
val correctedText = StringUtil.convertLineSeparators(lastUpToDateContent)
return BaseRevisionContent(correctedText)
}
override fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) {
tracker as LocalLineStatusTrackerImpl<*>
content as BaseRevisionContent
tracker.setBaseRevision(content.text)
}
override fun handleLoadingError(tracker: LocalLineStatusTracker<*>) {
tracker as LocalLineStatusTrackerImpl<*>
tracker.dropBaseRevision()
}
private class BaseRevisionContentInfo(val baseContent: VcsBaseContentProvider.BaseContent, val charset: Charset) : ContentInfo
private class BaseRevisionContent(val text: CharSequence) : TrackerContent
}
interface LocalLineStatusTrackerProvider {
fun isTrackedFile(project: Project, file: VirtualFile): Boolean
fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean
fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>?
companion object {
internal val EP_NAME =
ExtensionPointName<LocalLineStatusTrackerProvider>("com.intellij.openapi.vcs.impl.LocalLineStatusTrackerProvider")
}
}
interface LineStatusTrackerContentLoader : LocalLineStatusTrackerProvider {
fun getContentInfo(project: Project, file: VirtualFile): ContentInfo?
fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean
fun loadContent(project: Project, info: ContentInfo): TrackerContent?
fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent)
fun handleLoadingError(tracker: LocalLineStatusTracker<*>)
interface ContentInfo
interface TrackerContent
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt | 677158364 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
import com.intellij.util.execution.ParametersListUtil
import org.codehaus.groovy.runtime.ProcessGroovyMethods
import org.jetbrains.intellij.build.BuildMessages
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader
import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions
import org.jetbrains.intellij.build.dependencies.BuildDependenciesManualRunOnly
import java.io.OutputStream
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
object ToolboxLiteGen {
private fun downloadToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, liteGenVersion: String): Path {
val liteGenUri = URI("https://repo.labs.intellij.net/toolbox/lite-gen/lite-gen-$liteGenVersion.zip")
val zip = BuildDependenciesDownloader.downloadFileToCacheLocation(communityRoot, liteGenUri)
return BuildDependenciesDownloader.extractFileToCacheLocation(communityRoot, zip, BuildDependenciesExtractOptions.STRIP_ROOT)
}
fun runToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?,
messages: BuildMessages,
liteGenVersion: String,
vararg args: String) {
check(SystemInfo.isUnix) { "Currently, lite gen runs only on Unix" }
val liteGenPath = downloadToolboxLiteGen(communityRoot, liteGenVersion)
messages.info("Toolbox LiteGen is at $liteGenPath")
val binPath = liteGenPath.resolve("bin/lite")
check(Files.isExecutable(binPath)) { "File at \'$binPath\' is missing or not executable" }
val command: MutableList<String?> = ArrayList()
command.add(binPath.toString())
command.addAll(args)
messages.info("Running " + ParametersListUtil.join(command))
val processBuilder = ProcessBuilder(command)
processBuilder.directory(liteGenPath.toFile())
processBuilder.environment()["JAVA_HOME"] = SystemProperties.getJavaHome()
val process = processBuilder.start()
// todo get rid of ProcessGroovyMethods
ProcessGroovyMethods.consumeProcessOutputStream(process, System.out as OutputStream)
ProcessGroovyMethods.consumeProcessErrorStream(process, System.err as OutputStream)
val rc = process.waitFor()
check(rc == 0) { "\'${command.joinToString(separator = " ")}\' exited with exit code $rc" }
}
@JvmStatic
fun main(args: Array<String>) {
val path = downloadToolboxLiteGen(BuildDependenciesManualRunOnly.getCommunityRootFromWorkingDirectory(), "1.2.1553")
println("litegen is at $path")
}
} | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/ToolboxLiteGen.kt | 3830535654 |
package com.fsck.k9.activity.setup
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.fsck.k9.Account
import com.fsck.k9.Preferences
import com.fsck.k9.helper.EmailHelper.getDomainFromEmailAddress
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.mail.ServerSettings
import com.fsck.k9.mailstore.SpecialLocalFoldersCreator
import com.fsck.k9.preferences.Protocols
import com.fsck.k9.setup.ServerNameSuggester
import com.fsck.k9.ui.R
import com.fsck.k9.ui.base.K9Activity
import org.koin.android.ext.android.inject
/**
* Prompts the user to select an account type. The account type, along with the
* passed in email address, password and makeDefault are then passed on to the
* AccountSetupIncoming activity.
*/
class AccountSetupAccountType : K9Activity() {
private val preferences: Preferences by inject()
private val serverNameSuggester: ServerNameSuggester by inject()
private val localFoldersCreator: SpecialLocalFoldersCreator by inject()
private lateinit var account: Account
private var makeDefault = false
private lateinit var initialAccountSettings: InitialAccountSettings
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLayout(R.layout.account_setup_account_type)
setTitle(R.string.account_setup_account_type_title)
decodeArguments()
findViewById<View>(R.id.pop).setOnClickListener { setupPop3Account() }
findViewById<View>(R.id.imap).setOnClickListener { setupImapAccount() }
}
private fun decodeArguments() {
val accountUuid = intent.getStringExtra(EXTRA_ACCOUNT) ?: error("No account UUID provided")
account = preferences.getAccount(accountUuid) ?: error("No account with given UUID found")
makeDefault = intent.getBooleanExtra(EXTRA_MAKE_DEFAULT, false)
initialAccountSettings = intent.getParcelableExtra(EXTRA_INITIAL_ACCOUNT_SETTINGS)
?: error("Initial account settings are missing")
}
private fun setupPop3Account() {
setupAccount(Protocols.POP3)
}
private fun setupImapAccount() {
setupAccount(Protocols.IMAP)
}
private fun setupAccount(serverType: String) {
setupStoreAndSmtpTransport(serverType)
createSpecialLocalFolders()
returnAccountTypeSelectionResult()
}
private fun setupStoreAndSmtpTransport(serverType: String) {
val domainPart = getDomainFromEmailAddress(account.email) ?: error("Couldn't get domain from email address")
initializeIncomingServerSettings(serverType, domainPart)
initializeOutgoingServerSettings(domainPart)
}
private fun initializeIncomingServerSettings(serverType: String, domainPart: String) {
val suggestedStoreServerName = serverNameSuggester.suggestServerName(serverType, domainPart)
val storeServer = ServerSettings(
serverType,
suggestedStoreServerName,
-1,
ConnectionSecurity.SSL_TLS_REQUIRED,
initialAccountSettings.authenticationType,
initialAccountSettings.email,
initialAccountSettings.password,
initialAccountSettings.clientCertificateAlias
)
account.incomingServerSettings = storeServer
}
private fun initializeOutgoingServerSettings(domainPart: String) {
val suggestedTransportServerName = serverNameSuggester.suggestServerName(Protocols.SMTP, domainPart)
val transportServer = ServerSettings(
Protocols.SMTP,
suggestedTransportServerName,
-1,
ConnectionSecurity.STARTTLS_REQUIRED,
initialAccountSettings.authenticationType,
initialAccountSettings.email,
initialAccountSettings.password,
initialAccountSettings.clientCertificateAlias
)
account.outgoingServerSettings = transportServer
}
private fun createSpecialLocalFolders() {
localFoldersCreator.createSpecialLocalFolders(account)
}
private fun returnAccountTypeSelectionResult() {
AccountSetupIncoming.actionIncomingSettings(this, account, makeDefault)
}
companion object {
private const val EXTRA_ACCOUNT = "account"
private const val EXTRA_MAKE_DEFAULT = "makeDefault"
private const val EXTRA_INITIAL_ACCOUNT_SETTINGS = "initialAccountSettings"
@JvmStatic
fun actionSelectAccountType(
context: Context,
account: Account,
makeDefault: Boolean,
initialAccountSettings: InitialAccountSettings
) {
val intent = Intent(context, AccountSetupAccountType::class.java).apply {
putExtra(EXTRA_ACCOUNT, account.uuid)
putExtra(EXTRA_MAKE_DEFAULT, makeDefault)
putExtra(EXTRA_INITIAL_ACCOUNT_SETTINGS, initialAccountSettings)
}
context.startActivity(intent)
}
}
}
| app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.kt | 3446487609 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package ui
import com.automation.remarks.junit.VideoRule
import com.automation.remarks.video.annotations.Video
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ContainerFixture
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.keyboard
import org.assertj.swing.core.MouseButton
import org.junit.Rule
import org.junit.Test
import ui.pages.Editor
import ui.pages.IdeaFrame
import ui.pages.actionMenu
import ui.pages.actionMenuItem
import ui.pages.dialog
import ui.pages.editor
import ui.pages.gutter
import ui.pages.idea
import ui.pages.welcomeFrame
import ui.utils.JavaExampleSteps
import ui.utils.StepsLogger
import ui.utils.doubleClickOnRight
import ui.utils.invokeActionJs
import ui.utils.moveMouseForthAndBack
import ui.utils.moveMouseInGutterTo
import ui.utils.moveMouseTo
import ui.utils.moveMouseWithDelayTo
import ui.utils.tripleClickOnRight
import ui.utils.uiTest
import ui.utils.vimExit
import java.awt.Point
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class UiTests {
init {
StepsLogger.init()
}
@Rule
@JvmField
var videoRule = VideoRule()
@Test
@Video
fun ideaVimTest() = uiTest("ideaVimTest") {
val sharedSteps = JavaExampleSteps(this)
startNewProject()
Thread.sleep(1000)
closeUnrelated(sharedSteps)
Thread.sleep(1000)
idea {
createFile("MyDoc.txt", this@uiTest)
val editor = editor("MyDoc.txt") {
step("Write a text") {
injectText(
"""
|One Two
|Three Four
|Five
""".trimMargin()
)
}
}
testSelectTextWithDelay(editor)
testExtendSelection(editor)
testLargerDragSelection(editor)
testSelectLastCharacter(editor)
testMicrodragSelection(editor)
testUnnamedClipboard(editor)
testSelectAndRightClick(editor)
testSelectTextWithMouseInGutter(editor)
testSelectForthAndBack(editor)
testSelectTextUsingMouse(editor)
testTripleClickRightFromLineEnd(editor)
testClickRightFromLineEnd(editor)
testClickOnWord(editor)
testGutterClick(editor)
reenableIdeaVim(editor)
createFile("MyTest.java", this@uiTest)
val javaEditor = editor("MyTest.java") {
step("Write a text") {
injectText(
"""
|class Main {
| public static void main() {
| System.out.println("Hello");
| }
|}
""".trimMargin()
)
}
}
// This is a hack to wait till inline hints will appear
Thread.sleep(1000)
wrapWithIf(javaEditor)
}
}
private fun closeUnrelated(sharedSteps: JavaExampleSteps) {
with(sharedSteps) {
closeIdeaVimDialog()
closeTipOfTheDay()
closeAllTabs()
}
}
private fun RemoteRobot.startNewProject() {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
}
private fun IdeaFrame.testUnnamedClipboard(editor: Editor) {
keyboard {
enterText(":set clipboard+=unnamed")
enter()
enterText("gg")
enterText("yy")
enterText("jyy")
enterText("jyy")
enterText("p")
enterText("p")
enterText("p")
}
assertEquals(
"""
One Two
Three Four
Five
Five
Five
Five
""".trimIndent(),
editor.text
)
editor.injectText(
"""
|One Two
|Three Four
|Five
""".trimMargin()
)
keyboard {
enterText(":set clipboard-=unnamed")
enter()
}
}
private fun IdeaFrame.wrapWithIf(editor: Editor) {
editor.findText("System").click()
remoteRobot.invokeActionJs("SurroundWith")
editor.keyboard { enter() }
// assertFalse(editor.isBlockCursor)
editor.keyboard {
enterText("true")
escape()
}
// assertTrue(editor.isBlockCursor)
editor.keyboard {
enterText("h")
enterText("v")
}
assertEquals("u", editor.selectedText)
vimExit()
}
private fun IdeaFrame.createFile(fileName: String, remoteRobot: RemoteRobot) {
step("Create $fileName file") {
with(projectViewTree) {
expand(projectName, "src")
findText("src").click(MouseButton.RIGHT_BUTTON)
}
remoteRobot.actionMenu("New").click()
remoteRobot.actionMenuItem("File").click()
keyboard { enterText(fileName); enter() }
}
}
private fun IdeaFrame.reenableIdeaVim(editor: Editor) {
println("Run reenableIdeaVim...")
toggleIdeaVim()
val from = editor.findText("One")
from.doubleClick()
editor.click()
toggleIdeaVim()
from.click()
editor.keyboard {
enterText("i")
enterText("Hello")
escape()
enterText("4h")
enterText("5x")
}
assertEquals(
"""
One Two
Three Four
Five
""".trimIndent(),
editor.text
)
}
private fun IdeaFrame.toggleIdeaVim() {
this.remoteRobot.invokeActionJs("VimPluginToggle")
}
private fun ContainerFixture.testSelectTextWithMouseInGutter(editor: Editor) {
println("Run testSelectTextWithMouseInGutter...")
gutter {
val from = findText("1")
val to = findText("2")
from.moveMouseInGutterTo(to, this)
}
Thread.sleep(1000)
assertEquals("One Two\nThree Four\n", editor.selectedText)
keyboard { enterText("j") }
assertEquals("One Two\nThree Four\nFive", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testMicrodragSelection(editor: Editor) {
println("Run testMicrodragSelection...")
val point = editor.findText("Four").point
val startPoint = Point(point.x + 50, point.y)
val endPoint = Point(point.x + 49, point.y)
startPoint.moveMouseTo(endPoint, editor)
// Assert there was no selection
keyboard {
enterText("v")
}
assertEquals("r", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testLargerDragSelection(editor: Editor) {
println("Run testMicrodragSelection...")
val point = editor.findText("Four").point
val startPoint = Point(point.x + 50, point.y)
val endPoint = Point(point.x + 40, point.y)
startPoint.moveMouseTo(endPoint, editor)
// Assert there was no selection
keyboard {
enterText("v")
}
assertEquals("r", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testExtendSelection(editor: Editor) {
println("Run testExtendSelection...")
// Preparations
val from = editor.findText("One")
val to = editor.findText("Four")
from.moveMouseTo(to, editor)
vimExit()
keyboard {
enterText(":action EditorSelectWord")
enter()
}
assertEquals("One", editor.selectedText)
keyboard {
enterText("l")
}
assertEquals("ne", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testSelectTextWithDelay(editor: Editor) {
println("Run testSelectTextUsingMouse...")
val from = editor.findText("One")
val to = editor.findText("Four")
val caretIsBlockWhileDragging = from.moveMouseWithDelayTo(to, editor)
assertFalse(caretIsBlockWhileDragging)
Thread.sleep(1000)
assertEquals("One Two\nThree ", editor.selectedText)
keyboard { enterText("l") }
assertEquals("One Two\nThree F", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testSelectLastCharacter(editor: Editor) {
println("Run testSelectLastCharacter...")
val point = editor.findText("Four").point
val startPoint = Point(point.x + 50, point.y)
startPoint.moveMouseTo(point, editor)
assertEquals("Four", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testSelectTextUsingMouse(editor: Editor) {
println("Run testSelectTextUsingMouse...")
val from = editor.findText("One")
val to = editor.findText("Four")
val caretIsBlockWhileDragging = from.moveMouseTo(to, editor)
assertFalse(caretIsBlockWhileDragging)
Thread.sleep(1000)
assertEquals("One Two\nThree ", editor.selectedText)
keyboard { enterText("l") }
assertEquals("One Two\nThree F", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testSelectAndRightClick(editor: Editor) {
println("Run testSelectTextUsingMouse...")
val from = editor.findText("One")
val to = editor.findText("Five")
val caretIsBlockWhileDragging = from.moveMouseTo(to, editor)
assertFalse(caretIsBlockWhileDragging)
Thread.sleep(1000)
// Right click
editor.findText("Two").click(MouseButton.RIGHT_BUTTON)
Thread.sleep(1000)
assertTrue(editor.selectedText.isNotEmpty())
// Reset state
editor.findText("One").click()
vimExit()
}
private fun ContainerFixture.testSelectForthAndBack(editor: Editor) {
println("Run testSelectForthAndBack...")
val from = editor.findText("Two")
val to = editor.findText("Four")
from.moveMouseForthAndBack(to, editor)
Thread.sleep(1000)
// Currently null can't be serialized, so we cant get empty string as a selected text. So we move caret a bit,
// enter visual mode and check that only the char under the caret is selected.
keyboard { enterText("l") }
keyboard { enterText("v") }
assertEquals("w", editor.selectedText)
vimExit()
}
private fun ContainerFixture.testTripleClickRightFromLineEnd(editor: Editor) {
println("Run testTripleClickRightFromLineEnd...")
editor.findText("Two").tripleClickOnRight(40, editor)
assertEquals("One Two\n", editor.selectedText)
assertEquals(7, editor.caretOffset)
keyboard { enterText("h") }
assertEquals("One Two\n", editor.selectedText)
assertEquals(6, editor.caretOffset)
keyboard { enterText("j") }
assertEquals("One Two\nThree Four\n", editor.selectedText)
assertEquals(14, editor.caretOffset)
vimExit()
}
private fun ContainerFixture.testClickRightFromLineEnd(editor: Editor) {
println("Run testClickRightFromLineEnd...")
editor.findText("Two").doubleClickOnRight(40, editor)
assertEquals("Two", editor.selectedText)
assertEquals(6, editor.caretOffset)
keyboard { enterText("h") }
assertEquals("Tw", editor.selectedText)
assertEquals(5, editor.caretOffset)
vimExit()
}
private fun ContainerFixture.testClickOnWord(editor: Editor) {
println("Run testClickOnWord...")
editor.findText("One").doubleClick(MouseButton.LEFT_BUTTON)
assertEquals("One", editor.selectedText)
assertEquals(2, editor.caretOffset)
keyboard { enterText("h") }
assertEquals("On", editor.selectedText)
assertEquals(1, editor.caretOffset)
vimExit()
}
private fun ContainerFixture.testGutterClick(editor: Editor) {
println("Run testGutterClick...")
gutter {
findText("2").click()
}
assertEquals("Three Four\n", editor.selectedText)
keyboard {
enterText("k")
}
assertEquals("One Two\nThree Four\n", editor.selectedText)
vimExit()
}
}
| src/test/java/ui/UiTests.kt | 1185349394 |
package io.sledge.deployer.crx
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import java.io.File
import java.io.IOException
import java.util.zip.ZipFile
class VaultPropertiesXmlDataExtractor {
companion object {
const val VLT_PROPERTIES_PATH = "META-INF/vault/properties.xml"
}
val kotlinXmlMapper = XmlMapper(JacksonXmlModule().apply {
setDefaultUseWrapper(false)
}).registerKotlinModule()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false)
@Throws(IOException::class)
fun getEntryValue(zip: String, entryKeyName: String): String {
val zipFile = ZipFile(File(zip))
val zipEntry = zipFile.getEntry(VLT_PROPERTIES_PATH)
val zipFileInputStream = zipFile.getInputStream(zipEntry)
try {
val propertiesXml = kotlinXmlMapper.readValue(zipFileInputStream, Properties::class.java)
return propertiesXml.entries.find { entry -> entry.key.equals(entryKeyName) }?.value ?: ""
} finally {
zipFile.close()
}
}
@JacksonXmlRootElement(localName = "properties")
data class Properties(
@JacksonXmlElementWrapper(useWrapping = false)
@set:JacksonXmlProperty(localName = "entry")
var entries: List<Entry> = ArrayList()
)
data class Entry(
@set:JacksonXmlProperty(localName = "key", isAttribute = true)
var key: String?) {
@set:JacksonXmlText
lateinit var value: String
}
}
| src/main/kotlin/io/sledge/deployer/crx/VaultPropertiesXmlDataExtractor.kt | 2939218338 |
package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.Slider
import org.hexworks.zircon.api.component.data.ComponentState
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.Symbols
import org.hexworks.zircon.api.graphics.TileGraphics
@Suppress("DuplicatedCode")
class HorizontalSliderRenderer : ComponentRenderer<Slider> {
override fun render(tileGraphics: TileGraphics, context: ComponentRenderContext<Slider>) {
tileGraphics.applyStyle(context.currentStyle)
val defaultStyleSet = context.componentStyle.fetchStyleFor(ComponentState.DEFAULT)
val invertedDefaultStyleSet = defaultStyleSet
.withBackgroundColor(defaultStyleSet.foregroundColor)
.withForegroundColor(defaultStyleSet.backgroundColor)
val disabledStyleSet = context.componentStyle.fetchStyleFor(ComponentState.DISABLED)
val cursorPosition = context.component.currentStep
val barWidth = context.component.numberOfSteps
(0..barWidth).forEach { idx ->
when {
idx == cursorPosition -> tileGraphics.draw(
Tile.createCharacterTile(
Symbols.DOUBLE_LINE_VERTICAL,
context.currentStyle
), Position.create(idx, 0)
)
idx < cursorPosition -> tileGraphics.draw(
Tile.createCharacterTile(' ', invertedDefaultStyleSet),
Position.create(idx, 0)
)
else -> tileGraphics.draw(Tile.createCharacterTile(' ', disabledStyleSet), Position.create(idx, 0))
}
}
}
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/HorizontalSliderRenderer.kt | 745299896 |
package org.rust.ide.structure
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import org.rust.lang.core.psi.*
open class RustModTreeElement(item: RustModItem) : PsiTreeElementBase<RustModItem>(item) {
override fun getPresentableText() = element?.name
override fun getChildrenBase(): Collection<StructureViewTreeElement> =
element?.itemList?.let {
it.map { toTreeElement(it) }.filterNotNull()
}.orEmpty()
private fun toTreeElement(it: RustItem): StructureViewTreeElement? =
when (it) {
is RustEnumItem -> RustEnumTreeElement(it)
is RustTraitItem -> RustTraitTreeElement(it)
is RustStructItem -> RustStructTreeElement(it)
is RustImplItem -> RustImplTreeElement(it)
is RustFnItem -> RustFnTreeElement(it)
is RustModItem -> RustModTreeElement(it)
else -> null
}
}
| src/main/kotlin/org/rust/ide/structure/RustModTreeElement.kt | 2519345148 |
package org.wordpress.android.ui.posts.editor.media
import android.content.Context
import android.net.Uri
import dagger.Reusable
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.MediaModel.MediaUploadState.QUEUED
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.posts.editor.media.CopyMediaToAppStorageUseCase.CopyMediaResult
import org.wordpress.android.ui.posts.editor.media.GetMediaModelUseCase.CreateMediaModelsResult
import org.wordpress.android.ui.posts.editor.media.OptimizeMediaUseCase.OptimizeMediaResult
import org.wordpress.android.util.MediaUtilsWrapper
import javax.inject.Inject
/**
* Processes a list of local media items in the background (optimizing, resizing, rotating, etc.), adds them to
* the editor one at a time and initiates their upload.
*/
@Reusable
class AddLocalMediaToPostUseCase @Inject constructor(
private val copyMediaToAppStorageUseCase: CopyMediaToAppStorageUseCase,
private val optimizeMediaUseCase: OptimizeMediaUseCase,
private val getMediaModelUseCase: GetMediaModelUseCase,
private val updateMediaModelUseCase: UpdateMediaModelUseCase,
private val appendMediaToEditorUseCase: AppendMediaToEditorUseCase,
private val uploadMediaUseCase: UploadMediaUseCase,
private val mediaUtilsWrapper: MediaUtilsWrapper,
private val context: Context
) {
/**
* Adds media items with existing localMediaId to the editor and optionally initiates an upload.
* Does NOT optimize the items.
*/
suspend fun addLocalMediaToEditorAsync(
localMediaIds: List<Int>,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true
) {
// Add media to editor and optionally initiate upload
addToEditorAndOptionallyUpload(
getMediaModelUseCase.loadMediaByLocalId(localMediaIds),
editorMediaListener,
doUploadAfterAdding
)
}
/**
* Copies files to app storage, optimizes them, adds them to the editor and optionally initiates an upload.
*/
suspend fun addNewMediaToEditorAsync(
uriList: List<Uri>,
site: SiteModel,
freshlyTaken: Boolean,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true,
trackEvent: Boolean = true
): Boolean {
val allowedUris = uriList.filter {
// filter out long video files on free sites
if (mediaUtilsWrapper.isProhibitedVideoDuration(context, site, it)) {
// put out a notice to the user that the particular video file was rejected
editorMediaListener.showVideoDurationLimitWarning(it.path.toString())
return@filter false
}
return@filter true
}
return processMediaUris(
allowedUris,
site,
freshlyTaken,
editorMediaListener,
doUploadAfterAdding,
trackEvent)
}
private suspend fun processMediaUris(
uriList: List<Uri>,
site: SiteModel,
freshlyTaken: Boolean,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true,
trackEvent: Boolean = true
): Boolean {
// Copy files to apps storage to make sure they are permanently accessible.
val copyFilesResult: CopyMediaResult = copyMediaToAppStorageUseCase.copyFilesToAppStorageIfNecessary(uriList)
// Optimize and rotate the media
val optimizeMediaResult: OptimizeMediaResult = optimizeMediaUseCase
.optimizeMediaIfSupportedAsync(
site,
freshlyTaken,
copyFilesResult.permanentlyAccessibleUris,
trackEvent
)
// Transform Uris to MediaModels
val createMediaModelsResult: CreateMediaModelsResult = getMediaModelUseCase.createMediaModelFromUri(
site.id,
optimizeMediaResult.optimizedMediaUris
)
// here we pass a map of "old" (before optimisation) Uris to the new MediaModels which contain
// both the mediaModel ids and the optimized media URLs.
// this way, the listener will be able to process from other models pointing to the old URLs
// and make any needed updates
editorMediaListener.onMediaModelsCreatedFromOptimizedUris(
uriList.zip(createMediaModelsResult.mediaModels).toMap()
)
// Add media to editor and optionally initiate upload
addToEditorAndOptionallyUpload(createMediaModelsResult.mediaModels, editorMediaListener, doUploadAfterAdding)
return !optimizeMediaResult.loadingSomeMediaFailed &&
!createMediaModelsResult.loadingSomeMediaFailed &&
!copyFilesResult.copyingSomeMediaFailed
}
private fun addToEditorAndOptionallyUpload(
mediaModels: List<MediaModel>,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean
) {
// 1. first, set the Post's data in the mediaModels and set them QUEUED if we want to upload
if (doUploadAfterAdding) {
updateMediaModel(mediaModels, editorMediaListener)
}
// 2. actually append media to the Editor
appendMediaToEditorUseCase.addMediaToEditor(editorMediaListener, mediaModels)
// 3. finally, upload
if (doUploadAfterAdding) {
uploadMediaUseCase.saveQueuedPostAndStartUpload(editorMediaListener, mediaModels)
}
}
private fun updateMediaModel(
mediaModels: List<MediaModel>,
editorMediaListener: EditorMediaListener
) {
mediaModels.forEach {
updateMediaModelUseCase.updateMediaModel(
it,
editorMediaListener.getImmutablePost(),
QUEUED
)
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/editor/media/AddLocalMediaToPostUseCase.kt | 1188953633 |
package org.wordpress.android.ui.posts
import org.wordpress.android.R
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.PostActionBuilder
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.PostStore.RemotePostPayload
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.ToastUtils.Duration
import org.wordpress.android.viewmodel.helpers.ToastMessageHolder
/**
* This is a temporary class to make the PostListViewModel more manageable. Please feel free to refactor it any way
* you see fit.
*/
@Suppress("LongParameterList")
class PostConflictResolver(
private val dispatcher: Dispatcher,
private val site: SiteModel,
private val getPostByLocalPostId: (Int) -> PostModel?,
private val invalidateList: () -> Unit,
private val checkNetworkConnection: () -> Boolean,
private val showSnackbar: (SnackbarMessageHolder) -> Unit,
private val showToast: (ToastMessageHolder) -> Unit
) {
private var originalPostCopyForConflictUndo: PostModel? = null
private var localPostIdForFetchingRemoteVersionOfConflictedPost: Int? = null
fun updateConflictedPostWithRemoteVersion(localPostId: Int) {
// We need network connection to load a remote post
if (!checkNetworkConnection()) {
return
}
val post = getPostByLocalPostId.invoke(localPostId)
if (post != null) {
originalPostCopyForConflictUndo = post.clone()
dispatcher.dispatch(PostActionBuilder.newFetchPostAction(RemotePostPayload(post, site)))
showToast.invoke(ToastMessageHolder(R.string.toast_conflict_updating_post, Duration.SHORT))
}
}
fun updateConflictedPostWithLocalVersion(localPostId: Int) {
// We need network connection to push local version to remote
if (!checkNetworkConnection()) {
return
}
// Keep a reference to which post is being updated with the local version so we can avoid showing the conflicted
// label during the undo snackBar.
localPostIdForFetchingRemoteVersionOfConflictedPost = localPostId
invalidateList.invoke()
val post = getPostByLocalPostId.invoke(localPostId) ?: return
// and now show a snackBar, acting as if the Post was pushed, but effectively push it after the snackbar is gone
var isUndoed = false
val undoAction = {
isUndoed = true
// Remove the reference for the post being updated and re-show the conflicted label on undo
localPostIdForFetchingRemoteVersionOfConflictedPost = null
invalidateList.invoke()
}
val onDismissAction = { _: Int ->
if (!isUndoed) {
localPostIdForFetchingRemoteVersionOfConflictedPost = null
PostUtils.trackSavePostAnalytics(post, site)
dispatcher.dispatch(PostActionBuilder.newPushPostAction(RemotePostPayload(post, site)))
}
}
val snackBarHolder = SnackbarMessageHolder(
UiStringRes(R.string.snackbar_conflict_web_version_discarded),
UiStringRes(R.string.snackbar_conflict_undo),
undoAction,
onDismissAction
)
showSnackbar.invoke(snackBarHolder)
}
fun doesPostHaveUnhandledConflict(post: PostModel): Boolean {
// If we are fetching the remote version of a conflicted post, it means it's already being handled
val isFetchingConflictedPost = localPostIdForFetchingRemoteVersionOfConflictedPost != null &&
localPostIdForFetchingRemoteVersionOfConflictedPost == post.id
return !isFetchingConflictedPost && PostUtils.isPostInConflictWithRemote(post)
}
fun hasUnhandledAutoSave(post: PostModel): Boolean {
return PostUtils.hasAutoSave(post)
}
fun onPostSuccessfullyUpdated() {
originalPostCopyForConflictUndo?.id?.let {
val updatedPost = getPostByLocalPostId.invoke(it)
// Conflicted post has been successfully updated with its remote version
if (!PostUtils.isPostInConflictWithRemote(updatedPost)) {
conflictedPostUpdatedWithRemoteVersion()
}
}
}
private fun conflictedPostUpdatedWithRemoteVersion() {
val undoAction = {
// here replace the post with whatever we had before, again
if (originalPostCopyForConflictUndo != null) {
dispatcher.dispatch(PostActionBuilder.newUpdatePostAction(originalPostCopyForConflictUndo))
}
}
val onDismissAction = { _: Int ->
originalPostCopyForConflictUndo = null
}
val snackBarHolder = SnackbarMessageHolder(
UiStringRes(R.string.snackbar_conflict_local_version_discarded),
UiStringRes(R.string.snackbar_conflict_undo),
undoAction,
onDismissAction
)
showSnackbar.invoke(snackBarHolder)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/PostConflictResolver.kt | 2248722743 |
fun printAllWithPrefix(vararg messages: String, prefix: String) {
for (m in messages)
println(prefix + m)
}
fun main(args: Array<String>) {
printAllWithPrefix(
"Hello", "Hallo", "Salut", "Hola", "你好",
prefix = "Greeting: "
)
}
| languages/kotlin/varargs.kt | 2803780178 |
package org.wordpress.android.ui.reader.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver.OnPreDrawListener
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.ui.reader.discover.interests.TagUiState
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.utils.UiHelpers
import javax.inject.Inject
class ReaderExpandableTagsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ChipGroup(context, attrs, defStyleAttr) {
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var readerTracker: ReaderTracker
private var tagsUiState: List<TagUiState>? = null
private val tagChips
get() = (0 until childCount - 1).map { getChildAt(it) as Chip }
private val overflowIndicatorChip
get() = getChildAt(childCount - 1) as Chip
private val lastVisibleTagChipIndex
get() = tagChips.filter { it.visibility == View.VISIBLE }.lastIndex
private val lastVisibleTagChip
get() = getChildAt(lastVisibleTagChipIndex)
private val hiddenTagChipsCount
get() = tagChips.size - (lastVisibleTagChipIndex + 1)
private val isOverflowIndicatorChipOutsideBounds
get() = !isChipWithinBounds(overflowIndicatorChip)
init {
(context.applicationContext as WordPress).component().inject(this)
layoutDirection = View.LAYOUT_DIRECTION_LOCALE
}
fun updateUi(tagsUiState: List<TagUiState>) {
if (this.tagsUiState != null && this.tagsUiState == tagsUiState) {
return
}
this.tagsUiState = tagsUiState
removeAllViews()
addOverflowIndicatorChip()
addTagChips(tagsUiState)
expandLayout(false)
}
private fun addOverflowIndicatorChip() {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chip = inflater.inflate(R.layout.reader_expandable_tags_view_overflow_chip, this, false) as Chip
chip.setOnCheckedChangeListener { _, isChecked ->
readerTracker.track(Stat.READER_CHIPS_MORE_TOGGLED)
expandLayout(isChecked)
}
addView(chip)
}
private fun addTagChips(tagsUiState: List<TagUiState>) {
tagsUiState.forEachIndexed { index, tagUiState ->
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chip = inflater.inflate(R.layout.reader_expandable_tags_view_chip, this, false) as Chip
chip.tag = tagUiState.slug
chip.text = tagUiState.title
chip.maxWidth = tagUiState.maxWidth
tagUiState.onClick?.let { onClick ->
chip.setOnClickListener {
onClick.invoke(tagUiState.slug)
}
}
addView(chip, index)
}
}
private fun expandLayout(isChecked: Boolean) {
isSingleLine = !isChecked
showAllTagChips()
preLayout {
hideTagChipsOutsideBounds()
updateLastVisibleTagChip()
updateOverflowIndicatorChip()
}
requestLayout()
}
private fun showAllTagChips() {
tagChips.forEach { uiHelpers.updateVisibility(it, true) }
}
private fun hideTagChipsOutsideBounds() {
tagChips.forEach { uiHelpers.updateVisibility(it, isChipWithinBounds(it)) }
}
private fun isChipWithinBounds(chip: Chip) = if (isSingleLine) {
if (layoutDirection == View.LAYOUT_DIRECTION_LTR) {
chip.right <= right - (paddingEnd + chipSpacingHorizontal)
} else {
chip.left >= left + (paddingStart + chipSpacingHorizontal)
}
} else {
chip.bottom <= bottom
}
private fun updateLastVisibleTagChip() {
lastVisibleTagChip?.let {
if (lastVisibleTagChipIndex > 0) {
uiHelpers.updateVisibility(it, !isOverflowIndicatorChipOutsideBounds)
}
}
}
private fun updateOverflowIndicatorChip() {
val showOverflowIndicatorChip = hiddenTagChipsCount > 0 || !isSingleLine
uiHelpers.updateVisibility(overflowIndicatorChip, showOverflowIndicatorChip)
overflowIndicatorChip.contentDescription = String.format(
resources.getString(R.string.show_n_hidden_items_desc),
hiddenTagChipsCount
)
overflowIndicatorChip.text = if (isSingleLine) {
String.format(
resources.getString(R.string.reader_expandable_tags_view_overflow_indicator_expand_title),
hiddenTagChipsCount
)
} else {
resources.getString(R.string.reader_expandable_tags_view_overflow_indicator_collapse_title)
}
val chipBackgroundColorRes = if (isSingleLine) {
R.color.on_surface_chip
} else {
R.color.transparent
}
overflowIndicatorChip.setChipBackgroundColorResource(chipBackgroundColorRes)
}
private fun View.preLayout(what: () -> Unit) {
viewTreeObserver.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
viewTreeObserver.removeOnPreDrawListener(this)
what.invoke()
return true
}
})
}
}
| WordPress/src/main/java/org/wordpress/android/ui/reader/views/ReaderExpandableTagsView.kt | 2488643163 |
package com.kevinmost.koolbelt.extension
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
class ListUtilTest {
@Test fun `test setOrAppend() with append`() {
val res = mutableListOf(3, 4, 5).setOrAppend(3, 4)
assertEquals(4, res.size)
assertEquals(4, res[3])
}
@Test fun `test setOrAppend() with set`() {
val res = mutableListOf(3, 4, 5).setOrAppend(0, 2)
assertEquals(2, res[0])
}
@Test fun `test setOrAppend() with really high index throws exception`() {
try {
mutableListOf(3, 4, 5).setOrAppend(400, 6)
fail()
} catch(e: IndexOutOfBoundsException) {
}
}
@Test fun `test operator overload for sublist`() {
val numbers = (1..100).toList()
val sub = numbers[50..52]
Assert.assertEquals(2, sub.size)
Assert.assertEquals(51, sub[0])
Assert.assertEquals(52, sub[1])
val sub2 = numbers[0..0]
Assert.assertTrue(sub2.isEmpty())
val sub3 = numbers[10 downTo 0 step 5]
Assert.assertEquals(3, sub3.size)
Assert.assertEquals(11, sub3[0])
Assert.assertEquals(6, sub3[1])
Assert.assertEquals(1, sub3[2])
}
}
| core/src/test/java/com/kevinmost/koolbelt/extension/ListUtilTest.kt | 3110329358 |
// 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.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
internal fun KtExpression.getArguments() = when (this) {
is KtBinaryExpression -> this.left to this.right
is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()
else -> null
}
class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("replace.with.0.operator", "..")
) {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false
val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false
return fqName == "kotlin.ranges.until"
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return))
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUntilWithRangeToIntention.kt | 3122712226 |
package source
import target.foo
class C
fun test(c: C) {
c.foo()
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/changePackage/addExtensionImport/after/source/foo.kt | 2658957133 |
package com.telerik.metadata.parsing.kotlin.properties
import com.telerik.metadata.parsing.NativeMethodDescriptor
import com.telerik.metadata.parsing.NativePropertyDescriptor
class KotlinPropertyDescriptor(override val name: String,
override val getterMethod: NativeMethodDescriptor?,
override val setterMethod: NativeMethodDescriptor?, val duplicate: Boolean = false ) : NativePropertyDescriptor
| test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/kotlin/properties/KotlinPropertyDescriptor.kt | 2085710210 |
// 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.workspaceModel.codegen.classes
import com.intellij.workspaceModel.codegen.deft.meta.ObjClass
import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty
import com.intellij.workspaceModel.codegen.deft.meta.ValueType
import com.intellij.workspaceModel.codegen.isRefType
import com.intellij.workspaceModel.codegen.utils.LinesBuilder
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.utils.lines
import com.intellij.workspaceModel.codegen.utils.toQualifiedName
import com.intellij.workspaceModel.codegen.writer.allFields
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
internal fun ObjClass<*>.softLinksCode(context: LinesBuilder, hasSoftLinks: Boolean) {
context.conditionalLine({ hasSoftLinks }, "override fun getLinks(): Set<${PersistentEntityId::class.fqn}<*>>") {
line("val result = HashSet<${PersistentEntityId::class.fqn}<*>>()")
operate(this) { line("result.add($it)") }
line("return result")
}
context.conditionalLine(
{ hasSoftLinks },
"override fun index(index: ${WorkspaceMutableIndex::class.fqn}<${PersistentEntityId::class.fqn}<*>>)"
) {
operate(this) { line("index.index(this, $it)") }
}
context.conditionalLine(
{ hasSoftLinks },
"override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: ${WorkspaceMutableIndex::class.fqn}<${PersistentEntityId::class.fqn}<*>>)"
) {
line("// TODO verify logic")
line("val mutablePreviousSet = HashSet(prev)")
operate(this) {
line("val removedItem_${it.clean()} = mutablePreviousSet.remove($it)")
section("if (!removedItem_${it.clean()})") {
line("index.index(this, $it)")
}
}
section("for (removed in mutablePreviousSet)") {
line("index.remove(this, removed)")
}
}
context.conditionalLine(
{ hasSoftLinks },
"override fun updateLink(oldLink: ${PersistentEntityId::class.fqn}<*>, newLink: ${PersistentEntityId::class.fqn}<*>): Boolean"
) {
line("var changed = false")
operateUpdateLink(this)
line("return changed")
}
}
internal fun ObjClass<*>.hasSoftLinks(): Boolean {
return fields.noPersistentId().noRefs().any { field ->
field.hasSoftLinks()
}
}
internal fun ObjProperty<*, *>.hasSoftLinks(): Boolean {
if (name == "persistentId") return false
return valueType.hasSoftLinks()
}
internal fun ValueType<*>.hasSoftLinks(): Boolean = when (this) {
is ValueType.Blob -> isPersistentId
is ValueType.Collection<*, *> -> elementType.hasSoftLinks()
is ValueType.Optional<*> -> type.hasSoftLinks()
is ValueType.SealedClass<*> -> isPersistentId || subclasses.any { it.hasSoftLinks() }
is ValueType.DataClass<*> -> isPersistentId || properties.any { it.type.hasSoftLinks() }
else -> false
}
val ValueType.JvmClass<*>.isPersistentId: Boolean
get() = PersistentEntityId::class.java.simpleName in javaSuperClasses || //todo check qualified name only
PersistentEntityId::class.java.name in javaSuperClasses
private fun ObjClass<*>.operate(
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit
) {
allFields.noPersistentId().noRefs().forEach { field ->
field.valueType.operate(field.name, context, operation)
}
}
private fun ValueType<*>.operate(
varName: String,
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit,
generateNewName: Boolean = true,
) {
when (this) {
is ValueType.JvmClass -> {
when {
isPersistentId -> context.operation(varName)
this is ValueType.SealedClass<*> -> processSealedClass(this, varName, context, operation, generateNewName)
this is ValueType.DataClass<*> -> processDataClassProperties(varName, context, properties, operation)
}
}
is ValueType.Collection<*, *> -> {
val elementType = elementType
context.section("for (item in ${varName})") {
elementType.operate("item", this@section, operation, false)
}
}
is ValueType.Optional<*> -> {
if (type is ValueType.JvmClass && type.isPersistentId) {
context.line("val optionalLink_${varName.clean()} = $varName")
context.`if`("optionalLink_${varName.clean()} != null") label@{
type.operate("optionalLink_${varName.clean()}", this@label, operation)
}
}
}
else -> Unit
}
}
private fun processDataClassProperties(varName: String,
context: LinesBuilder,
dataClassProperties: List<ValueType.DataClassProperty>,
operation: LinesBuilder.(String) -> Unit) {
for (property in dataClassProperties) {
property.type.operate("$varName.${property.name}", context, operation)
}
}
private fun processSealedClass(thisClass: ValueType.SealedClass<*>,
varName: String,
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit,
generateNewName: Boolean = true) {
val newVarName = if (generateNewName) "_${varName.clean()}" else varName
if (generateNewName) context.line("val $newVarName = $varName")
context.section("when ($newVarName)") {
listBuilder(thisClass.subclasses) { item ->
val linesBuilder = LinesBuilder(StringBuilder(), context.indentLevel+1, context.indentSize).wrapper()
if (item is ValueType.SealedClass) {
processSealedClass(item, newVarName, linesBuilder, operation, generateNewName)
}
else if (item is ValueType.DataClass) {
processDataClassProperties(newVarName, linesBuilder, item.properties, operation)
}
section("is ${item.javaClassName.toQualifiedName()} -> ") {
result.append(linesBuilder.result)
}
}
}
}
private fun ObjClass<*>.operateUpdateLink(context: LinesBuilder) {
allFields.noPersistentId().noRefs().forEach { field ->
val retType = field.valueType.processType(context, field.name)
if (retType != null) {
context.`if`("$retType != null") {
if (field.valueType is ValueType.Set<*> && !field.valueType.isRefType()) {
line("${field.name} = $retType as MutableSet")
} else if (field.valueType is ValueType.List<*> && !field.valueType.isRefType()) {
line("${field.name} = $retType as MutableList")
} else {
line("${field.name} = $retType")
}
}
}
}
}
private fun ValueType<*>.processType(
context: LinesBuilder,
varName: String,
): String? {
return when (this) {
is ValueType.JvmClass -> {
when {
isPersistentId -> {
val name = "${varName.clean()}_data"
context.lineNoNl("val $name = ")
context.ifElse("$varName == oldLink", {
line("changed = true")
line("newLink as ${javaClassName.toQualifiedName()}")
}) { line("null") }
name
}
this is ValueType.SealedClass<*> -> {
processSealedClass(this, varName, context)
}
this is ValueType.DataClass<*> -> {
val updates = properties.mapNotNull label@{
val retVar = it.type.processType(
context,
"$varName.${it.name}"
)
if (retVar != null) it.name to retVar else null
}
if (updates.isEmpty()) {
null
}
else {
val name = "${varName.clean()}_data"
context.line("var $name = $varName")
updates.forEach { (fieldName, update) ->
context.`if`("$update != null") {
line("$name = $name.copy($fieldName = $update)")
}
}
name
}
}
else -> null
}
}
is ValueType.Collection<*, *> -> {
var name: String? = "${varName.clean()}_data"
val builder = lines(context.indentLevel) {
section("val $name = $varName.map") label@{
val returnVar = elementType.processType(
this@label,
"it"
)
if (returnVar != null) {
ifElse("$returnVar != null", {
line(returnVar)
}) { line("it") }
}
else {
name = null
}
}
}
if (name != null) {
context.result.append(builder)
}
name
}
is ValueType.Optional<*> -> {
var name: String? = "${varName.clean()}_data_optional"
val builder = lines(context.indentLevel) {
lineNoNl("var $name = ")
ifElse("$varName != null", labelIf@{
val returnVar = type.processType(
this@labelIf,
"$varName!!"
)
if (returnVar != null) {
line(returnVar)
}
else {
name = null
}
}) { line("null") }
}
if (name != null) {
context.result.append(builder)
}
name
}
else -> return null
}
}
private fun processSealedClass(thisClass: ValueType.SealedClass<*>,
varName: String,
context: LinesBuilder): String {
val newVarName = "_${varName.clean()}"
val resVarName = "res_${varName.clean()}"
context.line("val $newVarName = $varName")
context.lineNoNl("val $resVarName = ")
context.section("when ($newVarName)") {
listBuilder(thisClass.subclasses) { item ->
section("is ${item.javaClassName.toQualifiedName()} -> ") label@{
var sectionVarName = newVarName
val properties: List<ValueType.DataClassProperty>
if (item is ValueType.SealedClass) {
sectionVarName = processSealedClass(item, sectionVarName, this)
properties = emptyList()
}
else if (item is ValueType.DataClass) {
properties = item.properties
}
else {
properties = emptyList()
}
val updates = properties.mapNotNull {
val retVar = it.type.processType(
this@label,
"$sectionVarName.${it.name}"
)
if (retVar != null) it.name to retVar else null
}
if (updates.isEmpty()) {
line(sectionVarName)
}
else {
val name = "${sectionVarName.clean()}_data"
line("var $name = $sectionVarName")
updates.forEach { (fieldName, update) ->
`if`("$update != null") {
line("$name = $name.copy($fieldName = $update)")
}
}
line(name)
}
}
}
}
return resVarName
}
private fun String.clean(): String {
return this.replace(".", "_").replace('!', '_')
} | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/classes/SoftLinksCode.kt | 1671977077 |
package com.emberjs.translations
import com.intellij.json.psi.JsonProperty
import com.intellij.json.psi.JsonStringLiteral
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementVisitor
import java.util.*
class JsonStringPropertyCollector : PsiRecursiveElementVisitor() {
val properties = ArrayList<JsonProperty>()
override fun visitElement(element: PsiElement) {
if (element is JsonProperty && element.value is JsonStringLiteral) {
properties += element
}
super.visitElement(element)
}
fun collectFrom(element: PsiElement): Iterable<JsonProperty> {
element.accept(this)
return properties
}
}
| src/main/kotlin/com/emberjs/translations/JsonStringPropertyCollector.kt | 3985226036 |
package io.ipoli.android.friends.feed.post
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.feed.post.PostViewState.StateType.DATA_CHANGED
import io.ipoli.android.friends.feed.post.PostViewState.StateType.LOADING
sealed class PostAction : Action {
data class Load(val postId: String) : PostAction()
data class SaveComment(val postId: String, val text: String) : PostAction()
data class Remove(val postId: String) : PostAction()
data class React(val postId: String, val reaction: Post.ReactionType) : PostAction()
}
object PostReducer : BaseViewStateReducer<PostViewState>() {
override val stateKey = key<PostViewState>()
override fun reduce(state: AppState, subState: PostViewState, action: Action) =
when (action) {
is DataLoadedAction.PostChanged -> {
val currentPlayerId = state.dataState.player!!.id
subState.copy(
type = DATA_CHANGED,
post = action.post,
comments = action.post.comments
.sortedBy { it.createdAt.toEpochMilli() },
canDelete = action.post.playerId == currentPlayerId,
currentPlayerId = currentPlayerId
)
}
else -> subState
}
override fun defaultState() = PostViewState(
type = LOADING,
post = null,
comments = emptyList(),
canDelete = false,
currentPlayerId = null
)
}
data class PostViewState(
val type: StateType,
val post: Post?,
val comments: List<Post.Comment>,
val canDelete: Boolean,
val currentPlayerId : String?
) : BaseViewState() {
enum class StateType {
LOADING, DATA_CHANGED
}
} | app/src/main/java/io/ipoli/android/friends/feed/post/PostViewState.kt | 3384466877 |
package jetbrains.buildServer.nuget.feed.server.json
import jetbrains.buildServer.log.Loggers
import jetbrains.buildServer.web.util.WebUtil
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter
import java.util.concurrent.Callable
import javax.servlet.http.HttpServletRequest
class TimeoutCallableInterceptor : CallableProcessingInterceptorAdapter() {
override fun <T> handleTimeout(request: NativeWebRequest, task: Callable<T>): Any {
val originalRequest = request.getNativeRequest(HttpServletRequest::class.java)
if (originalRequest != null) {
Loggers.SERVER.warn("NuGet async request timeout. Request: " + WebUtil.getRequestDump(originalRequest))
}
return ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body(HttpStatus.REQUEST_TIMEOUT.reasonPhrase)
}
}
| nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/TimeoutCallableInterceptor.kt | 2061467359 |
package cn.mijack.imagedrive.ui
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import cn.mijack.imagedrive.R
import cn.mijack.imagedrive.base.BaseActivity
import cn.mijack.imagedrive.componment.NavigationHeaderView
import cn.mijack.imagedrive.fragment.BackUpFragment
import cn.mijack.imagedrive.fragment.ImageDriverFragment
import cn.mijack.imagedrive.fragment.ImageListFragment
import com.google.firebase.auth.FirebaseAuth
/**
* @author Mr.Yuan
* *
* @date 2017/4/16
*/
class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
private var toolbar: Toolbar? = null
private var drawerLayout: DrawerLayout? = null
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private var headerView: NavigationHeaderView? = null
private lateinit var navigationView: NavigationView
private var firebaseAuth: FirebaseAuth? = null
private var imageListFragment: ImageListFragment? = null
private var imageDriverFragment: ImageDriverFragment? = null
private var currentFragment: Fragment? = null
private var backUpFragment: BackUpFragment? = null
private var dialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById<Toolbar>(R.id.toolbar)
firebaseAuth = FirebaseAuth.getInstance()
drawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout)
navigationView = findViewById<NavigationView>(R.id.navigationView)
headerView = NavigationHeaderView(this, navigationView)
headerView!!.loadLoginInfo()
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.content_drawer_open, R.string.content_drawer_close)
drawerLayout!!.addDrawerListener(actionBarDrawerToggle!!)
actionBarDrawerToggle!!.syncState()
switchFragment(IMAGE_LIST_FRAGMENT)
navigationView!!.setNavigationItemSelectedListener({ this.onNavigationItemSelected(it) })
}
private fun switchFragment(fragmentCode: Int) {
val transaction = supportFragmentManager.beginTransaction()
if (currentFragment != null) {
transaction.hide(currentFragment)
}
when (fragmentCode) {
IMAGE_LIST_FRAGMENT -> {
title = getString(R.string.local)
if (imageListFragment == null) {
imageListFragment = ImageListFragment()
transaction.add(R.id.frameLayout, imageListFragment)
} else {
transaction.show(imageListFragment)
}
currentFragment = imageListFragment
}
IMAGE_DRIVER_FRAGMENT -> {
title = getString(R.string.driver)
if (imageDriverFragment == null) {
imageDriverFragment = ImageDriverFragment()
transaction.add(R.id.frameLayout, imageDriverFragment)
} else {
transaction.show(imageDriverFragment)
}
currentFragment = imageDriverFragment
}
BACKUP_FRAGMENT -> {
if (backUpFragment == null) {
backUpFragment = BackUpFragment()
transaction.add(R.id.frameLayout, backUpFragment)
} else {
transaction.show(backUpFragment)
}
currentFragment = backUpFragment
}
}
transaction.commit()
invalidateOptionsMenu()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu.setGroupVisible(R.id.actionShow, currentFragment is ImageListFragment)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_CODE_LOGIN -> {
if (resultCode == Activity.RESULT_CANCELED) {
return
}
if (resultCode == LoginActivity.RESULT_LOGIN) {
headerView!!.loadLoginInfo()
return
}
if (resultCode == LoginActivity.RESULT_NEW_ACCOUNT) {
headerView!!.loadLoginInfo()
}
}
REQUEST_CODE_PROFILE -> headerView!!.loadLoginInfo()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.actionShowFolder -> imageListFragment!!.showFolder()
R.id.actionShowImages -> imageListFragment!!.showImages()
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.actionProfile -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
headerView!!.startProfileActivity()
return true
}
R.id.actionDriver -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(IMAGE_DRIVER_FRAGMENT)
return true
}
R.id.actionLocal -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(IMAGE_LIST_FRAGMENT)
return true
}
R.id.actionBackUp -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(BACKUP_FRAGMENT)
return true
}
R.id.actionAbout -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
startActivity(Intent(this, AboutActivity::class.java))
return true
}
R.id.actionSettings -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
startActivity(Intent(this, SettingsActivity::class.java))
return true
}
R.id.actionLogout -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
if (dialog == null) {
val listener = { dialog: DialogInterface, which: Int ->
if (which == DialogInterface.BUTTON_POSITIVE) {
firebaseAuth!!.signOut()
headerView!!.loadLoginInfo()
}
}
dialog = AlertDialog.Builder(this)
.setTitle(R.string.sign_out)
.setIcon(R.drawable.ic_logout)
.setCancelable(false)
.setPositiveButton(R.string.ok, listener)
.setNegativeButton(R.string.cancel, listener)
.setMessage(R.string.sign_out_message)
.create()
}
dialog!!.show()
return true
}
}
return false
}
companion object {
val REQUEST_CODE_LOGIN = 1
val REQUEST_CODE_PROFILE = 2
private val IMAGE_LIST_FRAGMENT = 1
private val IMAGE_DRIVER_FRAGMENT = 2
private val BACKUP_FRAGMENT = 3
}
}
| app/src/main/java/cn/mijack/imagedrive/ui/MainActivity.kt | 1021665900 |
package foo.bar.baz
class AA {
class BB {
class CC
}
}
fun test(param: foo.bar.baz.<caret>AA.BB.CC) {}
// REF: (foo.bar.baz).AA
| plugins/kotlin/idea/tests/testData/resolve/references/nestedTypes/ResolveTypeInTheStartOfType.kt | 3768034405 |
// 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.execution
import com.intellij.execution.configurations.*
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.text.nullize
import org.jetbrains.annotations.ApiStatus
import java.util.regex.Pattern
/**
* Manages the list of run/debug configurations in a project.
* @see RunnerRegistry
* @see ExecutionManager
*/
abstract class RunManager {
companion object {
@JvmStatic
fun getInstance(project: Project): RunManager {
if (IS_RUN_MANAGER_INITIALIZED.get(project) != true) {
// https://gist.github.com/develar/5bcf39b3f0ec08f507ec112d73375f2b
LOG.warn("Must be not called before project components initialized")
}
return project.getService(RunManager::class.java)
}
@JvmStatic
fun getInstanceIfCreated(project: Project): RunManager? = project.serviceIfCreated()
private const val UNNAMED = "Unnamed"
@JvmField
@ApiStatus.Internal
val IS_RUN_MANAGER_INITIALIZED = Key.create<Boolean>("RunManagerInitialized")
private val LOG = logger<RunManager>()
@JvmStatic
fun suggestUniqueName(str: String, currentNames: Collection<String>): String {
if (!currentNames.contains(str)) {
return str
}
val originalName = extractBaseName(str)
var i = 1
while (true) {
val newName = String.format("%s (%d)", originalName, i)
if (!currentNames.contains(newName)) {
return newName
}
i++
}
}
private val UNIQUE_NAME_PATTERN = Pattern.compile("(.*?)\\s*\\(\\d+\\)")
@JvmStatic
fun extractBaseName(uniqueName: String): String {
val matcher = UNIQUE_NAME_PATTERN.matcher(uniqueName)
return if (matcher.matches()) matcher.group(1) else uniqueName
}
const val CONFIGURATION_TYPE_FEATURE_ID: String = "com.intellij.configurationType"
}
/**
* Returns the list of all configurations of a specified type.
* @param type a run configuration type.
* @return all configurations of the type, or an empty array if no configurations of the type are defined.
*/
abstract fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration>
/**
* Returns the list of [RunnerAndConfigurationSettings] for all configurations of a specified type.
* @param type a run configuration type.
* @return settings for all configurations of the type, or an empty array if no configurations of the type are defined.
*/
@Deprecated("", ReplaceWith("getConfigurationSettingsList(type)"))
@ApiStatus.ScheduledForRemoval
fun getConfigurationSettings(type: ConfigurationType): Array<RunnerAndConfigurationSettings> = getConfigurationSettingsList(type).toTypedArray()
/**
* Returns the list of [RunnerAndConfigurationSettings] for all configurations of a specified type.
*
* Template configuration is not included
* @param type a run configuration type.
* @return settings for all configurations of the type, or an empty array if no configurations of the type are defined.
*/
abstract fun getConfigurationSettingsList(type: ConfigurationType): List<RunnerAndConfigurationSettings>
fun getConfigurationSettingsList(type: Class<out ConfigurationType>): List<RunnerAndConfigurationSettings> {
return getConfigurationSettingsList(ConfigurationTypeUtil.findConfigurationType(type))
}
/**
* Returns the list of all run configurations.
*/
@Deprecated("", ReplaceWith("allConfigurationsList"))
@ApiStatus.ScheduledForRemoval
fun getAllConfigurations(): Array<RunConfiguration> = allConfigurationsList.toTypedArray()
/**
* Returns the list of all run configurations.
*/
abstract val allConfigurationsList: List<RunConfiguration>
/**
* Returns the list of all run configurations settings.
*/
abstract val allSettings: List<RunnerAndConfigurationSettings>
/**
* Returns the list of all temporary run configurations settings.
* @see RunnerAndConfigurationSettings.isTemporary
*/
abstract val tempConfigurationsList: List<RunnerAndConfigurationSettings>
/**
* Saves the specified temporary run settings and makes it a permanent one.
* @param settings the temporary settings to save.
*/
abstract fun makeStable(settings: RunnerAndConfigurationSettings)
/**
* The selected item in the run/debug configurations combobox.
*/
abstract var selectedConfiguration: RunnerAndConfigurationSettings?
/**
* should set selected configuration from context
*/
abstract fun shouldSetRunConfigurationFromContext(): Boolean
abstract fun isRunWidgetActive(): Boolean
/**
* Creates a configuration of the specified type with the specified name. Note that you need to call
* [.addConfiguration] if you want the configuration to be persisted in the project.
* @param name the name of the configuration to create (should be unique and not equal to any other existing configuration)
* @param factory the factory instance.
* @see RunManager.suggestUniqueName
*/
abstract fun createConfiguration(@NlsSafe name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings
fun createConfiguration(name: String, typeClass: Class<out ConfigurationType>): RunnerAndConfigurationSettings {
return createConfiguration(name, ConfigurationTypeUtil.findConfigurationType(typeClass).configurationFactories.first())
}
@Deprecated("", ReplaceWith("createConfiguration(name, factory)"))
fun createRunConfiguration(name: String, factory: ConfigurationFactory) = createConfiguration(name, factory)
/**
* Creates a configuration settings object based on a specified [RunConfiguration]. Note that you need to call
* [addConfiguration] if you want the configuration to be persisted in the project.
* @param runConfiguration the run configuration
* @param factory the factory instance.
*/
abstract fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings
/**
* Returns the template settings for the specified configuration type.
* @param factory the configuration factory.
*/
abstract fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettings
/**
* Adds the specified run configuration to the list of run configurations.
*/
abstract fun addConfiguration(settings: RunnerAndConfigurationSettings)
/**
* This method is deprecated because there are different ways of storing run configuration in a file.
* Clients should use [addConfiguration(RunnerAndConfigurationSettings)] and before that, if needed,
* [RunnerAndConfigurationSettings#storeInDotIdeaFolder()], [RunnerAndConfigurationSettings#storeInArbitraryFileInProject(String)]
* or [RunnerAndConfigurationSettings#storeInLocalWorkspace()].
* @see RunnerAndConfigurationSettings.storeInDotIdeaFolder
* @see RunnerAndConfigurationSettings.storeInArbitraryFileInProject
* @see RunnerAndConfigurationSettings.storeInLocalWorkspace
*/
@Deprecated("There are different ways of storing run configuration in a file. " +
"Clients should use RunManager.addConfiguration(RunnerAndConfigurationSettings) and before that, if needed, " +
"RunnerAndConfigurationSettings.storeInDotIdeaFolder(), storeInArbitraryFileInProject(String) or storeInLocalWorkspace().")
fun addConfiguration(settings: RunnerAndConfigurationSettings, storeInDotIdeaFolder: Boolean) {
if (storeInDotIdeaFolder) {
settings.storeInDotIdeaFolder()
}
else {
settings.storeInLocalWorkspace()
}
addConfiguration(settings)
}
/**
* Marks the specified run configuration as recently used (the temporary run configurations are deleted in LRU order).
* @param profile the run configuration to mark as recently used.
*/
abstract fun refreshUsagesList(profile: RunProfile)
abstract fun hasSettings(settings: RunnerAndConfigurationSettings): Boolean
fun suggestUniqueName(name: String?, type: ConfigurationType?): String {
val settingsList = if (type == null) allSettings else getConfigurationSettingsList(type)
return suggestUniqueName(name.nullize() ?: UNNAMED, settingsList.map { it.name })
}
/**
* Sets unique name if existing one is not 'unique'
* If settings type is not null (for example settings may be provided by plugin that is unavailable after IDE restart, so type would be suddenly null)
* name will be chosen unique for certain type otherwise name will be unique among all configurations
* @return `true` if name was changed
*/
fun setUniqueNameIfNeeded(settings: RunnerAndConfigurationSettings): Boolean {
val oldName = settings.name
settings.name = suggestUniqueName(oldName.takeIf { it.isNotBlank() } ?: UNNAMED, settings.type)
return oldName != settings.name
}
@Deprecated("The method name is grammatically incorrect", replaceWith = ReplaceWith("this.setUniqueNameIfNeeded(settings)"))
@ApiStatus.ScheduledForRemoval
fun setUniqueNameIfNeed(settings: RunnerAndConfigurationSettings): Boolean = setUniqueNameIfNeeded(settings)
/**
* Sets unique name if existing one is not 'unique' for corresponding configuration type
* @return `true` if name was changed
*/
fun setUniqueNameIfNeeded(configuration: RunConfiguration): Boolean {
val oldName = configuration.name
@Suppress("UsePropertyAccessSyntax")
configuration.setName(suggestUniqueName(oldName.takeIf { it.isNotBlank() } ?: UNNAMED, configuration.type))
return oldName != configuration.name
}
abstract fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings?
abstract fun findSettings(configuration: RunConfiguration): RunnerAndConfigurationSettings?
fun findConfigurationByTypeAndName(typeId: String, name: String) = allSettings.firstOrNull { typeId == it.type.id && name == it.name }
fun findConfigurationByTypeAndName(type: ConfigurationType, name: String) = allSettings.firstOrNull { type === it.type && name == it.name }
abstract fun removeConfiguration(settings: RunnerAndConfigurationSettings?)
abstract fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?)
// due to historical reasons findSettings() searches by name in addition to instance and this behavior is bad for isTemplate,
// so, client cannot for now use `findSettings()?.isTemplate() ?: false`.
@ApiStatus.Internal
abstract fun isTemplate(configuration: RunConfiguration): Boolean
} | platform/execution/src/com/intellij/execution/RunManager.kt | 181290114 |
// "Replace with dot call" "true"
// LANGUAGE_VERSION: 1.6
// SHOULD_BE_AVAILABLE_AFTER_EXECUTION
// Note: quick fix is available after the execution due to a separate warning (SAFE_CALL_WILL_CHANGE_NULLABILITY)
class Foo(val bar: Bar)
class Bar(val baz: Baz)
class Baz(val qux: Int)
fun test(foo: Foo) {
foo?.bar?<caret>.baz?.qux
}
/* IGNORE_FIR */ | plugins/kotlin/idea/tests/testData/quickfix/replaceWithDotCall/safeCallChain3.kt | 1474032805 |
package org.thoughtcrime.securesms.avatar.picker
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import org.signal.core.util.ThreadUtil
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.avatar.Avatar
import org.thoughtcrime.securesms.avatar.AvatarBundler
import org.thoughtcrime.securesms.avatar.photo.PhotoEditorFragment
import org.thoughtcrime.securesms.avatar.text.TextAvatarCreationFragment
import org.thoughtcrime.securesms.avatar.vector.VectorAvatarCreationFragment
import org.thoughtcrime.securesms.components.ButtonStripItemView
import org.thoughtcrime.securesms.components.recyclerview.GridDividerDecoration
import org.thoughtcrime.securesms.groups.ParcelableGroupId
import org.thoughtcrime.securesms.mediasend.AvatarSelectionActivity
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.visible
/**
* Primary Avatar picker fragment, displays current user avatar and a list of recently used avatars and defaults.
*/
class AvatarPickerFragment : Fragment(R.layout.avatar_picker_fragment) {
companion object {
const val REQUEST_KEY_SELECT_AVATAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR"
const val SELECT_AVATAR_MEDIA = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_MEDIA"
const val SELECT_AVATAR_CLEAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_CLEAR"
private const val REQUEST_CODE_SELECT_IMAGE = 1
}
private val viewModel: AvatarPickerViewModel by viewModels(factoryProducer = this::createFactory)
private lateinit var recycler: RecyclerView
private fun createFactory(): AvatarPickerViewModel.Factory {
val args = AvatarPickerFragmentArgs.fromBundle(requireArguments())
val groupId = ParcelableGroupId.get(args.groupId)
return AvatarPickerViewModel.Factory(AvatarPickerRepository(requireContext()), groupId, args.isNewGroup, args.groupAvatarMedia)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val toolbar: Toolbar = view.findViewById(R.id.avatar_picker_toolbar)
val cameraButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_camera)
val photoButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_photo)
val textButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_text)
val saveButton: View = view.findViewById(R.id.avatar_picker_save)
val clearButton: View = view.findViewById(R.id.avatar_picker_clear)
recycler = view.findViewById(R.id.avatar_picker_recycler)
recycler.addItemDecoration(GridDividerDecoration(4, ViewUtil.dpToPx(16)))
val adapter = MappingAdapter()
AvatarPickerItem.register(adapter, this::onAvatarClick, this::onAvatarLongClick)
recycler.adapter = adapter
val avatarViewHolder = AvatarPickerItem.ViewHolder(view)
viewModel.state.observe(viewLifecycleOwner) { state ->
if (state.currentAvatar != null) {
avatarViewHolder.bind(AvatarPickerItem.Model(state.currentAvatar, false))
}
clearButton.visible = state.canClear
val wasEnabled = saveButton.isEnabled
saveButton.isEnabled = state.canSave
if (wasEnabled != state.canSave) {
val alpha = if (state.canSave) 1f else 0.5f
saveButton.animate().cancel()
saveButton.animate().alpha(alpha)
}
val items = state.selectableAvatars.map { AvatarPickerItem.Model(it, it == state.currentAvatar) }
val selectedPosition = items.indexOfFirst { it.isSelected }
adapter.submitList(items) {
if (selectedPosition > -1)
recycler.smoothScrollToPosition(selectedPosition)
}
}
toolbar.setNavigationOnClickListener { Navigation.findNavController(it).popBackStack() }
cameraButton.setOnIconClickedListener { openCameraCapture() }
photoButton.setOnIconClickedListener { openGallery() }
textButton.setOnIconClickedListener { openTextEditor(null) }
saveButton.setOnClickListener { v ->
viewModel.save(
{
setFragmentResult(
REQUEST_KEY_SELECT_AVATAR,
Bundle().apply {
putParcelable(SELECT_AVATAR_MEDIA, it)
}
)
ThreadUtil.runOnMain { Navigation.findNavController(v).popBackStack() }
},
{
setFragmentResult(
REQUEST_KEY_SELECT_AVATAR,
Bundle().apply {
putBoolean(SELECT_AVATAR_CLEAR, true)
}
)
ThreadUtil.runOnMain { Navigation.findNavController(v).popBackStack() }
}
)
}
clearButton.setOnClickListener { viewModel.clear() }
setFragmentResultListener(TextAvatarCreationFragment.REQUEST_KEY_TEXT) { _, bundle ->
val text = AvatarBundler.extractText(bundle)
viewModel.onAvatarEditCompleted(text)
}
setFragmentResultListener(VectorAvatarCreationFragment.REQUEST_KEY_VECTOR) { _, bundle ->
val vector = AvatarBundler.extractVector(bundle)
viewModel.onAvatarEditCompleted(vector)
}
setFragmentResultListener(PhotoEditorFragment.REQUEST_KEY_EDIT) { _, bundle ->
val photo = AvatarBundler.extractPhoto(bundle)
viewModel.onAvatarEditCompleted(photo)
}
}
override fun onResume() {
super.onResume()
ViewUtil.hideKeyboard(requireContext(), requireView())
}
@Suppress("DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
val media: Media = requireNotNull(data.getParcelableExtra(AvatarSelectionActivity.EXTRA_MEDIA))
viewModel.onAvatarPhotoSelectionCompleted(media)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun onAvatarClick(avatar: Avatar, isSelected: Boolean) {
if (isSelected) {
openEditor(avatar)
} else {
viewModel.onAvatarSelectedFromGrid(avatar)
}
}
private fun onAvatarLongClick(anchorView: View, avatar: Avatar): Boolean {
val menuRes = when (avatar) {
is Avatar.Photo -> R.menu.avatar_picker_context
is Avatar.Text -> R.menu.avatar_picker_context
is Avatar.Vector -> return true
is Avatar.Resource -> return true
}
val popup = PopupMenu(context, anchorView, Gravity.TOP)
popup.menuInflater.inflate(menuRes, popup.menu)
popup.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_delete -> viewModel.delete(avatar)
}
true
}
popup.show()
return true
}
fun openEditor(avatar: Avatar) {
when (avatar) {
is Avatar.Photo -> openPhotoEditor(avatar)
is Avatar.Resource -> throw UnsupportedOperationException()
is Avatar.Text -> openTextEditor(avatar)
is Avatar.Vector -> openVectorEditor(avatar)
}
}
private fun openPhotoEditor(photo: Avatar.Photo) {
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToAvatarPhotoEditorFragment(AvatarBundler.bundlePhoto(photo)))
}
private fun openVectorEditor(vector: Avatar.Vector) {
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToVectorAvatarCreationFragment(AvatarBundler.bundleVector(vector)))
}
private fun openTextEditor(text: Avatar.Text?) {
val bundle = if (text != null) AvatarBundler.bundleText(text) else null
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToTextAvatarCreationFragment(bundle))
}
@Suppress("DEPRECATION")
private fun openCameraCapture() {
Permissions.with(this)
.request(Manifest.permission.CAMERA)
.ifNecessary()
.onAllGranted {
val intent = AvatarSelectionActivity.getIntentForCameraCapture(requireContext())
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE)
}
.onAnyDenied {
Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__taking_a_photo_requires_the_camera_permission, Toast.LENGTH_SHORT)
.show()
}
.execute()
}
@Suppress("DEPRECATION")
private fun openGallery() {
Permissions.with(this)
.request(Manifest.permission.READ_EXTERNAL_STORAGE)
.ifNecessary()
.onAllGranted {
val intent = AvatarSelectionActivity.getIntentForGallery(requireContext())
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE)
}
.onAnyDenied {
Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__viewing_your_gallery_requires_the_storage_permission, Toast.LENGTH_SHORT)
.show()
}
.execute()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
}
}
| app/src/main/java/org/thoughtcrime/securesms/avatar/picker/AvatarPickerFragment.kt | 3042557383 |
package org.signal.contactstest
import android.app.Service
import android.content.Intent
import android.os.IBinder
class ContactsSyncAdapterService : Service() {
@Synchronized
override fun onCreate() {
if (syncAdapter == null) {
syncAdapter = ContactsSyncAdapter(this, true)
}
}
override fun onBind(intent: Intent): IBinder? {
return syncAdapter!!.syncAdapterBinder
}
companion object {
private var syncAdapter: ContactsSyncAdapter? = null
}
}
| contacts/app/src/main/java/org/signal/contactstest/ContactsSyncAdapterService.kt | 2649443779 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUExpressionList
import org.jetbrains.uast.java.internal.JavaUElementWithComments
import org.jetbrains.uast.java.kinds.JavaSpecialExpressionKinds
abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, JvmDeclarationUElement {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUElement(givenParent)", ReplaceWith("JavaAbstractUElement(givenParent)"))
constructor() : this(null)
override fun equals(other: Any?): Boolean {
if (other !is UElement || other.javaClass != this.javaClass) return false
return if (this.psi != null) this.psi == other.psi else this === other
}
override fun hashCode(): Int = psi?.hashCode() ?: System.identityHashCode(this)
override fun asSourceString(): String {
return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString()
}
override fun toString(): String = asRenderString()
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
protected open fun convertParent(): UElement? =
getPsiParentForLazyConversion()
?.let { JavaConverter.unwrapElements(it).toUElement() }
?.let { unwrapSwitch(it) }
?.also {
if (it === this) throw IllegalStateException("lazy parent loop for $this")
if (it.psi != null && it.psi === this.psi)
throw IllegalStateException("lazy parent loop: psi ${this.psi}(${this.psi?.javaClass}) for $this of ${this.javaClass}")
}
protected open fun getPsiParentForLazyConversion(): PsiElement? = this.psi?.parent
//explicitly overridden in abstract class to be binary compatible with Kotlin
override val comments: List<UComment>
get() = super<JavaUElementWithComments>.comments
override val sourcePsi: PsiElement?
get() = super<JavaUElementWithComments>.sourcePsi
override val javaPsi: PsiElement?
get() = super<JavaUElementWithComments>.javaPsi
}
private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement {
when (uParent) {
is JavaUCodeBlockExpression -> {
val codeBlockParent = uParent.uastParent
if (codeBlockParent is JavaUExpressionList && codeBlockParent.kind == JavaSpecialExpressionKinds.SWITCH) {
if (branchHasElement(psi, codeBlockParent.psi) { it is PsiSwitchLabelStatement }) {
return codeBlockParent
}
val uSwitchExpression = codeBlockParent.uastParent as? JavaUSwitchExpression ?: return uParent
val psiElement = psi ?: return uParent
return findUSwitchClauseBody(uSwitchExpression, psiElement) ?: return codeBlockParent
}
if (codeBlockParent is JavaUSwitchExpression) {
return unwrapSwitch(codeBlockParent)
}
return uParent
}
is USwitchExpression -> {
val parentPsi = uParent.psi as PsiSwitchStatement
return if (this === uParent.body || branchHasElement(psi, parentPsi) { it === parentPsi.expression })
uParent
else
uParent.body
}
else -> return uParent
}
}
private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean {
var current: PsiElement? = child;
while (current != null && current != parent) {
if (predicate(current)) return true
current = current.parent
}
return false
}
abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUExpression(givenParent)", ReplaceWith("JavaAbstractUExpression(givenParent)"))
constructor() : this(null)
override fun evaluate(): Any? {
val project = psi?.project ?: return null
return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi)
}
override val annotations: List<UAnnotation>
get() = emptyList()
override fun getExpressionType(): PsiType? {
val expression = psi as? PsiExpression ?: return null
return expression.type
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceExpression -> it.parent
is PsiReferenceExpression -> (it.parent as? PsiMethodCallExpression) ?: it
else -> it
}
}
override fun convertParent(): UElement? = super.convertParent().let { uParent ->
when (uParent) {
is UAnonymousClass -> uParent.uastParent
else -> uParent
}
}.let(this::unwrapCompositeQualifiedReference)
}
| uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt | 3434757740 |
/*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.kotlinsql.monadic.actions
import io.github.pdvrieze.kotlinsql.ddl.Database
import io.github.pdvrieze.kotlinsql.dml.SelectStatement
import io.github.pdvrieze.kotlinsql.monadic.impl.SelectResultsetRow
interface SelectAction<DB : Database, S : SelectStatement>:
ResultSetWrapperProducingAction<DB, SelectResultsetRow<S>> {
val query: S
} | monadic/src/main/kotlin/io/github/pdvrieze/kotlinsql/monadic/actions/SelectAction.kt | 1833162959 |
package com.beust.kobalt.maven.aether
import com.beust.kobalt.misc.KobaltLogger
import com.beust.kobalt.misc.log
import org.eclipse.aether.transfer.AbstractTransferListener
import org.eclipse.aether.transfer.MetadataNotFoundException
import org.eclipse.aether.transfer.TransferEvent
import org.eclipse.aether.transfer.TransferResource
import java.io.PrintStream
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class ConsoleTransferListener @JvmOverloads constructor(out: PrintStream? = null) : AbstractTransferListener() {
private val out: PrintStream
private val downloads = ConcurrentHashMap<TransferResource, Long>()
private var lastLength: Int = 0
init {
this.out = out ?: System.out
}
override fun transferInitiated(event: TransferEvent?) {
val message = if (event!!.requestType == TransferEvent.RequestType.PUT) "Uploading" else "Downloading"
log(2, message + ": " + event.resource.repositoryUrl + event.resource.resourceName)
}
override fun transferProgressed(event: TransferEvent?) {
val resource = event!!.resource
downloads.put(resource, java.lang.Long.valueOf(event.transferredBytes))
val buffer = StringBuilder(64)
for (entry in downloads.entries) {
val total = entry.key.contentLength
val complete = entry.value.toLong()
buffer.append(getStatus(complete, total)).append(" ")
}
val pad = lastLength - buffer.length
lastLength = buffer.length
pad(buffer, pad)
buffer.append('\r')
out.print(buffer)
}
private fun getStatus(complete: Long, total: Long): String {
if (total >= 1024) {
return toKB(complete).toString() + "/" + toKB(total) + " KB "
} else if (total >= 0) {
return complete.toString() + "/" + total + " B "
} else if (complete >= 1024) {
return toKB(complete).toString() + " KB "
} else {
return complete.toString() + " B "
}
}
private fun pad(buffer: StringBuilder, spaces: Int) {
var spaces = spaces
val block = " "
while (spaces > 0) {
val n = Math.min(spaces, block.length)
buffer.append(block, 0, n)
spaces -= n
}
}
override fun transferSucceeded(event: TransferEvent) {
transferCompleted(event)
val resource = event.resource
val contentLength = event.transferredBytes
if (contentLength >= 0) {
val type = if (event.requestType == TransferEvent.RequestType.PUT) "Uploaded" else "Downloaded"
val len = if (contentLength >= 1024) toKB(contentLength).toString() + " KB"
else contentLength.toString() + " B"
var throughput = ""
val duration = System.currentTimeMillis() - resource.transferStartTime
if (duration > 0) {
val bytes = contentLength - resource.resumeOffset
val format = DecimalFormat("0.0", DecimalFormatSymbols(Locale.ENGLISH))
val kbPerSec = bytes / 1024.0 / (duration / 1000.0)
throughput = " at " + format.format(kbPerSec) + " KB/sec"
}
log(2, type + ": " + resource.repositoryUrl + resource.resourceName + " (" + len
+ throughput + ")")
}
}
override fun transferFailed(event: TransferEvent) {
transferCompleted(event)
if (event.exception !is MetadataNotFoundException) {
if (KobaltLogger.LOG_LEVEL > 1) {
event.exception.printStackTrace(out)
}
}
}
private fun transferCompleted(event: TransferEvent) {
downloads.remove(event.resource)
val buffer = StringBuilder(64)
pad(buffer, lastLength)
buffer.append('\r')
out.print(buffer)
}
override fun transferCorrupted(event: TransferEvent?) {
event!!.exception.printStackTrace(out)
}
protected fun toKB(bytes: Long): Long {
return (bytes + 1023) / 1024
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/ConsoleTransferListener.kt | 3058463796 |
package com.contentful.java.cma
import com.contentful.java.cma.Constants.CMAFieldType
import com.contentful.java.cma.lib.TestUtils
import com.contentful.java.cma.model.CMAField
import com.google.gson.Gson
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import java.lang.reflect.InvocationTargetException
import java.util.logging.LogManager
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import org.junit.Test as test
class GeneralTests{
var server: MockWebServer? = null
var client: CMAClient? = null
var gson: Gson? = null
@Before
fun setUp() {
LogManager.getLogManager().reset()
// MockWebServer
server = MockWebServer()
server!!.start()
// Client
client = CMAClient.Builder()
.setAccessToken("token")
.setCoreEndpoint(server!!.url("/").toString())
.setUploadEndpoint(server!!.url("/").toString())
.setSpaceId("configuredSpaceId")
.setEnvironmentId("configuredEnvironmentId")
.build()
gson = CMAClient.createGson()
}
@After
fun tearDown() {
server!!.shutdown()
}
@test
fun testGsonInstanceRetained() {
assertTrue(CMAClient.createGson() === CMAClient.createGson())
}
@test
fun testFieldSerialization() {
val field = gson!!.fromJson(
TestUtils.fileToString("field_object.json"),
CMAField::class.java)
assertTrue(field.isRequired)
assertTrue(field.isDisabled)
assertTrue(field.isOmitted)
// True
var json = gson!!.toJsonTree(field, CMAField::class.java).asJsonObject
assertTrue(json.has("required"))
assertTrue(json.has("disabled"))
assertTrue(json.has("omitted"))
// False
field.isRequired = false
field.isDisabled = false
field.isOmitted = false
// General attributes
json = gson!!.toJsonTree(field, CMAField::class.java).asJsonObject
assertEquals("fieldname", json.get("name").asString)
assertEquals("fieldid", json.get("id").asString)
assertEquals("Text", json.get("type").asString)
}
@test
fun testFieldArraySerialization() {
val field = CMAField().setType(CMAFieldType.Array)
.setArrayItems(mapOf(Pair("type", CMAFieldType.Symbol.toString())))
val json = gson!!.toJsonTree(field, CMAField::class.java).asJsonObject
assertEquals("Array", json.get("type").asString)
val items = json.get("items").asJsonObject
assertEquals("Symbol", items.get("type").asString)
}
@test
fun testConstantsThrowsUnsupportedException() {
assertPrivateConstructor(Constants::class.java)
}
@test
fun testRxExtensionsThrowsUnsupportedException() {
assertPrivateConstructor(RxExtensions::class.java)
}
fun assertPrivateConstructor(clazz: Class<out Any>) {
val constructor = clazz.getDeclaredConstructor()
constructor.isAccessible = true
val exception = try {
constructor.newInstance()
} catch (e: Exception) {
e
}
assertNotNull(exception)
assertTrue(exception is InvocationTargetException)
assertTrue((exception as InvocationTargetException).cause is
UnsupportedOperationException)
}
}
| src/test/kotlin/com/contentful/java/cma/GeneralTests.kt | 1733863211 |
package ch.abertschi.adfree.crashhandler
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.view.View
import android.widget.TextView
import ch.abertschi.adfree.R
import android.widget.Toast
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.warn
import java.io.File
import java.lang.Exception
import android.content.Intent
import org.jetbrains.anko.info
// TODO: refator this into presenter and view
class SendCrashReportActivity : AppCompatActivity(), View.OnClickListener, AnkoLogger {
companion object {
val ACTION_NAME = "ch.abertschi.adfree.SEND_LOG_CRASH"
val EXTRA_LOGFILE = "ch.abertschi.adfree.extra.logfile"
val EXTRA_SUMMARY = "ch.abertschi.adfree.extra.summary"
val MAIL_ADDR = "[email protected]"
val SUBJECT = "[ad-free-crash-report]"
}
private var logfile: String? = null
private var summary: String? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
parseIntent(this.intent)
doOnCreate()
} catch (e: Exception) {
warn(e)
Toast.makeText(this, "Error: $e", Toast.LENGTH_LONG).show()
}
}
fun parseIntent(i: Intent?) {
logfile = i?.extras?.getString(EXTRA_LOGFILE)
summary = i?.extras?.getString(EXTRA_SUMMARY) ?: ""
}
fun sendReport() {
try {
val file = File(applicationContext.filesDir, logfile)
val log = file.readText()
info { "sending report with $file $log" }
launchSendIntent(summary!!)
} catch (e: Exception) {
warn { e }
}
}
private fun launchSendIntent(msg: String) {
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(MAIL_ADDR))
sendIntent.putExtra(Intent.EXTRA_TEXT, msg)
sendIntent.putExtra(Intent.EXTRA_SUBJECT, SUBJECT)
sendIntent.type = "text/plain"
this.applicationContext
.startActivity(Intent.createChooser(sendIntent, "Choose an Email client"))
}
private fun doOnCreate() {
setupUI()
}
// TODO: Send logcat output and summary
private fun setupUI() {
setContentView(R.layout.crash_view)
setFinishOnTouchOutside(false)
val v = findViewById(R.id.crash_container) as View
v.setOnClickListener(this)
var typeFace: Typeface = Typeface.createFromAsset(baseContext.assets, "fonts/Raleway-ExtraLight.ttf")
val title = findViewById(R.id.crash_Title) as TextView
title.typeface = typeFace
title.setOnClickListener(this)
val text =
"success is not final, failure is not fatal: it is the " +
"<font color=#FFFFFF>courage</font> to <font color=#FFFFFF>continue</font> that counts. -- " +
"Winston Churchill"
title?.text = Html.fromHtml(text)
val subtitle = findViewById(R.id.debugSubtitle) as TextView
subtitle.typeface = typeFace
subtitle.setOnClickListener(this)
val subtitletext =
"<font color=#FFFFFF>ad-free</font> crashed. be courageous and continue. " +
"send the <font color=#FFFFFF>crash report </font>. tab here, choose your mail application and send the report.</font>"
subtitle.text = Html.fromHtml(subtitletext)
}
override fun onClick(v: View) {
info { "clicking view for crashreport" }
logfile?.let {
try {
sendReport()
} catch (e: Exception) {
warn { "cant send crash report" }
warn { e }
e.printStackTrace()
Toast.makeText(this, "No crash report available.",
Toast.LENGTH_LONG).show()
}
} ?: run {
Toast.makeText(this, "No crash report available.",
Toast.LENGTH_LONG).show()
}
}
} | app/src/main/java/ch/abertschi/adfree/crashhandler/SendCrashReportActivity.kt | 2152140015 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
import io.ktor.client.plugins.json.*
import io.ktor.client.plugins.kotlinx.serializer.*
import io.ktor.http.*
import io.ktor.http.content.*
import kotlinx.serialization.json.*
import kotlin.test.*
@Suppress("DEPRECATION")
class CollectionsSerializationTest {
private val testSerializer = KotlinxSerializer()
@Test
fun testJsonElements() {
testSerializer.testWrite(
buildJsonObject {
put("a", "1")
put(
"b",
buildJsonObject {
put("c", 3)
}
)
put("x", JsonNull)
}
).let { result ->
assertEquals("""{"a":"1","b":{"c":3},"x":null}""", result)
}
testSerializer.testWrite(
buildJsonObject {
put("a", "1")
put(
"b",
buildJsonArray {
add("c")
add(JsonPrimitive(2))
}
)
}
).let { result ->
assertEquals("""{"a":"1","b":["c",2]}""", result)
}
}
@Test
fun testMapsElements() {
testSerializer.testWrite(
mapOf(
"a" to "1",
"b" to "2"
)
).let { result ->
assertEquals("""{"a":"1","b":"2"}""", result)
}
testSerializer.testWrite(
mapOf(
"a" to "1",
"b" to null
)
).let { result ->
assertEquals("""{"a":"1","b":null}""", result)
}
testSerializer.testWrite(
mapOf(
"a" to "1",
null to "2"
)
).let { result ->
assertEquals("""{"a":"1",null:"2"}""", result)
}
// this is not yet supported
assertFails {
testSerializer.testWrite(
mapOf(
"a" to "1",
"b" to 2
)
)
}
}
private fun JsonSerializer.testWrite(data: Any): String =
(write(data, ContentType.Application.Json) as? TextContent)?.text ?: error("Failed to get serialized $data")
}
| ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/test/CollectionsSerializationTest.kt | 1947320058 |
package com.androidarchitecture.data.auth
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import javax.inject.Inject
class AuthRestJsonInterceptor @Inject
constructor(private val mAuthorizationService: AuthorizationService) : Interceptor {
companion object {
private val CONTENT_TYPE_JSON = "application/json; charset=utf-8"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
// Customize the request
val builder = original.newBuilder()
.header("CONTENT_TYPE", CONTENT_TYPE_JSON)
val token = mAuthorizationService.mTokenStore.userToken
if (token != null) {
builder.header("AUTHORIZATION", token.accessToken)
}
val request = builder.build()
// Customize or return the response
return chain.proceed(request)
}
}
| app/src/main/java/com/androidarchitecture/data/auth/AuthRestJsonInterceptor.kt | 496907072 |
package com.atslangplugin
//TODO: static import these
import com.atslangplugin.psi.ATSTokenTypes
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors.*
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import java.util.*
class ATSSyntaxHighlighter : SyntaxHighlighterBase() {
companion object {
// this interface seems like it could be more concise, see MakefileSyntaxHighlighter.kt
val ATS_BLOCK_COMMENT = createTextAttributesKey("BLOCK_COMMENT", BLOCK_COMMENT)
val ATS_BRACES = createTextAttributesKey("BRACES", BRACES)
val ATS_BRACKETS = createTextAttributesKey("BRACKETS", BRACKETS)
val ATS_COMMA = createTextAttributesKey("COMMA", COMMA)
val ATS_DIRECTIVES = createTextAttributesKey("DIRECTIVES", PREDEFINED_SYMBOL)
val ATS_DOC_COMMENT = createTextAttributesKey("DOC_COMMENT", DOC_COMMENT)
val ATS_EXTERNAL_CODE = createTextAttributesKey("EXTERNAL_CODE", TEMPLATE_LANGUAGE_COLOR)
val ATS_FUNCTION_CALL = createTextAttributesKey("FUNCTION_CALL", FUNCTION_CALL)
val ATS_IDENTIFIER = createTextAttributesKey("IDENTIFIER", IDENTIFIER)
val ATS_LINE_COMMENT = createTextAttributesKey("LINE_COMMENT", LINE_COMMENT)
val ATS_KEYWORD = createTextAttributesKey("KEYWORD", KEYWORD)
val ATS_LOCAL_VARIABLE = createTextAttributesKey("LOCAL_VARIABLE", LOCAL_VARIABLE)
val ATS_NUMBER = createTextAttributesKey("NUMBER", NUMBER)
val ATS_OPERATION_SIGN = createTextAttributesKey("OPERATION_SIGN", OPERATION_SIGN)
val ATS_PARENTHESES = createTextAttributesKey("PARENTHESES", PARENTHESES)
val ATS_REST_COMMENT = createTextAttributesKey("REST_COMMENT", BLOCK_COMMENT)
val ATS_SEMICOLON = createTextAttributesKey("SEMICOLON", SEMICOLON)
val ATS_STRING = createTextAttributesKey("STRING", STRING)
val ATS_TYPE_DECLARATIONS = createTextAttributesKey("TYPE_DECLARATIONS", KEYWORD)
val ATS_VAL_DECLARATIONS = createTextAttributesKey("VAL_DECLARATIONS", INSTANCE_FIELD)
val ATS_INVALID_STRING_ESCAPE = createTextAttributesKey("INVALID_STRING_ESCAPE", INVALID_STRING_ESCAPE)
val ATS_VALID_STRING_ESCAPE = createTextAttributesKey("VALID_STRING_ESCAPE", VALID_STRING_ESCAPE)
private val EMPTY_KEYS = emptyArray<TextAttributesKey>()
private val ATS_BLOCK_COMMENT_KEYS = arrayOf(ATS_BLOCK_COMMENT)
private val ATS_BRACES_KEYS = arrayOf(ATS_BRACES)
private val ATS_BRACKETS_KEYS = arrayOf(ATS_BRACKETS)
private val ATS_COMMA_KEYS = arrayOf(ATS_COMMA)
private val ATS_DOC_COMMENT_KEYS = arrayOf(ATS_DOC_COMMENT)
private val ATS_DIRECTIVES_KEYS = arrayOf(ATS_DIRECTIVES)
private val ATS_EXTERNAL_CODE_KEYS = arrayOf(ATS_EXTERNAL_CODE)
private val ATS_FUNCTION_CALL_KEYS = arrayOf(ATS_FUNCTION_CALL)
private val ATS_IDENTIFIER_KEYS = arrayOf(ATS_IDENTIFIER)
private val ATS_LINE_COMMENT_KEYS = arrayOf(ATS_LINE_COMMENT)
private val ATS_KEYWORD_KEYS = arrayOf(ATS_KEYWORD)
private val ATS_LOCAL_VARIABLE_KEYS = arrayOf(ATS_LOCAL_VARIABLE)
private val ATS_NUMBER_KEYS = arrayOf(ATS_NUMBER)
private val ATS_OPERATION_SIGN_KEYS = arrayOf(ATS_OPERATION_SIGN)
private val ATS_PARENTHESES_KEYS = arrayOf(ATS_PARENTHESES)
private val ATS_REST_COMMENT_KEYS = arrayOf(ATS_REST_COMMENT)
private val ATS_SEMICOLON_KEYS = arrayOf(ATS_SEMICOLON)
private val ATS_STRING_KEYS = arrayOf(ATS_STRING)
private val ATS_TYPE_DECLARATIONS_KEYS = arrayOf(ATS_TYPE_DECLARATIONS)
private val ATS_VAL_DECLARATIONS_KEYS = arrayOf(ATS_VAL_DECLARATIONS)
private val tokenColorMap: Map<IElementType, Array<TextAttributesKey>>
//TODO: bake this into the function so it is more concise and readable
init {
val tmpMap = HashMap<IElementType, Array<TextAttributesKey>>()
tmpMap.put(ATSTokenTypes.ABSTYPE, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.ADDRAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.AND, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.AS, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.ASSUME, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.AT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.ATLBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.ATLPAREN, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.BACKSLASH, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BANG, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BAR, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BEGIN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.BQUOTE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.CASE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.CHAR, ATS_STRING_KEYS)
tmpMap.put(ATSTokenTypes.CLASSDEC, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.COLON, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.COLONLT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.COMMA, ATS_COMMA_KEYS)
tmpMap.put(ATSTokenTypes.COMMALPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_BLOCK, ATS_BLOCK_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_DOC, ATS_DOC_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_LINE, ATS_LINE_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_REST, ATS_REST_COMMENT_KEYS)
// Do not want to color CRLF
tmpMap.put(ATSTokenTypes.DATASORT, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.DLRARRPSZ, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.DLRBREAK, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRCONTINUE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRDELAY, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREFFMASK, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREFFMASK_ARG, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTERN, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTFCALL, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTVAL, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTYPE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTYPE_STRUCT, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRLST, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYFILENAME, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYFILENAME, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYLOCATION, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRRAISE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRREC, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRSHOWTYPE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRTUP, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRTEMPENVER, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRVCOPYENV, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DO, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DOLLAR, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTDOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTDOTDOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTINT, ATS_OPERATION_SIGN_KEYS) // what is it?
tmpMap.put(ATSTokenTypes.DOTLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DOTLTGTDOT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SRPDYNLOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.ELSE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.END, ATS_KEYWORD_KEYS)
// don't color EOF
tmpMap.put(ATSTokenTypes.EQ, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQGTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQLT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQLTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQSLASHEQGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQSLASHEQGTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EXCEPTION, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.EXTCODE_CLOSE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.EXTERN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.EXTVAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FIX, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FIXITY, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FLOAT, ATS_NUMBER_KEYS)
tmpMap.put(ATSTokenTypes.FOLDAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FORSTAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FREEAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FUN, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.GT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.GTDOT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.GTLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.HASH, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.HASHLBRACKETOLON, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.IF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IMPLEMENT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IMPORT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.INT, ATS_NUMBER_KEYS)
tmpMap.put(ATSTokenTypes.LAM, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.LBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.LBRACKET, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.LET, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.LOCAL, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.LPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.LT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.MACDEF, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.MINUSGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.MINUSLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.MINUSLTGT, ATS_KEYWORD_KEYS)
// NONE isn't used here
tmpMap.put(ATSTokenTypes.NONFIX, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OP, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OVERLOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.PERCENT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.PERCENTLPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.QMARK, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELBRACKET, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.RBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.RBRACKET, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.REC, ATS_TYPE_DECLARATIONS_KEYS) // recursive
tmpMap.put(ATSTokenTypes.REFAT, ATS_FUNCTION_CALL_KEYS) // CHECK_ME
tmpMap.put(ATSTokenTypes.REF_IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.REQUIRE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.RPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.SCASE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SEMICOLON, ATS_SEMICOLON_KEYS)
tmpMap.put(ATSTokenTypes.SIF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SORTDEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SRPASSERT, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPDEFINE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIFDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIFNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELSE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPENDIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPERROR, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIFDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIFNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPINCLUDE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPPRINT, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPTHEN, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPUNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.STACST, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.STADEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SRPSTALOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.STATIC, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.STRING, ATS_STRING_KEYS)
tmpMap.put(ATSTokenTypes.SYMELIM, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SYMINTR, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.THEN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.TILDE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.TKINDEF, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.TRY, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.TYPE, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.TYPEDEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.VAL, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.VAL_IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.VIEWAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHEN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHERE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHILE, ATS_KEYWORD_KEYS)
// do not color WHITESPACE
tmpMap.put(ATSTokenTypes.WHILESTAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WITH, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WITHTYPE, ATS_KEYWORD_KEYS)
tokenColorMap = tmpMap
}
}
override fun getTokenHighlights(tokenType: IElementType) = when (tokenType) {
// MakefileTypes.DOC_COMMENT -> DOCCOMMENT_KEYS
// MakefileTypes.COMMENT -> COMMENT_KEYS
// MakefileTypes.TARGET -> TARGET_KEYS
// MakefileTypes.COLON, MakefileTypes.DOUBLECOLON, MakefileTypes.ASSIGN, MakefileTypes.SEMICOLON, MakefileTypes.PIPE -> SEPARATOR_KEYS
// MakefileTypes.KEYWORD_INCLUDE, MakefileTypes.KEYWORD_IFEQ, MakefileTypes.KEYWORD_IFNEQ, MakefileTypes.KEYWORD_IFDEF, MakefileTypes.KEYWORD_IFNDEF, MakefileTypes.KEYWORD_ELSE, MakefileTypes.KEYWORD_ENDIF, MakefileTypes.KEYWORD_DEFINE, MakefileTypes.KEYWORD_ENDEF, MakefileTypes.KEYWORD_UNDEFINE, MakefileTypes.KEYWORD_OVERRIDE, MakefileTypes.KEYWORD_EXPORT, MakefileTypes.KEYWORD_PRIVATE, MakefileTypes.KEYWORD_VPATH -> KEYWORD_KEYS
// MakefileTypes.PREREQUISITE -> PREREQUISITE_KEYS
// MakefileTypes.VARIABLE -> VARIABLE_KEYS
// MakefileTypes.VARIABLE_VALUE -> VARIABLE_VALUE_KEYS
// MakefileTypes.SPLIT -> LINE_SPLIT_KEYS
// MakefileTypes.TAB -> TAB_KEYS
// TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS
ATSTokenTypes.EXTCODE -> ATS_EXTERNAL_CODE_KEYS
ATSTokenTypes.DATATYPE -> ATS_TYPE_DECLARATIONS_KEYS
else -> tokenColorMap.getOrDefault(tokenType,EMPTY_KEYS) //TODO: remove the map in favor of the cleaner syntax
}
override fun getHighlightingLexer(): Lexer {
return FlexAdapter(ATSLexer(null))
}
}
| src/main/kotlin/com/atslangplugin/ATSSyntaxHighlighter.kt | 393692058 |
import io.ktor.client.engine.*
import io.ktor.client.request.*
import io.ktor.util.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
internal object TestEngine : HttpClientEngine {
override val dispatcher: CoroutineDispatcher
get() = Dispatchers.Default
override val config: HttpClientEngineConfig = HttpClientEngineConfig()
@InternalAPI
override suspend fun execute(data: HttpRequestData): HttpResponseData {
TODO("Not yet implemented")
}
override val coroutineContext: CoroutineContext
get() = Job()
override fun close() {
}
}
| ktor-client/ktor-client-core/common/test/TestEngine.kt | 3553597211 |
package com.airbnb.lottie.compose
import android.graphics.Rect
import androidx.collection.LongSparseArray
import androidx.collection.SparseArrayCompat
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.model.Marker
import org.junit.Assert.*
import org.junit.Test
class LottieClipSpecTest {
@Test
fun testMinFrame() {
val spec = LottieClipSpec.Frame(min = 20)
val composition = createComposition(endFrame = 40f)
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(1f, spec.getMaxProgress(composition))
}
@Test
fun testMaxFrame() {
val spec = LottieClipSpec.Frame(max = 20)
val composition = createComposition(endFrame = 40f)
assertEquals(0f, spec.getMinProgress(composition))
assertEquals(0.5f, spec.getMaxProgress(composition))
}
@Test
fun testMaxFrameNotInclusive() {
val spec = LottieClipSpec.Frame(max = 20, maxInclusive = false)
val composition = createComposition(endFrame = 40f)
assertEquals(0f, spec.getMinProgress(composition))
assertEquals(0.475f, spec.getMaxProgress(composition))
}
@Test
fun testMinAndMaxFrame() {
val spec = LottieClipSpec.Frame(min = 20, max = 30)
val composition = createComposition(endFrame = 40f)
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.75f, spec.getMaxProgress(composition))
}
@Test
fun testMinAndMaxFrameNotExclusive() {
val spec = LottieClipSpec.Frame(min = 20, max = 30, maxInclusive = false)
val composition = createComposition(endFrame = 40f)
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.725f, spec.getMaxProgress(composition))
}
@Test
fun testMinProgress() {
val spec = LottieClipSpec.Progress(min = 0.5f)
val composition = createComposition(endFrame = 40f)
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(1f, spec.getMaxProgress(composition))
}
@Test
fun testMaxProgress() {
val spec = LottieClipSpec.Progress(max = 0.5f)
val composition = createComposition(endFrame = 40f)
assertEquals(0f, spec.getMinProgress(composition))
assertEquals(0.5f, spec.getMaxProgress(composition))
}
@Test
fun testMinAndMaxProgress() {
val spec = LottieClipSpec.Progress(min = 0.5f, max = 0.75f)
val composition = createComposition(endFrame = 40f)
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.75f, spec.getMaxProgress(composition))
}
@Test
fun testMinMarker() {
val spec = LottieClipSpec.Markers(min = "start")
val composition = createComposition(endFrame = 40f, listOf(Marker("start", 20f, 10f)))
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(1f, spec.getMaxProgress(composition))
}
@Test
fun testMaxMarker() {
val spec = LottieClipSpec.Markers(max = "end")
val composition = createComposition(endFrame = 40f, listOf(Marker("end", 20f, 10f)))
assertEquals(0f, spec.getMinProgress(composition))
assertEquals(0.5f, spec.getMaxProgress(composition))
}
@Test
fun testMaxMarkerExclusive() {
val spec = LottieClipSpec.Markers(max = "end", maxInclusive = false)
val composition = createComposition(endFrame = 40f, listOf(Marker("end", 20f, 10f)))
assertEquals(0f, spec.getMinProgress(composition))
assertEquals(0.475f, spec.getMaxProgress(composition))
}
@Test
fun testMinAndMaxMarker() {
val spec = LottieClipSpec.Markers(min = "start", max = "end")
val composition = createComposition(endFrame = 40f, listOf(Marker("start", 20f, 10f), Marker("end", 30f, 10f)))
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.75f, spec.getMaxProgress(composition))
}
@Test
fun testMinAndMaxMarkerExclusive() {
val spec = LottieClipSpec.Markers(min = "start", max = "end", maxInclusive = false)
val composition = createComposition(endFrame = 40f, listOf(Marker("start", 20f, 10f), Marker("end", 30f, 10f)))
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.725f, spec.getMaxProgress(composition))
}
@Test
fun testMarker() {
val spec = LottieClipSpec.Marker("span")
val composition = createComposition(endFrame = 40f, listOf(Marker("span", 20f, 10f)))
assertEquals(0.5f, spec.getMinProgress(composition))
assertEquals(0.75f, spec.getMaxProgress(composition))
}
private fun createComposition(endFrame: Float, markers: List<Marker> = emptyList()): LottieComposition {
val composition = LottieComposition()
composition.init(
Rect(),
0f,
endFrame,
30f,
emptyList(),
LongSparseArray(),
emptyMap(),
emptyMap(),
SparseArrayCompat(),
emptyMap(),
markers,
)
return composition
}
} | lottie-compose/src/test/java/com/airbnb/lottie/compose/LottieClipSpecTest.kt | 2713250733 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.