repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitter.kt | 4 | 2331 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.*
import org.jetbrains.annotations.Nls
class ChangeListCommitState(val changeList: LocalChangeList, val changes: List<Change>, val commitMessage: String) {
internal fun copy(commitMessage: String): ChangeListCommitState =
if (this.commitMessage == commitMessage) this else ChangeListCommitState(changeList, changes, commitMessage)
}
class SingleChangeListCommitter
@Deprecated("Prefer using SingleChangeListCommitter.create",
replaceWith = ReplaceWith("SingleChangeListCommitter.create(project, commitState, commitContext, localHistoryActionName)"))
constructor(
project: Project,
commitState: ChangeListCommitState,
commitContext: CommitContext,
localHistoryActionName: @Nls String,
isDefaultChangeListFullyIncluded: Boolean
) : LocalChangesCommitter(project, commitState, commitContext, localHistoryActionName) {
@Deprecated("Prefer using CommitterResultHandler")
fun addResultHandler(resultHandler: CommitResultHandler) {
addResultHandler(CommitResultHandlerNotifier(this, resultHandler))
}
init {
addResultHandler(EmptyChangeListDeleter(this))
}
companion object {
@JvmStatic
fun create(project: Project,
commitState: ChangeListCommitState,
commitContext: CommitContext,
localHistoryActionName: @Nls String): LocalChangesCommitter {
val committer = LocalChangesCommitter(project, commitState, commitContext, localHistoryActionName)
committer.addResultHandler(EmptyChangeListDeleter(committer))
return committer
}
}
}
private class EmptyChangeListDeleter(val committer: LocalChangesCommitter) : CommitterResultHandler {
override fun onAfterRefresh() {
if (committer.isSuccess) {
val changeListManager = ChangeListManagerImpl.getInstanceImpl(committer.project)
val listName = committer.commitState.changeList.name
val localList = changeListManager.findChangeList(listName) ?: return
if (!localList.isDefault) {
changeListManager.scheduleAutomaticEmptyChangeListDeletion(localList)
}
}
}
}
| apache-2.0 | 5a981e2ad2cfb0128cdea0ab19911966 | 39.189655 | 140 | 0.773917 | 5.25 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/EmojiPageMappingModel.kt | 2 | 673 | package org.thoughtcrime.securesms.keyboard.emoji
import org.thoughtcrime.securesms.components.emoji.EmojiPageModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
class EmojiPageMappingModel(val key: String, val emojiPageModel: EmojiPageModel) : MappingModel<EmojiPageMappingModel> {
override fun areItemsTheSame(newItem: EmojiPageMappingModel): Boolean {
return key == newItem.key
}
override fun areContentsTheSame(newItem: EmojiPageMappingModel): Boolean {
return areItemsTheSame(newItem) &&
newItem.emojiPageModel.spriteUri == emojiPageModel.spriteUri &&
newItem.emojiPageModel.iconAttr == emojiPageModel.iconAttr
}
}
| gpl-3.0 | ab5fe1f18ba4af99f0a06083720ecaf3 | 41.0625 | 120 | 0.803863 | 4.547297 | false | false | false | false |
ktorio/ktor | ktor-io/posix/src/io/ktor/utils/io/charsets/CharsetNative.kt | 1 | 14043 | @file:OptIn(UnsafeNumber::class)
package io.ktor.utils.io.charsets
import io.ktor.utils.io.core.*
import kotlinx.cinterop.*
import platform.iconv.*
import platform.posix.*
public actual abstract class Charset(internal val _name: String) {
public actual abstract fun newEncoder(): CharsetEncoder
public actual abstract fun newDecoder(): CharsetDecoder
public actual companion object {
public actual fun forName(name: String): Charset {
if (name == "UTF-8" || name == "utf-8" || name == "UTF8" || name == "utf8") return Charsets.UTF_8
if (name == "ISO-8859-1" || name == "iso-8859-1" || name == "ISO_8859_1") return Charsets.ISO_8859_1
if (name == "UTF-16" || name == "utf-16" || name == "UTF16" || name == "utf16") return Charsets.UTF_16
return CharsetImpl(name)
}
public actual fun isSupported(charset: String): Boolean = when (charset) {
"UTF-8", "utf-8", "UTF8", "utf8" -> true
"ISO-8859-1", "iso-8859-1" -> true
"UTF-16", "utf-16", "UTF16", "utf16" -> true
else -> false
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Charset) return false
if (_name != other._name) return false
return true
}
override fun hashCode(): Int {
return _name.hashCode()
}
override fun toString(): String {
return _name
}
}
private class CharsetImpl(name: String) : Charset(name) {
init {
val v = iconv_open(name, "UTF-8")
checkErrors(v, name)
iconv_close(v)
}
override fun newEncoder(): CharsetEncoder = CharsetEncoderImpl(this)
override fun newDecoder(): CharsetDecoder = CharsetDecoderImpl(this)
}
public actual val Charset.name: String get() = _name
// -----------------------
public actual abstract class CharsetEncoder(internal val _charset: Charset)
private data class CharsetEncoderImpl(private val charset: Charset) : CharsetEncoder(charset)
public actual val CharsetEncoder.charset: Charset get() = _charset
private fun iconvCharsetName(name: String) = when (name) {
"UTF-16" -> platformUtf16
else -> name
}
private val negativePointer = (-1L).toCPointer<IntVar>()
private fun checkErrors(iconvOpenResults: COpaquePointer?, charset: String) {
if (iconvOpenResults == null || iconvOpenResults === negativePointer) {
throw IllegalArgumentException("Failed to open iconv for charset $charset with error code ${posix_errno()}")
}
}
public actual fun CharsetEncoder.encodeToByteArray(input: CharSequence, fromIndex: Int, toIndex: Int): ByteArray =
encodeToByteArrayImpl1(input, fromIndex, toIndex)
internal actual fun CharsetEncoder.encodeImpl(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Buffer): Int {
val length = toIndex - fromIndex
if (length == 0) return 0
val chars = input.substring(fromIndex, toIndex).toCharArray()
val charset = iconvCharsetName(_charset._name)
val cd: COpaquePointer? = iconv_open(charset, platformUtf16)
checkErrors(cd, charset)
var charsConsumed = 0
try {
dst.writeDirect { buffer ->
chars.usePinned { pinned ->
memScoped {
val inbuf = alloc<CPointerVar<ByteVar>>()
val outbuf = alloc<CPointerVar<ByteVar>>()
val inbytesleft = alloc<size_tVar>()
val outbytesleft = alloc<size_tVar>()
val dstRemaining = dst.writeRemaining.convert<size_t>()
inbuf.value = pinned.addressOf(0).reinterpret()
outbuf.value = buffer
inbytesleft.value = (length * 2).convert<size_t>()
outbytesleft.value = dstRemaining
if (iconv(cd, inbuf.ptr, inbytesleft.ptr, outbuf.ptr, outbytesleft.ptr) == MAX_SIZE) {
checkIconvResult(posix_errno())
}
charsConsumed = ((length * 2).convert<size_t>() - inbytesleft.value).toInt() / 2
(dstRemaining - outbytesleft.value).toInt()
}
}
}
return charsConsumed
} finally {
iconv_close(cd)
}
}
public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) {
val cd = iconv_open(charset.name, "UTF-8")
checkErrors(cd, "UTF-8")
try {
var readSize = 1
var writeSize = 1
while (true) {
val srcView = input.prepareRead(readSize)
if (srcView == null) {
if (readSize != 1) throw MalformedInputException("...")
break
}
dst.writeWhileSize(writeSize) { dstBuffer ->
var written = 0
dstBuffer.writeDirect { buffer ->
var read = 0
srcView.readDirect { src ->
memScoped {
val length = srcView.readRemaining.convert<size_t>()
val inbuf = alloc<CPointerVar<ByteVar>>()
val outbuf = alloc<CPointerVar<ByteVar>>()
val inbytesleft = alloc<size_tVar>()
val outbytesleft = alloc<size_tVar>()
val dstRemaining = dstBuffer.writeRemaining.convert<size_t>()
inbuf.value = src
outbuf.value = buffer
inbytesleft.value = length
outbytesleft.value = dstRemaining
if (iconv(cd, inbuf.ptr, inbytesleft.ptr, outbuf.ptr, outbytesleft.ptr) == MAX_SIZE) {
checkIconvResult(posix_errno())
}
read = (length - inbytesleft.value).toInt()
written = (dstRemaining - outbytesleft.value).toInt()
}
read
}
if (read == 0) {
readSize++
writeSize = 8
} else {
input.headPosition = srcView.readPosition
readSize = 1
writeSize = 1
}
if (written > 0 && srcView.canRead()) writeSize else 0
}
written
}
}
} finally {
iconv_close(cd)
}
}
private fun checkIconvResult(errno: Int) {
if (errno == EILSEQ) throw MalformedInputException("Malformed or unmappable bytes at input")
if (errno == EINVAL) return // too few input bytes
if (errno == E2BIG) return // too few output buffer bytes
throw IllegalStateException("Failed to call 'iconv' with error code $errno")
}
internal actual fun CharsetEncoder.encodeComplete(dst: Buffer): Boolean = true
// ----------------------------------------------------------------------
public actual abstract class CharsetDecoder(internal val _charset: Charset)
private data class CharsetDecoderImpl(private val charset: Charset) : CharsetDecoder(charset)
public actual val CharsetDecoder.charset: Charset get() = _charset
private val platformUtf16: String = if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) "UTF-16BE" else "UTF-16LE"
public actual fun CharsetDecoder.decode(input: Input, dst: Appendable, max: Int): Int {
val charset = iconvCharsetName(charset.name)
val cd = iconv_open(platformUtf16, charset)
checkErrors(cd, charset)
val chars = CharArray(8192)
var copied = 0
try {
var readSize = 1
chars.usePinned { pinned ->
memScoped {
val inbuf = alloc<CPointerVar<ByteVar>>()
val outbuf = alloc<CPointerVar<ByteVar>>()
val inbytesleft = alloc<size_tVar>()
val outbytesleft = alloc<size_tVar>()
val buffer = pinned.addressOf(0).reinterpret<ByteVar>()
input.takeWhileSize { srcView ->
val rem = max - copied
if (rem == 0) return@takeWhileSize 0
var written: Int
var read: Int
srcView.readDirect { src ->
val length = srcView.readRemaining.convert<size_t>()
val dstRemaining = (minOf(chars.size, rem) * 2).convert<size_t>()
inbuf.value = src
outbuf.value = buffer
inbytesleft.value = length
outbytesleft.value = dstRemaining
if (iconv(cd, inbuf.ptr, inbytesleft.ptr, outbuf.ptr, outbytesleft.ptr) == MAX_SIZE) {
checkIconvResult(posix_errno())
}
read = (length - inbytesleft.value).toInt()
written = (dstRemaining - outbytesleft.value).toInt() / 2
read
}
if (read == 0) {
readSize++
} else {
readSize = 1
repeat(written) {
dst.append(chars[it])
}
copied += written
}
readSize
}
}
}
return copied
} finally {
iconv_close(cd)
}
}
internal actual fun CharsetDecoder.decodeBuffer(
input: Buffer,
out: Appendable,
lastBuffer: Boolean,
max: Int
): Int {
if (!input.canRead() || max == 0) {
return 0
}
val charset = iconvCharsetName(charset.name)
val cd = iconv_open(platformUtf16, charset)
checkErrors(cd, charset)
var charactersCopied = 0
try {
input.readDirect { ptr ->
val size = input.readRemaining
val result = CharArray(size)
val bytesLeft = memScoped {
result.usePinned { pinnedResult ->
val inbuf = alloc<CPointerVar<ByteVar>>()
val outbuf = alloc<CPointerVar<ByteVar>>()
val inbytesleft = alloc<size_tVar>()
val outbytesleft = alloc<size_tVar>()
inbuf.value = ptr
outbuf.value = pinnedResult.addressOf(0).reinterpret()
inbytesleft.value = size.convert()
outbytesleft.value = (size * 2).convert()
if (iconv(cd, inbuf.ptr, inbytesleft.ptr, outbuf.ptr, outbytesleft.ptr) == MAX_SIZE) {
checkIconvResult(posix_errno())
}
charactersCopied += (size * 2 - outbytesleft.value.convert<Int>()) / 2
inbytesleft.value.convert<Int>()
}
}
repeat(charactersCopied) { index ->
out.append(result[index])
}
size - bytesLeft
}
return charactersCopied
} finally {
iconv_close(cd)
}
}
public actual fun CharsetDecoder.decodeExactBytes(input: Input, inputLength: Int): String {
if (inputLength == 0) return ""
val charset = iconvCharsetName(charset.name)
val cd = iconv_open(platformUtf16, charset)
checkErrors(cd, charset)
val chars = CharArray(inputLength)
var charsCopied = 0
var bytesConsumed = 0
try {
var readSize = 1
chars.usePinned { pinned ->
memScoped {
val inbuf = alloc<CPointerVar<ByteVar>>()
val outbuf = alloc<CPointerVar<ByteVar>>()
val inbytesleft = alloc<size_tVar>()
val outbytesleft = alloc<size_tVar>()
input.takeWhileSize { srcView ->
val rem = inputLength - charsCopied
if (rem == 0) return@takeWhileSize 0
var written: Int
var read: Int
srcView.readDirect { src ->
val length = minOf(srcView.readRemaining, inputLength - bytesConsumed).convert<size_t>()
val dstRemaining = (rem * 2).convert<size_t>()
inbuf.value = src
outbuf.value = pinned.addressOf(charsCopied).reinterpret()
inbytesleft.value = length
outbytesleft.value = dstRemaining
if (iconv(cd, inbuf.ptr, inbytesleft.ptr, outbuf.ptr, outbytesleft.ptr) == MAX_SIZE) {
checkIconvResult(posix_errno())
}
read = (length - inbytesleft.value).toInt()
written = (dstRemaining - outbytesleft.value).toInt() / 2
read
}
bytesConsumed += read
if (read == 0) {
readSize++
} else {
readSize = 1
charsCopied += written
}
if (bytesConsumed < inputLength) readSize else 0
}
}
}
if (bytesConsumed < inputLength) {
throw EOFException("Not enough bytes available: had only $bytesConsumed instead of $inputLength")
}
return chars.concatToString(0, 0 + charsCopied)
} finally {
iconv_close(cd)
}
}
// -----------------------------------------------------------
public actual object Charsets {
public actual val UTF_8: Charset = CharsetImpl("UTF-8")
public actual val ISO_8859_1: Charset = CharsetImpl("ISO-8859-1")
internal val UTF_16: Charset = CharsetImpl(platformUtf16)
}
public actual open class MalformedInputException actual constructor(message: String) : Throwable(message)
| apache-2.0 | ac140cfb44a719ec97c1c76d68c2e531 | 33.334963 | 116 | 0.524318 | 4.758726 | false | false | false | false |
chiclaim/android-sample | language-kotlin/kotlin-sample/kotlin-in-action/src/generic/GenericReified.kt | 1 | 5150 | package generic
/**
* Desc:
* Created by Chiclaim on 2018/10/9.
*/
//starting===========关于泛型为空 ================================
class Processor<T> {
//value是可以为null,尽管没有使用‘?‘做标记
fun process(value: T) {
value?.hashCode()
}
}
//使用泛型约束,则T不能为空
class Processor2<T : Any> {
fun process(value: T) {
value.hashCode()
}
}
class Processor3<T : Any?> {
fun process(value: T) {
value?.hashCode()
}
}
//ending=======================================================
//starting===========泛型擦除 type erasure ================================
//和Java一样,在运行时Kotlin的泛型也会被擦除,所以说泛型只是在编译时有效
fun isList(obj: Any): Boolean {
//Cannot check for instance of erased type: List<String>
//return obj is List<String>
return obj is List<*>
}
fun isList2(obj: Any): Boolean {
//Unchecked cast: Any to List<Int>
//return obj as? List<Int> != null
return obj as? List<*> != null
}
//ending===========泛型擦除 type erasure ================================
//starting===========reified type ================================
//我们知道泛型在运行时会擦除,但是在inline函数中我们可以指定泛型不被擦除,因为inline函数在编译期会copy到调用它的方法里
//所以编译器会知道当前的方法中泛型对应的具体类型是什么,然后把具体类型替换泛型,从而达到不被擦除的目的
//在inline函数中我们可以通过reified关键字来标记这个泛型不被擦除
//Error: Cannot check for instance of erased type: T
//fun <T> isType(value: Any) = value is T
inline fun <reified T> isType(value: Any) = value is T
//这个是很有用的特性,因为我们在封装的时候,为了尽可能的复用代码,通常把泛型封装到最底层,但是受到泛型运行时擦除的限制
//比如下面的的逻辑:请求网络,成功后把返回的json解析成对应的bean,所有的网络请求都有这样的逻辑,所以把网络请求和json解析成bean的逻辑通过泛型抽取出来
//但是不同的逻辑对应不同的bean,由于泛型参数在运行时被擦除所以拿不到上层传下的bean类型,从而json解析成bean的时候失败
//通过inline和reified就可以很好的解决这个问题,达到代码重用最大化
/*
//第一版本网络请求逻辑
@Override
public Observable<List<Menu>> getMenuList(final MenuListRequest request) {
return RxUtils.wrapCallable(new Callable<HttpResult<HttpBean<List<Menu>>>>() {
@Override
public HttpResult<HttpBean<List<Menu>>> call() throws Exception {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put(MenuHttpConstant.MenuList.ENTITY_ID, request.getEntityId());
paramMap.put(MenuHttpConstant.MenuList.SEAT_CODE, request.getSeatCode());
Type listType = new TypeToken<HttpResult<HttpBean<List<Menu>>>>() {
}.getType();
RequestModel requestModel = HttpHelper.getDefaultRequestModel(paramMap, MenuHttpConstant.MenuList.METHOD)
.newBuilder().responseType(listType).build();
ResponseModel<HttpResult<HttpBean<List<Menu>>>> responseModel = NetworkService.getDefault().request(requestModel);
return responseModel.data();
}
});
}
//第二版本:抽取网络请求逻辑
fun <T> requestRemoteSource(paramMap: Map<String, Any?>, method: String, responseType: Type): Observable<T> {
return RxUtils.wrapCallable<T> {
val requestModel = HttpHelper.getDefaultRequestModel(paramMap, method)
.newBuilder()
.responseType(responseType)
.build()
val responseModel = NetworkService.getDefault().request<HttpResult<HttpBean<T>>>(requestModel)
responseModel.data()
}
}
//第三版本:通过inline和reified重构代码
inline fun <reified T> requestRemoteSource(paramMap: Map<String, Any?>, method: String): Observable<T> {
val responseType = object : TypeToken<HttpResult<HttpBean<T>>>() {}.type
return requestRemoteSource(paramMap, method, responseType)
}
*/
//--------reified type很好用,它有以下限制:
//1, 只能用于类型检查和转换 ( is , !is , as , as? )
//2, 用于Kotlin反射
//3, 获取泛型对应的class(java.lang.Class(::class.java))
//4, 调用其他函数时作为类型参数
//--------reified type很好用,不能用于:
//1, Create new instances of the class specified as a type parameter
//2, Call methods on the companion object of the type parameter class
//3, Use a non-reified type parameter as a type argument when calling a function with a reified type parameter
//4, Mark type parameters of classes, properties, or non-inline functions as reified
//--------需要注意的是,inline reified type的函数不能被Java方法调用,只能被Kotlin函数调用
//反编译后的class可以知道, inline reified type的函数是private的
//ending===========================================
| apache-2.0 | be00f383cc877f33cad39ae236dd9337 | 29.176471 | 126 | 0.652534 | 3.377778 | false | false | false | false |
marcbaldwin/RxAdapter | rxadapter/src/main/kotlin/xyz/marcb/rxadapter/internal/AdapterPartSnapshotDelta.kt | 1 | 731 | package xyz.marcb.rxadapter.internal
import androidx.recyclerview.widget.DiffUtil
import xyz.marcb.rxadapter.AdapterPartSnapshot
internal class AdapterPartSnapshotDelta(
private val old: AdapterPartSnapshot,
private val new: AdapterPartSnapshot
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = old.itemCount
override fun getNewListSize(): Int = new.itemCount
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
old.itemIds[oldItemPosition] == new.itemIds[newItemPosition]
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
old.underlyingObject(oldItemPosition) == new.underlyingObject(newItemPosition)
}
| mit | a459bc01303536593c60e1c1e32ae7e6 | 37.473684 | 90 | 0.779754 | 4.809211 | false | false | false | false |
seirion/code | facebook/2019/qualification/2/main.kt | 1 | 361 | fun main(args: Array<String>) {
val n = readLine()!!.toInt()
repeat(n) {
print("Case #${it + 1}: ")
solve(readLine()!!)
}
}
fun solve(s: String) {
val empty = s.filter { it == '.' }.count()
val b = s.filter { it == 'B' }.count()
if ((b == 1 && empty == 1) || (1 <= empty && 2 <= b)) println("Y")
else println("N")
}
| apache-2.0 | e1e7862a78c315cddcb7598203b67341 | 24.785714 | 70 | 0.457064 | 3.08547 | false | false | false | false |
marius-m/wt4 | components/src/main/java/lt/markmerkk/TimeGapGenerator.kt | 1 | 2144 | package lt.markmerkk
import lt.markmerkk.entities.TimeGap
import lt.markmerkk.utils.LogFormatters
import org.joda.time.LocalDateTime
import org.joda.time.LocalTime
/**
* Can generate time range
* Screens that provide time ranges
*/
class TimeGapGenerator(
val startDateSource: Source,
val startTimeSource: Source,
val endDateSource: Source,
val endTimeSource: Source,
) {
fun generateTimeGap(): TimeGap {
return TimeGap.fromRaw(
startDateRaw = startDateSource.rawInput(),
startTimeRaw = startTimeSource.rawInput(),
endDateRaw = endDateSource.rawInput(),
endTimeRaw = endTimeSource.rawInput()
)
}
fun timeValuesStart(): List<LocalTime> {
val timeValues = mutableListOf<LocalTime>()
val dtStart: LocalDateTime = LogFormatters.formatDate.parseLocalDate(startDateSource.rawInput())
.toLocalDateTime(LocalTime.MIDNIGHT)
val dtEnd: LocalDateTime = dtStart
.toLocalDate()
.toLocalDateTime(LogFormatters.formatTime.parseLocalTime(endTimeSource.rawInput()))
var currentTime: LocalDateTime = dtStart
while (currentTime.isBefore(dtEnd) || currentTime == dtEnd) {
timeValues.add(currentTime.toLocalTime())
currentTime = currentTime.plusMinutes(1)
}
return timeValues.toList()
}
fun timeValuesEnd(): List<LocalTime> {
val timeValues = mutableListOf<LocalTime>()
val dtStart: LocalDateTime = LogFormatters.formatDate.parseLocalDate(startDateSource.rawInput())
.toLocalDateTime(LogFormatters.formatTime.parseLocalTime(startTimeSource.rawInput()))
val dtEnd: LocalDateTime = dtStart
.toLocalDate()
.plusDays(1)
.toLocalDateTime(LocalTime.MIDNIGHT)
var currentTime: LocalDateTime = dtStart
while (currentTime.isBefore(dtEnd)) {
timeValues.add(currentTime.toLocalTime())
currentTime = currentTime.plusMinutes(1)
}
return timeValues.toList()
}
interface Source {
fun rawInput(): String
}
}
| apache-2.0 | c3b7c50195cbcda1e235952a55f0dab6 | 33.580645 | 104 | 0.666978 | 4.796421 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMDebugInfo.kt | 4 | 51853 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val LLVMDebugInfo = "LLVMDebugInfo".nativeClass(
Module.LLVM,
prefixConstant = "LLVM",
prefixMethod = "LLVM",
binding = LLVM_BINDING_DELEGATE
) {
documentation = ""
EnumConstant(
"""
Debug info flags.
({@code LLVMDIFlags})
""",
"DIFlagZero".enum("", "0"),
"DIFlagPrivate".enum,
"DIFlagProtected".enum,
"DIFlagPublic".enum,
"DIFlagFwdDecl".enum("", "1 << 2"),
"DIFlagAppleBlock".enum("", "1 << 3"),
"DIFlagReservedBit4".enum("", "1 << 4"),
"DIFlagVirtual".enum("", "1 << 5"),
"DIFlagArtificial".enum("", "1 << 6"),
"DIFlagExplicit".enum("", "1 << 7"),
"DIFlagPrototyped".enum("", "1 << 8"),
"DIFlagObjcClassComplete".enum("", "1 << 9"),
"DIFlagObjectPointer".enum("", "1 << 10"),
"DIFlagVector".enum("", "1 << 11"),
"DIFlagStaticMember".enum("", "1 << 12"),
"DIFlagLValueReference".enum("", "1 << 13"),
"DIFlagRValueReference".enum("", "1 << 14"),
"DIFlagReserved".enum("", "1 << 15"),
"DIFlagSingleInheritance".enum("", "1 << 16"),
"DIFlagMultipleInheritance".enum("", "2 << 16"),
"DIFlagVirtualInheritance".enum("", "3 << 16"),
"DIFlagIntroducedVirtual".enum("", "1 << 18"),
"DIFlagBitField".enum("", "1 << 19"),
"DIFlagNoReturn".enum("", "1 << 20"),
"DIFlagTypePassByValue".enum("", "1 << 22"),
"DIFlagTypePassByReference".enum("", "1 << 23"),
"DIFlagEnumClass".enum("", "1 << 24"),
"DIFlagFixedEnum".enum("", "LLVMDIFlagEnumClass"),
"DIFlagThunk".enum("", "1 << 25"),
"DIFlagNonTrivial".enum("", "1 << 26"),
"DIFlagBigEndian".enum("", "1 << 27"),
"DIFlagLittleEndian".enum("", "1 << 28"),
"DIFlagIndirectVirtualBase".enum("", "(1 << 2) | (1 << 5)"),
"DIFlagAccessibility".enum("", "LLVMDIFlagPrivate | LLVMDIFlagProtected | LLVMDIFlagPublic"),
"DIFlagPtrToMemberRep".enum("", "LLVMDIFlagSingleInheritance | LLVMDIFlagMultipleInheritance | LLVMDIFlagVirtualInheritance")
)
EnumConstant(
"""
Source languages known by DWARF.
({@code LLVMDWARFSourceLanguage})
""",
"DWARFSourceLanguageC89".enum("", "0"),
"DWARFSourceLanguageC".enum,
"DWARFSourceLanguageAda83".enum,
"DWARFSourceLanguageC_plus_plus".enum,
"DWARFSourceLanguageCobol74".enum,
"DWARFSourceLanguageCobol85".enum,
"DWARFSourceLanguageFortran77".enum,
"DWARFSourceLanguageFortran90".enum,
"DWARFSourceLanguagePascal83".enum,
"DWARFSourceLanguageModula2".enum,
"DWARFSourceLanguageJava".enum("New in DWARF v3:"),
"DWARFSourceLanguageC99".enum("New in DWARF v3:"),
"DWARFSourceLanguageAda95".enum("New in DWARF v3:"),
"DWARFSourceLanguageFortran95".enum("New in DWARF v3:"),
"DWARFSourceLanguagePLI".enum("New in DWARF v3:"),
"DWARFSourceLanguageObjC".enum("New in DWARF v3:"),
"DWARFSourceLanguageObjC_plus_plus".enum("New in DWARF v3:"),
"DWARFSourceLanguageUPC".enum("New in DWARF v3:"),
"DWARFSourceLanguageD".enum("New in DWARF v3:"),
"DWARFSourceLanguagePython".enum("New in DWARF v4:"),
"DWARFSourceLanguageOpenCL".enum("New in DWARF v5:"),
"DWARFSourceLanguageGo".enum("New in DWARF v5:"),
"DWARFSourceLanguageModula3".enum("New in DWARF v5:"),
"DWARFSourceLanguageHaskell".enum("New in DWARF v5:"),
"DWARFSourceLanguageC_plus_plus_03".enum("New in DWARF v5:"),
"DWARFSourceLanguageC_plus_plus_11".enum("New in DWARF v5:"),
"DWARFSourceLanguageOCaml".enum("New in DWARF v5:"),
"DWARFSourceLanguageRust".enum("New in DWARF v5:"),
"DWARFSourceLanguageC11".enum("New in DWARF v5:"),
"DWARFSourceLanguageSwift".enum("New in DWARF v5:"),
"DWARFSourceLanguageJulia".enum("New in DWARF v5:"),
"DWARFSourceLanguageDylan".enum("New in DWARF v5:"),
"DWARFSourceLanguageC_plus_plus_14".enum("New in DWARF v5:"),
"DWARFSourceLanguageFortran03".enum("New in DWARF v5:"),
"DWARFSourceLanguageFortran08".enum("New in DWARF v5:"),
"DWARFSourceLanguageRenderScript".enum("New in DWARF v5:"),
"DWARFSourceLanguageBLISS".enum("New in DWARF v5:"),
"DWARFSourceLanguageMips_Assembler".enum("Vendor extensions:"),
"DWARFSourceLanguageGOOGLE_RenderScript".enum("Vendor extensions:"),
"DWARFSourceLanguageBORLAND_Delphi".enum("Vendor extensions:")
)
EnumConstant(
"""
The amount of debug information to emit.
({@code LLVMDWARFEmissionKind})
""",
"DWARFEmissionNone".enum("", "0"),
"DWARFEmissionFull".enum,
"DWARFEmissionLineTablesOnly".enum
)
EnumConstant(
"The kind of metadata nodes.",
"MDStringMetadataKind".enum("", "0"),
"ConstantAsMetadataMetadataKind".enum,
"LocalAsMetadataMetadataKind".enum,
"DistinctMDOperandPlaceholderMetadataKind".enum,
"MDTupleMetadataKind".enum,
"DILocationMetadataKind".enum,
"DIExpressionMetadataKind".enum,
"DIGlobalVariableExpressionMetadataKind".enum,
"GenericDINodeMetadataKind".enum,
"DISubrangeMetadataKind".enum,
"DIEnumeratorMetadataKind".enum,
"DIBasicTypeMetadataKind".enum,
"DIDerivedTypeMetadataKind".enum,
"DICompositeTypeMetadataKind".enum,
"DISubroutineTypeMetadataKind".enum,
"DIFileMetadataKind".enum,
"DICompileUnitMetadataKind".enum,
"DISubprogramMetadataKind".enum,
"DILexicalBlockMetadataKind".enum,
"DILexicalBlockFileMetadataKind".enum,
"DINamespaceMetadataKind".enum,
"DIModuleMetadataKind".enum,
"DITemplateTypeParameterMetadataKind".enum,
"DITemplateValueParameterMetadataKind".enum,
"DIGlobalVariableMetadataKind".enum,
"DILocalVariableMetadataKind".enum,
"DILabelMetadataKind".enum,
"DIObjCPropertyMetadataKind".enum,
"DIImportedEntityMetadataKind".enum,
"DIMacroMetadataKind".enum,
"DIMacroFileMetadataKind".enum,
"DICommonBlockMetadataKind".enum,
"DIStringTypeMetadataKind".enum,
"DIGenericSubrangeMetadataKind".enum,
"DIArgListMetadataKind".enum
)
EnumConstant(
"""
Describes the kind of macro declaration used for {@code LLVMDIBuilderCreateMacro}. ({@code LLVMDWARFMacinfoRecordType})
See {@code llvm::dwarf::MacinfoRecordType}.
Note: Values are from {@code DW_MACINFO_*} constants in the DWARF specification.
""",
"DWARFMacinfoRecordTypeDefine".enum("", "0x01"),
"DWARFMacinfoRecordTypeMacro".enum("", "0x02"),
"DWARFMacinfoRecordTypeStartFile".enum("", "0x03"),
"DWARFMacinfoRecordTypeEndFile".enum("", "0x04"),
"DWARFMacinfoRecordTypeVendorExt".enum("", "0xff")
)
unsigned_int(
"DebugMetadataVersion",
"The current debug metadata version number.",
void()
)
unsigned_int(
"GetModuleDebugMetadataVersion",
"The version of debug metadata that's present in the provided {@code Module}.",
LLVMModuleRef("Module", "")
)
LLVMBool(
"StripModuleDebugInfo",
"""
Strip debug info in the module if it exists. To do this, we remove all calls to the debugger intrinsics and any named metadata for debugging. We also
remove debug locations for instructions. Return true if module is modified.
""",
LLVMModuleRef("Module", "")
)
LLVMDIBuilderRef(
"CreateDIBuilderDisallowUnresolved",
"Construct a builder for a module, and do not allow for unresolved nodes attached to the module.",
LLVMModuleRef("M", "")
)
LLVMDIBuilderRef(
"CreateDIBuilder",
"""
Construct a builder for a module and collect unresolved nodes attached to the module in order to resolve cycles during a call to {@code
LLVMDIBuilderFinalize}.
""",
LLVMModuleRef("M", "")
)
void(
"DisposeDIBuilder",
"""
Deallocates the {@code DIBuilder} and everything it owns.
${note("""You must call {@code #DIBuilderFinalize()} before this""")}
""",
LLVMDIBuilderRef("Builder", "")
)
void(
"DIBuilderFinalize",
"Construct any deferred debug info descriptors.",
LLVMDIBuilderRef("Builder", "")
)
LLVMMetadataRef(
"DIBuilderCreateCompileUnit",
"A {@code CompileUnit} provides an anchor for all debugging information generated during this instance of compilation.",
LLVMDIBuilderRef("Builder", ""),
LLVMDWARFSourceLanguage("Lang", "source programming language, eg. {@code LLVMDWARFSourceLanguageC99}"),
LLVMMetadataRef("FileRef", "file info"),
charUTF8.const.p("Producer", "identify the producer of debugging information and code. Usually this is a compiler version string."),
AutoSize("Producer")..size_t("ProducerLen", "the length of the C string passed to {@code Producer}"),
LLVMBool("isOptimized", "a boolean flag which indicates whether optimization is enabled or not"),
charUTF8.const.p(
"Flags",
"""
this string lists command line options. This string is directly embedded in debug info output which may be used by a tool analyzing generated
debugging information.
"""
),
AutoSize("Flags")..size_t("FlagsLen", "the length of the C string passed to {@code Flags}"),
unsigned_int("RuntimeVer", "this indicates runtime version for languages like Objective-C"),
charUTF8.const.p("SplitName", "the name of the file that we'll split debug info out into"),
AutoSize("SplitName")..size_t("SplitNameLen", "the length of the C string passed to {@code SplitName}"),
LLVMDWARFEmissionKind("Kind", "the kind of debug information to generate"),
unsigned_int("DWOId", "the DWOId if this is a split skeleton compile unit"),
LLVMBool("SplitDebugInlining", "whether to emit inline debug info"),
LLVMBool("DebugInfoForProfiling", "whether to emit extra debug info for profile collection"),
charUTF8.const.p("SysRoot", "the Clang system root (value of {@code -isysroot})"),
AutoSize("SysRoot")..size_t("SysRootLen", "the length of the C string passed to {@code SysRoot}"),
charUTF8.const.p("SDK", "the SDK. On Darwin, the last component of the {@code sysroot}."),
AutoSize("SDK")..size_t("SDKLen", "the length of the C string passed to {@code SDK}")
)
LLVMMetadataRef(
"DIBuilderCreateFile",
"Create a file descriptor to hold debugging information for a file.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
charUTF8.const.p("Filename", "file name"),
AutoSize("Filename")..size_t("FilenameLen", "the length of the C string passed to {@code Filename}"),
charUTF8.const.p("Directory", "directory"),
AutoSize("Directory")..size_t("DirectoryLen", "the length of the C string passed to {@code Directory}")
)
LLVMMetadataRef(
"DIBuilderCreateModule",
"Creates a new descriptor for a module with the specified parent scope.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("ParentScope", "the parent scope containing this module declaration"),
charUTF8.const.p("Name", "module name"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
charUTF8.const.p("ConfigMacros", "a space-separated shell-quoted list of {@code -D} macro definitions as they would appear on a command line"),
AutoSize("ConfigMacros")..size_t("ConfigMacrosLen", "the length of the C string passed to {@code ConfigMacros}"),
charUTF8.const.p("IncludePath", "the path to the module map file"),
AutoSize("IncludePath")..size_t("IncludePathLen", "the length of the C string passed to {@code IncludePath}"),
charUTF8.const.p("APINotesFile", "the path to an API notes file for the module"),
AutoSize("APINotesFile")..size_t("APINotesFileLen", "he length of the C string passed to {@code APINotestFile}")
)
LLVMMetadataRef(
"DIBuilderCreateNameSpace",
"Creates a new descriptor for a namespace with the specified parent scope.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("ParentScope", "the parent scope containing this module declaration"),
charUTF8.const.p("Name", "nameSpace name"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
LLVMBool("ExportSymbols", "whether or not the namespace exports symbols, e.g. this is true of C++ inline namespaces.")
)
LLVMMetadataRef(
"DIBuilderCreateFunction",
"Create a new descriptor for the specified subprogram.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "function scope"),
charUTF8.const.p("Name", "function name"),
AutoSize("Name")..size_t("NameLen", "length of enumeration name"),
charUTF8.const.p("LinkageName", "mangled function name"),
AutoSize("LinkageName")..size_t("LinkageNameLen", "length of linkage name"),
LLVMMetadataRef("File", "file where this variable is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Ty", "function type"),
LLVMBool("IsLocalToUnit", "true if this function is not externally visible"),
LLVMBool("IsDefinition", "true if this is a function definition"),
unsigned_int("ScopeLine", "set to the beginning of the scope this starts"),
LLVMDIFlags("Flags", "e.g.: {@code LLVMDIFlagLValueReference}. These flags are used to emit dwarf attributes."),
LLVMBool("IsOptimized", "true if optimization is ON")
)
LLVMMetadataRef(
"DIBuilderCreateLexicalBlock",
"Create a descriptor for a lexical block with the specified parent context.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "parent lexical block"),
LLVMMetadataRef("File", "source file"),
unsigned_int("Line", "the line in the source file"),
unsigned_int("Column", "the column in the source file")
)
LLVMMetadataRef(
"DIBuilderCreateLexicalBlockFile",
"Create a descriptor for a lexical block with a new file attached.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "lexical block"),
LLVMMetadataRef("File", "source file"),
unsigned_int("Discriminator", "DWARF path discriminator value")
)
LLVMMetadataRef(
"DIBuilderCreateImportedModuleFromNamespace",
"Create a descriptor for an imported namespace. Suitable for e.g. C++ using declarations.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "the scope this module is imported into"),
LLVMMetadataRef("NS", ""),
LLVMMetadataRef("File", "file where the declaration is located"),
unsigned_int("Line", "line number of the declaration")
)
LLVMMetadataRef(
"DIBuilderCreateImportedModuleFromAlias",
"Create a descriptor for an imported module that aliases another imported entity descriptor.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "the scope this module is imported into"),
LLVMMetadataRef("ImportedEntity", "previous imported entity to alias"),
LLVMMetadataRef("File", "file where the declaration is located"),
unsigned_int("Line", "line number of the declaration")
)
LLVMMetadataRef(
"DIBuilderCreateImportedModuleFromModule",
"Create a descriptor for an imported module.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "the scope this module is imported into"),
LLVMMetadataRef("M", "the module being imported here"),
LLVMMetadataRef("File", "file where the declaration is located"),
unsigned_int("Line", "line number of the declaration")
)
LLVMMetadataRef(
"DIBuilderCreateImportedDeclaration",
"Create a descriptor for an imported function, type, or variable. Suitable for e.g. FORTRAN-style USE declarations.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "the scope this module is imported into"),
LLVMMetadataRef("Decl", "the declaration (or definition) of a function, type, or variable"),
LLVMMetadataRef("File", "file where the declaration is located"),
unsigned_int("Line", "line number of the declaration"),
charUTF8.const.p("Name", "a name that uniquely identifies this imported declaration"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}")
)
LLVMMetadataRef(
"DIBuilderCreateDebugLocation",
"""
Creates a new DebugLocation that describes a source location.
${note("""If the item to which this location is attached cannot be attributed to a source line, pass 0 for the line and column.""")}
""",
LLVMContextRef("Ctx", ""),
unsigned_int("Line", "the line in the source file"),
unsigned_int("Column", "the column in the source file"),
LLVMMetadataRef("Scope", "the scope in which the location resides"),
LLVMMetadataRef("InlinedAt", "the scope where this location was inlined, if at all. (optional).")
)
unsigned_int(
"DILocationGetLine",
"Get the line number of this debug location.",
LLVMMetadataRef("Location", "the debug location")
)
unsigned_int(
"DILocationGetColumn",
"Get the column number of this debug location.",
LLVMMetadataRef("Location", "the debug location")
)
LLVMMetadataRef(
"DILocationGetScope",
"Get the local scope associated with this debug location.",
LLVMMetadataRef("Location", "the debug location")
)
IgnoreMissing..LLVMMetadataRef(
"DILocationGetInlinedAt",
"""
Get the "inline at" location associated with this debug location.
See {@code DILocation::getInlinedAt()}.
""",
LLVMMetadataRef("Location", "the debug location"),
since = "9"
)
IgnoreMissing..LLVMMetadataRef(
"DIScopeGetFile",
"""
Get the metadata of the file associated with a given scope.
See {@code DIScope::getFile()}.
""",
LLVMMetadataRef("Scope", "the scope object"),
since = "9"
)
IgnoreMissing..charUTF8.const.p(
"DIFileGetDirectory",
"""
Get the directory of a given file.
See {@code DIFile::getDirectory()}
""",
LLVMMetadataRef("File", "the file object"),
AutoSizeResult..Check(1)..unsigned.p("Len", "the length of the returned string"),
since = "9"
)
IgnoreMissing..charUTF8.const.p(
"DIFileGetFilename",
"""
Get the name of a given file.
See {@code DIFile::getFilename()}.
""",
LLVMMetadataRef("File", "the file object"),
AutoSizeResult..Check(1)..unsigned.p("Len", "the length of the returned string"),
since = "9"
)
IgnoreMissing..charUTF8.const.p(
"DIFileGetSource",
"""
Get the source of a given file.
See {@code DIFile::getSource()}.
""",
LLVMMetadataRef("File", "the file object"),
AutoSizeResult..Check(1)..unsigned.p("Len", "the length of the returned string"),
since = "9"
)
LLVMMetadataRef(
"DIBuilderGetOrCreateTypeArray",
"Create a type array.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef.p("Data", "the type elements"),
AutoSize("Data")..size_t("NumElements", "number of type elements")
)
LLVMMetadataRef(
"DIBuilderCreateSubroutineType",
"Create subroutine type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("File", "the file in which the subroutine resides"),
LLVMMetadataRef.p("ParameterTypes", "an array of subroutine parameter types. This includes return type at 0th index."),
AutoSize("ParameterTypes")..unsigned_int("NumParameterTypes", "the number of parameter types in {@code ParameterTypes}"),
LLVMDIFlags("Flags", "e.g.: {@code LLVMDIFlagLValueReference}. These flags are used to emit dwarf attributes.")
)
IgnoreMissing..LLVMMetadataRef(
"DIBuilderCreateMacro",
"Create debugging information entry for a macro.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
nullable..LLVMMetadataRef("ParentMacroFile", "macro parent (could be #NULL)."),
unsigned("Line", "source line number where the macro is defined"),
LLVMDWARFMacinfoRecordType("RecordType", "{@code DW_MACINFO_define} or {@code DW_MACINFO_undef}"),
charUTF8.const.p("Name", "macro name"),
AutoSize("Name")..size_t("NameLen", "macro name length"),
charUTF8.const.p("Value", "macro value"),
AutoSize("Value")..size_t("ValueLen", "macro value length"),
since = "10"
)
IgnoreMissing..LLVMMetadataRef(
"DIBuilderCreateTempMacroFile",
"""
Create debugging information temporary entry for a macro file.
List of macro node direct children will be calculated by {@code DIBuilder}, using the {@code ParentMacroFile} relationship.
""",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("ParentMacroFile", "macro parent (could be #NULL)"),
unsigned("Line", "source line number where the macro file is included"),
LLVMMetadataRef("File", "file descriptor containing the name of the macro file"),
since = "10"
)
IgnoreMissing..LLVMMetadataRef(
"DIBuilderCreateEnumerator",
"Create debugging information entry for an enumerator.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
char.const.p("Name", "enumerator name"),
AutoSize("Name")..size_t("NameLen", "length of enumerator name"),
int64_t("Value", "enumerator value"),
LLVMBool("IsUnsigned", "true if the value is unsigned"),
since = "10"
)
LLVMMetadataRef(
"DIBuilderCreateEnumerationType",
"Create debugging information entry for an enumeration.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "scope in which this enumeration is defined"),
charUTF8.const.p("Name", "enumeration name"),
AutoSize("Name")..size_t("NameLen", "length of enumeration name"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNumber", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
LLVMMetadataRef.p("Elements", "enumeration elements"),
AutoSize("Elements")..unsigned_int("NumElements", "number of enumeration elements"),
LLVMMetadataRef("ClassTy", "underlying type of a C++11/ObjC fixed enum")
)
LLVMMetadataRef(
"DIBuilderCreateUnionType",
"Create debugging information entry for a union.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "scope in which this union is defined"),
charUTF8.const.p("Name", "union name"),
AutoSize("Name")..size_t("NameLen", "length of union name"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNumber", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private"),
LLVMMetadataRef.p("Elements", "union elements"),
AutoSize("Elements")..unsigned_int("NumElements", "number of union elements"),
unsigned_int("RunTimeLang", "optional parameter, Objective-C runtime version"),
charUTF8.const.p("UniqueId", "a unique identifier for the union"),
AutoSize("UniqueId")..size_t("UniqueIdLen", "length of unique identifier")
)
LLVMMetadataRef(
"DIBuilderCreateArrayType",
"Create debugging information entry for an array.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
uint64_t("Size", "array size"),
uint32_t("AlignInBits", "alignment"),
LLVMMetadataRef("Ty", "element type"),
LLVMMetadataRef.p("Subscripts", "subscripts"),
AutoSize("Subscripts")..unsigned_int("NumSubscripts", "number of subscripts")
)
LLVMMetadataRef(
"DIBuilderCreateVectorType",
"Create debugging information entry for a vector type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
uint64_t("Size", "vector size"),
uint32_t("AlignInBits", "alignment"),
LLVMMetadataRef("Ty", "element type"),
LLVMMetadataRef.p("Subscripts", "subscripts"),
AutoSize("Subscripts")..unsigned_int("NumSubscripts", "number of subscripts")
)
LLVMMetadataRef(
"DIBuilderCreateUnspecifiedType",
"Create a DWARF unspecified type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
charUTF8.const.p("Name", "the unspecified type's name"),
AutoSize("Name")..size_t("NameLen", "length of type name")
)
LLVMMetadataRef(
"DIBuilderCreateBasicType",
"Create debugging information entry for a basic type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
charUTF8.const.p("Name", "type name"),
AutoSize("Name")..size_t("NameLen", "length of type name"),
uint64_t("SizeInBits", "size of the type"),
LLVMDWARFTypeEncoding("Encoding", "DWARF encoding code, e.g. {@code LLVMDWARFTypeEncoding_float}."),
LLVMDIFlags("Flags", "flags to encode optional attribute like endianity")
)
LLVMMetadataRef(
"DIBuilderCreatePointerType",
"Create debugging information entry for a pointer.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("PointeeTy", "type pointed by this pointer"),
uint64_t("SizeInBits", "size"),
uint32_t("AlignInBits", "alignment. (optional, pass 0 to ignore)"),
unsigned_int("AddressSpace", "DWARF address space. (optional, pass 0 to ignore)"),
charUTF8.const.p("Name", "pointer type name. (optional)"),
AutoSize("Name")..size_t("NameLen", "length of pointer type name. (optional)")
)
LLVMMetadataRef(
"DIBuilderCreateStructType",
"Create debugging information entry for a struct.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "scope in which this struct is defined"),
charUTF8.const.p("Name", "struct name"),
AutoSize("Name")..size_t("NameLen", "struct name length"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNumber", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private"),
LLVMMetadataRef("DerivedFrom", ""),
LLVMMetadataRef.p("Elements", "struct elements"),
AutoSize("Elements")..unsigned_int("NumElements", "number of struct elements"),
unsigned_int("RunTimeLang", "optional parameter, Objective-C runtime version"),
LLVMMetadataRef("VTableHolder", "the object containing the vtable for the struct"),
charUTF8.const.p("UniqueId", "a unique identifier for the struct"),
AutoSize("UniqueId")..size_t("UniqueIdLen", "length of the unique identifier for the struct")
)
LLVMMetadataRef(
"DIBuilderCreateMemberType",
"Create debugging information entry for a member.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "member scope"),
charUTF8.const.p("Name", "member name"),
AutoSize("Name")..size_t("NameLen", "length of member name"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNo", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
uint64_t("OffsetInBits", "member offset"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private"),
LLVMMetadataRef("Ty", "parent type")
)
LLVMMetadataRef(
"DIBuilderCreateStaticMemberType",
"Create debugging information entry for a C++ static data member.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "member scope"),
charUTF8.const.p("Name", "member name"),
AutoSize("Name")..size_t("NameLen", "length of member name"),
LLVMMetadataRef("File", "file where this member is declared"),
unsigned_int("LineNumber", "line number"),
LLVMMetadataRef("Type", "type of the static member"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private."),
LLVMValueRef("ConstantVal", "const initializer of the member"),
uint32_t("AlignInBits", "member alignment")
)
LLVMMetadataRef(
"DIBuilderCreateMemberPointerType",
"Create debugging information entry for a pointer to member.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("PointeeType", "type pointed to by this pointer"),
LLVMMetadataRef("ClassType", "type for which this pointer points to members of"),
uint64_t("SizeInBits", "size"),
uint32_t("AlignInBits", "alignment"),
LLVMDIFlags("Flags", "flags")
)
LLVMMetadataRef(
"DIBuilderCreateObjCIVar",
"Create debugging information entry for Objective-C instance variable.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
charUTF8.const.p("Name", "member name"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNo", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
uint64_t("OffsetInBits", "member offset"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private"),
LLVMMetadataRef("Ty", "parent type"),
LLVMMetadataRef("PropertyNode", "property associated with this ivar")
)
LLVMMetadataRef(
"DIBuilderCreateObjCProperty",
"Create debugging information entry for Objective-C property.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
charUTF8.const.p("Name", "property name"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
LLVMMetadataRef("File", "file where this property is defined"),
unsigned_int("LineNo", "line number"),
charUTF8.const.p("GetterName", "name of the Objective C property getter selector"),
AutoSize("GetterName")..size_t("GetterNameLen", "the length of the C string passed to {@code GetterName}"),
charUTF8.const.p("SetterName", "name of the Objective C property setter selector"),
AutoSize("SetterName")..size_t("SetterNameLen", "the length of the C string passed to {@code SetterName}"),
unsigned_int("PropertyAttributes", "objective C property attributes"),
LLVMMetadataRef("Ty", "type")
)
LLVMMetadataRef(
"DIBuilderCreateObjectPointerType",
"Create a uniqued DIType* clone with FlagObjectPointer and FlagArtificial set.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Type", "the underlying type to which this pointer points")
)
LLVMMetadataRef(
"DIBuilderCreateQualifiedType",
"Create debugging information entry for a qualified type, e.g. 'const int'.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
unsigned_int("Tag", "tag identifying type, e.g. {@code LLVMDWARFTypeQualifier_volatile_type}"),
LLVMMetadataRef("Type", "base Type")
)
LLVMMetadataRef(
"DIBuilderCreateReferenceType",
"Create debugging information entry for a c++ style reference or {@code rvalue} reference type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
unsigned_int("Tag", "tag identifying type,"),
LLVMMetadataRef("Type", "base Type")
)
LLVMMetadataRef(
"DIBuilderCreateNullPtrType",
"Create C++11 {@code nullptr} type.",
LLVMDIBuilderRef("Builder", "the DIBuilder")
)
LLVMMetadataRef(
"DIBuilderCreateTypedef",
"Create debugging information entry for a typedef.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Type", "original type"),
charUTF8.const.p("Name", "typedef name"),
AutoSize("Name")..size_t("NameLen", ""),
LLVMMetadataRef("File", "file where this type is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Scope", "the surrounding context for the typedef"),
uint32_t("AlignInBits", "")
)
LLVMMetadataRef(
"DIBuilderCreateInheritance",
"Create debugging information entry to establish inheritance relationship between two types.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Ty", "original type"),
LLVMMetadataRef("BaseTy", "base type. Ty is inherits from base."),
uint64_t("BaseOffset", "base offset"),
uint32_t("VBPtrOffset", "virtual base pointer offset"),
LLVMDIFlags("Flags", "flags to describe inheritance attribute, e.g. private")
)
LLVMMetadataRef(
"DIBuilderCreateForwardDecl",
"Create a permanent forward-declared type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
unsigned_int("Tag", "a unique tag for this type"),
charUTF8.const.p("Name", "type name"),
AutoSize("Name")..size_t("NameLen", "length of type name"),
LLVMMetadataRef("Scope", "type scope"),
LLVMMetadataRef("File", "file where this type is defined"),
unsigned_int("Line", "line number where this type is defined"),
unsigned_int("RuntimeLang", "indicates runtime version for languages like Objective-C"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
charUTF8.const.p("UniqueIdentifier", "a unique identifier for the type"),
AutoSize("UniqueIdentifier")..size_t("UniqueIdentifierLen", "length of the unique identifier")
)
LLVMMetadataRef(
"DIBuilderCreateReplaceableCompositeType",
"Create a temporary forward-declared type.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
unsigned_int("Tag", "a unique tag for this type"),
charUTF8.const.p("Name", "type name"),
AutoSize("Name")..size_t("NameLen", "length of type name"),
LLVMMetadataRef("Scope", "type scope"),
LLVMMetadataRef("File", "file where this type is defined"),
unsigned_int("Line", "line number where this type is defined"),
unsigned_int("RuntimeLang", "indicates runtime version for languages like Objective-C"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
LLVMDIFlags("Flags", "flags"),
charUTF8.const.p("UniqueIdentifier", "a unique identifier for the type"),
AutoSize("UniqueIdentifier")..size_t("UniqueIdentifierLen", "length of the unique identifier")
)
LLVMMetadataRef(
"DIBuilderCreateBitFieldMemberType",
"Create debugging information entry for a bit field member.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Scope", "member scope"),
charUTF8.const.p("Name", "member name"),
AutoSize("Name")..size_t("NameLen", "length of member name"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNumber", "line number"),
uint64_t("SizeInBits", "member size"),
uint64_t("OffsetInBits", "member offset"),
uint64_t("StorageOffsetInBits", "member storage offset"),
LLVMDIFlags("Flags", "flags to encode member attribute"),
LLVMMetadataRef("Type", "parent type")
)
LLVMMetadataRef(
"DIBuilderCreateClassType",
"Create debugging information entry for a class.",
LLVMDIBuilderRef("Builder", ""),
LLVMMetadataRef("Scope", "scope in which this class is defined"),
charUTF8.const.p("Name", "class name"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
LLVMMetadataRef("File", "file where this member is defined"),
unsigned_int("LineNumber", "line number"),
uint64_t("SizeInBits", "member size"),
uint32_t("AlignInBits", "member alignment"),
uint64_t("OffsetInBits", "member offset"),
LLVMDIFlags("Flags", "flags to encode member attribute, e.g. private."),
LLVMMetadataRef("DerivedFrom", "debug info of the base class of this type"),
LLVMMetadataRef.p("Elements", "class members"),
AutoSize("Elements")..unsigned_int("NumElements", "number of class elements"),
LLVMMetadataRef(
"VTableHolder",
"debug info of the base class that contains vtable for this type. This is used in DW_AT_containing_type. See DWARF documentation for more info."
),
LLVMMetadataRef("TemplateParamsNode", "template type parameters"),
charUTF8.const.p("UniqueIdentifier", "a unique identifier for the type"),
AutoSize("UniqueIdentifier")..size_t("UniqueIdentifierLen", "length of the unique identifier")
)
LLVMMetadataRef(
"DIBuilderCreateArtificialType",
"Create a uniqued {@code DIType*} clone with {@code FlagArtificial} set.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef("Type", "the underlying type")
)
charUTF8.const.p(
"DITypeGetName",
"Get the name of this {@code DIType}.",
LLVMMetadataRef("DType", "the DIType"),
AutoSizeResult..size_t.p("Length", "the length of the returned string")
)
uint64_t(
"DITypeGetSizeInBits",
"Get the size of this {@code DIType} in bits.",
LLVMMetadataRef("DType", "the DIType")
)
uint64_t(
"DITypeGetOffsetInBits",
"Get the offset of this {@code DIType} in bits.",
LLVMMetadataRef("DType", "the DIType")
)
uint32_t(
"DITypeGetAlignInBits",
"Get the alignment of this {@code DIType} in bits.",
LLVMMetadataRef("DType", "the DIType")
)
unsigned_int(
"DITypeGetLine",
"Get the source line where this {@code DIType} is declared.",
LLVMMetadataRef("DType", "the DIType")
)
LLVMDIFlags(
"DITypeGetFlags",
"Get the flags associated with this {@code DIType}.",
LLVMMetadataRef("DType", "the DIType")
)
LLVMMetadataRef(
"DIBuilderGetOrCreateSubrange",
"Create a descriptor for a value range.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
int64_t("LowerBound", "lower bound of the subrange, e.g. 0 for C, 1 for Fortran."),
int64_t("Count", "count of elements in the subrange")
)
LLVMMetadataRef(
"DIBuilderGetOrCreateArray",
"Create an array of {@code DI} Nodes.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
LLVMMetadataRef.p("Data", "the DI Node elements"),
AutoSize("Data")..size_t("NumElements", "number of DI Node elements")
)
LLVMMetadataRef(
"DIBuilderCreateExpression",
"Create a new descriptor for the specified variable which has a complex address expression for its address.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
int64_t.p("Addr", "an array of complex address operations"),
AutoSize("Addr")..size_t("Length", "length of the address operation array")
)
LLVMMetadataRef(
"DIBuilderCreateConstantValueExpression",
"Create a new descriptor for the specified variable that does not have an address, but does have a constant value.",
LLVMDIBuilderRef("Builder", "the DIBuilder"),
int64_t("Value", "the constant value")
)
LLVMMetadataRef(
"DIBuilderCreateGlobalVariableExpression",
"Create a new descriptor for the specified variable.",
LLVMDIBuilderRef("Builder", ""),
LLVMMetadataRef("Scope", "variable scope"),
charUTF8.const.p("Name", "name of the variable"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
charUTF8.const.p("Linkage", "mangled name of the variable"),
AutoSize("Linkage")..size_t("LinkLen", "the length of the C string passed to {@code Linkage}"),
LLVMMetadataRef("File", "file where this variable is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Ty", "variable Type"),
LLVMBool("LocalToUnit", "boolean flag indicate whether this variable is externally visible or not"),
LLVMMetadataRef("Expr", "the location of the global relative to the attached GlobalVariable"),
LLVMMetadataRef("Decl", "reference to the corresponding declaration. variables."),
uint32_t("AlignInBits", "variable alignment(or 0 if no alignment attr was specified)")
)
IgnoreMissing..LLVMMetadataRef(
"DIGlobalVariableExpressionGetVariable",
"""
Retrieves the {@code DIVariable} associated with this global variable expression.
See {@code llvm::DIGlobalVariableExpression::getVariable()}.
""",
LLVMMetadataRef("GVE", "the global variable expression"),
since = "9"
)
IgnoreMissing..LLVMMetadataRef(
"DIGlobalVariableExpressionGetExpression",
"""
Retrieves the {@code DIExpression} associated with this global variable expression.
See {@code llvm::DIGlobalVariableExpression::getExpression()}.
""",
LLVMMetadataRef("GVE", "the global variable expression"),
since = "9"
)
IgnoreMissing..LLVMMetadataRef(
"DIVariableGetFile",
"""
Get the metadata of the file associated with a given variable.
See {@code DIVariable::getFile()},
""",
LLVMMetadataRef("Var", "the variable object"),
since = "9"
)
IgnoreMissing..LLVMMetadataRef(
"DIVariableGetScope",
"""
Get the metadata of the scope associated with a given variable.
See {@code DIVariable::getScope()},
""",
LLVMMetadataRef("Var", "the variable object"),
since = "9"
)
IgnoreMissing..unsigned(
"DIVariableGetLine",
"""
Get the source line where this {@code DIVariable} is declared.
See {@code DIVariable::getLine()}.
""",
LLVMMetadataRef("Var", "the {@code DIVariable}"),
since = "9"
)
LLVMMetadataRef(
"TemporaryMDNode",
"""
Create a new temporary {@code MDNode}. Suitable for use in constructing cyclic {@code MDNode} structures. A temporary {@code MDNode} is not uniqued,
may be RAUW'd, and must be manually deleted with {@code LLVMDisposeTemporaryMDNode}.
""",
LLVMContextRef("Ctx", "the context in which to construct the temporary node"),
LLVMMetadataRef.p("Data", "the metadata elements"),
AutoSize("Data")..size_t("NumElements", "number of metadata elements")
)
void(
"DisposeTemporaryMDNode",
"""
Deallocate a temporary node.
Calls {@code replaceAllUsesWith(nullptr)} before deleting, so any remaining references will be reset.
""",
LLVMMetadataRef("TempNode", "the temporary metadata node")
)
void(
"MetadataReplaceAllUsesWith",
"Replace all uses of temporary metadata.",
LLVMMetadataRef("TempTargetMetadata", "the temporary metadata node"),
LLVMMetadataRef("Replacement", "the replacement metadata node")
)
LLVMMetadataRef(
"DIBuilderCreateTempGlobalVariableFwdDecl",
"Create a new descriptor for the specified global variable that is temporary and meant to be RAUWed.",
LLVMDIBuilderRef("Builder", ""),
LLVMMetadataRef("Scope", "variable scope"),
charUTF8.const.p("Name", "name of the variable"),
AutoSize("Name")..size_t("NameLen", "the length of the C string passed to {@code Name}"),
charUTF8.const.p("Linkage", "mangled name of the variable"),
AutoSize("Linkage")..size_t("LnkLen", "the length of the C string passed to {@code Linkage}"),
LLVMMetadataRef("File", "file where this variable is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Ty", "variable Type"),
LLVMBool("LocalToUnit", "boolean flag indicate whether this variable is externally visible or not"),
LLVMMetadataRef("Decl", "reference to the corresponding declaration"),
uint32_t("AlignInBits", "variable alignment(or 0 if no alignment attr was specified)")
)
LLVMValueRef(
"DIBuilderInsertDeclareBefore",
"Insert a new {@code llvm.dbg.declare} intrinsic call before the given instruction.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMValueRef("Storage", "the storage of the variable to declare"),
LLVMMetadataRef("VarInfo", "the variable's debug info descriptor"),
LLVMMetadataRef("Expr", "a complex location expression for the variable"),
LLVMMetadataRef("DebugLoc", "debug info location"),
LLVMValueRef("Instr", "instruction acting as a location for the new intrinsic")
)
LLVMValueRef(
"DIBuilderInsertDeclareAtEnd",
"""
Insert a new {@code llvm.dbg.declare} intrinsic call at the end of the given basic block. If the basic block has a terminator instruction, the
intrinsic is inserted before that terminator instruction.
""",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMValueRef("Storage", "the storage of the variable to declare"),
LLVMMetadataRef("VarInfo", "the variable's debug info descriptor"),
LLVMMetadataRef("Expr", "a complex location expression for the variable"),
LLVMMetadataRef("DebugLoc", "debug info location"),
LLVMBasicBlockRef("Block", "basic block acting as a location for the new intrinsic")
)
LLVMValueRef(
"DIBuilderInsertDbgValueBefore",
"Insert a new {@code llvm.dbg.value} intrinsic call before the given instruction.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMValueRef("Val", "the value of the variable"),
LLVMMetadataRef("VarInfo", "the variable's debug info descriptor"),
LLVMMetadataRef("Expr", "a complex location expression for the variable"),
LLVMMetadataRef("DebugLoc", "debug info location"),
LLVMValueRef("Instr", "instruction acting as a location for the new intrinsic")
)
LLVMValueRef(
"DIBuilderInsertDbgValueAtEnd",
"""
Insert a new {@code llvm.dbg.value} intrinsic call at the end of the given basic block. If the basic block has a terminator instruction, the intrinsic
is inserted before that terminator instruction.
""",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMValueRef("Val", "the value of the variable"),
LLVMMetadataRef("VarInfo", "the variable's debug info descriptor"),
LLVMMetadataRef("Expr", "a complex location expression for the variable"),
LLVMMetadataRef("DebugLoc", "debug info location"),
LLVMBasicBlockRef("Block", "basic block acting as a location for the new intrinsic")
)
LLVMMetadataRef(
"DIBuilderCreateAutoVariable",
"Create a new descriptor for a local auto variable.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "the local scope the variable is declared in"),
charUTF8.const.p("Name", "variable name"),
AutoSize("Name")..size_t("NameLen", "length of variable name"),
LLVMMetadataRef("File", "file where this variable is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Ty", "metadata describing the type of the variable"),
LLVMBool("AlwaysPreserve", "if true, this descriptor will survive optimizations"),
LLVMDIFlags("Flags", "flags"),
uint32_t("AlignInBits", "variable alignment")
)
LLVMMetadataRef(
"DIBuilderCreateParameterVariable",
"Create a new descriptor for a function parameter variable.",
LLVMDIBuilderRef("Builder", "the {@code DIBuilder}"),
LLVMMetadataRef("Scope", "the local scope the variable is declared in"),
charUTF8.const.p("Name", "variable name"),
AutoSize("Name")..size_t("NameLen", "length of variable name"),
unsigned_int("ArgNo", "unique argument number for this variable; starts at 1"),
LLVMMetadataRef("File", "file where this variable is defined"),
unsigned_int("LineNo", "line number"),
LLVMMetadataRef("Ty", "metadata describing the type of the variable"),
LLVMBool("AlwaysPreserve", "if true, this descriptor will survive optimizations"),
LLVMDIFlags("Flags", "flags")
)
LLVMMetadataRef(
"GetSubprogram",
"Get the metadata of the subprogram attached to a function.",
LLVMValueRef("Func", "")
)
void(
"SetSubprogram",
"Set the subprogram attached to a function.",
LLVMValueRef("Func", ""),
LLVMMetadataRef("SP", "")
)
IgnoreMissing..unsigned(
"DISubprogramGetLine",
"""
Get the line associated with a given subprogram.
See {@code DISubprogram::getLine()}.
""",
LLVMMetadataRef("Subprogram", "the subprogram object"),
since = "9"
)
IgnoreMissing..unsigned(
"InstructionGetDebugLoc",
"""
Get the debug location for the given instruction.
See {@code llvm::Instruction::getDebugLoc()}
""",
LLVMValueRef("Inst", ""),
since = "9"
)
IgnoreMissing..void(
"InstructionSetDebugLoc",
"""
Set the debug location for the given instruction.
To clear the location metadata of the given instruction, pass #NULL to {@code Loc}.
See {@code llvm::Instruction::setDebugLoc()}
""",
LLVMValueRef("Inst", ""),
nullable..LLVMMetadataRef("Loc", ""),
since = "9"
)
IgnoreMissing..LLVMMetadataKind(
"GetMetadataKind",
"Obtain the enumerated type of a Metadata instance.",
LLVMMetadataRef("Metadata", "")
)
} | bsd-3-clause | cfcff00c69b89b05a7ab315ecb5890a6 | 39.958926 | 158 | 0.640098 | 4.366568 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/linux/templates/fcntl.kt | 4 | 41319 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.linux.templates
import core.linux.*
import org.lwjgl.generator.*
val fcntl = "FCNTL".nativeClass(Module.CORE_LINUX, nativeSubPath = "linux") {
nativeImport(
"<fcntl.h>",
"<errno.h>"
)
documentation = "Native bindings to <fcntl.h>."
EnumConstant(
"",
"O_ACCMODE".enum("", "00000003"),
"O_RDONLY".enum("", "00000000"),
"O_WRONLY".enum("", "00000001"),
"O_RDWR".enum("", "00000002"),
"O_APPEND".enum(
"""
The file is opened in append mode.
Before each {@code write(2)}, the file offset is positioned at the end of the file, as if with {@code lseek(2)}. {@code O_APPEND} may lead to
corrupted files on NFS file systems if more than one process appends data to a file at once. This is because NFS does not support appending to a
file, so the client kernel has to simulate it, which can't be done without a race condition.
""",
"00002000"
),
"O_ASYNC".enum(
"""
Enable signal-driven I/O: generate a signal ({@code SIGIO} by default, but this can be changed via {@code fcntl(2)}) when input or output becomes
possible on this file descriptor.
This feature is only available for terminals, pseudoterminals, sockets, and (since Linux 2.6) pipes and FIFOs. See {@code fcntl(2)} for further
details.
""",
"020000"
),
"O_CLOEXEC".enum(
"""
Enable the close-on-exec flag for the new file descriptor.
Specifying this flag permits a program to avoid additional {@code fcntl(2) F_SETFD} operations to set the {@code FD_CLOEXEC} flag. Additionally,
use of this flag is essential in some multithreaded programs since using a separate {@code fcntl(2) F_SETFD} operation to set the
{@code FD_CLOEXEC} flag does not suffice to avoid race conditions where one thread opens a file descriptor at the same time as another thread does
a {@code fork(2)} plus {@code execve(2)}.
""",
"02000000"
),
"O_CREAT".enum(
"""
If the file does not exist it will be created.
The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group
ID of the process or to the group ID of the parent directory (depending on file system type and mount options, and the mode of the parent
directory, see the mount options {@code bsdgroups} and {@code sysvgroups} described in {@code mount(8)}).
""",
"00000100"
),
"O_DIRECT".enum(
"""
Try to minimize cache effects of the I/O to and from this file.
In general this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File I/O is done
directly to/from user-space buffers. The {@code O_DIRECT} flag on its own makes an effort to transfer data synchronously, but does not give the
guarantees of the {@code O_SYNC} flag that data and necessary metadata are transferred. To guarantee synchronous I/O, {@code O_SYNC} must be used
in addition to {@code O_DIRECT}.
A semantically similar (but deprecated) interface for block devices is described in {@code raw(8)}.
""",
"040000"
),
"O_DIRECTORY".enum(
"""
If pathname is not a directory, cause the open to fail.
This flag is Linux-specific, and was added in kernel version 2.1.126, to avoid denial-of-service problems if {@code opendir(3)} is called on a FIFO
or tape device, but should not be used outside of the implementation of {@code opendir(3)}.
""",
"0200000"
),
"O_DSYNC".enum("""""", "00010000"),
"O_EXCL".enum(
"""
Ensure that this call creates the file: if this flag is specified in conjunction with {@code O_CREAT}, and pathname already exists, then
{@code open()} will fail.
When these two flags are specified, symbolic links are not followed: if {@code pathname} is a symbolic link, then {@code open()} fails regardless
of where the symbolic link points to.
In general, the behavior of {@code O_EXCL} is undefined if it is used without {@code O_CREAT}. There is one exception: on Linux 2.6 and later,
{@code O_EXCL} can be used without {@code O_CREAT} if {@code pathname} refers to a block device. If the block device is in use by the system (e.g.,
mounted), {@code open()} fails with the error {@code EBUSY}.
On NFS, {@code O_EXCL} is only supported when using NFSv3 or later on kernel 2.6 or later. In NFS environments where {@code O_EXCL} support is not
provided, programs that rely on it for performing locking tasks will contain a race condition. Portable programs that want to perform atomic file
locking using a lockfile, and need to avoid reliance on NFS support for {@code O_EXCL}, can create a unique file on the same file system (e.g.,
incorporating hostname and PID), and use {@code link(2)} to make a link to the lockfile. If {@code link(2)} returns 0, the lock is successful.
Otherwise, use {@code stat(2)} on the unique file to check if its link count has increased to 2, in which case the lock is also successful.
""",
"00000200"
),
"O_LARGEFILE".enum(
"""
(LFS) Allow files whose sizes cannot be represented in an {@code off_t} (but can be represented in an {@code off64_t}) to be opened.
The {@code _LARGEFILE64_SOURCE} macro must be defined (before including any header files) in order to obtain this definition. Setting the
{@code _FILE_OFFSET_BITS} feature test macro to 64 (rather than using {@code O_LARGEFILE}) is the preferred method of accessing large files on
32-bit systems (see {@code feature_test_macros(7)}).
""",
"00100000"
),
"O_NOATIME".enum(
"""
Do not update the file last access time ({@code st_atime} in the {@code inode}) when the file is {@code read(2)}.
This flag is intended for use by indexing or backup programs, where its use can significantly reduce the amount of disk activity. This flag may not
be effective on all file systems. One example is NFS, where the server maintains the access time.
""",
"01000000"
),
"O_NOCTTY".enum(
"""
If {@code pathname} refers to a terminal device --see {@code tty(4)}-- it will not become the process's controlling terminal even if the process
does not have one.
""",
"00000400"
),
"O_NOFOLLOW".enum(
"""
If {@code pathname} is a symbolic link, then the open fails.
This is a FreeBSD extension, which was added to Linux in version 2.1.126. Symbolic links in earlier components of the {@code pathname} will still
be followed.
""",
"00400000"
),
"O_NONBLOCK".enum(
"""
When possible, the file is opened in nonblocking mode.
Neither the {@code open()} nor any subsequent operations on the file descriptor which is returned will cause the calling process to wait. For the
handling of FIFOs (named pipes), see also {@code fifo(7)}. For a discussion of the effect of {@code O_NONBLOCK} in conjunction with mandatory file
locks and with file leases, see {@code fcntl(2)}.
""",
"00004000"
),
"O_NDELAY".enum("""""", "O_NONBLOCK"),
"O_PATH".enum("""""", "010000000"),
"O_SYNC".enum(
"""
The file is opened for synchronous I/O.
Any {@code write(2)}s on the resulting file descriptor will block the calling process until the data has been physically written to the underlying
hardware.
""",
"04010000"
),
"O_TMPFILE".enum("""""", "020000000 | O_DIRECTORY"),
"O_TRUNC".enum(
"""
If the file already exists and is a regular file and the open mode allows writing (i.e., is {@code O_RDWR} or {@code O_WRONLY}) it will be
truncated to length 0.
If the file is a FIFO or terminal device file, the {@code O_TRUNC} flag is ignored. Otherwise the effect of {@code O_TRUNC} is unspecified.
""",
"00001000"
),
)
EnumConstant(
"File types encoded in type {@code mode_t}.",
"S_IFMT".enum("Type of file.", "00170000"),
"S_IFBLK".enum("Block special.", "0060000"),
"S_IFCHR".enum("Character special.", "0020000"),
"S_IFIFO".enum("FIFO special.", "0010000"),
"S_IFREG".enum("Regular.", "0100000"),
"S_IFDIR".enum("Directory.", "0040000"),
"S_IFLNK".enum("Symbolic link.", "0120000"),
"S_IFSOCK".enum("Socket.", "0140000")
)
val ModeBits = EnumConstant(
"File mode bits encoded in type {@code mode_t}.",
"S_IRWXU".enum("Read, write, execute/search by owner.", "0700"),
"S_IRUSR".enum("Read permission, owner.", "0400"),
"S_IWUSR".enum("Write permission, owner.", "0200"),
"S_IXUSR".enum("Execute/search permission, owner.", "0100"),
"S_IRWXG".enum("Read, write, execute/search by group.", "070"),
"S_IRGRP".enum("Read permission, group.", "040"),
"S_IWGRP".enum("Write permission, group.", "020"),
"S_IXGRP".enum("Execute/search permission, group.", "010"),
"S_IRWXO".enum("Read, write, execute/search by others.", "07"),
"S_IROTH".enum("Read permission, others.", "04"),
"S_IWOTH".enum("Write permission, others.", "02"),
"S_IXOTH".enum("Execute/search permission, others.", "01"),
"S_ISUID".enum("Set-user-ID on execution.", "04000"),
"S_ISGID".enum("Set-group-ID on execution.", "02000"),
"S_ISVTX".enum("On directories, restricted deletion flag.", "01000")
).javaDocLinks
val commands = EnumConstant(
"#fcntl() commands.",
"F_DUPFD".enum(
"""
Duplicate the file descriptor {@code fd} using the lowest-numbered available file descriptor greater than or equal to {@code arg}.
This is different from {@code dup2(2)}, which uses exactly the file descriptor specified.
On success, the new file descriptor is returned.
See {@code dup(2)} for further details.
""",
"0"
),
"F_GETFD".enum("Return (as the function result) the file descriptor flags; {@code arg} is ignored.", "1"),
"F_SETFD".enum("Set the file descriptor flags to the value specified by {@code arg}.", "2"),
"F_GETFL".enum("Return (as the function result) the file access mode and the file status flags; {@code arg} is ignored.", "3"),
"F_SETFL".enum(
"""
Set the file status flags to the value specified by {@code arg}.
File access mode (#O_RDONLY, #O_WRONLY, #O_RDWR) and file creation flags (i.e., #O_CREAT, #O_EXCL, #O_NOCTTY, #O_TRUNC) in {@code arg} are ignored.
On Linux, this command can change only the #O_APPEND, #O_ASYNC, #O_DIRECT, #O_NOATIME, and #O_NONBLOCK flags. It is not possible to change the
#O_DSYNC and #O_SYNC flags; see BUGS, below.
""",
"4"
),
"F_GETLK".enum(
"""
On input to this call, lock describes a lock we would like to place on the file.
If the lock could be placed, {@code fcntl()} does not actually place it, but returns #F_UNLCK in the {@code l_type} field of lock and leaves the
other fields of the structure unchanged.
If one or more incompatible locks would prevent this lock being placed, then {@code fcntl()} returns details about one of those locks in the
{@code l_type}, {@code l_whence}, {@code l_start}, and {@code l_len} fields of lock. If the conflicting lock is a traditional (process-associated)
record lock, then the {@code l_pid} field is set to the {@code PID} of the process holding that lock. If the conflicting lock is an open file
description lock, then {@code l_pid} is set to -1. Note that the returned information may already be out of date by the time the caller inspects
it.
""",
"5"
),
"F_SETLK".enum(
"""
Acquire a lock (when {@code l_type} is #F_RDLCK or #F_WRLCK) or release a lock (when {@code l_type} is #F_UNLCK) on the bytes specified by the
{@code l_whence}, {@code l_start}, and {@code l_len} fields of lock.
If a conflicting lock is held by another process, this call returns -1 and sets {@code errno} to {@code EACCES} or {@code EAGAIN}. (The error
returned in this case differs across implementations, so POSIX requires a portable application to check for both errors.)
""",
"8"
),
"F_SETLKW".enum(
"""
As for #F_SETLK, but if a conflicting lock is held on the file, then wait for that lock to be released.
If a signal is caught while waiting, then the call is interrupted and (after the signal handler has returned) returns immediately (with return
value -1 and errno set to {@code EINTR}; see {@code signal(7)}).
""",
"7"
),
"F_SETOWN".enum(
"""
Set the process ID or process group ID that will receive {@code SIGIO} and {@code SIGURG} signals for events on the file descriptor {@code fd}.
The target process or process group ID is specified in {@code arg}. A process ID is specified as a positive value; a process group ID is specified
as a negative value. Most commonly, the calling process specifies itself as the owner (that is, {@code arg} is specified as {@code getpid(2)}).
As well as setting the file descriptor owner, one must also enable generation of signals on the file descriptor. This is done by using the
{@code fcntl()} #F_SETFL command to set the #O_ASYNC file status flag on the file descriptor. Subsequently, a {@code SIGIO} signal is sent whenever
input or output becomes possible on the file descriptor. The {@code fcntl()} #F_SETSIG command can be used to obtain delivery of a signal other
than {@code SIGIO}.
Sending a signal to the owner process (group) specified by {@code F_SETOWN} is subject to the same permissions checks as are described for
{@code kill(2)}, where the sending process is the one that employs {@code F_SETOWN} (but see BUGS below). If this permission check fails, then the
signal is silently discarded. Note: The {@code F_SETOWN} operation records the caller's credentials at the time of the {@code fcntl()} call, and it
is these saved credentials that are used for the permission checks.
If the file descriptor {@code fd} refers to a socket, {@code F_SETOWN} also selects the recipient of {@code SIGURG} signals that are delivered when
out-of-band data arrives on that socket. ({@code SIGURG} is sent in any situation where {@code select(2)} would report the socket as having an
"exceptional condition".)
The following was true in 2.6.x kernels up to and including kernel 2.6.11:
If a nonzero value is given to #F_SETSIG in a multithreaded process running with a threading library that supports thread groups (e.g., NPTL), then
a positive value given to {@code F_SETOWN} has a different meaning: instead of being a process ID identifying a whole process, it is a thread ID
identifying a specific thread within a process. Consequently, it may be necessary to pass {@code F_SETOWN} the result of {@code gettid(2)} instead
of {@code getpid(2)} to get sensible results when {@code F_SETSIG} is used. (In current Linux threading implementations, a main thread's thread ID
is the same as its process ID. This means that a single-threaded program can equally use {@code gettid(2)} or {@code getpid(2)} in this scenario.)
Note, however, that the statements in this paragraph do not apply to the {@code SIGURG} signal generated for out-of-band data on a socket: this
signal is always sent to either a process or a process group, depending on the value given to {@code F_SETOWN}.
The above behavior was accidentally dropped in Linux 2.6.12, and won't be restored. From Linux 2.6.32 onward, use #F_SETOWN_EX to target
{@code SIGIO} and {@code SIGURG} signals at a particular thread.
""",
"8"
),
"F_GETOWN".enum(
"""
Return (as the function result) the process ID or process group ID currently receiving {@code SIGIO} and {@code SIGURG} signals for events on file
descriptor {@code fd}.
Process IDs are returned as positive values; process group IDs are returned as negative values (but see BUGS below). {@code arg} is ignored.
""",
"9"
),
"F_SETSIG".enum(
"""
Set the signal sent when input or output becomes possible to the value given in {@code arg}.
A value of zero means to send the default {@code SIGIO} signal. Any other value (including {@code SIGIO}) is the signal to send instead, and in
this case additional info is available to the signal handler if installed with {@code SA_SIGINFO}.
By using {@code F_SETSIG} with a nonzero value, and setting {@code SA_SIGINFO} for the signal handler (see {@code sigaction(2)}), extra information
about I/O events is passed to the handler in a {@code siginfo_t} structure. If the {@code si_code} field indicates the source is {@code SI_SIGIO},
the {@code si_fd} field gives the file descriptor associated with the event. Otherwise, there is no indication which file descriptors are pending,
and you should use the usual mechanisms ({@code select(2)}, {@code poll(2)}, {@code read(2)} with {@code O_NONBLOCK} set etc.) to determine which
file descriptors are available for I/O.
Note that the file descriptor provided in {@code si_fd} is the one that was specified during the {@code F_SETSIG} operation. This can lead to an
unusual corner case. If the file descriptor is duplicated ({@code dup(2)} or similar), and the original file descriptor is closed, then I/O events
will continue to be generated, but the {@code si_fd} field will contain the number of the now closed file descriptor.
By selecting a real time signal (value ≥ {@code SIGRTMIN}), multiple I/O events may be queued using the same signal numbers. (Queuing is
dependent on available memory.) Extra information is available if {@code SA_SIGINFO} is set for the signal handler, as above.
Note that Linux imposes a limit on the number of real-time signals that may be queued to a process (see {@code getrlimit(2)} and {@code signal(7)})
and if this limit is reached, then the kernel reverts to delivering {@code SIGIO}, and this signal is delivered to the entire process rather than
to a specific thread.
""",
"10"
),
"F_GETSIG".enum(
"""
Return (as the function result) the signal sent when input or output becomes possible.
A value of zero means {@code SIGIO} is sent. Any other value (including {@code SIGIO}) is the signal sent instead, and in this case additional info
is available to the signal handler if installed with {@code SA_SIGINFO}. {@code arg} is ignored.
""",
"11"
),
"F_SETOWN_EX".enum(
"""
This operation performs a similar task to #F_SETOWN. It allows the caller to direct I/O availability signals to a specific thread, process, or
process group.
The caller specifies the target of signals via {@code arg}, which is a pointer to a ##FOwnerEx structure. The type field has one of the following
values, which define how pid is interpreted: #F_OWNER_TID, #F_OWNER_PID, #F_OWNER_PGRP.
""",
"15"
),
"F_GETOWN_EX".enum(
"""
Return the current file descriptor owner settings as defined by a previous #F_SETOWN_EX operation.
The information is returned in the ##FOwnerEx structure pointed to by {@code arg}.
The type field will have one of the values #F_OWNER_TID, #F_OWNER_PID, or #F_OWNER_PGRP. The {@code pid} field is a positive integer representing a
thread ID, process ID, or process group ID. See #F_SETOWN_EX for more details.
""",
"16"
),
"F_OFD_GETLK".enum(
"""
On input to this call, {@code lock} describes an open file description lock we would like to place on the file.
If the lock could be placed, {@code fcntl()} does not actually place it, but returns #F_UNLCK in the {@code l_type} field of {@code lock} and
leaves the other fields of the structure unchanged. If one or more incompatible locks would prevent this lock being placed, then details about one
of these locks are returned via {@code lock}, as described above for #F_GETLK.
""",
"36"
),
"F_OFD_SETLK".enum(
"""
Acquire an open file description lock (when {@code l_type} is #F_RDLCK or #F_WRLCK) or release an open file description lock (when {@code l_type}
is #F_UNLCK) on the bytes specified by the {@code l_whence}, {@code l_start}, and {@code l_len} fields of {@code lock}.
If a conflicting lock is held by another process, this call returns -1 and sets {@code errno} to {@code EAGAIN}.
""",
"37"
),
"F_OFD_SETLKW".enum(
"""
As for #F_OFD_SETLK, but if a conflicting lock is held on the file, then wait for that lock to be released.
If a signal is caught while waiting, then the call is interrupted and (after the signal handler has returned) returns immediately (with return
value -1 and {@code errno} set to {@code EINTR}; see {@code signal(7)}).
""",
"38"
),
"F_SETLEASE".enum(
"Set or remove a file lease according to which of the following values is specified in the integer {@code arg}: #F_RDLCK, #F_WRLCK, #F_UNLCK",
"1024"
),
"F_GETLEASE".enum(
"""
Indicates what type of lease is associated with the file descriptor {@code fd} by returning either #F_RDLCK, #F_WRLCK, or #F_UNLCK, indicating,
respectively, a read lease, a write lease, or no lease. {@code arg} is ignored.
""",
"1025"
),
"F_NOTIFY".enum(
"""
(Linux 2.4 onward) Provide notification when the directory referred to by {@code fd} or any of the files that it contains is changed.
The events to be notified are specified in {@code arg}, which is a bit mask specified by ORing together zero or more of the following bits:
#DN_ACCESS, #DN_MODIFY, #DN_CREATE, #DN_DELETE, #DN_RENAME, #DN_ATTRIB
(In order to obtain these definitions, the {@code _GNU_SOURCE} feature test macro must be defined before including any header files.)
Directory notifications are normally "one-shot", and the application must reregister to receive further notifications. Alternatively, if
#DN_MULTISHOT is included in {@code arg}, then notification will remain in effect until explicitly removed.
A series of {@code F_NOTIFY} requests is cumulative, with the events in {@code arg} being added to the set already monitored. To disable
notification of all events, make an {@code F_NOTIFY} call specifying {@code arg} as 0.
Notification occurs via delivery of a signal. The default signal is {@code SIGIO}, but this can be changed using the #F_SETSIG command to
{@code fcntl()}. (Note that {@code SIGIO} is one of the nonqueuing standard signals; switching to the use of a real-time signal means that multiple
notifications can be queued to the process.) In the latter case, the signal handler receives a {@code siginfo_t} structure as its second argument
(if the handler was established using {@code SA_SIGINFO}) and the {@code si_fd} field of this structure contains the file descriptor which
generated the notification (useful when establishing notification on multiple directories).
Especially when using {@code DN_MULTISHOT}, a real time signal should be used for notification, so that multiple notifications can be queued.
NOTE: New applications should use the {@code inotify} interface (available since kernel 2.6.13), which provides a much superior interface for
obtaining notifications of filesystem events. See {@code inotify(7)}.
""",
"1026"
),
"F_SETPIPE_SZ".enum(
"""
Change the capacity of the pipe referred to by {@code fd} to be at least {@code arg} bytes.
An unprivileged process can adjust the pipe capacity to any value between the system page size and the limit defined in
{@code /proc/sys/fs/pipe-max-size} (see {@code proc(5)}). Attempts to set the pipe capacity below the page size are silently rounded up to the page
size. Attempts by an unprivileged process to set the pipe capacity above the limit in {@code /proc/sys/fs/pipe-max-size} yield the error
{@code EPERM}; a privileged process ({@code CAP_SYS_RESOURCE}) can override the limit.
When allocating the buffer for the pipe, the kernel may use a capacity larger than {@code arg}, if that is convenient for the implementation. (In
the current implementation, the allocation is the next higher power-of-two page-size multiple of the requested size.) The actual capacity (in
bytes) that is set is returned as the function result.
Attempting to set the pipe capacity smaller than the amount of buffer space currently used to store data produces the error {@code EBUSY}.
Note that because of the way the pages of the pipe buffer are employed when data is written to the pipe, the number of bytes that can be written
may be less than the nominal size, depending on the size of the writes.
""",
"1031"
),
"F_GETPIPE_SZ".enum("Return (as the function result) the capacity of the pipe referred to by {@code fd}.", "1032"
),
"F_ADD_SEALS".enum(
"""
Add the seals given in the bit-mask argument {@code arg} to the set of seals of the {@code inode} referred to by the file descriptor {@code fd}.
Seals cannot be removed again. Once this call succeeds, the seals are enforced by the kernel immediately. If the current set of seals includes
#F_SEAL_SEAL (see below), then this call will be rejected with {@code EPERM}. Adding a seal that is already set is a no-op, in case
{@code F_SEAL_SEAL} is not set already. In order to place a seal, the file descriptor {@code fd} must be writable.
""",
"1033"
),
"F_GET_SEALS".enum(
"""
Return (as the function result) the current set of seals of the {@code inode} referred to by {@code fd}.
If no seals are set, 0 is returned. If the file does not support sealing, -1 is returned and {@code errno} is set to {@code EINVAL}.
""",
"1034"
),
"F_GET_RW_HINT".enum("Returns the value of the read/write hint associated with the underlying {@code inode} referred to by {@code fd}.", "1035"),
"F_SET_RW_HINT".enum(
"""
Sets the read/write hint value associated with the underlying {@code inode} referred to by {@code fd}.
This hint persists until either it is explicitly modified or the underlying filesystem is unmounted.
""",
"1036"
),
"F_GET_FILE_RW_HINT".enum("Returns the value of the read/write hint associated with the open file description referred to by {@code fd}.", "1037"),
"F_SET_FILE_RW_HINT".enum("Sets the read/write hint value associated with the open file description referred to by {@code fd}.", "1038"),
"F_DUPFD_CLOEXEC".enum(
"""
As for #F_DUPFD, but additionally set the close-on-exec flag for the duplicate file descriptor.
Specifying this flag permits a program to avoid an additional {@code fcntl()} #F_SETFD operation to set the #FD_CLOEXEC flag. For an explanation of
why this flag is useful, see the description of #O_CLOEXEC in {@code open(2)}.
""",
"1030"
)
).javaDocLinks
IntConstant("", "FD_CLOEXEC".."1")
EnumConstant(
"For posix #fcntl() and {@code l_type} field of an ##Flock for {@code lockf()}.",
"F_RDLCK".enum(
"""
Take out a read lease.
This will cause the calling process to be notified when the file is opened for writing or is truncated. A read lease can be placed only on a file
descriptor that is opened read-only.
""",
"0"
),
"F_WRLCK".enum(
"""
Take out a write lease.
This will cause the caller to be notified when the file is opened for reading or writing or is truncated. A write lease may be placed on a file
only if there are no other open file descriptors for the file.
""",
"1"
),
"F_UNLCK".enum("Remove our lease from the file.", "2"),
"F_EXLCK".enum("", "4"),
"F_SHLCK".enum("", "8")
)
EnumConstant(
"##FOwnerEx{@code ::type} values.",
"F_OWNER_TID".enum(
"""
Send the signal to the thread whose thread ID (the value returned by a call to {@code clone(2)} or {@code gettid(2)}) is specified in {@code pid}.
""",
"0"
),
"F_OWNER_PID".enum(" Send the signal to the process whose ID is specified in {@code pid}.", "1"),
"F_OWNER_PGRP".enum(
"""
Send the signal to the process group whose ID is specified in {@code pid}.
(Note that, unlike with #F_SETOWN, a process group ID is specified as a positive value here.)
""",
"2"
)
)
EnumConstant(
"",
"LOCK_SH".enum("shared lock", "1"),
"LOCK_EX".enum("exclusive lock", "2"),
"LOCK_NB".enum("or'd with one of the above to prevent blocking", "4"),
"LOCK_UN".enum("remove lock", "8"),
"LOCK_MAND".enum("This is a mandatory flock...", "32"),
"LOCK_READ".enum("which allows concurrent read operations", "64"),
"LOCK_WRITE".enum("which allows concurrent write operations", "128"),
"LOCK_RW".enum("which allows concurrent read & writes ops", "192")
)
EnumConstant(
"",
"DN_ACCESS".enum("A file was accessed ({@code read(2)}, {@code pread(2)}, {@code readv(2)}, and similar).", 0x00000001),
"DN_MODIFY".enum(
"A file was modified ({@code write(2)}, {@code pwrite(2)}, {@code writev(2)}, {@code truncate(2)}, {@code ftruncate(2)}, and similar).",
0x00000002
),
"DN_CREATE".enum(
"""
A file was created ({@code open(2)}, {@code creat(2)}, {@code mknod(2)}, {@code mkdir(2)}, {@code link(2)}, {@code symlink(2)}, {@code rename(2)}
into this directory).
""",
0x00000004
),
"DN_DELETE".enum("A file was unlinked ({@code unlink(2)}, {@code rename(2)} to another directory, {@code rmdir(2)}).", 0x00000008),
"DN_RENAME".enum("A file was renamed within this directory ({@code rename(2)}).", 0x00000010),
"DN_ATTRIB".enum(
"The attributes of a file were changed ({@code chown(2)}, {@code chmod(2)}, {@code utime(2)}, {@code utimensat(2)}, and similar).",
0x00000020
),
"DN_MULTISHOT".enum("Don't remove notifier", "0x80000000")
)
EnumConstant(
"",
"F_SEAL_SEAL".enum(
"""
If this seal is set, any further call to {@code fcntl()} with #F_ADD_SEALS fails with the error {@code EPERM}.
Therefore, this seal prevents any modifications to the set of seals itself. If the initial set of seals of a file includes {@code F_SEAL_SEAL},
then this effectively causes the set of seals to be constant and locked.
""",
"0x0001"
),
"F_SEAL_SHRINK".enum(
"""
If this seal is set, the file in question cannot be reduced in size.
This affects {@code open(2)} with the #O_TRUNC flag as well as {@code truncate(2)} and {@code ftruncate(2)}. Those calls fail with {@code EPERM} if
you try to shrink the file in question. Increasing the file size is still possible.
""",
"0x0002"
),
"F_SEAL_GROW".enum(
"""
If this seal is set, the size of the file in question cannot be increased.
This affects {@code write(2)} beyond the end of the file, {@code truncate(2)}, {@code ftruncate(2)}, and {@code fallocate(2)}. These calls fail
with {@code EPERM} if you use them to increase the file size. If you keep the size or shrink it, those calls still work as expected.
""",
"0x0004"
),
"F_SEAL_WRITE".enum(
"""
If this seal is set, you cannot modify the contents of the file.
Note that shrinking or growing the size of the file is still possible and allowed. Thus, this seal is normally used in combination with one of the
other seals. This seal affects {@code write(2)} and {@code fallocate(2)} (only in combination with the {@code FALLOC_FL_PUNCH_HOLE} flag). Those
calls fail with {@code EPERM} if this seal is set. Furthermore, trying to create new shared, writable memory-mappings via {@code mmap(2)} will also
fail with {@code EPERM}.
Using the #F_ADD_SEALS operation to set the {@code F_SEAL_WRITE} seal fails with {@code EBUSY} if any writable, shared mapping exists. Such
mappings must be unmapped before you can add this seal. Furthermore, if there are any asynchronous I/O operations ({@code io_submit(2)}) pending on
the file, all outstanding writes will be discarded.
""",
"0x0008"
),
"F_SEAL_FUTURE_WRITE".enum(
"""
The effect of this seal is similar to #F_SEAL_WRITE, but the contents of the file can still be modified via shared writable mappings that were
created prior to the seal being set.
Any attempt to create a new writable mapping on the file via {@code mmap(2)} will fail with {@code EPERM}. Likewise, an attempt to write to the
file via {@code write(2)} will fail with {@code EPERM}.
Using this seal, one process can create a memory buffer that it can continue to modify while sharing that buffer on a "read-only" basis with other
processes.
(since Linux 5.1)
""",
"0x0010"
)
)
EnumConstant(
"",
"RWH_WRITE_LIFE_NOT_SET".enum("No specific hint has been set. This is the default value.", "0"),
"RWH_WRITE_LIFE_NONE".enum("No specific write lifetime is associated with this file or {@code inode}."),
"RWH_WRITE_LIFE_SHORT".enum("Data written to this {@code inode} or via this open file description is expected to have a short lifetime."),
"RWH_WRITE_LIFE_MEDIUM".enum(
"""
Data written to this {@code inode} or via this open file description is expected to have a lifetime longer than data written with
#RWH_WRITE_LIFE_SHORT.
"""
),
"RWH_WRITE_LIFE_LONG".enum(
"""
Data written to this {@code inode} or via this open file description is expected to have a lifetime longer than data written with
#RWH_WRITE_LIFE_MEDIUM.
"""
),
"RWH_WRITE_LIFE_EXTREME".enum(
"""
Data written to this {@code inode} or via this open file description is expected to have a lifetime longer than data written with
#RWH_WRITE_LIFE_LONG.
"""
)
)
SaveErrno..int(
"open",
"""
Given a {@code pathname} for a file, {@code open()} returns a file descriptor, a small, nonnegative integer for use in subsequent system calls
({@code read(2)}, {@code write(2)}, {@code lseek(2)}, {@code fcntl(2)}, etc.).
The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.
""",
charUTF8.const.p("pathname", ""),
int("flags", ""),
mode_t("mode", "", ModeBits, LinkMode.BITFIELD),
returnDoc = "the new file descriptor, or -1 if an error occurred (in which case, {@code errno} is set appropriately)."
)
SaveErrno..int(
"openat",
"""
The {@code openat()} system call operates in exactly the same way as {@code open(2)}, except for the differences described in this manual page.
If the pathname given in {@code pathname} is relative, then it is interpreted relative to the directory referred to by the file descriptor
{@code dirfd} (rather than relative to the current working directory of the calling process, as is done by {@code open(2)} for a relative pathname).
If {@code pathname} is relative and {@code dirfd} is the special value {@code AT_FDCWD}, then pathname is interpreted relative to the current working
directory of the calling process (like {@code open(2)}).
If {@code pathname} is absolute, then {@code dirfd} is ignored.
""",
int("dirfd", ""),
charUTF8.const.p("pathname", ""),
int("flags", ""),
mode_t("mode", "", ModeBits, LinkMode.BITFIELD),
returnDoc = "a new file descriptor on success. On error, -1 is returned and {@code errno} is set to indicate the error."
)
SaveErrno..int(
"creat",
"""
Equivalent to {@code open()} with {@code flags} equal to {@code O_CREAT|O_WRONLY|O_TRUNC}.
""",
charUTF8.const.p("pathname", ""),
mode_t("mode", "", ModeBits, LinkMode.BITFIELD)
)
SaveErrno..int(
"fcntl",
"""
Performs one of the operations determined by {@code cmd} on the open file descriptor {@code fd}.
{@code fcntl()} can take an optional third argument. Whether or not this argument is required is determined by {@code cmd}. The required argument type
is indicated in parentheses after each {@code cmd} name (in most cases, the required type is {@code int}, and we identify the argument using the name
{@code arg}), or {@code void} is specified if the argument is not required.
<b>LWJGL note</b>: Use #fcntli() or #fcntlp() to pass a third argument of the appropriate type.
Certain of the operations below are supported only since a particular Linux kernel version. The preferred method of checking whether the host kernel
supports a particular operation is to invoke {@code fcntl()} with the desired {@code cmd} value and then test whether the call failed with
{@code EINVAL}, indicating that the kernel does not recognize this value.
""",
int("fd", ""),
int("cmd", "", commands)
)
SaveErrno..NativeName("fcntl")..int(
"fcntli",
"#fcntl() overload that takes a third argument of type {@code int}.",
int("fd", ""),
int("cmd", "", commands),
int("arg", "")
)
SaveErrno..NativeName("fcntl")..int(
"fcntlp",
"#fcntl() overload that takes a third argument of type {@code void *}.",
int("fd", ""),
int("cmd", "", commands),
opaque_p("arg", "")
)
} | bsd-3-clause | fe8932e694aca2d170e3662ed9bf7da4 | 53.368421 | 159 | 0.612358 | 4.240021 | false | false | false | false |
sannies/isoviewer | application/src/main/kotlin/org/mp4parser/isoviewer/views/MainView.kt | 1 | 9392 | package org.mp4parser.isoviewer.views
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.geometry.Orientation
import javafx.scene.control.Alert
import javafx.scene.control.SelectionMode
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.scene.input.Clipboard
import javafx.scene.input.ClipboardContent
import javafx.scene.layout.VBox
import javafx.scene.layout.HBox
import javafx.stage.FileChooser
import org.mp4parser.Box
import org.mp4parser.Container
import org.mp4parser.isoviewer.BoxParser
import org.mp4parser.isoviewer.Dummy
import org.mp4parser.isoviewer.MyIsoFile
import org.mp4parser.isoviewer.Styles
import org.mp4parser.isoviewer.util.Toast
import org.mp4parser.tools.Hex
import tornadofx.*
import java.io.File
import java.io.FileInputStream
import java.io.RandomAccessFile
import java.nio.ByteBuffer
class MainView : View("ISO Viewer") {
var tree: TreeView<Box> by singleAssign()
var hexLines: ObservableList<ByteArray> = FXCollections.observableArrayList()
var offsets: MutableMap<Box, Long> = mutableMapOf()
var pathsOfBoxes: MutableMap<Box, String> = mutableMapOf()
var raf: RandomAccessFile = RandomAccessFile(File.createTempFile("MainView", ""), "r");
var details: VBox by singleAssign()
var openedFile: File = File("");
var selectedBoxPath: String? = null
override fun onBeforeShow() {
// try loading file from command line parameters if set
if (app.parameters.unnamed.size == 1) {
try {
loadIso(File(app.parameters.unnamed[0]), false)
} catch (e: Exception) {
// todo: popup exception
}
}
}
fun loadIso(file: File, reopenBox: Boolean) {
raf = RandomAccessFile(file, "r")
openedFile = file
runAsync {
val isoFile = MyIsoFile(file)
offsets = mutableMapOf(Pair(isoFile, 0L))
hexLines.clear()
isoFile.initContainer(FileInputStream(file).getChannel(), file.length(), BoxParser(offsets))
pathsOfBoxes = resolvePathsForBoxes(isoFile, emptyList(), mutableMapOf())
Platform.runLater {
hexLines.clear()
details.children.clear()
}
isoFile
} success {
tree.root = TreeItem<Box>(it)
tree.populate(
childFactory = fun(ti: TreeItem<Box>): List<Box>? {
if (ti.value is Container) {
return (ti.value as Container).boxes
} else {
return null
}
})
if (reopenBox) {
// re-open previously opened box if same path exists
val path = selectedBoxPath
if (path != null) {
if (pathsOfBoxes.containsValue(path)) {
Platform.runLater {
expandTreeView(path, tree.root)
}
}
}
}
}
}
private fun expandTreeView(fullPath: String, node: TreeItem<Box>) {
node.expandTo(1)
val children = node.children
for (child in children) {
val childPath = pathsOfBoxes[child.value as Box] ?: continue
if (fullPath == childPath) {
tree.selectionModel.select(child)
break
} else if (fullPath.startsWith(childPath)) {
expandTreeView(fullPath, child)
}
}
}
fun displayDetails(box: Box) {
hexLines.clear()
raf.seek(offsets.getOrDefault(box, 0))
var size = box.size
ByteBuffer.allocate(16).array()
while (size > 0) {
val buf = ByteArray(Math.min(16, size.toInt()))
if (hexLines.size > 1000) {
break
}
size -= raf.read(buf)
hexLines.add(buf)
}
details.children.clear()
details.children.add(BoxPane(box))
selectedBoxPath = pathsOfBoxes.get(box)
}
fun resolvePathsForBoxes(container: Container, chain: List<String>, results: MutableMap<Box, String>): MutableMap<Box, String> {
for (box in container.boxes) {
val boxes = container.getBoxes(box.javaClass)
var chainHere = if (boxes.size > 1) {
chain + (box.type + "[" + boxes.indexOf(box) + "]");
} else {
chain + box.type;
}
results.put(box, chainHere.joinToString(separator = "/"))
if (box is Container) {
resolvePathsForBoxes(box, chainHere, results)
}
}
return results
}
fun copyHex() {
val path = selectedBoxPath
if (path != null) {
if (pathsOfBoxes.containsValue(path)) {
val reversed = pathsOfBoxes.entries.associate { (k, v) -> v to k }
val box = reversed[path] ?: Dummy()
raf.seek(offsets.getOrDefault(box, 0))
var size = box.size
val content = ByteArray(Math.min(size, 10000L).toInt())
raf.readFully(content)
val clipboard: Clipboard = Clipboard.getSystemClipboard()
val cc = ClipboardContent()
// doesn't have to be efficient
cc.putString(content.hex.chunked(2).joinToString(separator = " ").chunked(32 + 16).joinToString(separator = "\n"))
clipboard.setContent(cc)
val toastText = if (box.size > 1000) "Copied trimmed" else "Copied";
Toast.makeText(currentStage, toastText, 50, 200, 200)
}
} else {
val alert = Alert(Alert.AlertType.INFORMATION)
alert.title = "Problem"
alert.headerText = "Misssing selection"
alert.contentText = "Select box from the tree menu on the left."
alert.showAndWait()
}
}
override val root = borderpane {
top {
menubar {
menu("File") {
item("Open", "Shortcut+O").action {
val file = chooseFile(initialDirectory = openedFile.parentFile, filters = arrayOf(
FileChooser.ExtensionFilter("MP4 files", "*.mp4", "*.uvu", "*.m4v", "*.m4a", "*.uva", "*.uvv", "*.uvt", "*.mov", "*.m4s", "*.ism?"),
FileChooser.ExtensionFilter("All files", "*.*")))
if (file.isNotEmpty()) {
loadIso(file[0], false)
}
}
item("Reload", "Shortcut+R").action {
loadIso(openedFile, true)
}
item("Copy hex", "Shortcut+C").action {
copyHex()
}
separator()
item("Exit", "Shortcut+Q").action {
Platform.exit()
}
}
}.isUseSystemMenuBar = System.getProperty("os.name").contains("Mac")
}
center {
splitpane(Orientation.HORIZONTAL) {
setDividerPositions(0.2)
tree = treeview {
cellFormat { text = it.type }
root = TreeItem<Box>(Dummy())
onUserSelect { it ->
run {
displayDetails(it)
}
}
}
splitpane(Orientation.VERTICAL) {
details = vbox {
}
tableview(hexLines) {
addClass(Styles.hexview)
selectionModel.isCellSelectionEnabled = true
selectionModel.selectionMode = SelectionMode.MULTIPLE
column(" 0 1 2 3 4 5 6 7 8 9 A B C D E F", String::class) {
value { param ->
Hex.encodeHex(param.value).replace(Regex("(.{2})"), "$1 ")
}
isSortable = false
prefWidth = 400.0
}
column("................", String::class) {
isSortable = false
prefWidth = 150.0
value { param ->
var s = ""
val itra = param.value.iterator()
while (itra.hasNext()) {
val b = itra.nextByte()
s += if (Character.isLetterOrDigit(b.toInt())) {
Character.forDigit(b.toInt(), 10)
} else {
'.'
}
}
s
}
}
}
}
}
}
}
}
| apache-2.0 | 63702443a1ed0c2f62d0f8b45797766c | 35.831373 | 164 | 0.485626 | 4.985138 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/editor/lists/MarkdownTypedHandlerDelegateTest.kt | 7 | 1063 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.lists
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import com.intellij.testFramework.RegistryKeyRule
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class MarkdownTypedHandlerDelegateTest: LightPlatformCodeInsightTestCase() {
@Rule
@JvmField
val rule = RegistryKeyRule("markdown.lists.renumber.on.type.enable", true)
override fun getTestDataPath(): String = MarkdownTestingUtil.TEST_DATA_PATH + "/editor/lists/typing/"
@Test
fun testRenumberOnItemCreation() = doTest()
@Test
fun testRenumberOnItemCreationInBlockQuote() = doTest()
private fun doTest() {
val testName = getTestName(true)
configureByFile("$testName.md")
type(' ')
checkResultByFile("$testName-after.md")
}
} | apache-2.0 | 2ee3094db932b253e31a9db70a68a0d5 | 32.25 | 140 | 0.78175 | 4.28629 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt | 5 | 26230 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.j2k
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.impl.PsiExpressionEvaluator
import org.jetbrains.kotlin.j2k.ast.*
import java.io.PrintStream
import java.util.*
enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String, val parameterCount: Int?) {
CHAR_SEQUENCE_LENGTH(CharSequence::class.java.name, "length", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
COLLECTION_SIZE(Collection::class.java.name, "size", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
COLLECTION_TO_ARRAY(Collection::class.java.name, "toArray", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toTypedArray", argumentsNotNull())
},
COLLECTION_TO_ARRAY_WITH_ARG(Collection::class.java.name, "toArray", 1) {
override fun ConvertCallData.convertCall() = copy(arguments = emptyList()).convertWithChangedName("toTypedArray", emptyList())
},
MAP_SIZE(Map::class.java.name, "size", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
MAP_KEY_SET(Map::class.java.name, "keySet", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("keys")
},
MAP_PUT_IF_ABSENT(Map::class.java.name, "putIfAbsent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REMOVE(Map::class.java.name, "remove", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REPLACE(Map::class.java.name, "replace", 3) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REPLACE_ALL(Map::class.java.name, "replaceAll", 1) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE(Map::class.java.name, "compute", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE_IF_ABSENT(Map::class.java.name, "computeIfAbsent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE_IF_PRESENT(Map::class.java.name, "computeIfPresent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_MERGE(Map::class.java.name, "merge", 3) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_GET_OR_DEFAULT(Map::class.java.name, "getOrDefault", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_VALUES(Map::class.java.name, "values", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
MAP_ENTRY_SET(Map::class.java.name, "entrySet", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("entries")
},
ENUM_NAME(Enum::class.java.name, "name", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("name")
},
ENUM_ORDINAL(Enum::class.java.name, "ordinal", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
CHAR_AT(CharSequence::class.java.name, "charAt", 1) {
override fun ConvertCallData.convertCall() = convertWithChangedName("get", argumentsNotNull())
},
NUMBER_BYTE_VALUE(Number::class.java.name, "byteValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toByte", argumentsNotNull())
},
NUMBER_SHORT_VALUE(Number::class.java.name, "shortValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toShort", argumentsNotNull())
},
NUMBER_INT_VALUE(Number::class.java.name, "intValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toInt", argumentsNotNull())
},
NUMBER_LONG_VALUE(Number::class.java.name, "longValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toLong", argumentsNotNull())
},
NUMBER_FLOAT_VALUE(Number::class.java.name, "floatValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toFloat", argumentsNotNull())
},
NUMBER_DOUBLE_VALUE(Number::class.java.name, "doubleValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toDouble", argumentsNotNull())
},
LIST_REMOVE(List::class.java.name, "remove", 1) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher)
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == "int"
override fun ConvertCallData.convertCall() = convertWithChangedName("removeAt", argumentsNotNull())
},
THROWABLE_GET_MESSAGE(Throwable::class.java.name, "getMessage", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("message")
},
THROWABLE_GET_CAUSE(Throwable::class.java.name, "getCause", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("cause")
},
MAP_ENTRY_GET_KEY(Map::class.java.name + ".Entry", "getKey", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("key")
},
MAP_ENTRY_GET_VALUE(Map::class.java.name + ".Entry", "getValue", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("value")
},
OBJECT_EQUALS(null, "equals", 1) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == JAVA_LANG_OBJECT
override fun ConvertCallData.convertCall(): Expression? {
if (qualifier == null || qualifier is PsiSuperExpression) return null
return BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator.EQEQ)
}
},
OBJECT_GET_CLASS(JAVA_LANG_OBJECT, "getClass", 0) {
override fun ConvertCallData.convertCall(): Expression {
val identifier = Identifier.withNoPrototype("javaClass", isNullable = false)
return if (qualifier != null)
QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, null)
else
identifier
}
},
OBJECTS_EQUALS("java.util.Objects", "equals", 2) {
override fun ConvertCallData.convertCall()
= BinaryExpression(codeConverter.convertExpression(arguments[0]), codeConverter.convertExpression(arguments[1]), Operator.EQEQ)
},
COLLECTIONS_EMPTY_LIST(Collections::class.java.name, "emptyList", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptyList", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_EMPTY_SET(Collections::class.java.name, "emptySet", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptySet", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_EMPTY_MAP(Collections::class.java.name, "emptyMap", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptyMap", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_SINGLETON_LIST(Collections::class.java.name, "singletonList", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single()))
return MethodCallExpression.buildNonNull(null, "listOf", argumentList, typeArgumentsConverted)
}
},
COLLECTIONS_SINGLETON(Collections::class.java.name, "singleton", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single()))
return MethodCallExpression.buildNonNull(null, "setOf", argumentList, typeArgumentsConverted)
}
},
STRING_TRIM(JAVA_LANG_STRING, "trim", 0) {
override fun ConvertCallData.convertCall(): Expression {
val comparison = BinaryExpression(Identifier.withNoPrototype("it", isNullable = false), LiteralExpression("' '").assignNoPrototype(), Operator(JavaTokenType.LE).assignNoPrototype()).assignNoPrototype()
val argumentList = ArgumentList.withNoPrototype(LambdaExpression(null, Block.of(comparison).assignNoPrototype()))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "trim", argumentList, dotPrototype = dot)
}
},
STRING_REPLACE_ALL(JAVA_LANG_STRING, "replaceAll", 2) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(
codeConverter.convertToRegex(arguments[0]),
codeConverter.convertExpression(arguments[1])
)
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "replace", argumentList, dotPrototype = dot)
}
},
STRING_REPLACE_FIRST(JAVA_LANG_STRING, "replaceFirst", 2) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier), "replaceFirst",
ArgumentList.withNoPrototype(
codeConverter.convertToRegex(arguments[0]),
codeConverter.convertExpression(arguments[1])
),
dotPrototype = dot
)
}
},
STRING_MATCHES(JAVA_LANG_STRING, "matches", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single()))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "matches", argumentList, dotPrototype = dot)
}
},
STRING_SPLIT(JAVA_LANG_STRING, "split", 1) {
override fun ConvertCallData.convertCall(): Expression {
val splitCall = MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"split",
ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single())),
dotPrototype = dot
).assignNoPrototype()
val isEmptyCall = MethodCallExpression.buildNonNull(Identifier.withNoPrototype("it", isNullable = false), "isEmpty").assignNoPrototype()
val isEmptyCallBlock = Block.of(isEmptyCall).assignNoPrototype()
val dropLastCall = MethodCallExpression.buildNonNull(
splitCall,
"dropLastWhile",
ArgumentList.withNoPrototype(LambdaExpression(null, isEmptyCallBlock).assignNoPrototype())
).assignNoPrototype()
return MethodCallExpression.buildNonNull(dropLastCall, "toTypedArray")
}
},
STRING_SPLIT_LIMIT(JAVA_LANG_STRING, "split", 2) {
override fun ConvertCallData.convertCall(): Expression? {
val patternArgument = codeConverter.convertToRegex(arguments[0])
val limitArgument = codeConverter.convertExpression(arguments[1])
val evaluator = PsiExpressionEvaluator()
val limit = evaluator.computeConstantExpression(arguments[1], /* throwExceptionOnOverflow = */ false) as? Int
val splitArguments = when {
limit == null -> // not a constant
listOf(patternArgument, MethodCallExpression.buildNonNull(limitArgument, "coerceAtLeast", ArgumentList.withNoPrototype(LiteralExpression("0").assignNoPrototype())).assignNoPrototype())
limit < 0 -> // negative, same behavior as split(regex) in kotlin
listOf(patternArgument)
limit == 0 -> { // zero, same replacement as for split without limit
val newCallData = copy(arguments = listOf(arguments[0]))
return STRING_SPLIT.convertCall(newCallData)
}
else -> // positive, same behavior as split(regex, limit) in kotlin
listOf(patternArgument, limitArgument)
}
val splitCall = MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"split",
ArgumentList.withNoPrototype(splitArguments),
dotPrototype = dot
).assignNoPrototype()
return MethodCallExpression.buildNonNull(splitCall, "toTypedArray")
}
},
STRING_JOIN(JAVA_LANG_STRING, "join", 2) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.last().type.canonicalText == "java.lang.Iterable<? extends java.lang.CharSequence>"
override fun ConvertCallData.convertCall(): Expression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1)))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments[1]), "joinToString", argumentList)
}
},
STRING_JOIN_VARARG(JAVA_LANG_STRING, "join", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.let { it.parametersCount == 2 && it.parameters.last().isVarArgs }
override fun ConvertCallData.convertCall(): Expression? {
return if (arguments.size == 2 && arguments.last().isAssignableToCharSequenceArray()) {
STRING_JOIN.convertCall(this)
}
else {
MethodCallExpression.buildNonNull(
MethodCallExpression.buildNonNull(null, "arrayOf", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.drop(1)))).assignNoPrototype(),
"joinToString",
ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1)))
)
}
}
private fun PsiExpression.isAssignableToCharSequenceArray(): Boolean {
val charSequenceType = PsiType.getTypeByName("java.lang.CharSequence", project, resolveScope)
return (type as? PsiArrayType)?.componentType?.let { charSequenceType.isAssignableFrom(it) } ?: false
}
},
STRING_CONCAT(JAVA_LANG_STRING, "concat", 1) {
override fun ConvertCallData.convertCall()
= BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator(JavaTokenType.PLUS).assignNoPrototype())
},
STRING_COMPARE_TO_IGNORE_CASE(JAVA_LANG_STRING, "compareToIgnoreCase", 1) {
override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("compareTo")
},
STRING_EQUALS_IGNORE_CASE(JAVA_LANG_STRING, "equalsIgnoreCase", 1) {
override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("equals")
},
STRING_REGION_MATCHES(JAVA_LANG_STRING, "regionMatches", 5) {
override fun ConvertCallData.convertCall()
= copy(arguments = arguments.drop(1)).convertWithIgnoreCaseArgument("regionMatches", ignoreCaseArgument = arguments.first())
},
STRING_GET_BYTES(JAVA_LANG_STRING, "getBytes", null) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val charsetArg = arguments.lastOrNull()?.takeIf { it.type?.canonicalText == JAVA_LANG_STRING }
val convertedArguments = codeConverter.convertExpressionsInList(arguments).map {
if (charsetArg != null && it.prototypes?.singleOrNull()?.element == charsetArg)
MethodCallExpression.buildNonNull(null, "charset", ArgumentList.withNoPrototype(it)).assignNoPrototype()
else
it
}
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"toByteArray",
ArgumentList.withNoPrototype(convertedArguments),
dotPrototype = dot
)
}
},
STRING_GET_CHARS(JAVA_LANG_STRING, "getChars", 4) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
// reorder parameters: srcBegin(0), srcEnd(1), dst(2), dstOffset(3) -> destination(2), destinationOffset(3), startIndex(0), endIndex(1)
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.slice(listOf(2, 3, 0, 1))))
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"toCharArray",
argumentList,
dotPrototype = dot
)
}
},
STRING_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "valueOf", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
return super.matches(method, superMethodsSearcher)
&& method.parameterList.parametersCount.let { it == 1 || it == 3}
&& method.parameterList.parameters.first().type.canonicalText == "char[]"
}
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "String", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments)))
},
STRING_COPY_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "copyValueOf", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
return super.matches(method, superMethodsSearcher)
&& method.parameterList.parametersCount.let { it == 1 || it == 3 }
&& method.parameterList.parameters.first().type.canonicalText == "char[]"
}
override fun ConvertCallData.convertCall()
= STRING_VALUE_OF_CHAR_ARRAY.convertCall(this)
},
STRING_VALUE_OF(JAVA_LANG_STRING, "valueOf", 1) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments.single(), shouldParenthesize = true), "toString")
},
SYSTEM_OUT_PRINTLN(PrintStream::class.java.name, "println", null) {
override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName)
},
SYSTEM_OUT_PRINT(PrintStream::class.java.name, "print", null) {
override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName)
};
open fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= method.name == methodName && matchesClass(method, superMethodsSearcher) && matchesParameterCount(method)
protected fun matchesClass(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
if (qualifiedClassName == null) return true
val superMethods = superMethodsSearcher.findDeepestSuperMethods(method)
return if (superMethods.isEmpty())
method.containingClass?.qualifiedName == qualifiedClassName
else
superMethods.any { it.containingClass?.qualifiedName == qualifiedClassName }
}
protected fun matchesParameterCount(method: PsiMethod) = parameterCount == null || parameterCount == method.parameterList.parametersCount
data class ConvertCallData(
val qualifier: PsiExpression?,
val arguments: List<PsiExpression>,
val typeArgumentsConverted: List<Type>,
val dot: PsiElement?,
val lPar: PsiElement?,
val rPar: PsiElement?,
val codeConverter: CodeConverter
)
@JvmName("convertCallPublic")
fun convertCall(data: ConvertCallData): Expression? = data.convertCall()
protected abstract fun ConvertCallData.convertCall(): Expression?
protected fun ConvertCallData.convertMethodCallToPropertyUse(propertyName: String = methodName): Expression {
val identifier = Identifier.withNoPrototype(propertyName, isNullable = false)
return if (qualifier != null)
QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, dot)
else
identifier
}
protected fun ConvertCallData.argumentsNotNull() = arguments.map { Nullability.NotNull }
protected fun ConvertCallData.convertWithChangedName(name: String, argumentNullabilities: List<Nullability>): MethodCallExpression {
assert(argumentNullabilities.size == arguments.size)
val argumentsConverted = arguments.zip(argumentNullabilities).map {
codeConverter.convertExpression(it.first, null, it.second).assignPrototype(it.first, CommentsAndSpacesInheritance.LINE_BREAKS)
}
val argumentList = ArgumentList(argumentsConverted, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype()
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
name,
argumentList,
typeArgumentsConverted,
dot)
}
protected fun ConvertCallData.convertWithReceiverCast(): MethodCallExpression? {
val convertedArguments = codeConverter.convertExpressionsInList(arguments)
val qualifierWithCast = castQualifierToType(codeConverter, qualifier!!, qualifiedClassName!!)
return MethodCallExpression.buildNonNull(
qualifierWithCast,
methodName,
ArgumentList.withNoPrototype(convertedArguments),
typeArgumentsConverted,
dot)
}
private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression {
val convertedQualifier = codeConverter.convertExpression(qualifier)
val qualifierType = codeConverter.typeConverter.convertType(qualifier.type)
val typeArgs = (qualifierType as? ClassType)?.referenceElement?.typeArgs ?: emptyList()
val referenceElement = ReferenceElement(Identifier.withNoPrototype(type), typeArgs).assignNoPrototype()
val newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype()
return TypeCastExpression(newType, convertedQualifier).assignNoPrototype()
}
protected fun ConvertCallData.convertWithIgnoreCaseArgument(methodName: String, ignoreCaseArgument: PsiExpression? = null): Expression {
val ignoreCaseExpression = ignoreCaseArgument?.let { codeConverter.convertExpression(it) }
?: LiteralExpression("true").assignNoPrototype()
val ignoreCaseArgumentExpression = AssignmentExpression(Identifier.withNoPrototype("ignoreCase"), ignoreCaseExpression, Operator.EQ).assignNoPrototype()
val convertedArguments = arguments.map {
codeConverter.convertExpression(it, null, Nullability.NotNull).assignPrototype(it, CommentsAndSpacesInheritance.LINE_BREAKS)
} + ignoreCaseArgumentExpression
val argumentList = ArgumentList(convertedArguments, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype()
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
methodName,
argumentList,
typeArgumentsConverted,
dot)
}
protected fun ConvertCallData.convertSystemOutMethodCall(methodName: String): Expression? {
if (qualifier !is PsiReferenceExpression) return null
val qqualifier = qualifier.qualifierExpression as? PsiReferenceExpression ?: return null
if (qqualifier.canonicalText != "java.lang.System") return null
if (qualifier.referenceName != "out") return null
if (typeArgumentsConverted.isNotEmpty()) return null
val argumentList = ArgumentList(
codeConverter.convertExpressionsInList(arguments),
LPar.withPrototype(lPar),
RPar.withPrototype(rPar)
).assignNoPrototype()
return MethodCallExpression.buildNonNull(null, methodName, argumentList)
}
protected fun CodeConverter.convertToRegex(expression: PsiExpression?): Expression
= MethodCallExpression.buildNonNull(convertExpression(expression, shouldParenthesize = true), "toRegex").assignNoPrototype()
companion object {
private val valuesByName = values().groupBy { it.methodName }
fun match(method: PsiMethod, argumentCount: Int, services: JavaToKotlinConverterServices): SpecialMethod? {
val candidates = valuesByName[method.name] ?: return null
return candidates
.firstOrNull { it.matches(method, services.superMethodsSearcher) }
?.takeIf { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct
}
}
}
| apache-2.0 | 9fde4eaa58056adb7d88cd9cf1eb68f7 | 49.932039 | 213 | 0.678955 | 5.553674 | false | false | false | false |
DreierF/MyTargets | app/src/androidTest/java/de/dreier/mytargets/features/training/input/InputActivityTest.kt | 1 | 5663 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.training.input
import android.content.Intent
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import androidx.test.uiautomator.UiObjectNotFoundException
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.views.TargetViewBase
import de.dreier.mytargets.test.base.UITestBase
import de.dreier.mytargets.test.utils.actions.TargetViewActions
import de.dreier.mytargets.test.utils.assertions.TargetViewAssertions
import de.dreier.mytargets.test.utils.matchers.ViewMatcher.clickOnPreference
import de.dreier.mytargets.test.utils.rules.DbTestRuleBase
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
import java.util.*
@Ignore
@RunWith(AndroidJUnit4::class)
class InputActivityTest : UITestBase() {
private val activityTestRule = ActivityTestRule(
InputActivity::class.java, true, false
)
@get:Rule
val rule: RuleChain = RuleChain.outerRule(object : DbTestRuleBase() {
override fun addDatabaseContent() {
val generator = Random(3435)
val standardRound =
ApplicationInstance.db.standardRoundDAO().loadStandardRoundOrNull(32L)
val (id) = saveDefaultTraining(standardRound!!.id, generator)
round =
Round(ApplicationInstance.db.standardRoundDAO().loadRoundTemplates(standardRound.id)[0])
round.trainingId = id
round.comment = ""
ApplicationInstance.db.roundDAO().insertRound(round)
val round2 =
Round(ApplicationInstance.db.standardRoundDAO().loadRoundTemplates(standardRound.id)[1])
round2.trainingId = id
round2.comment = ""
ApplicationInstance.db.roundDAO().insertRound(round2)
}
}).around(activityTestRule)
private lateinit var round: Round
@Before
fun setUp() {
SettingsManager.inputMethod = TargetViewBase.EInputMethod.KEYBOARD
SettingsManager.timerEnabled = false
}
@Test
@Throws(UiObjectNotFoundException::class)
fun inputActivityTest() {
val i = Intent()
i.putExtra(InputActivity.TRAINING_ID, round.trainingId)
i.putExtra(InputActivity.ROUND_ID, round.id)
i.putExtra(InputActivity.END_INDEX, 0)
activityTestRule.launchActivity(i)
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickVirtualButton("10"))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 1: 10"))
clickActionBarItem(R.id.action_settings, R.string.preferences)
clickOnPreference(R.string.keyboard_enabled)
pressBack()
// Wait for keyboard animation to finish
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
//assertVirtualViewNotExists("10");
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(0f, 0f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 2: X"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickVirtualButton("Backspace"))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonNotExists("Shot 2: X"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(0.1f, 0.2f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 2: 8"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(0f, 0f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 3: X"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(-0.9f, -0.9f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 4: Miss"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(0f, 0f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 5: X"))
onView(withId(R.id.targetViewContainer))
.perform(TargetViewActions.clickTarget(0f, 0f))
onView(withId(R.id.targetViewContainer))
.check(TargetViewAssertions.virtualButtonExists("Shot 6: X"))
onView(withId(R.id.next)).perform(click())
}
}
| gpl-2.0 | e1c3cc47689ffae32786f6b5f2b50b77 | 37.787671 | 104 | 0.708105 | 4.359507 | false | true | false | false |
vicboma1/GameBoyEmulatorEnvironment | src/main/kotlin/assets/display/Display.kt | 1 | 713 | package src.configuration
import src.GBEE
import java.awt.Component
import java.awt.GraphicsEnvironment
import java.awt.LayoutManager
/**
* Created by vicboma on 02/12/16.
*/
interface Display {
companion object {
private val localGraphics = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds()
val KFRAME_JAVA = "GB Emulator Environment ${GBEE.version}"
val WIDHT = localGraphics.width // 1280
val HEIGTH = localGraphics.height // 773
val VISIBLE = true
}
var title: String
val widht: Int?
val heigth: Int?
val visible: Boolean?
val layout: LayoutManager?
val closeOp: Int?
val location: Component?
}
| lgpl-3.0 | 99de609da1fc90c2ea92a57f1a31925a | 24.464286 | 111 | 0.68864 | 4.244048 | false | false | false | false |
seratch/jslack | slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/DatePickerElementBuilder.kt | 1 | 2742 | package com.slack.api.model.kotlin_extension.block.element
import com.slack.api.model.block.composition.ConfirmationDialogObject
import com.slack.api.model.block.composition.PlainTextObject
import com.slack.api.model.block.element.DatePickerElement
import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder
import com.slack.api.model.kotlin_extension.block.Builder
import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder
@BlockLayoutBuilder
class DatePickerElementBuilder : Builder<DatePickerElement> {
private var placeholder: PlainTextObject? = null
private var actionId: String? = null
private var initialDate: String? = null
private var confirm: ConfirmationDialogObject? = null
/**
* Creates a plain text object in the placeholder field.
*
* The placeholder text shown on the datepicker. Maximum length for the text in this field is 150 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#datepicker">Date picker element documentation</a>
*/
fun placeholder(text: String, emoji: Boolean? = null) {
placeholder = PlainTextObject(text, emoji)
}
/**
* An identifier for the action triggered when a menu option is selected. You can use this when you receive an
* interaction payload to identify the source of the action. Should be unique among all other action_ids used
* elsewhere by your app. Maximum length for this field is 255 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#datepicker">Date picker element documentation</a>
*/
fun actionId(id: String) {
actionId = id
}
/**
* The initial date that is selected when the element is loaded. This should be in the format YYYY-MM-DD.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#datepicker">Date picker element documentation</a>
*/
fun initialDate(date: String) {
initialDate = date
}
/**
* A confirm object that defines an optional confirmation dialog that appears after a date is selected.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#datepicker">Date picker element documentation</a>
*/
fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) {
confirm = ConfirmationDialogObjectBuilder().apply(builder).build()
}
override fun build(): DatePickerElement {
return DatePickerElement.builder()
.actionId(actionId)
.placeholder(placeholder)
.initialDate(initialDate)
.confirm(confirm)
.build()
}
} | mit | 8cd061d4520eff66a0b6f4f3bdad24b4 | 41.2 | 127 | 0.702042 | 4.352381 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/actions/Bear.kt | 1 | 2288 | package simyukkuri.gameobject.yukkuri.event.action.actions
import simyukkuri.GameScene
import simyukkuri.Time
import simyukkuri.gameobject.yukkuri.event.IndividualEvent
import simyukkuri.gameobject.yukkuri.event.action.Action
import simyukkuri.gameobject.yukkuri.event.action.MultipleAction
import simyukkuri.gameobject.yukkuri.event.action.Posture
import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats
import simyukkuri.gameobject.yukkuri.statistic.statistics.Emotion
/**
* 出産アクション.
*
* もしゲスならば, 出産後ふりふりする.
*/
class Bear(self: YukkuriStats, gameScene: GameScene) : MultipleAction() {
override var currentAction: Action = BearImpl(self, gameScene)
}
private class BearImpl(val self: YukkuriStats, val gameScene: GameScene) : Action {
override var hasEnded = false
override var currentAction: Action = this
private set
override val posture: Posture
get() = Posture.SHOW_ANUS
private var elapsedTime = 0f
private val bearingTime = 5f
// TODO: お腹の中の赤ちゃんが多すぎる場合は失敗する.
override fun execute() {
elapsedTime += Time.UNIT
if (elapsedTime <= bearingTime) return
if (self.hasWrapper) {
bearWithWrapper()
currentAction = Say(self, self.msgList.lamentsForAbortingBaby)
return
} else {
bearChild()
when {
self.isPregnant -> return
self.willFurifuri() -> {
hasEnded = true
currentAction = Furifuri()
return
}
else -> {
hasEnded = true
return
}
}
}
}
/** 子供を一匹産む. */
private fun bearChild() {
TODO()
}
/** おくるみを着た状態で出産する. */
private fun bearWithWrapper() {
self.isDirty = true
self.babiesInWomb.clear()
self.feels(Emotion.Happiness.VERY_SAD)
}
override fun interrupt() = Unit
override fun isTheSameAs(other: IndividualEvent): Boolean = other is Bear || other is BearImpl
} | apache-2.0 | 166eb153d5860afb4ed82064b8f8e9c5 | 27.589041 | 98 | 0.606117 | 3.996296 | false | false | false | false |
MGaetan89/ShowsRage | app/src/androidTest/kotlin/com/mgaetan89/showsrage/extension/preferences/SharedPreferencesExtension_UseDarkThemeTest.kt | 1 | 1751 | package com.mgaetan89.showsrage.extension.preferences
import android.content.SharedPreferences
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import com.mgaetan89.showsrage.TestActivity
import com.mgaetan89.showsrage.extension.Fields
import com.mgaetan89.showsrage.extension.getPreferences
import com.mgaetan89.showsrage.extension.useDarkTheme
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SharedPreferencesExtension_UseDarkThemeTest {
@JvmField
@Rule
val activityRule = ActivityTestRule(TestActivity::class.java, false, false)
private lateinit var preference: SharedPreferences
@Before
fun before() {
this.preference = InstrumentationRegistry.getTargetContext().getPreferences()
}
@Test
fun useDarkTheme_False() {
this.preference.edit().putBoolean(Fields.THEME.field, false).apply()
val useDarkTheme = this.preference.useDarkTheme()
assertThat(useDarkTheme).isFalse()
}
@Test
fun useDarkTheme_Missing() {
this.preference.edit().putBoolean(Fields.THEME.field, false).apply()
val useDarkTheme = this.preference.useDarkTheme()
assertThat(useDarkTheme).isFalse()
}
@Test
fun useDarkTheme_Null() {
val useDarkTheme = null.useDarkTheme()
assertThat(useDarkTheme).isTrue()
}
@Test
fun useDarkTheme_True() {
this.preference.edit().putBoolean(Fields.THEME.field, true).apply()
val useDarkTheme = this.preference.useDarkTheme()
assertThat(useDarkTheme).isTrue()
}
@After
fun after() {
this.preference.edit().clear().apply()
}
}
| apache-2.0 | de6a2f5492d17221fb09a6d62da28a50 | 24.376812 | 79 | 0.789263 | 3.781857 | false | true | false | false |
syncloud/android | syncloud/src/main/java/org/syncloud/android/ui/dialog/ErrorDialog.kt | 1 | 1108 | package org.syncloud.android.ui.dialog
import android.app.Activity
import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import org.syncloud.android.R
import org.syncloud.android.SyncloudApplication
class ErrorDialog(private val context: Activity, private val message: String) : AlertDialog(context) {
private val application: SyncloudApplication = context.application as SyncloudApplication
override fun onCreate(savedInstanceState: Bundle) {
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_error, null)
val viewMessage = view.findViewById<View>(R.id.view_message) as TextView
viewMessage.text = message
val btnReport = view.findViewById<View>(R.id.btn_report) as Button
btnReport.setOnClickListener { reportError() }
setView(view)
super.onCreate(savedInstanceState)
}
fun reportError() = application.reportError()
init {
setCancelable(true)
}
} | gpl-3.0 | 5ffb80400e51471875325e98c3723be5 | 34.774194 | 102 | 0.749097 | 4.379447 | false | false | false | false |
kmagiera/react-native-gesture-handler | android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerEnabledRootView.kt | 1 | 2218 | package com.swmansion.gesturehandler.react
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.view.MotionEvent
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactRootView
@Deprecated(message = "Use <GestureHandlerRootView /> component instead. Check gesture handler installation instructions in documentation for more information.")
class RNGestureHandlerEnabledRootView : ReactRootView {
private lateinit var _reactInstanceManager: ReactInstanceManager
private var gestureRootHelper: RNGestureHandlerRootHelper? = null
constructor(context: Context?) : super(context) {}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
gestureRootHelper?.requestDisallowInterceptTouchEvent(disallowIntercept)
super.requestDisallowInterceptTouchEvent(disallowIntercept)
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return if (gestureRootHelper?.dispatchTouchEvent(ev) == true) {
true
} else super.dispatchTouchEvent(ev)
}
/**
* This method is used to enable root view to start processing touch events through the gesture
* handler library logic. Unless this method is called (which happens as a result of instantiating
* new gesture handler from JS) the root view component will just proxy all touch related methods
* to its superclass. Thus in the "disabled" state all touch related events will fallback to
* default RN behavior.
*/
fun initialize() {
check(gestureRootHelper == null) { "GestureHandler already initialized for root view $this" }
gestureRootHelper = RNGestureHandlerRootHelper(
_reactInstanceManager.currentReactContext!!, this)
}
fun tearDown() {
gestureRootHelper?.let {
it.tearDown()
gestureRootHelper = null
}
}
override fun startReactApplication(
reactInstanceManager: ReactInstanceManager,
moduleName: String,
initialProperties: Bundle?,
) {
super.startReactApplication(reactInstanceManager, moduleName, initialProperties)
_reactInstanceManager = reactInstanceManager
}
}
| mit | 5930aafa57eabb333ddd538152d6e720 | 37.912281 | 161 | 0.775023 | 5.15814 | false | false | false | false |
jmfayard/skripts | kotlin/asciitohex/AsciiView.kt | 1 | 2909 | package asciitohex
import javafx.geometry.Pos
import javafx.scene.control.Label
import javafx.scene.control.TextArea
import javafx.scene.layout.Priority
import tornadofx.View
import tornadofx.action
import tornadofx.addClass
import tornadofx.borderpane
import tornadofx.button
import tornadofx.fieldset
import tornadofx.form
import tornadofx.hbox
import tornadofx.hgrow
import tornadofx.label
import tornadofx.textarea
import tornadofx.useMaxWidth
import tornadofx.vbox
class AsciiView : View() {
val converter: AsciiConverter by inject()
val areas = mutableMapOf<AsciiConversion, TextArea>()
val labels = mutableMapOf<AsciiConversion, Label>()
init {
subscribe<NewConversion> { event ->
println("Event $event areas: ${areas.keys}")
for (conversion in AsciiConversion.values()) {
val display = converter.convert(conversion)
if (conversion.readOnly()) labels[conversion]!!.text = display
else areas[conversion]!!.text = display
}
}
}
override val root = borderpane {
prefHeight = 600.0
title = "ASCII to Hex"
top = hbox {
addClass(Styles.title)
label("ASCII to Hex")
label("...and other text conversion tools")
}
center = convertView()
println(converter.content.get())
converter.subscribeEvents()
runAsync { }.ui { fire(NewConversion) }
}
fun convertView() = form {
for (conversion in AsciiConversion.values()) {
hbox {
fieldset(conversion.name) {
useMaxWidth = true
if (conversion.readOnly()) {
labels += conversion to label("") {
hgrow = Priority.ALWAYS
}
} else {
val area = textarea("") {
isWrapText = true
}
areas += conversion to area
}
}
vbox(spacing = 16, alignment = Pos.BOTTOM_CENTER) {
addClass(Styles.buttons)
button("Copy") {
useMaxWidth = conversion.readOnly().not()
action {
fire(ClipboardEvent(conversion))
}
}
if (conversion.readOnly().not()) button("Convert") {
useMaxWidth = true
action {
val event = ConvertEvent(conversion, areas[conversion]!!.text)
println("Action Convert for $conversion <= $event")
fire(event)
}
}
}
}
}
}
}
| apache-2.0 | ce1aaa74b5e8ce6acca268cc79576fc2 | 30.967033 | 90 | 0.507391 | 5.61583 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/NullableBooleanElvisInspection.kt | 2 | 5094 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
/**
* A class for nullable boolean elvis inspection.
*
* For an elvis operation, this class detects and replaces it with a boolean equality check:
* - `nb ?: true` => `nb != false`
* - `nb ?: false` => `nb == true`
* - `!(nb ?: true)` => `nb == false`
* - `!(nb ?: false)` => `nb != true`
* See plugins/kotlin/code-insight/descriptions/resources-en/inspectionDescriptions/NullableBooleanElvis.html for details.
*/
class NullableBooleanElvisInspection :
AbstractKotlinApplicatorBasedInspection<KtBinaryExpression, NullableBooleanElvisInspection.NullableBooleanInput>(
KtBinaryExpression::class
) {
class NullableBooleanInput : KotlinApplicatorInput
override fun getApplicabilityRange() = ApplicabilityRanges.SELF
override fun getInputProvider() =
inputProvider { expression: KtBinaryExpression ->
val lhsType = expression.left?.getKtType() ?: return@inputProvider null
// Returns a non-null input only if LHS has the nullable boolean type.
if (lhsType.nullability.isNullable && lhsType.isBoolean) NullableBooleanInput() else null
}
override fun getApplicator() =
applicator<KtBinaryExpression, NullableBooleanInput> {
familyAndActionName(KotlinBundle.lazyMessage(("inspection.nullable.boolean.elvis.display.name")))
isApplicableByPsi { expression -> expression.isTargetOfNullableBooleanElvisInspection() }
applyTo { expression, _ ->
val lhs = expression.left ?: return@applyTo
val rhs = expression.right as? KtConstantExpression ?: return@applyTo
val parentWithNegation = expression.parentThroughParenthesisWithNegation()
if (parentWithNegation == null) {
expression.replaceElvisWithBooleanEqualityOperation(lhs, rhs)
} else {
parentWithNegation.replaceElvisWithBooleanEqualityOperation(lhs, rhs, hasNegation = true)
}
}
}
/**
* A method checking whether the KtBinaryExpression is a target of the nullable boolean elvis inspection or not.
*
* To be a target of the nullable boolean elvis inspection,
* - The binary operator must be elvis.
* - RHS must be a boolean constant.
* - LHS must have a nullable boolean type. - This is checked by the "getInputProvider()" above.
*
* @return True if the KtBinaryExpression is a target of the nullable boolean elvis inspection.
*/
private fun KtBinaryExpression.isTargetOfNullableBooleanElvisInspection(): Boolean {
if (operationToken != KtTokens.ELVIS) return false
val rhs = right ?: return false
if (!KtPsiUtil.isBooleanConstant(rhs)) return false
return true
}
/**
* A method to find the nearest recursive parent with a negation operator.
*
* This method recursively visits parent of the binary expression when the parent is KtParenthesizedExpression.
* Finally, when it finds the nearest recursive parent with a negation operator, it returns the parent.
* If there is no such parent, it returns null.
*/
private fun KtBinaryExpression.parentThroughParenthesisWithNegation(): KtUnaryExpression? {
var result = parent
while (result is KtParenthesizedExpression) result = result.parent
val unaryExpressionParent = result as? KtUnaryExpression ?: return null
return if (unaryExpressionParent.operationToken == KtTokens.EXCL) unaryExpressionParent else null
}
/**
* A method to replace the elvis operation with an equality check operation.
*
* This method replaces "lhs ?: rhs" with "lhs == true" or "lhs != false" depending on "rhs".
*/
private fun KtExpression.replaceElvisWithBooleanEqualityOperation(
lhs: KtExpression,
rhs: KtConstantExpression,
hasNegation: Boolean = false
) {
val isFalse = KtPsiUtil.isFalseConstant(rhs)
val constantToCompare = if (isFalse) "true" else "false"
val operator = if (isFalse xor hasNegation) "==" else "!="
replaced(KtPsiFactory(rhs).buildExpression {
appendExpression(lhs)
appendFixedText(" $operator $constantToCompare")
})
}
} | apache-2.0 | 63e3bee79978f29baffaa8a73187c26c | 48.466019 | 122 | 0.703377 | 4.999019 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ui/KtScratchFileEditorProvider.kt | 2 | 12004 | // 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.scratch.ui
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.diff.tools.util.BaseSyncScrollable
import com.intellij.diff.tools.util.SyncScrollSupport.TwosideSyncScrollSupport
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.event.VisibleAreaListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.*
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiManager
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.scratch.*
import org.jetbrains.kotlin.idea.scratch.output.*
import org.jetbrains.kotlin.psi.UserDataProperty
private const val KTS_SCRATCH_EDITOR_PROVIDER: String = "KtsScratchFileEditorProvider"
class KtScratchFileEditorProvider : FileEditorProvider, DumbAware {
override fun getEditorTypeId(): String = KTS_SCRATCH_EDITOR_PROVIDER
override fun accept(project: Project, file: VirtualFile): Boolean {
if (!file.isValid) return false
if (!(file.isKotlinScratch || file.isKotlinWorksheet)) return false
val psiFile = PsiManager.getInstance(project).findFile(file) ?: return false
return ScratchFileLanguageProvider.get(psiFile.fileType) != null
}
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
val scratchFile = createScratchFile(project, file) ?: return TextEditorProvider.getInstance().createEditor(project, file)
return KtScratchFileEditorWithPreview.create(scratchFile)
}
override fun getPolicy(): FileEditorPolicy = FileEditorPolicy.HIDE_DEFAULT_EDITOR
}
class KtScratchFileEditorWithPreview private constructor(
val scratchFile: ScratchFile,
sourceTextEditor: TextEditor,
previewTextEditor: TextEditor
) : TextEditorWithPreview(sourceTextEditor, previewTextEditor), TextEditor, ScratchEditorLinesTranslator {
private val sourceEditor = sourceTextEditor.editor as EditorEx
private val previewEditor = previewTextEditor.editor as EditorEx
private val previewOutputManager: PreviewOutputBlocksManager = PreviewOutputBlocksManager(previewEditor)
private val toolWindowHandler: ScratchOutputHandler = requestToolWindowHandler()
private val inlayScratchOutputHandler = InlayScratchOutputHandler(sourceTextEditor, toolWindowHandler)
private val previewEditorScratchOutputHandler = PreviewEditorScratchOutputHandler(
previewOutputManager,
toolWindowHandler,
previewTextEditor as Disposable
)
private val commonPreviewOutputHandler = LayoutDependantOutputHandler(
noPreviewOutputHandler = inlayScratchOutputHandler,
previewOutputHandler = previewEditorScratchOutputHandler,
layoutProvider = ::getLayout
)
private val scratchTopPanel = ScratchTopPanel(scratchFile)
init {
sourceTextEditor.parentScratchEditorWithPreview = this
previewTextEditor.parentScratchEditorWithPreview = this
scratchFile.compilingScratchExecutor?.addOutputHandler(commonPreviewOutputHandler)
scratchFile.replScratchExecutor?.addOutputHandler(commonPreviewOutputHandler)
configureSyncScrollForSourceAndPreview()
configureSyncHighlighting(sourceEditor, previewEditor, translator = this)
ScratchFileAutoRunner.addListener(scratchFile.project, sourceTextEditor)
}
override fun getFile(): VirtualFile {
return scratchFile.file
}
override fun previewLineToSourceLines(previewLine: Int): Pair<Int, Int>? {
val expressionUnderCaret = scratchFile.getExpressionAtLine(previewLine) ?: return null
val outputBlock = previewOutputManager.getBlock(expressionUnderCaret) ?: return null
return outputBlock.lineStart to outputBlock.lineEnd
}
override fun sourceLineToPreviewLines(sourceLine: Int): Pair<Int, Int>? {
val block = previewOutputManager.getBlockAtLine(sourceLine) ?: return null
if (!block.sourceExpression.linesInformationIsCorrect()) return null
return block.sourceExpression.lineStart to block.sourceExpression.lineEnd
}
private fun configureSyncScrollForSourceAndPreview() {
val scrollable = object : BaseSyncScrollable() {
override fun processHelper(helper: ScrollHelper) {
if (!helper.process(0, 0)) return
val alignments = previewOutputManager.computeSourceToPreviewAlignments()
for ((fromSource, fromPreview) in alignments) {
if (!helper.process(fromSource, fromPreview)) return
if (!helper.process(fromSource, fromPreview)) return
}
helper.process(sourceEditor.document.lineCount, previewEditor.document.lineCount)
}
override fun isSyncScrollEnabled(): Boolean = true
}
val scrollSupport = TwosideSyncScrollSupport(listOf(sourceEditor, previewEditor), scrollable)
val listener = VisibleAreaListener { e -> scrollSupport.visibleAreaChanged(e) }
sourceEditor.scrollingModel.addVisibleAreaListener(listener)
previewEditor.scrollingModel.addVisibleAreaListener(listener)
}
override fun dispose() {
scratchFile.replScratchExecutor?.stop()
scratchFile.compilingScratchExecutor?.stop()
releaseToolWindowHandler(toolWindowHandler)
super.dispose()
}
override fun navigateTo(navigatable: Navigatable) {
myEditor.navigateTo(navigatable)
}
override fun canNavigateTo(navigatable: Navigatable): Boolean {
return myEditor.canNavigateTo(navigatable)
}
override fun getEditor(): Editor {
return myEditor.editor
}
override fun createToolbar(): ActionToolbar {
return scratchTopPanel.actionsToolbar
}
fun clearOutputHandlers() {
commonPreviewOutputHandler.clear(scratchFile)
}
override fun createViewActionGroup(): ActionGroup {
return DefaultActionGroup(showEditorAction, showEditorAndPreviewAction)
}
/**
* For simple actions, [Presentation.getText] is shown in the tooltip in the [ActionToolbar], and [Presentation.getDescription] is shown
* in the bottom tool panel. But when action implements [com.intellij.openapi.actionSystem.ex.CustomComponentAction], its tooltip is
* controlled only by its [javax.swing.JComponent.setToolTipText] method.
*
* That's why we set long and descriptive [Presentation.getText], but short [Presentation.getDescription].
*/
override fun getShowEditorAction(): ToggleAction = super.getShowEditorAction().apply {
templatePresentation.text = KotlinJvmBundle.message("scratch.inlay.output.mode.title")
templatePresentation.description = KotlinJvmBundle.message("scratch.inlay.output.mode.description")
}
override fun getShowEditorAndPreviewAction(): ToggleAction = super.getShowEditorAndPreviewAction().apply {
templatePresentation.text = KotlinJvmBundle.message("scratch.side.panel.output.mode.title")
templatePresentation.description = KotlinJvmBundle.message("scratch.side.panel.output.mode.description")
}
override fun onLayoutChange(oldValue: Layout?, newValue: Layout?) {
when {
oldValue != newValue -> clearOutputHandlers()
}
}
@TestOnly
fun setPreviewEnabled(isPreviewEnabled: Boolean) {
layout = if (isPreviewEnabled) Layout.SHOW_EDITOR_AND_PREVIEW else Layout.SHOW_EDITOR
}
companion object {
fun create(scratchFile: ScratchFile): KtScratchFileEditorWithPreview {
val textEditorProvider = TextEditorProvider.getInstance()
val mainEditor = textEditorProvider.createEditor(scratchFile.project, scratchFile.file) as TextEditor
val editorFactory = EditorFactory.getInstance()
val viewer = editorFactory.createViewer(editorFactory.createDocument(""), scratchFile.project, EditorKind.PREVIEW)
Disposer.register(mainEditor, Disposable { editorFactory.releaseEditor(viewer) })
val previewEditor = textEditorProvider.getTextEditor(viewer)
return KtScratchFileEditorWithPreview(scratchFile, mainEditor, previewEditor)
}
}
}
fun TextEditor.findScratchFileEditorWithPreview(): KtScratchFileEditorWithPreview? =
if (this is KtScratchFileEditorWithPreview) this else parentScratchEditorWithPreview
private var TextEditor.parentScratchEditorWithPreview: KtScratchFileEditorWithPreview?
by UserDataProperty(Key.create("parent.preview.editor"))
fun createScratchFile(project: Project, file: VirtualFile): ScratchFile? {
val psiFile = PsiManager.getInstance(project).findFile(file) ?: return null
val scratchFile = ScratchFileLanguageProvider.get(psiFile.language)?.newScratchFile(project, file) ?: return null
setupCodeAnalyzerRestarterOutputHandler(project, scratchFile)
return scratchFile
}
private fun setupCodeAnalyzerRestarterOutputHandler(project: Project, scratchFile: ScratchFile) {
scratchFile.replScratchExecutor?.addOutputHandler(object : ScratchOutputHandlerAdapter() {
override fun onFinish(file: ScratchFile) {
ApplicationManager.getApplication().invokeLater {
if (!file.project.isDisposed) {
val scratch = file.getPsiFile()
if (scratch?.isValid == true) {
DaemonCodeAnalyzer.getInstance(project).restart(scratch)
}
}
}
}
})
}
/**
* Redirects output to [noPreviewOutputHandler] or [previewOutputHandler] depending on the result of [layoutProvider] call.
*
* However, clears both handlers to simplify clearing when switching between layouts.
*/
private class LayoutDependantOutputHandler(
private val noPreviewOutputHandler: ScratchOutputHandler,
private val previewOutputHandler: ScratchOutputHandler,
private val layoutProvider: () -> TextEditorWithPreview.Layout
) : ScratchOutputHandler {
override fun onStart(file: ScratchFile) {
targetHandler.onStart(file)
}
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
targetHandler.handle(file, expression, output)
}
override fun error(file: ScratchFile, message: String) {
targetHandler.error(file, message)
}
override fun onFinish(file: ScratchFile) {
targetHandler.onFinish(file)
}
override fun clear(file: ScratchFile) {
noPreviewOutputHandler.clear(file)
previewOutputHandler.clear(file)
}
private val targetHandler
get() = when (layoutProvider()) {
TextEditorWithPreview.Layout.SHOW_EDITOR -> noPreviewOutputHandler
else -> previewOutputHandler
}
}
/**
* Checks if [ScratchExpression.element] is actually starts at the [ScratchExpression.lineStart]
* and ends at the [ScratchExpression.lineEnd].
*/
private fun ScratchExpression.linesInformationIsCorrect(): Boolean {
if (!element.isValid) return false
return element.getLineNumber(start = true) == lineStart && element.getLineNumber(start = false) == lineEnd
}
| apache-2.0 | 96be5def612b36538ef84df77348dc05 | 41.119298 | 158 | 0.743669 | 5.165232 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/postProcessing/J2kPostProcessor.kt | 1 | 13455 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.j2k.post.processing.postProcessing
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.impl.source.PostprocessReformattingAspect
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeinsight.utils.commitAndUnblockDocument
import org.jetbrains.kotlin.idea.codeinsights.impl.base.KotlinInspectionFacade
import org.jetbrains.kotlin.idea.inspections.*
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody
import org.jetbrains.kotlin.idea.quickfix.*
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.j2k.ConverterContext
import org.jetbrains.kotlin.j2k.JKPostProcessingTarget
import org.jetbrains.kotlin.j2k.PostProcessor
import org.jetbrains.kotlin.j2k.files
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.idea.j2k.post.processing.KotlinNJ2KServicesBundle
import org.jetbrains.kotlin.idea.j2k.post.processing.postProcessing.processings.*
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
class NewJ2kPostProcessor : PostProcessor {
companion object {
private val LOG = Logger.getInstance("@org.jetbrains.kotlin.idea.j2k.post.processings.NewJ2kPostProcessor")
}
override fun insertImport(file: KtFile, fqName: FqName) {
runUndoTransparentActionInEdt(inWriteAction = true) {
val descriptors = file.resolveImportReference(fqName)
descriptors.firstOrNull()?.let { ImportInsertHelper.getInstance(file.project).importDescriptor(file, it) }
}
}
override val phasesCount = processings.size
override fun doAdditionalProcessing(
target: JKPostProcessingTarget,
converterContext: ConverterContext?,
onPhaseChanged: ((Int, String) -> Unit)?
) {
if (converterContext !is NewJ2kConverterContext) error("Invalid converter context for new J2K")
for ((i, group) in processings.withIndex()) {
ProgressManager.checkCanceled()
onPhaseChanged?.invoke(i, group.description)
for (processing in group.processings) {
ProgressManager.checkCanceled()
try {
processing.runProcessingConsideringOptions(target, converterContext)
target.files().forEach(::commitFile)
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) {
target.files().forEach(::commitFile)
LOG.error(t)
}
}
}
}
private fun GeneralPostProcessing.runProcessingConsideringOptions(
target: JKPostProcessingTarget,
converterContext: NewJ2kConverterContext
) {
if (options.disablePostprocessingFormatting) {
PostprocessReformattingAspect.getInstance(converterContext.project).disablePostprocessFormattingInside {
runProcessing(target, converterContext)
}
} else {
runProcessing(target, converterContext)
}
}
private fun commitFile(file: KtFile) {
runUndoTransparentActionInEdt(inWriteAction = true) {
file.commitAndUnblockDocument()
}
}
}
private val errorsFixingDiagnosticBasedPostProcessingGroup =
DiagnosticBasedPostProcessingGroup(
diagnosticBasedProcessing(Errors.REDUNDANT_OPEN_IN_INTERFACE) { element: KtModifierListOwner, _ ->
element.removeModifier(KtTokens.OPEN_KEYWORD)
},
diagnosticBasedProcessing(Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN) { element: KtDotQualifiedExpression, _ ->
val parent = element.parent as? KtImportDirective ?: return@diagnosticBasedProcessing
parent.delete()
},
diagnosticBasedProcessing(
UnsafeCallExclExclFixFactory,
Errors.UNSAFE_CALL,
Errors.UNSAFE_INFIX_CALL,
Errors.UNSAFE_OPERATOR_CALL
),
diagnosticBasedProcessing(
MissingIteratorExclExclFixFactory,
Errors.ITERATOR_ON_NULLABLE
),
diagnosticBasedProcessing(
SmartCastImpossibleExclExclFixFactory,
Errors.SMARTCAST_IMPOSSIBLE
),
diagnosticBasedProcessing(
ReplacePrimitiveCastWithNumberConversionFix,
Errors.CAST_NEVER_SUCCEEDS
),
diagnosticBasedProcessing(
ChangeCallableReturnTypeFix.ReturnTypeMismatchOnOverrideFactory,
Errors.RETURN_TYPE_MISMATCH_ON_OVERRIDE
),
diagnosticBasedProcessing(
RemoveModifierFixBase.createRemoveProjectionFactory(true),
Errors.REDUNDANT_PROJECTION
),
diagnosticBasedProcessing(
AddModifierFixFE10.createFactory(KtTokens.OVERRIDE_KEYWORD),
Errors.VIRTUAL_MEMBER_HIDDEN
),
diagnosticBasedProcessing(
RemoveModifierFixBase.createRemoveModifierFromListOwnerPsiBasedFactory(KtTokens.OPEN_KEYWORD),
Errors.NON_FINAL_MEMBER_IN_FINAL_CLASS, Errors.NON_FINAL_MEMBER_IN_OBJECT
),
diagnosticBasedProcessing(
MakeVisibleFactory,
Errors.INVISIBLE_MEMBER
),
diagnosticBasedProcessing(
RemoveModifierFixBase.removeNonRedundantModifier,
Errors.WRONG_MODIFIER_TARGET
),
diagnosticBasedProcessing(
ChangeVisibilityOnExposureFactory,
Errors.EXPOSED_FUNCTION_RETURN_TYPE,
Errors.EXPOSED_PARAMETER_TYPE,
Errors.EXPOSED_PROPERTY_TYPE,
Errors.EXPOSED_PROPERTY_TYPE_IN_CONSTRUCTOR.errorFactory,
Errors.EXPOSED_PROPERTY_TYPE_IN_CONSTRUCTOR.warningFactory,
Errors.EXPOSED_RECEIVER_TYPE,
Errors.EXPOSED_SUPER_CLASS,
Errors.EXPOSED_SUPER_INTERFACE
),
fixValToVarDiagnosticBasedProcessing,
fixTypeMismatchDiagnosticBasedProcessing
)
private val addOrRemoveModifiersProcessingGroup =
InspectionLikeProcessingGroup(
runSingleTime = true,
processings = listOf(
RemoveRedundantVisibilityModifierProcessing(),
RemoveRedundantModalityModifierProcessing(),
inspectionBasedProcessing(AddOperatorModifierInspection(), writeActionNeeded = false),
)
)
private val removeRedundantElementsProcessingGroup =
InspectionLikeProcessingGroup(
runSingleTime = true,
processings = listOf(
RemoveExplicitTypeArgumentsProcessing(),
RemoveJavaStreamsCollectCallTypeArgumentsProcessing(),
ExplicitThisInspectionBasedProcessing(),
RemoveOpenModifierOnTopLevelDeclarationsProcessing(),
inspectionBasedProcessing(KotlinInspectionFacade.instance.removeEmptyClassBody)
)
)
private val inspectionLikePostProcessingGroup =
InspectionLikeProcessingGroup(
RemoveRedundantConstructorKeywordProcessing(),
RemoveExplicitOpenInInterfaceProcessing(),
RemoveRedundantOverrideVisibilityProcessing(),
MoveLambdaOutsideParenthesesProcessing(),
intentionBasedProcessing(ConvertToStringTemplateIntention(), writeActionNeeded = false) {
ConvertToStringTemplateIntention.shouldSuggestToConvert(it)
},
intentionBasedProcessing(UsePropertyAccessSyntaxIntention(), writeActionNeeded = false),
UninitializedVariableReferenceFromInitializerToThisReferenceProcessing(),
UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing(),
RemoveRedundantSamAdaptersProcessing(),
RemoveRedundantCastToNullableProcessing(),
inspectionBasedProcessing(ReplacePutWithAssignmentInspection()),
ReplaceGetterBodyWithSingleReturnStatementWithExpressionBody(),
inspectionBasedProcessing(UnnecessaryVariableInspection(), writeActionNeeded = false),
RedundantExplicitTypeInspectionBasedProcessing(),
JavaObjectEqualsToEqOperatorProcessing(),
RemoveExplicitPropertyTypeProcessing(),
RemoveRedundantNullabilityProcessing(),
CanBeValInspectionBasedProcessing(),
inspectionBasedProcessing(FoldInitializerAndIfToElvisInspection(), writeActionNeeded = false),
inspectionBasedProcessing(JavaMapForEachInspection()),
intentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() },
intentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) {
it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments(
it
) as KtReturnExpression).returnedExpression.isTrivialStatementBody()
},
inspectionBasedProcessing(IfThenToSafeAccessInspection(inlineWithPrompt = false), writeActionNeeded = false),
inspectionBasedProcessing(IfThenToElvisInspection(highlightStatement = true, inlineWithPrompt = false), writeActionNeeded = false),
inspectionBasedProcessing(KotlinInspectionFacade.instance.simplifyNegatedBinaryExpression),
inspectionBasedProcessing(ReplaceGetOrSetInspection()),
intentionBasedProcessing(ObjectLiteralToLambdaIntention(), writeActionNeeded = true),
intentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()),
intentionBasedProcessing(DestructureIntention(), writeActionNeeded = false),
inspectionBasedProcessing(SimplifyAssertNotNullInspection()),
intentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention()),
LiftReturnInspectionBasedProcessing(),
LiftAssignmentInspectionBasedProcessing(),
intentionBasedProcessing(RemoveEmptyPrimaryConstructorIntention()),
MayBeConstantInspectionBasedProcessing(),
RemoveForExpressionLoopParameterTypeProcessing(),
intentionBasedProcessing(ReplaceMapGetOrDefaultIntention()),
inspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection()),
inspectionBasedProcessing(KotlinInspectionFacade.instance.sortModifiers),
intentionBasedProcessing(ConvertToRawStringTemplateIntention()) { element ->
element.parents.none {
(it as? KtProperty)?.hasModifier(KtTokens.CONST_KEYWORD) == true
} && ConvertToStringTemplateIntention.buildReplacement(element).entries.any {
(it as? KtEscapeStringTemplateEntry)?.unescapedValue == "\n"
}
},
intentionBasedProcessing(IndentRawStringIntention())
)
private val cleaningUpDiagnosticBasedPostProcessingGroup =
DiagnosticBasedPostProcessingGroup(
removeUselessCastDiagnosticBasedProcessing,
removeUnnecessaryNotNullAssertionDiagnosticBasedProcessing,
fixValToVarDiagnosticBasedProcessing
)
private val processings: List<NamedPostProcessingGroup> = listOf(
NamedPostProcessingGroup(
KotlinNJ2KServicesBundle.message("processing.step.inferring.types"),
listOf(
InspectionLikeProcessingGroup(
processings = listOf(
VarToValProcessing(),
CanBeValInspectionBasedProcessing()
),
runSingleTime = true
),
NullabilityInferenceProcessing(),
MutabilityInferenceProcessing(),
ClearUnknownLabelsProcessing()
)
),
NamedPostProcessingGroup(
KotlinNJ2KServicesBundle.message("processing.step.cleaning.up.code"),
listOf(
InspectionLikeProcessingGroup(VarToValProcessing()),
ConvertGettersAndSettersToPropertyProcessing(),
InspectionLikeProcessingGroup(MoveGetterAndSetterAnnotationsToPropertyProcessing()),
InspectionLikeProcessingGroup(
RemoveExplicitGetterInspectionBasedProcessing(),
RemoveExplicitSetterInspectionBasedProcessing()
),
MergePropertyWithConstructorParameterProcessing(),
errorsFixingDiagnosticBasedPostProcessingGroup,
addOrRemoveModifiersProcessingGroup,
inspectionLikePostProcessingGroup,
removeRedundantElementsProcessingGroup,
cleaningUpDiagnosticBasedPostProcessingGroup
)
),
NamedPostProcessingGroup(
KotlinNJ2KServicesBundle.message("processing.step.optimizing.imports.and.formatting.code"),
listOf(
ShortenReferenceProcessing(),
OptimizeImportsProcessing(),
FormatCodeProcessing()
)
)
)
| apache-2.0 | 81d767d1123f639bba169bca79b02d05 | 44.456081 | 137 | 0.731401 | 5.95354 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 1 | 9949 | // 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.script
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
@Deprecated("migrating to new configuration refinement: drop usages")
override val id = "ScriptTemplatesFromDependenciesProvider"
@Deprecated("migrating to new configuration refinement: drop usages")
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val disposable = KotlinPluginDisposable.getInstance(project)
val connection = project.messageBus.connect(disposable)
connection.subscribe(FileTypeIndex.INDEX_CHANGE_TOPIC, FileTypeIndex.IndexChangeListener { fileType ->
if (fileType == ScriptDefinitionMarkerFileType && project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
})
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault || project.isDisposed) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val pluginDisposable = KotlinPluginDisposable.getInstance(project)
val (templates, classpath) =
ReadAction.nonBlocking(Callable {
val files = FileTypeIndex.getFiles(ScriptDefinitionMarkerFileType, project.allScope())
getTemplateClassPath(files, indicator)
})
.expireWith(pluginDisposable)
.wrapProgress(indicator)
.executeSynchronously() ?: return onEarlyEnd()
try {
indicator.checkCanceled()
if (pluginDisposable.disposed || !inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
indicator.checkCanceled()
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>, indicator: ProgressIndicator): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
// parent of SCRIPT_DEFINITION_MARKERS_PATH, i.e. of `META-INF/kotlin/script/templates/`
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
indicator.checkCanceled()
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getRootFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
indicator.checkCanceled()
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | apache-2.0 | 303aede3df87d5794179e1cbab85a6bd | 42.449782 | 158 | 0.634637 | 5.975375 | false | false | false | false |
ronocod/BeerSignal | android/app/src/main/kotlin/com/starstorm/beer/fragment/YouFragment.kt | 1 | 8567 | package com.starstorm.beer.fragment
import android.app.AlertDialog
import android.app.Fragment
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import com.crashlytics.android.Crashlytics
import com.dd.CircularProgressButton
import com.novoda.notils.caster.Views
import com.parse.FunctionCallback
import com.parse.ParseException
import com.parse.ParseFacebookUtils
import com.parse.ParseUser
import com.parse.SaveCallback
import com.starstorm.beer.R
import com.starstorm.beer.activity.LoginActivity
import com.starstorm.beer.service.ParseAuthService
import com.starstorm.beer.service.ParseUserService
import com.starstorm.beer.util.FacebookHelper
import com.starstorm.beer.util.Toaster
import java.util.Arrays
public class YouFragment : Fragment() {
private val authService = ParseAuthService
private val userService = ParseUserService
private var usernameText: TextView? = null
private var emailField: EditText? = null
private var linkFacebookButton: CircularProgressButton? = null
private var facebookLoginNote: TextView? = null
private var saveUserButton: CircularProgressButton? = null
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle item selection
when (item.getItemId()) {
R.id.action_change_username -> {
showUsernameChanger()
return true
}
R.id.action_logout -> {
logOut()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun showUsernameChanger() {
val alert = AlertDialog.Builder(getActivity())
alert.setTitle("Choose your username")
// Set an EditText view to get user input
val input = getActivity().getLayoutInflater().inflate(R.layout.dialog_choose_username, null)
val inputField = input.findViewById(R.id.choose_username_field) as EditText
alert.setView(input)
alert.setPositiveButton("Ok", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, whichButton: Int) {
val progressDialog = ProgressDialog(getActivity())
progressDialog.setMessage("Checking username")
progressDialog.show()
val newUsername = inputField.getText().toString()
// Do something with value!
userService.changeUsername(newUsername, object : FunctionCallback<String> {
override fun done(responseString: String?, e: ParseException?) {
progressDialog.dismiss()
if (e == null) {
ParseUser.getCurrentUser().setUsername(newUsername)
showLoggedInDetails()
FacebookHelper.getFacebookIdInBackground()
dialog.dismiss()
} else {
Log.w(TAG, e.getMessage())
if (responseString != null) {
Log.w(TAG, responseString)
if (responseString == "username_taken") {
Toaster.showShort(getActivity(), "That username is already taken")
}
} else {
Crashlytics.logException(e)
}
}
}
})
}
})
alert.setNegativeButton("Cancel", null)
alert.show()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.you, menu)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_you, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
usernameText = Views.findById<TextView>(view, R.id.username_text)
emailField = Views.findById<EditText>(view, R.id.email_field)
linkFacebookButton = Views.findById<CircularProgressButton>(view, R.id.link_facebook_button)
facebookLoginNote = Views.findById<TextView>(view, R.id.facebook_login_note)
saveUserButton = Views.findById<CircularProgressButton>(view, R.id.save_user_button)
linkFacebookButton!!.setIndeterminateProgressMode(true)
saveUserButton!!.setIndeterminateProgressMode(true)
showLoggedInDetails()
}
private fun logOut() {
try {
authService.logOut()
Toaster.showShort(getActivity(), "Logged out")
val intent = Intent(getActivity(), javaClass<LoginActivity>())
getActivity().startActivity(intent)
getActivity().finish()
} catch (e: Exception) {
Toaster.showShort(getActivity(), "Logout failed: " + e.getMessage())
Crashlytics.logException(e)
}
}
private fun showLoggedInDetails() {
val currentUser = ParseUser.getCurrentUser()
usernameText!!.setText(currentUser.getUsername())
emailField!!.setText(currentUser.getEmail())
saveUserButton!!.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
saveUser()
}
})
val isFacebookLinked = ParseFacebookUtils.isLinked(currentUser)
if (isFacebookLinked) {
facebookLoginNote!!.setVisibility(View.GONE)
linkFacebookButton!!.setIdleText("Linked to Facebook")
linkFacebookButton!!.setText("Linked to Facebook")
linkFacebookButton!!.setOnClickListener(null)
} else {
facebookLoginNote!!.setVisibility(View.VISIBLE)
linkFacebookButton!!.setIdleText("Link to Facebook")
linkFacebookButton!!.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
linkFacebookButton!!.setProgress(1)
val permissions = Arrays.asList<String>("email")
ParseFacebookUtils.link(ParseUser.getCurrentUser(), permissions, getActivity(), object : SaveCallback {
override fun done(e: ParseException?) {
if (e == null) {
linkFacebookButton!!.setIdleText("Linked to Facebook")
linkFacebookButton!!.setText("Linked to Facebook")
FacebookHelper.getFacebookIdInBackground()
} else {
Log.e(TAG, e.getMessage())
Crashlytics.logException(e)
}
linkFacebookButton!!.setProgress(0)
}
})
}
})
}
}
private fun saveUser() {
saveUserButton!!.setProgress(1)
ParseUser.getCurrentUser().setEmail(emailField!!.getText().toString())
ParseUser.getCurrentUser().saveInBackground(object : SaveCallback {
override fun done(e: ParseException?) {
if (e == null) {
saveUserButton!!.setProgress(0)
Toaster.showShort(getActivity(), "Your settings have been updated")
} else {
Log.e(TAG, e.getMessage())
Crashlytics.logException(e)
Toaster.showShort(getActivity(), "Save error: " + e.getCode())
saveUserButton!!.setProgress(-1)
}
}
})
}
class object {
private val TAG = javaClass<YouFragment>().getSimpleName()
public fun newInstance(): YouFragment {
return YouFragment()
}
}
}
| gpl-2.0 | 6bbf60ca913c5aade76de3b535140999 | 37.41704 | 123 | 0.598109 | 5.394836 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/LocalStats.kt | 1 | 544 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.util.ArrayList
@Parcelize
class LocalStats(
var cleaningDays: ArrayList<CleaningDayItem>? = null,
var cleaningAreas: ArrayList<CleaningDayItem>? = null,
var avarageCleaningPlusChargingTime: Int = 0,
var avarageCleaningArea: Double = 0.toDouble(),
var totalCleanedTime: Int = 0,
var totalCleanedArea: Double = 0.toDouble()
): Parcelable
| mit | 1d178c8149af2479bd97b6da053f2a86 | 23.727273 | 58 | 0.744485 | 3.751724 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/HtlElMemberAccessCompletionProvider.kt | 1 | 1613 | package com.aemtools.completion.htl.provider
import com.aemtools.analysis.htl.callchain
import com.aemtools.analysis.htl.callchain.elements.segment.resolveSelectedItem
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.htl.model.ResolutionResult
import com.aemtools.lang.htl.psi.mixin.PropertyAccessMixin
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
/**
* @author Dmytro_Troynikov
*/
object HtlElMemberAccessCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val currentPosition = parameters.position
val resolutionResult = resolve(currentPosition)
resolutionResult.predefined?.let {
result.addAllElements(it)
}
result.stopHere()
}
/**
* Resolve given psi element.
*
* @param element the element
* @return resolution result object
*/
fun resolve(element: PsiElement): ResolutionResult {
val propertyAccessElement = element.findParentByType(PropertyAccessMixin::class.java)
?: return ResolutionResult()
val chain = propertyAccessElement.callchain()
?: return ResolutionResult()
val lastSegment = chain.callChainSegments.lastOrNull()
?: return ResolutionResult()
return lastSegment.resolveSelectedItem()
}
}
| gpl-3.0 | ab1cdccfd0149fa1b65a29f01039e40e | 31.26 | 89 | 0.776813 | 4.963077 | false | false | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/gui/document/segments/HeadingSegment.kt | 1 | 839 | package de.theunknownxy.mcdocs.gui.document.segments
import de.theunknownxy.mcdocs.docs.HeadingBlock
import de.theunknownxy.mcdocs.gui.document.Document
import net.minecraft.client.Minecraft
import org.lwjgl.opengl.GL11
class HeadingSegment(document: Document, val heading: HeadingBlock) : Segment(document) {
private val base_height = 9f
private fun heading_scale(): Float = -0.15f * heading.level + 1.5f
private fun font_height(): Float = heading_scale() * base_height
override val height: Float = font_height() + 2
override fun draw() {
GL11.glPushMatrix()
GL11.glTranslatef(x, y, 0f)
GL11.glScalef(heading_scale(), heading_scale(), 1f)
val mc = Minecraft.getMinecraft().fontRenderer
mc.drawString("§n" + heading.text, 0, 0, 0xFFFFFF)
GL11.glPopMatrix()
}
} | mit | c1bd852b4388310b688cc080fdc3e3ba | 32.56 | 89 | 0.699284 | 3.643478 | false | false | false | false |
pattyjogal/MusicScratchpad | app/src/main/java/com/viviose/musicscratchpad/MainActivity.kt | 2 | 11637 | package com.viviose.musicscratchpad
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.drawable.VectorDrawable
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.SwitchCompat
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.OvershootInterpolator
import android.widget.ImageButton
import android.widget.LinearLayout
import com.github.clans.fab.FloatingActionButton
import com.github.clans.fab.FloatingActionMenu
import java.util.*
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
internal var rBar: LinearLayout? = null
internal var showCaseIterator: Int = 0
internal var ev: View? = null
private val pianoSwitch: SwitchCompat? = null
internal var dl: DrawerLayout? = null
internal val PREFS_NAME = "StaffpadPrefs"
internal val SELECTED_COLOR: Int = Color.rgb(229, 115, 115)
internal var REGULAR_COLOR: Int = Color.RED
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val con = this
ev = findViewById(R.id.editor_canvas)
//Loading Prefs
val preferences: SharedPreferences = getSharedPreferences(PREFS_NAME, 0)
val editor: SharedPreferences.Editor = preferences.edit()
val navigationView = findViewById(R.id.nav_view) as NavigationView
val singleTap = navigationView.menu.getItem(0).actionView.findViewById(R.id.singletap_switch) as SwitchCompat
singleTap.isChecked = preferences.getBoolean("single_tap", false)
Settings.piano = preferences.getBoolean("single_tap", false)
singleTap.setOnCheckedChangeListener { buttonView, isChecked ->
Settings.piano = isChecked
editor.putBoolean("single_tap", isChecked)
editor.commit()
Log.d("Switch", "You a-toggled mah switch")
}
Thread(Runnable {
val quarterNoteHead = ContextCompat.getDrawable(con, R.drawable.quarter_note_head) as VectorDrawable
NoteBitmap.qnh = NoteBitmap.getBitmap(quarterNoteHead)
//VectorDrawable halfNoteHead = (VectorDrawable) ContextCompat.getDrawable(con, R.drawable.half_note_head);
//NoteBitmap.hnh = NoteBitmap.getBitmap(halfNoteHead);
}).start()
Thread(Runnable {
//VectorDrawable quarterNoteHead = (VectorDrawable) ContextCompat.getDrawable(con, R.drawable.quarter_note_head);
//NoteBitmap.qnh = NoteBitmap.getBitmap(quarterNoteHead);
val halfNoteHead = ContextCompat.getDrawable(con, R.drawable.half_note_head) as VectorDrawable
NoteBitmap.hnh = NoteBitmap.getBitmap(halfNoteHead)
}).start()
DP.r = resources
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
DensityMetrics.toolbar = toolbar
val settings = getSharedPreferences(PREFS_NAME, 0)
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments", "First time")
// first time task
//SHOWCASES[0].build().show();
// record the fact that the app has been started at least once
//settings.edit().putBoolean("my_first_time", false).commit();
}
//Setting the correct media stream
volumeControlStream = AudioManager.STREAM_MUSIC
val upInc = findViewById(R.id.inc_octave) as ImageButton
upInc.setOnClickListener { Octave.octave += 1 }
val downDec = findViewById(R.id.dec_octave) as ImageButton
downDec.setOnClickListener { Octave.octave -= 1 }
dl = findViewById(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, dl, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
dl?.setDrawerListener(toggle)
toggle.syncState()
navigationView.setNavigationItemSelectedListener(this)
/*val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { nextInput() }*/
val rhythmMenu: FloatingActionMenu = findViewById(R.id.rhythm_menu) as FloatingActionMenu
REGULAR_COLOR = rhythmMenu.menuButtonColorNormal
//Loading fabs
val fab_sixteenth: FloatingActionButton = findViewById(R.id.sixteenth_note) as FloatingActionButton
fab_sixteenth.setOnClickListener {
LastRhythm.value = .25
rhythmMenu.close(true)
}
val fab_eighth: FloatingActionButton = findViewById(R.id.eighth_note) as FloatingActionButton
fab_eighth.setOnClickListener {
LastRhythm.value = .5
rhythmMenu.close(true)
}
val fab_quarter: FloatingActionButton = findViewById(R.id.quarter_note) as FloatingActionButton
fab_quarter.setOnClickListener {
LastRhythm.value = 1.0
rhythmMenu.close(true)
}
val fab_half: FloatingActionButton = findViewById(R.id.half_note) as FloatingActionButton
fab_half.setOnClickListener {
LastRhythm.value = 2.0
rhythmMenu.close(true)
}
val fab_whole: FloatingActionButton = findViewById(R.id.whole_note) as FloatingActionButton
fab_whole.setOnClickListener {
LastRhythm.value = 4.0
rhythmMenu.close(true)
}
var set: AnimatorSet = AnimatorSet()
var scaleOutX: ObjectAnimator = ObjectAnimator.ofFloat(rhythmMenu.menuIconView, "scaleX", 1.0f, 0.2f)
var scaleOutY: ObjectAnimator = ObjectAnimator.ofFloat(rhythmMenu.menuIconView, "scaleY", 1.0f, 0.2f)
var scaleInX: ObjectAnimator = ObjectAnimator.ofFloat(rhythmMenu.menuIconView, "scaleX", 0.2f, 1.0f)
var scaleInY: ObjectAnimator = ObjectAnimator.ofFloat(rhythmMenu.menuIconView, "scaleY", 0.2f, 1.0f)
scaleOutX.duration = 50
scaleOutY.duration = 50
scaleInX.duration = 150
scaleInY.duration = 150
scaleInX.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
rhythmMenu.menuIconView.setImageResource(if (rhythmMenu.isOpened)
R.drawable.ic_audiotrack_24dp_white
else
R.drawable.ic_close_white_24dp)
if (!rhythmMenu.isOpened) {
when (LastRhythm.value) {
4.0 -> fab_whole.colorNormal = SELECTED_COLOR
2.0 -> fab_half.colorNormal = SELECTED_COLOR
1.0 -> fab_quarter.colorNormal = SELECTED_COLOR
.5 -> fab_eighth.colorNormal = SELECTED_COLOR
.25 -> fab_sixteenth.colorNormal = SELECTED_COLOR
}
} else {
fab_whole.colorNormal = REGULAR_COLOR
fab_half.colorNormal = REGULAR_COLOR
fab_quarter.colorNormal = REGULAR_COLOR
fab_eighth.colorNormal = REGULAR_COLOR
fab_sixteenth.colorNormal = REGULAR_COLOR
}
}
})
set.play(scaleOutX).with(scaleOutY)
set.play(scaleInX).with(scaleInY).after(scaleOutX)
set.interpolator = OvershootInterpolator(2f)
rhythmMenu.iconToggleAnimatorSet = set
}
override fun onBackPressed() {
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
} else if (id == R.id.action_skip) {
nextInput()
} else if (id == R.id.action_undo) {
if (MusicStore.activeNotes.size == 0) {
if (MusicStore.sheet.size > 0) {
MusicStore.sheet.removeAt(MusicStore.sheet.size - 1)
}
} else {
MusicStore.activeNotes.clear()
}
}
return super.onOptionsItemSelected(item)
}
@SuppressWarnings("StatementWithEmptyBody")
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_keys) {
val sendToKeys = Intent(this, KeyChanger::class.java)
startActivity(sendToKeys)
} else if (id == R.id.nav_clefs) {
val sendToClefs = Intent(this, ClefChanger::class.java)
startActivity(sendToClefs)
} else if (id == R.id.nav_view_composition) {
val sendToComp = Intent(this, Composition::class.java)
startActivity(sendToComp)
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} else if (id == R.id.singletap) {
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
fun nextInput() {
object : Thread() {
override fun run() {
MusicStore.sheet.add(MusicStore.activeNotes)
System.gc()
for (note in MusicStore.activeNotes) {
val mediaPlayer = MediaPlayer()
try {
mediaPlayer.setDataSource(applicationContext, Uri.parse("android.resource://com.viviose.musicscratchpad/raw/" + note.name!!.toString() + Integer.toString(note.octave)))
} catch (e: Exception) {
}
Log.i("Media Playing:", "Player created!")
mediaPlayer.setOnPreparedListener { player -> player.start() }
mediaPlayer.setOnCompletionListener { mp -> mp.release() }
try {
mediaPlayer.prepareAsync()
} catch (e: Exception) {
}
}
MusicStore.activeNotes = ArrayList<Note>()
}
}.start()
}
}
| gpl-3.0 | 037fe5975ea2772c63342d6ed4653977 | 38.181818 | 192 | 0.636075 | 4.583301 | false | false | false | false |
allotria/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/impl/PrefixLengthFactor.kt | 3 | 2503 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.completion.ml.personalization.impl
import com.intellij.completion.ml.personalization.UserFactorBase
import com.intellij.completion.ml.personalization.UserFactorDescriptions
import com.intellij.completion.ml.personalization.UserFactorReaderBase
import com.intellij.completion.ml.personalization.UserFactorUpdaterBase
/**
* @author Vitaliy.Bibaev
*/
class PrefixLengthReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) {
fun getCountsByPrefixLength(): Map<Int, Double> {
return factor.aggregateSum().asIterable().associate { (key, value) -> key.toInt() to value }
}
fun getAveragePrefixLength(): Double? {
val lengthToCount = getCountsByPrefixLength()
if (lengthToCount.isEmpty()) return null
val totalChars = lengthToCount.asSequence().sumByDouble { it.key * it.value }
val completionCount = lengthToCount.asSequence().sumByDouble { it.value }
if (completionCount == 0.0) return null
return totalChars / completionCount
}
}
class PrefixLengthUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) {
fun fireCompletionPerformed(prefixLength: Int) {
factor.incrementOnToday(prefixLength.toString())
}
}
class MostFrequentPrefixLength : UserFactorBase<PrefixLengthReader>("mostFrequentPrefixLength",
UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) {
override fun compute(reader: PrefixLengthReader): String? {
return reader.getCountsByPrefixLength().maxBy { it.value }?.key?.toString()
}
}
class AveragePrefixLength : UserFactorBase<PrefixLengthReader>("averagePrefixLength", UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) {
override fun compute(reader: PrefixLengthReader): String? {
return reader.getAveragePrefixLength()?.toString()
}
} | apache-2.0 | 82d29f41de7bcfb49714a3bfdc21dbff | 40.04918 | 139 | 0.734718 | 4.430088 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/index/indexer/AemComponentDeclarationIndexer.kt | 1 | 1029 | package com.aemtools.index.indexer
import com.aemtools.common.constant.const.xml.JCR_PRIMARY_TYPE_CQ_COMPONENT
import com.aemtools.common.util.getXmlFile
import com.aemtools.index.model.AemComponentDefinition
import com.intellij.util.indexing.DataIndexer
import com.intellij.util.indexing.FileContent
/**
* @author Dmytro Troynikov
*/
object AemComponentDeclarationIndexer : DataIndexer<String, AemComponentDefinition, FileContent> {
override fun map(inputData: FileContent): MutableMap<String, AemComponentDefinition> {
val content = inputData.contentAsText
if (content.contains(JCR_PRIMARY_TYPE_CQ_COMPONENT)) {
val file = inputData.psiFile.getXmlFile()
?: return mutableMapOf()
val mainTag = file.rootTag
?: return mutableMapOf()
val key = inputData.file.path
val aemComponentDefinition = AemComponentDefinition.fromTag(mainTag, key)
?: return mutableMapOf()
return mutableMapOf(key to aemComponentDefinition)
}
return mutableMapOf()
}
}
| gpl-3.0 | feaea48302228dc16daae2194b7a62cf | 32.193548 | 98 | 0.749271 | 4.435345 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/controlFlow/forStatement.kt | 2 | 756 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Controller {
var result = ""
suspend fun <T> suspendWithResult(value: T): T = suspendCoroutineOrReturn { c ->
c.resume(value)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend Controller.() -> Unit): String {
val controller = Controller()
c.startCoroutine(controller, EmptyContinuation)
return controller.result
}
fun box(): String {
val value = builder {
for (x in listOf("O", "K")) {
result += suspendWithResult(x)
}
result += "."
}
if (value != "OK.") return "fail: suspend in for body: $value"
return "OK"
}
| apache-2.0 | 51d164ed35faf372f1b041d1cf499f2b | 21.909091 | 84 | 0.626984 | 4.153846 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/nonLocalReturnFromCatchBlock.kt | 3 | 839 | // MODULE: lib
// FILE: lib.kt
package utils
inline fun foo(a: Int) {
bar(a)
}
inline fun bar(a: Int) {
try {
if (a > 0) throw Exception()
log("foo($a) #1")
}
catch (e: Exception) {
myRun {
log("foo($a) #2")
if (a > 1) return
log("foo($a) #3")
}
}
log("foo($a) #4")
}
var LOG: String = ""
fun log(s: String): String {
LOG += s + ";"
return LOG
}
inline fun myRun(f: () -> Unit) = f()
// MODULE: main(lib)
// FILE: main.kt
import utils.*
fun box(): String {
foo(0)
if (LOG != "foo(0) #1;foo(0) #4;") return "fail1: $LOG"
LOG = ""
foo(1)
if (LOG != "foo(1) #2;foo(1) #3;foo(1) #4;") return "fail2: $LOG"
LOG = ""
foo(2)
if (LOG != "foo(2) #2;") return "fail3: $LOG"
LOG = ""
return "OK"
} | apache-2.0 | 9273f216a194140db421c1f58fd76704 | 14.555556 | 69 | 0.446961 | 2.646688 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/service/ZipService.kt | 1 | 1101 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import model.BlokadaException
import net.lingala.zip4j.ZipFile
import net.lingala.zip4j.io.inputstream.ZipInputStream
import java.io.InputStream
object ZipService {
private val fileService = FileService
fun decodeStream(stream: InputStream, key: String): InputStream {
var zipInput: InputStream? = null
try {
zipInput = ZipInputStream(stream, key.toCharArray())
val entry = zipInput.nextEntry ?: throw BlokadaException("Unexpected format of the zip file")
val decoded = fileService.load(zipInput)
return decoded.toByteArray().inputStream()
} catch (ex: Exception) {
throw BlokadaException("Could not unpack zip file", ex)
}
}
} | mpl-2.0 | 809cd2712b2874dc18af9f60913d916f | 28.756757 | 105 | 0.681818 | 4.166667 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/WrongPrimitiveLiteralFix.kt | 3 | 4118 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.ExpressionCodegen
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isUnsignedNumberType
import kotlin.math.floor
private val valueRanges = mapOf(
StandardNames.FqNames._byte to Byte.MIN_VALUE.toLong()..Byte.MAX_VALUE.toLong(),
StandardNames.FqNames._short to Short.MIN_VALUE.toLong()..Short.MAX_VALUE.toLong(),
StandardNames.FqNames._int to Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong(),
StandardNames.FqNames._long to Long.MIN_VALUE..Long.MAX_VALUE
)
class WrongPrimitiveLiteralFix(element: KtConstantExpression, type: KotlinType) : KotlinQuickFixAction<KtExpression>(element) {
private val typeName = DescriptorUtils.getFqName(type.constructor.declarationDescriptor!!)
private val expectedTypeIsFloat = KotlinBuiltIns.isFloat(type)
private val expectedTypeIsDouble = KotlinBuiltIns.isDouble(type)
private val expectedTypeIsUnsigned = type.isUnsignedNumberType()
private val constValue = run {
val shouldInlineConstVals = element.languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
ExpressionCodegen.getPrimitiveOrStringCompileTimeConstant(
element, element.analyze(BodyResolveMode.PARTIAL), shouldInlineConstVals
)?.value as? Number
}
private val fixedExpression = buildString {
if (expectedTypeIsFloat || expectedTypeIsDouble) {
append(constValue)
if (expectedTypeIsFloat) {
append('F')
} else if ('.' !in this) {
append(".0")
}
} else if (expectedTypeIsUnsigned) {
append(constValue)
append('u')
} else {
if (constValue is Float || constValue is Double) {
append(constValue.toLong())
} else {
append(element.text.trimEnd('l', 'L', 'u'))
}
if (KotlinBuiltIns.isLong(type)) {
append('L')
}
}
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
if (constValue == null) return false
if (expectedTypeIsFloat || expectedTypeIsDouble || expectedTypeIsUnsigned) return true
if (constValue is Float || constValue is Double) {
val value = constValue.toDouble()
if (value != floor(value)) return false
if (value !in Long.MIN_VALUE.toDouble()..Long.MAX_VALUE.toDouble()) return false
}
return constValue.toLong() in (valueRanges[typeName] ?: return false)
}
override fun getFamilyName() = KotlinBundle.message("change.to.correct.primitive.type")
override fun getText() = KotlinBundle.message("change.to.0", fixedExpression)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val expressionToInsert = KtPsiFactory(file).createExpression(fixedExpression)
val newExpression = element.replaced(expressionToInsert)
editor?.caretModel?.moveToOffset(newExpression.endOffset)
}
}
| apache-2.0 | 0473a21139d43a54fee7adb9e2f7f006 | 43.27957 | 158 | 0.71661 | 4.590858 | false | false | false | false |
mdaniel/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/MoveToCaretStopTest.kt | 13 | 17300 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.actions
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.actions.MoveToCaretStopTest.Action.DELETE
import com.intellij.openapi.editor.actions.MoveToCaretStopTest.Action.MOVE
import com.intellij.openapi.editor.actions.MoveToCaretStopTest.Direction.BACKWARD
import com.intellij.openapi.editor.actions.MoveToCaretStopTest.Direction.FORWARD
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.Comparing
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class MoveToCaretStopTest : BasePlatformTestCase() {
enum class Action { MOVE, DELETE }
enum class Direction : Comparator<Int> {
BACKWARD, FORWARD;
override fun compare(o1: Int, o2: Int): Int {
return when (this) {
FORWARD -> Comparing.compare(o1, o2)
BACKWARD -> Comparing.compare(o2, o1)
}
}
}
fun `test Move to Next Word IDEA default`() {
doTest(MOVE, FORWARD, """doTest^(^"^test^"^,^ Direction^.^FORWARD^)^""")
doTest(MOVE, FORWARD, """
^ assert^(^i^ <^ expectedCaretOffset^)^ {^ "^Duplicate^ carets^:^ '^${'$'}stringWithCaretStops^'^"^ }^
""")
doTest(MOVE, FORWARD, """
^ private^ fun^ doTest^(^stringWithCaretStops^:^ String^,^
^ direction^:^ Direction^,^
^ isDelete^:^ Boolean^ =^ false^)^ {^
""")
doTest(MOVE, FORWARD, """
^data^ class^ CaretStopOptions^(^@^OptionTag^(^"^BACKWARD^"^)^ val^ backwardPolicy^:^ CaretStopPolicy^,^
^ @^OptionTag^(^"^FORWARD^"^)^ val^ forwardPolicy^:^ CaretStopPolicy^)^ {^
""")
doTest(MOVE, FORWARD, """
^ public^ void^ setCaretStopOptions^(^@^NotNull^ CaretStopOptions^ options^)^ {^
^ myOsSpecificState^.^CARET_STOP_OPTIONS^ =^ options^;^
^ }^
""")
doTest(MOVE, FORWARD, """
^my_list^ =^ [^"^one^"^,^ "^two^"^,^ "^three^"^,^
^ "^four^"^,^ "^five^"^,^
^ "^six^"^.^six^,^ "^seven^"^seven^,^
^ eight^"^eight^"^,^ nine^/^"^nine^"^,^
^ "^...^"^"^ten^"^,^ (^"^...^"^"^eleven^"^"^...^"^)^,^ "^twelve^"^"^...^"^]^
""")
doTest(MOVE, FORWARD, """
^ [^ "^word^"^"^...^"^]^ ,^
^ [^"^word^"^ "^...^"^]^ ,^
^ [^"^word^"^"^...^"^ ]^ ,^
^ [^ "^word^"^"^...^"^ ]^ ,^
^ [^"^ word^"^"^...^"^]^ ,^
^ [^"^ word^ "^"^...^"^]^ ,^
^ [^"^word^ "^"^...^"^]^ ,^
^ [^"^word^"^"^ ...^"^]^ ,^
^ [^"^word^"^"^ ...^ "^]^ ,^
^ [^"^word^"^"^...^ "^]^ ,^
""")
}
fun `test Move to Previous Word IDEA default`() {
doTest(MOVE, BACKWARD, """^doTest^(^"^test^"^, ^Direction^.^FORWARD^)""")
doTest(MOVE, BACKWARD, """
^assert^(^i ^< ^expectedCaretOffset^) ^{ ^"^Duplicate ^carets^: ^'^${'$'}stringWithCaretStops^'^" ^}^
""")
doTest(MOVE, BACKWARD, """
^private ^fun ^doTest^(^stringWithCaretStops^: ^String^,^
^direction^: ^Direction^,^
^isDelete^: ^Boolean ^= ^false^) ^{^
""")
doTest(MOVE, BACKWARD, """
^data ^class ^CaretStopOptions^(^@^OptionTag^(^"^BACKWARD^"^) ^val ^backwardPolicy^: ^CaretStopPolicy^,^
^@^OptionTag^(^"^FORWARD^"^) ^val ^forwardPolicy^: ^CaretStopPolicy^) ^{^
""")
doTest(MOVE, BACKWARD, """
^public ^void ^setCaretStopOptions^(^@^NotNull ^CaretStopOptions ^options^) ^{^
^myOsSpecificState^.^CARET_STOP_OPTIONS ^= ^options^;^
^}^
""")
doTest(MOVE, BACKWARD, """
^my_list ^= ^[^"^one^"^, ^"^two^"^, ^"^three^"^,^
^"^four^"^, ^"^five^"^,^
^"^six^"^.^six^, ^"^seven^"^seven^,^
^eight^"^eight^"^, ^nine^/^"^nine^"^,^
^"^...^"^"^ten^"^, ^(^"^...^"^"^eleven^"^"^...^"^)^, ^"^twelve^"^"^...^"^]]^
""")
doTest(MOVE, BACKWARD, """
^[ ^"^word^"^"^...^"^] ^,^
^[^"^word^" ^"^...^"^] ^,^
^[^"^word^"^"^...^" ^] ^,^
^[ ^"^word^"^"^...^" ^] ^,^
^[^" ^word^"^"^...^"^] ^,^
^[^" ^word ^"^"^...^"^] ^,^
^[^"^word ^"^"^...^"^] ^,^
^[^"^word^"^" ^...^"^] ^,^
^[^"^word^"^" ^... ^"^] ^,^
^[^"^word^"^"^... ^"^] ^,^
""")
}
fun `test Move to Next Word on Unix`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_UNIX)
doTest(MOVE, FORWARD, """doTest^(^"^test^"^,^ Direction^.^FORWARD^)^""")
doTest(MOVE, FORWARD, """
assert^(^i^ <^ expectedCaretOffset^)^ {^ "^Duplicate^ carets^:^ '^${'$'}stringWithCaretStops^'^"^ }^
""")
doTest(MOVE, FORWARD, """
private^ fun^ doTest^(^stringWithCaretStops^:^ String^,^
direction^:^ Direction^,^
isDelete^:^ Boolean^ =^ false^)^ {^
""")
doTest(MOVE, FORWARD, """
data^ class^ CaretStopOptions^(^@^OptionTag^(^"^BACKWARD^"^)^ val^ backwardPolicy^:^ CaretStopPolicy^,^
@^OptionTag^(^"^FORWARD^"^)^ val^ forwardPolicy^:^ CaretStopPolicy^)^ {^
""")
doTest(MOVE, FORWARD, """
public^ void^ setCaretStopOptions^(^@^NotNull^ CaretStopOptions^ options^)^ {^
myOsSpecificState^.^CARET_STOP_OPTIONS^ =^ options^;^
}^
""")
doTest(MOVE, FORWARD, """
my_list^ =^ [^"^one^"^,^ "^two^"^,^ "^three^"^,^
"^four^"^,^ "^five^"^,^
"^six^"^.^six^,^ "^seven^"^seven^,^
eight^"^eight^"^,^ nine^/^"^nine^"^,^
"^...^"^"^ten^"^,^ (^"^...^"^"^eleven^"^"^...^"^)^,^ "^twelve^"^"^...^"^]^
""")
doTest(MOVE, FORWARD, """
[^ "^word^"^"^...^"^]^ ,^
[^"^word^"^ "^...^"^]^ ,^
[^"^word^"^"^...^"^ ]^ ,^
[^ "^word^"^"^...^"^ ]^ ,^
[^"^ word^"^"^...^"^]^ ,^
[^"^ word^ "^"^...^"^]^ ,^
[^"^word^ "^"^...^"^]^ ,^
[^"^word^"^"^ ...^"^]^ ,^
[^"^word^"^"^ ...^ "^]^ ,^
[^"^word^"^"^...^ "^]^ ,^
""")
}
fun `test Move to Previous Word on Unix`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_UNIX)
doTest(MOVE, BACKWARD, """^doTest^(^"^test^"^, ^Direction^.^FORWARD^)""")
doTest(MOVE, BACKWARD, """
^assert^(^i ^< ^expectedCaretOffset^) ^{ ^"^Duplicate ^carets^: ^'^${'$'}stringWithCaretStops^'^" ^}
""")
doTest(MOVE, BACKWARD, """
^private ^fun ^doTest^(^stringWithCaretStops^: ^String^,
^direction^: ^Direction^,
^isDelete^: ^Boolean ^= ^false^) ^{
""")
doTest(MOVE, BACKWARD, """
^data ^class ^CaretStopOptions^(^@^OptionTag^(^"^BACKWARD^"^) ^val ^backwardPolicy^: ^CaretStopPolicy^,
^@^OptionTag^(^"^FORWARD^"^) ^val ^forwardPolicy^: ^CaretStopPolicy^) ^{
""")
doTest(MOVE, BACKWARD, """
^public ^void ^setCaretStopOptions^(^@^NotNull ^CaretStopOptions ^options^) ^{
^myOsSpecificState^.^CARET_STOP_OPTIONS ^= ^options^;
^}
""")
doTest(MOVE, BACKWARD, """
^my_list ^= ^[^"^one^"^, ^"^two^"^, ^"^three^"^,
^"^four^"^, ^"^five^"^,
^"^six^"^.^six^, ^"^seven^"^seven^,
^eight^"^eight^"^, ^nine^/^"^nine^"^,
^"^...^"^"^ten^"^, ^(^"^...^"^"^eleven^"^"^...^"^)^, ^"^twelve^"^"^...^"^]]
""")
doTest(MOVE, BACKWARD, """
^[ ^"^word^"^"^...^"^] ^,
^[^"^word^" ^"^...^"^] ^,
^[^"^word^"^"^...^" ^] ^,
^[ ^"^word^"^"^...^" ^] ^,
^[^" ^word^"^"^...^"^] ^,
^[^" ^word ^"^"^...^"^] ^,
^[^"^word ^"^"^...^"^] ^,
^[^"^word^"^" ^...^"^] ^,
^[^"^word^"^" ^... ^"^] ^,
^[^"^word^"^"^... ^"^] ^,
""")
}
fun `test Move to Next Word on Windows`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_WINDOWS)
`do test Move to Neighbor Word on Windows`(FORWARD)
}
fun `test Move to Previous Word on Windows`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_WINDOWS)
`do test Move to Neighbor Word on Windows`(BACKWARD)
}
private fun `do test Move to Neighbor Word on Windows`(direction: Direction) {
doTest(MOVE, direction, """doTest^(^"^test^"^, ^Direction^.^FORWARD^)""")
doTest(MOVE, direction, """
^ ^assert^(^i ^< ^expectedCaretOffset^) ^{ ^"^Duplicate ^carets^: ^'^${'$'}stringWithCaretStops^'^" ^}^
""")
doTest(MOVE, direction, """
^ ^private ^fun ^doTest^(^stringWithCaretStops^: ^String^,^
^ ^direction^: ^Direction^,^
^ ^isDelete^: ^Boolean ^= ^false^) ^{^
""")
doTest(MOVE, direction, """
^data ^class ^CaretStopOptions^(^@^OptionTag^(^"^BACKWARD^"^) ^val ^backwardPolicy^: ^CaretStopPolicy^,^
^ ^@^OptionTag^(^"^FORWARD^"^) ^val ^forwardPolicy^: ^CaretStopPolicy^) ^{^
""")
doTest(MOVE, direction, """
^ ^public ^void ^setCaretStopOptions^(^@^NotNull ^CaretStopOptions ^options^) ^{^
^ ^myOsSpecificState^.^CARET_STOP_OPTIONS ^= ^options^;^
^ ^}^
""")
doTest(MOVE, direction, """
^my_list ^= ^[^"^one^"^, ^"^two^"^, ^"^three^"^,^
^ ^"^four^"^, ^"^five^"^,^
^ ^"^six^"^.^six^, ^"^seven^"^seven^,^
^ ^eight^"^eight^"^, ^nine^/^"^nine^"^,^
^ ^"^...^"^"^ten^"^, ^(^"^...^"^"^eleven^"^"^...^"^)^, ^"^twelve^"^"^...^"^]^
""")
doTest(MOVE, direction, """
^ ^[ ^"^word^"^"^...^"^] ^,^
^ ^[^"^word^" ^"^...^"^] ^,^
^ ^[^"^word^"^"^...^" ^] ^,^
^ ^[ ^"^word^"^"^...^" ^] ^,^
^ ^[^" ^word^"^"^...^"^] ^,^
^ ^[^" ^word ^"^"^...^"^] ^,^
^ ^[^"^word ^"^"^...^"^] ^,^
^ ^[^"^word^"^" ^...^"^] ^,^
^ ^[^"^word^"^" ^... ^"^] ^,^
^ ^[^"^word^"^"^... ^"^] ^,^
""")
}
fun `test Delete to Word End on Unix`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_UNIX)
`do test Delete to Word End`()
}
fun `test Delete to Word End on Windows`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_WINDOWS)
`do test Delete to Word End`()
}
private fun `do test Delete to Word End`() {
doTest(DELETE, FORWARD, """doTest^(^"`test`"^,^ ^Direction^.^FORWARD^)^""")
doTest(DELETE, FORWARD, """
^ ^assert^(^i^ ^<^ ^expectedCaretOffset^)^ ^{^ ^"^Duplicate^ ^carets^:^ ^'^${'$'}stringWithCaretStops^'^"^ ^}^
""")
doTest(DELETE, FORWARD, """
^ ^private^ ^fun^ ^doTest^(^stringWithCaretStops^:^ ^String^,^
^ ^direction^:^ ^Direction^,^
^ ^isDelete^:^ ^Boolean^ ^=^ ^false^)^ ^{^
""")
doTest(DELETE, FORWARD, """
^data^ ^class^ ^CaretStopOptions^(^@^OptionTag^(^"`BACKWARD`"^)^ ^val^ ^backwardPolicy^:^ ^CaretStopPolicy^,^
^ ^@^OptionTag^(^"`FORWARD`"^)^ ^val^ ^forwardPolicy^:^ ^CaretStopPolicy^)^ ^{^
""")
doTest(DELETE, FORWARD, """
^ ^public^ ^void^ ^setCaretStopOptions^(^@^NotNull^ ^CaretStopOptions^ ^options^)^ ^{^
^ ^myOsSpecificState^.^CARET_STOP_OPTIONS^ ^=^ ^options^;^
^ ^}^
""")
doTest(DELETE, FORWARD, """
^my_list^ ^=^ ^[^"`one`"^,^ ^"`two`"^,^ ^"`three`"^,^
^ ^"`four`"^,^ ^"`five`"^,^
^ ^"`six`"^.^six^,^ ^"`seven`"^seven^,^
^ ^eight^"`eight`"^,^ ^nine^/^"`nine`"^,^
^ ^"`...`"^"`ten`"^,^ ^(^"`...`"^"`eleven`"^"`...`"^)^,^ ^"`twelve`"^"`...`"^]^
""")
}
fun `test Delete to Word Start on Unix`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_UNIX)
`do test Delete to Word Start`()
}
fun `test Delete to Word Start on Windows`() {
setupTestCaretStops(CaretStopOptionsTransposed.DEFAULT_WINDOWS)
`do test Delete to Word Start`()
}
// TODO for some reason this test performs 4-5 time slower than its twin "Delete to Word End" test
private fun `do test Delete to Word Start`() {
doTest(DELETE, BACKWARD, """^doTest^(^"`test`"^, ^Direction^.^FORWARD^)""")
doTest(DELETE, BACKWARD, """
^ ^assert^(^i ^< ^expectedCaretOffset^) ^{ ^"^Duplicate ^carets^: ^'^${'$'}stringWithCaretStops^'^" ^}^
""")
doTest(DELETE, BACKWARD, """
^ ^private ^fun ^doTest^(^stringWithCaretStops^: ^String^,^
^ ^direction^: ^Direction^,^
^ ^isDelete^: ^Boolean ^= ^false^) ^{^
""")
doTest(DELETE, BACKWARD, """
^data ^class ^CaretStopOptions^(^@^OptionTag^(^"`BACKWARD`"^) ^val ^backwardPolicy^: ^CaretStopPolicy^,^
^ ^@^OptionTag^(^"`FORWARD`"^) ^val ^forwardPolicy^: ^CaretStopPolicy^) ^{^
""")
doTest(DELETE, BACKWARD, """
^ ^public ^void ^setCaretStopOptions^(^@^NotNull ^CaretStopOptions ^options^) ^{^
^ ^myOsSpecificState^.^CARET_STOP_OPTIONS ^= ^options^;^
^ ^}^
""")
doTest(DELETE, BACKWARD, """
^my_list ^= ^[^"`one`"^, ^"`two`"^, ^"`three`"^,^
^ ^"`four`"^, ^"`five`"^,^
^ ^"`six`"^.^six^, ^"`seven`"^seven^,^
^ ^eight^"`eight`"^, ^nine^/^"`nine`"^,^
^ ^"`...`"^"`ten`"^, ^(^"`...`"^"`eleven`"^"`...`"^)^, ^"`twelve`"^"`...`"^]^
""")
}
private fun doTest(action: Action,
direction: Direction,
stringWithCaretStops: String) {
val (str, caretOffsets: List<CaretOffset>) = stringWithCaretStops.extractCaretOffsets()
myFixture.configureByText("a.java", str)
val editor = myFixture.editor
val document = editor.document
str.offsets(direction).forEach { i ->
val expectedCaretOffset = caretOffsets.nextTo(i, direction)
editor.caretModel.moveToOffset(i)
try {
myFixture.performEditorAction(ideAction(action, direction))
val expectedWithReadableCarets = when (action) {
MOVE -> str.withCaretMarkerAt(i, expectedCaretOffset.offset)
DELETE -> str.withCaretMarkerBetween(i, expectedCaretOffset.offset)
}
val actualWithReadableCarets = when (action) {
MOVE -> document.text.withCaretMarkerAt(i, myFixture.caretOffset)
DELETE -> document.text.withCaretMarkerAt(myFixture.caretOffset)
}
assertEquals(expectedWithReadableCarets, actualWithReadableCarets)
}
finally {
if (action == DELETE) {
WriteCommandAction.runWriteCommandAction(project) {
// for some reason moving the caret forward makes "Delete to Word Start" tests run 2-3 times faster
val caretOffset = (myFixture.caretOffset + 1).coerceIn(0, document.textLength)
editor.caretModel.moveToOffset(caretOffset)
document.setText(str)
}
}
}
}
}
private fun setupTestCaretStops(caretStopSettings: CaretStopOptionsTransposed) {
val savedCaretStopOptions = EditorSettingsExternalizable.getInstance().caretStopOptions
EditorSettingsExternalizable.getInstance().caretStopOptions = caretStopSettings.toCaretStopOptions()
disposeOnTearDown(Disposable {
EditorSettingsExternalizable.getInstance().caretStopOptions = savedCaretStopOptions
})
}
companion object {
private const val READABLE_CARET = '^'
private const val SKIP_INNARDS_CARET = '`' // delete word consumes "quoted" words
private fun isTestCaret(ch: Char) =
ch == READABLE_CARET || ch == SKIP_INNARDS_CARET
private data class CaretOffset(val offset: Int, val isSkipInnards: Boolean = false)
private fun String.extractCaretOffsets(): Pair<String, List<CaretOffset>> {
val caretOffsets: List<CaretOffset> = trim(READABLE_CARET, SKIP_INNARDS_CARET)
.let { "^$it^" }
.mapIndexedNotNull { offset, ch ->
(offset to (ch == SKIP_INNARDS_CARET)).takeIf { isTestCaret(ch) }
}.mapIndexed { i, (offset, isSkipInnards) ->
CaretOffset(offset - i, isSkipInnards)
}
val str = filterNot(::isTestCaret)
return str to caretOffsets
}
private fun List<CaretOffset>.nextTo(offset: Int, direction: Direction): CaretOffset {
val foundIndex = binarySearch { it.offset.compareTo(offset) }
val skip = !when {
foundIndex >= 0 -> this[foundIndex].isSkipInnards
else -> -foundIndex - 1 in indices && this[-foundIndex - 1].isSkipInnards &&
-foundIndex - 2 in indices && this[-foundIndex - 2].isSkipInnards
}
return when (direction) {
FORWARD -> first { it.offset > offset && !(skip && it.isSkipInnards) }
BACKWARD -> last { it.offset < offset && !(skip && it.isSkipInnards) }
}
}
private fun ideAction(action: Action, direction: Direction): String =
when (action) {
MOVE -> when (direction) {
FORWARD -> IdeActions.ACTION_EDITOR_NEXT_WORD
BACKWARD -> IdeActions.ACTION_EDITOR_PREVIOUS_WORD
}
DELETE -> when (direction) {
FORWARD -> IdeActions.ACTION_EDITOR_DELETE_TO_WORD_END
BACKWARD -> IdeActions.ACTION_EDITOR_DELETE_TO_WORD_START
}
}
private fun CharSequence.offsets(direction: Direction): IntProgression =
when (direction) {
FORWARD -> 0 until length
BACKWARD -> length downTo 1
}
private fun String.withCaretMarkerAt(firstOffset: Int, secondOffset: Int = firstOffset): String =
if (firstOffset == secondOffset)
withCaretMarkerBetween(firstOffset, secondOffset)
else
withCaretMarkerBetween(maxOf(firstOffset, secondOffset))
.withCaretMarkerBetween(minOf(firstOffset, secondOffset))
private fun String.withCaretMarkerBetween(firstOffset: Int, secondOffset: Int = firstOffset): String =
substring(0, minOf(firstOffset, secondOffset)) + READABLE_CARET +
substring(maxOf(firstOffset, secondOffset))
}
} | apache-2.0 | 0c23804c6393672d3b201ec1f44681fd | 36.286638 | 140 | 0.544451 | 2.994634 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/code-insight-groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/KotlinGradleInspectionVisitor.kt | 1 | 3206 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.groovy.inspections
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.externalSystem.KotlinGradleFacade
import org.jetbrains.kotlin.idea.base.util.isGradleModule
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleConstants
import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.findGradleProjectStructure
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
const val KOTLIN_PLUGIN_CLASSPATH_MARKER = "${KotlinGradleConstants.GROUP_ID}:${KotlinGradleConstants.GRADLE_PLUGIN_ID}:"
abstract class KotlinGradleInspectionVisitor : BaseInspectionVisitor() {
override fun visitFile(file: GroovyFileBase) {
if (!FileUtilRt.extensionEquals(file.name, KotlinGradleConstants.GROOVY_EXTENSION)) return
val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex
if (!isUnitTestMode()) {
val module = fileIndex.getModuleForFile(file.virtualFile) ?: return
if (!module.isGradleModule) return
}
if (fileIndex.isExcluded(file.virtualFile)) return
super.visitFile(file)
}
}
@Deprecated("Use findResolvedKotlinGradleVersion() instead.", ReplaceWith("findResolvedKotlinGradleVersion(module)?.rawVersion"))
fun getResolvedKotlinGradleVersion(file: PsiFile): String? =
ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let {
@Suppress("DEPRECATION")
getResolvedKotlinGradleVersion(it)
}
fun findResolvedKotlinGradleVersion(file: PsiFile): IdeKotlinVersion? =
ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let { findResolvedKotlinGradleVersion(it) }
@Deprecated("Use findResolvedKotlinGradleVersion() instead.", ReplaceWith("findResolvedKotlinGradleVersion(module)?.rawVersion"))
fun getResolvedKotlinGradleVersion(module: Module): String? {
return findResolvedKotlinGradleVersion(module)?.rawVersion
}
fun findResolvedKotlinGradleVersion(module: Module): IdeKotlinVersion? {
val projectStructureNode = findGradleProjectStructure(module) ?: return null
val gradleFacade = KotlinGradleFacade.instance ?: return null
for (node in ExternalSystemApiUtil.findAll(projectStructureNode, ProjectKeys.MODULE)) {
if (node.data.internalName == module.name) {
val kotlinPluginVersion = gradleFacade.findKotlinPluginVersion(node)
if (kotlinPluginVersion != null) {
return kotlinPluginVersion
}
}
}
return null
}
| apache-2.0 | 06e3fbd96dced5d6487ddb24977b0004 | 45.463768 | 158 | 0.784155 | 4.924731 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/context/DeclarationExporter.kt | 1 | 6906 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.context
import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.isInlineOnlyOrReifiable
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isLibraryObject
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isNativeObject
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.assignment
import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.DescriptorUtils
internal class DeclarationExporter(val context: StaticContext) {
private val objectLikeKinds = setOf(ClassKind.OBJECT, ClassKind.ENUM_ENTRY)
private val exportedDeclarations = mutableSetOf<MemberDescriptor>()
private val localPackageNames = mutableMapOf<FqName, JsName>()
val statements = mutableListOf<JsStatement>()
fun export(descriptor: MemberDescriptor, force: Boolean) {
if (exportedDeclarations.contains(descriptor)) return
if (descriptor is ConstructorDescriptor && descriptor.isPrimary) return
if (isNativeObject(descriptor) || isLibraryObject(descriptor)) return
if (descriptor.isInlineOnlyOrReifiable()) return
val suggestedName = context.nameSuggestion.suggest(descriptor) ?: return
val container = suggestedName.scope
if (!descriptor.shouldBeExported(force)) return
exportedDeclarations.add(descriptor)
val qualifier = when {
container is PackageFragmentDescriptor -> {
getLocalPackageReference(container.fqName)
}
DescriptorUtils.isObject(container) -> {
JsAstUtils.prototypeOf(context.getInnerNameForDescriptor(container).makeRef())
}
else -> {
context.getInnerNameForDescriptor(container).makeRef()
}
}
when {
descriptor is ClassDescriptor && descriptor.kind in objectLikeKinds -> {
exportObject(descriptor, qualifier)
}
descriptor is PropertyDescriptor && container is PackageFragmentDescriptor -> {
exportProperty(descriptor, qualifier)
}
else -> {
assign(descriptor, qualifier, context.getInnerNameForDescriptor(descriptor).makeRef())
}
}
}
private fun assign(descriptor: DeclarationDescriptor, qualifier: JsExpression, expression: JsExpression) {
val propertyName = context.getNameForDescriptor(descriptor)
if (propertyName.staticRef == null) {
if (expression !is JsNameRef || expression.name !== propertyName) {
propertyName.staticRef = expression
}
}
statements += assignment(JsNameRef(propertyName, qualifier), expression).makeStmt()
}
private fun exportObject(declaration: ClassDescriptor, qualifier: JsExpression) {
val name = context.getNameForDescriptor(declaration)
statements += JsAstUtils.defineGetter(context.program, qualifier, name.ident,
context.getNameForObjectInstance(declaration).makeRef())
}
private fun exportProperty(declaration: PropertyDescriptor, qualifier: JsExpression) {
val propertyLiteral = JsObjectLiteral(true)
val name = context.getNameForDescriptor(declaration).ident
val simpleProperty = JsDescriptorUtils.isSimpleFinalProperty(declaration) &&
!TranslationUtils.shouldAccessViaFunctions(declaration)
val getterBody: JsExpression = if (simpleProperty) {
val accessToField = JsReturn(context.getInnerNameForDescriptor(declaration).makeRef())
JsFunction(context.rootFunction.scope, JsBlock(accessToField), "$declaration getter")
}
else {
context.getInnerNameForDescriptor(declaration.getter!!).makeRef()
}
propertyLiteral.propertyInitializers += JsPropertyInitializer(JsNameRef("get"), getterBody)
if (declaration.isVar) {
val setterBody: JsExpression = if (simpleProperty) {
val statements = mutableListOf<JsStatement>()
val function = JsFunction(context.rootFunction.scope, JsBlock(statements), "$declaration setter")
val valueName = function.scope.declareTemporaryName("value")
function.parameters += JsParameter(valueName)
statements += assignment(context.getInnerNameForDescriptor(declaration).makeRef(), valueName.makeRef()).makeStmt()
function
}
else {
context.getInnerNameForDescriptor(declaration.setter!!).makeRef()
}
propertyLiteral.propertyInitializers += JsPropertyInitializer(JsNameRef("set"), setterBody)
}
statements += JsAstUtils.defineProperty(qualifier, name, propertyLiteral, context.program).makeStmt()
}
private fun getLocalPackageReference(packageName: FqName): JsExpression {
if (packageName.isRoot) {
return context.rootFunction.scope.declareName(Namer.getRootPackageName()).makeRef()
}
var name = localPackageNames[packageName]
if (name == null) {
name = context.rootFunction.scope.declareTemporaryName("package$" + packageName.shortName().asString())
localPackageNames.put(packageName, name)
val parentRef = getLocalPackageReference(packageName.parent())
val selfRef = JsNameRef(packageName.shortName().asString(), parentRef)
val rhs = JsAstUtils.or(selfRef, assignment(selfRef.deepCopy(), JsObjectLiteral(false)))
statements.add(JsAstUtils.newVar(name, rhs))
}
return name.makeRef()
}
}
private fun MemberDescriptor.shouldBeExported(force: Boolean) =
force || effectiveVisibility(checkPublishedApi = true).publicApi || AnnotationsUtils.getJsNameAnnotation(this) != null
| apache-2.0 | 104098754ccae16c92306b8c525ed403 | 46.30137 | 130 | 0.695627 | 5.09292 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/support/sheets/LithoOptionBottomSheet.kt | 1 | 6410 | package com.maubis.scarlet.base.support.sheets
import android.app.Dialog
import android.graphics.Color
import android.graphics.Typeface.BOLD
import com.facebook.litho.ClickEvent
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.Row
import com.facebook.litho.annotations.LayoutSpec
import com.facebook.litho.annotations.OnCreateLayout
import com.facebook.litho.annotations.OnEvent
import com.facebook.litho.annotations.Prop
import com.facebook.litho.widget.Text
import com.facebook.yoga.YogaAlign
import com.facebook.yoga.YogaEdge
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface
import com.maubis.scarlet.base.support.specs.RoundIcon
import com.maubis.scarlet.base.support.ui.ThemeColorType
class LithoOptionsItem(
val title: Int,
val subtitle: Int,
val content: String = "",
val icon: Int,
val isSelectable: Boolean = false,
val selected: Boolean = false,
val actionIcon: Int = 0,
val visible: Boolean = true,
val listener: () -> Unit)
@LayoutSpec
object OptionItemLayoutSpec {
@OnCreateLayout
fun onCreate(
context: ComponentContext,
@Prop option: LithoOptionsItem): Component {
val titleColor = sAppTheme.get(ThemeColorType.SECONDARY_TEXT)
val subtitleColor = sAppTheme.get(ThemeColorType.HINT_TEXT)
val selectedColor = sAppTheme.get(ThemeColorType.ACCENT_TEXT)
val subtitle = when (option.subtitle) {
0 -> option.content
else -> context.getString(option.subtitle)
}
val row = Row.create(context)
.widthPercent(100f)
.alignItems(YogaAlign.CENTER)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.paddingDip(YogaEdge.VERTICAL, 12f)
.child(
RoundIcon.create(context)
.iconRes(option.icon)
.bgColor(titleColor)
.iconColor(titleColor)
.iconSizeRes(R.dimen.toolbar_round_icon_size)
.iconPaddingRes(R.dimen.toolbar_round_icon_padding)
.bgAlpha(15)
.onClick { }
.isClickDisabled(true)
.marginDip(YogaEdge.END, 16f))
.child(
Column.create(context)
.flexGrow(1f)
.child(
Text.create(context)
.textRes(option.title)
.textSizeRes(R.dimen.font_size_normal)
.typeface(sAppTypeface.title())
.textStyle(BOLD)
.textColor(titleColor))
.child(
Text.create(context)
.text(subtitle)
.textSizeRes(R.dimen.font_size_small)
.typeface(sAppTypeface.title())
.textColor(subtitleColor)))
if (option.isSelectable) {
row.child(RoundIcon.create(context)
.iconRes(if (option.actionIcon == 0) R.drawable.ic_done_white_48dp else option.actionIcon)
.bgColor(if (option.selected) selectedColor else titleColor)
.bgAlpha(if (option.selected) 200 else 25)
.iconAlpha(if (option.selected) 1f else 0.6f)
.iconColor(if (option.selected) Color.WHITE else titleColor)
.iconSizeRes(R.dimen.toolbar_round_small_icon_size)
.iconPaddingRes(R.dimen.toolbar_round_small_icon_padding)
.onClick { }
.isClickDisabled(true)
.marginDip(YogaEdge.START, 12f))
} else if (!option.isSelectable && option.actionIcon != 0) {
row.child(RoundIcon.create(context)
.iconRes(option.actionIcon)
.bgColor(titleColor)
.bgAlpha(25)
.iconAlpha(0.9f)
.iconColor(titleColor)
.iconSizeRes(R.dimen.toolbar_round_small_icon_size)
.iconPaddingRes(R.dimen.toolbar_round_small_icon_padding)
.onClick { }
.isClickDisabled(true)
.marginDip(YogaEdge.START, 12f))
}
row.clickHandler(OptionItemLayout.onItemClick(context))
return row.build()
}
@OnEvent(ClickEvent::class)
fun onItemClick(context: ComponentContext, @Prop onClick: () -> Unit) {
onClick()
}
}
class LithoLabelOptionsItem(
val title: Int,
val icon: Int,
val visible: Boolean = true,
val listener: () -> Unit)
@LayoutSpec
object OptionLabelItemLayoutSpec {
@OnCreateLayout
fun onCreate(
context: ComponentContext,
@Prop option: LithoLabelOptionsItem): Component {
val titleColor = sAppTheme.get(ThemeColorType.SECONDARY_TEXT)
val row = Column.create(context)
.widthPercent(100f)
.alignItems(YogaAlign.CENTER)
.paddingDip(YogaEdge.VERTICAL, 16f)
.child(
RoundIcon.create(context)
.iconRes(option.icon)
.bgColor(titleColor)
.iconColor(titleColor)
.iconSizeRes(R.dimen.toolbar_round_icon_size)
.iconPaddingRes(R.dimen.toolbar_round_icon_padding)
.bgAlpha(15)
.onClick { }
.isClickDisabled(true)
.marginDip(YogaEdge.BOTTOM, 4f))
.child(
Text.create(context)
.textRes(option.title)
.textSizeRes(R.dimen.font_size_normal)
.typeface(sAppTypeface.title())
.textStyle(BOLD)
.textColor(titleColor))
row.clickHandler(OptionItemLayout.onItemClick(context))
return row.build()
}
@OnEvent(ClickEvent::class)
fun onItemClick(context: ComponentContext, @Prop onClick: () -> Unit) {
onClick()
}
}
abstract class LithoOptionBottomSheet : LithoBottomSheet() {
abstract fun title(): Int
abstract fun getOptions(componentContext: ComponentContext, dialog: Dialog): List<LithoOptionsItem>
override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component {
val column = Column.create(componentContext)
.widthPercent(100f)
.paddingDip(YogaEdge.VERTICAL, 8f)
.child(getLithoBottomSheetTitle(componentContext).textRes(title()))
getOptions(componentContext, dialog).forEach {
if (it.visible) {
column.child(OptionItemLayout.create(componentContext)
.option(it)
.onClick {
it.listener()
})
}
}
return column.build()
}
}
| gpl-3.0 | 7c8b54f51d6cc06e2fa09cb1a206f296 | 33.462366 | 108 | 0.647582 | 4.200524 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/typeAliases/compoundWithDeprecatedArgumentsAndConstructor.kt | 1 | 592 | // "Replace with 'New<T, U>'" "false"
// ACTION: Compiler warning 'TYPEALIAS_EXPANSION_DEPRECATION' options
// ACTION: Convert to block body
// ACTION: Do not show return expression hints
// ACTION: Introduce import alias
// ACTION: Remove explicit type specification
@Deprecated("Use New", replaceWith = ReplaceWith("New<T, U>"))
class Old<T, U>
@Deprecated("Use New1", replaceWith = ReplaceWith("New1"))
class Old1
@Deprecated("Use New2", replaceWith = ReplaceWith("New2"))
class Old2
typealias OOO = Old<Old1, Old2>
class New<T, U>
class New1
class New2
fun foo(): <caret>OOO? = null | apache-2.0 | 1715ed2b01735aa671ec05cb0010d6d6 | 24.782609 | 69 | 0.721284 | 3.44186 | false | false | false | false |
JetBrains/kotlin-native | Interop/Indexer/prebuilt/nativeInteropStubs/kotlin/clang/clang.kt | 1 | 176176 | @file:JvmName("clang")
@file:Suppress("UNUSED_VARIABLE", "UNUSED_EXPRESSION", "DEPRECATION")
package clang
import kotlinx.cinterop.*
// NOTE THIS FILE IS AUTO-GENERATED
@CNaturalStruct("data", "private_flags")
class CXString(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var data: COpaquePointer?
get() = memberAt<COpaquePointerVar>(0).value
set(value) { memberAt<COpaquePointerVar>(0).value = value }
var private_flags: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
}
@CNaturalStruct("Strings", "Count")
class CXStringSet(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var Strings: CPointer<CXString>?
get() = memberAt<CPointerVar<CXString>>(0).value
set(value) { memberAt<CPointerVar<CXString>>(0).value = value }
var Count: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
}
class CXVirtualFileOverlayImpl(rawPtr: NativePtr) : COpaque(rawPtr)
class CXModuleMapDescriptorImpl(rawPtr: NativePtr) : COpaque(rawPtr)
class CXTargetInfoImpl(rawPtr: NativePtr) : COpaque(rawPtr)
class CXTranslationUnitImpl(rawPtr: NativePtr) : COpaque(rawPtr)
@CNaturalStruct("Filename", "Contents", "Length")
class CXUnsavedFile(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var Filename: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(0).value
set(value) { memberAt<CPointerVar<ByteVar>>(0).value = value }
var Contents: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(8).value
set(value) { memberAt<CPointerVar<ByteVar>>(8).value = value }
var Length: Long
get() = memberAt<LongVar>(16).value
set(value) { memberAt<LongVar>(16).value = value }
}
@CNaturalStruct("Major", "Minor", "Subminor")
class CXVersion(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(12, 4)
var Major: Int
get() = memberAt<IntVar>(0).value
set(value) { memberAt<IntVar>(0).value = value }
var Minor: Int
get() = memberAt<IntVar>(4).value
set(value) { memberAt<IntVar>(4).value = value }
var Subminor: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
}
@CNaturalStruct("data")
class CXFileUniqueID(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
@CLength(3)
val data: CArrayPointer<LongVar>
get() = arrayMemberAt(0)
}
@CNaturalStruct("ptr_data", "int_data")
class CXSourceLocation(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
@CLength(2)
val ptr_data: CArrayPointer<COpaquePointerVar>
get() = arrayMemberAt(0)
var int_data: Int
get() = memberAt<IntVar>(16).value
set(value) { memberAt<IntVar>(16).value = value }
}
@CNaturalStruct("ptr_data", "begin_int_data", "end_int_data")
class CXSourceRange(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
@CLength(2)
val ptr_data: CArrayPointer<COpaquePointerVar>
get() = arrayMemberAt(0)
var begin_int_data: Int
get() = memberAt<IntVar>(16).value
set(value) { memberAt<IntVar>(16).value = value }
var end_int_data: Int
get() = memberAt<IntVar>(20).value
set(value) { memberAt<IntVar>(20).value = value }
}
@CNaturalStruct("count", "ranges")
class CXSourceRangeList(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var count: Int
get() = memberAt<IntVar>(0).value
set(value) { memberAt<IntVar>(0).value = value }
var ranges: CPointer<CXSourceRange>?
get() = memberAt<CPointerVar<CXSourceRange>>(8).value
set(value) { memberAt<CPointerVar<CXSourceRange>>(8).value = value }
}
@CNaturalStruct("kind", "amount")
class CXTUResourceUsageEntry(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var kind: CXTUResourceUsageKind
get() = memberAt<CXTUResourceUsageKind.Var>(0).value
set(value) { memberAt<CXTUResourceUsageKind.Var>(0).value = value }
var amount: Long
get() = memberAt<LongVar>(8).value
set(value) { memberAt<LongVar>(8).value = value }
}
@CNaturalStruct("data", "numEntries", "entries")
class CXTUResourceUsage(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var data: COpaquePointer?
get() = memberAt<COpaquePointerVar>(0).value
set(value) { memberAt<COpaquePointerVar>(0).value = value }
var numEntries: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
var entries: CPointer<CXTUResourceUsageEntry>?
get() = memberAt<CPointerVar<CXTUResourceUsageEntry>>(16).value
set(value) { memberAt<CPointerVar<CXTUResourceUsageEntry>>(16).value = value }
}
@CNaturalStruct("kind", "xdata", "data")
class CXCursor(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(32, 8)
var kind: CXCursorKind
get() = memberAt<CXCursorKind.Var>(0).value
set(value) { memberAt<CXCursorKind.Var>(0).value = value }
var xdata: Int
get() = memberAt<IntVar>(4).value
set(value) { memberAt<IntVar>(4).value = value }
@CLength(3)
val data: CArrayPointer<COpaquePointerVar>
get() = arrayMemberAt(8)
}
@CNaturalStruct("Platform", "Introduced", "Deprecated", "Obsoleted", "Unavailable", "Message")
class CXPlatformAvailability(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(72, 8)
val Platform: CXString
get() = memberAt(0)
val Introduced: CXVersion
get() = memberAt(16)
val Deprecated: CXVersion
get() = memberAt(28)
val Obsoleted: CXVersion
get() = memberAt(40)
var Unavailable: Int
get() = memberAt<IntVar>(52).value
set(value) { memberAt<IntVar>(52).value = value }
val Message: CXString
get() = memberAt(56)
}
class CXCursorSetImpl(rawPtr: NativePtr) : COpaque(rawPtr)
@CNaturalStruct("kind", "data")
class CXType(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var kind: CXTypeKind
get() = memberAt<CXTypeKind.Var>(0).value
set(value) { memberAt<CXTypeKind.Var>(0).value = value }
@CLength(2)
val data: CArrayPointer<COpaquePointerVar>
get() = arrayMemberAt(8)
}
@CNaturalStruct("int_data", "ptr_data")
class CXToken(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
@CLength(4)
val int_data: CArrayPointer<IntVar>
get() = arrayMemberAt(0)
var ptr_data: COpaquePointer?
get() = memberAt<COpaquePointerVar>(16).value
set(value) { memberAt<COpaquePointerVar>(16).value = value }
}
@CNaturalStruct("CursorKind", "CompletionString")
class CXCompletionResult(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var CursorKind: CXCursorKind
get() = memberAt<CXCursorKind.Var>(0).value
set(value) { memberAt<CXCursorKind.Var>(0).value = value }
var CompletionString: CXCompletionString?
get() = memberAt<CXCompletionStringVar>(8).value
set(value) { memberAt<CXCompletionStringVar>(8).value = value }
}
@CNaturalStruct("Results", "NumResults")
class CXCodeCompleteResults(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var Results: CPointer<CXCompletionResult>?
get() = memberAt<CPointerVar<CXCompletionResult>>(0).value
set(value) { memberAt<CPointerVar<CXCompletionResult>>(0).value = value }
var NumResults: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
}
@CNaturalStruct("context", "visit")
class CXCursorAndRangeVisitor(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var context: COpaquePointer?
get() = memberAt<COpaquePointerVar>(0).value
set(value) { memberAt<COpaquePointerVar>(0).value = value }
var visit: CPointer<CFunction<(COpaquePointer?, CValue<CXCursor>, CValue<CXSourceRange>) -> CXVisitorResult>>?
get() = memberAt<CPointerVar<CFunction<(COpaquePointer?, CValue<CXCursor>, CValue<CXSourceRange>) -> CXVisitorResult>>>(8).value
set(value) { memberAt<CPointerVar<CFunction<(COpaquePointer?, CValue<CXCursor>, CValue<CXSourceRange>) -> CXVisitorResult>>>(8).value = value }
}
@CNaturalStruct("ptr_data", "int_data")
class CXIdxLoc(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
@CLength(2)
val ptr_data: CArrayPointer<COpaquePointerVar>
get() = arrayMemberAt(0)
var int_data: Int
get() = memberAt<IntVar>(16).value
set(value) { memberAt<IntVar>(16).value = value }
}
@CNaturalStruct("hashLoc", "filename", "file", "isImport", "isAngled", "isModuleImport")
class CXIdxIncludedFileInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(56, 8)
val hashLoc: CXIdxLoc
get() = memberAt(0)
var filename: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(24).value
set(value) { memberAt<CPointerVar<ByteVar>>(24).value = value }
var file: CXFile?
get() = memberAt<CXFileVar>(32).value
set(value) { memberAt<CXFileVar>(32).value = value }
var isImport: Int
get() = memberAt<IntVar>(40).value
set(value) { memberAt<IntVar>(40).value = value }
var isAngled: Int
get() = memberAt<IntVar>(44).value
set(value) { memberAt<IntVar>(44).value = value }
var isModuleImport: Int
get() = memberAt<IntVar>(48).value
set(value) { memberAt<IntVar>(48).value = value }
}
@CNaturalStruct("file", "module", "loc", "isImplicit")
class CXIdxImportedASTFileInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(48, 8)
var file: CXFile?
get() = memberAt<CXFileVar>(0).value
set(value) { memberAt<CXFileVar>(0).value = value }
var module: CXModule?
get() = memberAt<CXModuleVar>(8).value
set(value) { memberAt<CXModuleVar>(8).value = value }
val loc: CXIdxLoc
get() = memberAt(16)
var isImplicit: Int
get() = memberAt<IntVar>(40).value
set(value) { memberAt<IntVar>(40).value = value }
}
@CNaturalStruct("kind", "cursor", "loc")
class CXIdxAttrInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(64, 8)
var kind: CXIdxAttrKind
get() = memberAt<CXIdxAttrKindVar>(0).value
set(value) { memberAt<CXIdxAttrKindVar>(0).value = value }
val cursor: CXCursor
get() = memberAt(8)
val loc: CXIdxLoc
get() = memberAt(40)
}
@CNaturalStruct("kind", "templateKind", "lang", "name", "USR", "cursor", "attributes", "numAttributes")
class CXIdxEntityInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(80, 8)
var kind: CXIdxEntityKind
get() = memberAt<CXIdxEntityKind.Var>(0).value
set(value) { memberAt<CXIdxEntityKind.Var>(0).value = value }
var templateKind: CXIdxEntityCXXTemplateKind
get() = memberAt<CXIdxEntityCXXTemplateKindVar>(4).value
set(value) { memberAt<CXIdxEntityCXXTemplateKindVar>(4).value = value }
var lang: CXIdxEntityLanguage
get() = memberAt<CXIdxEntityLanguageVar>(8).value
set(value) { memberAt<CXIdxEntityLanguageVar>(8).value = value }
var name: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(16).value
set(value) { memberAt<CPointerVar<ByteVar>>(16).value = value }
var USR: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(24).value
set(value) { memberAt<CPointerVar<ByteVar>>(24).value = value }
val cursor: CXCursor
get() = memberAt(32)
var attributes: CPointer<CPointerVar<CXIdxAttrInfo>>?
get() = memberAt<CPointerVar<CPointerVar<CXIdxAttrInfo>>>(64).value
set(value) { memberAt<CPointerVar<CPointerVar<CXIdxAttrInfo>>>(64).value = value }
var numAttributes: Int
get() = memberAt<IntVar>(72).value
set(value) { memberAt<IntVar>(72).value = value }
}
@CNaturalStruct("cursor")
class CXIdxContainerInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(32, 8)
val cursor: CXCursor
get() = memberAt(0)
}
@CNaturalStruct("attrInfo", "objcClass", "classCursor", "classLoc")
class CXIdxIBOutletCollectionAttrInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(72, 8)
var attrInfo: CPointer<CXIdxAttrInfo>?
get() = memberAt<CPointerVar<CXIdxAttrInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxAttrInfo>>(0).value = value }
var objcClass: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(8).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(8).value = value }
val classCursor: CXCursor
get() = memberAt(16)
val classLoc: CXIdxLoc
get() = memberAt(48)
}
@CNaturalStruct("entityInfo", "cursor", "loc", "semanticContainer", "lexicalContainer", "isRedeclaration", "isDefinition", "isContainer", "declAsContainer", "isImplicit", "attributes", "numAttributes", "flags")
class CXIdxDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(128, 8)
var entityInfo: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(0).value = value }
val cursor: CXCursor
get() = memberAt(8)
val loc: CXIdxLoc
get() = memberAt(40)
var semanticContainer: CPointer<CXIdxContainerInfo>?
get() = memberAt<CPointerVar<CXIdxContainerInfo>>(64).value
set(value) { memberAt<CPointerVar<CXIdxContainerInfo>>(64).value = value }
var lexicalContainer: CPointer<CXIdxContainerInfo>?
get() = memberAt<CPointerVar<CXIdxContainerInfo>>(72).value
set(value) { memberAt<CPointerVar<CXIdxContainerInfo>>(72).value = value }
var isRedeclaration: Int
get() = memberAt<IntVar>(80).value
set(value) { memberAt<IntVar>(80).value = value }
var isDefinition: Int
get() = memberAt<IntVar>(84).value
set(value) { memberAt<IntVar>(84).value = value }
var isContainer: Int
get() = memberAt<IntVar>(88).value
set(value) { memberAt<IntVar>(88).value = value }
var declAsContainer: CPointer<CXIdxContainerInfo>?
get() = memberAt<CPointerVar<CXIdxContainerInfo>>(96).value
set(value) { memberAt<CPointerVar<CXIdxContainerInfo>>(96).value = value }
var isImplicit: Int
get() = memberAt<IntVar>(104).value
set(value) { memberAt<IntVar>(104).value = value }
var attributes: CPointer<CPointerVar<CXIdxAttrInfo>>?
get() = memberAt<CPointerVar<CPointerVar<CXIdxAttrInfo>>>(112).value
set(value) { memberAt<CPointerVar<CPointerVar<CXIdxAttrInfo>>>(112).value = value }
var numAttributes: Int
get() = memberAt<IntVar>(120).value
set(value) { memberAt<IntVar>(120).value = value }
var flags: Int
get() = memberAt<IntVar>(124).value
set(value) { memberAt<IntVar>(124).value = value }
}
@CNaturalStruct("declInfo", "kind")
class CXIdxObjCContainerDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var declInfo: CPointer<CXIdxDeclInfo>?
get() = memberAt<CPointerVar<CXIdxDeclInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxDeclInfo>>(0).value = value }
var kind: CXIdxObjCContainerKind
get() = memberAt<CXIdxObjCContainerKindVar>(8).value
set(value) { memberAt<CXIdxObjCContainerKindVar>(8).value = value }
}
@CNaturalStruct("base", "cursor", "loc")
class CXIdxBaseClassInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(64, 8)
var base: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(0).value = value }
val cursor: CXCursor
get() = memberAt(8)
val loc: CXIdxLoc
get() = memberAt(40)
}
@CNaturalStruct("protocol", "cursor", "loc")
class CXIdxObjCProtocolRefInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(64, 8)
var protocol: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(0).value = value }
val cursor: CXCursor
get() = memberAt(8)
val loc: CXIdxLoc
get() = memberAt(40)
}
@CNaturalStruct("protocols", "numProtocols")
class CXIdxObjCProtocolRefListInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(16, 8)
var protocols: CPointer<CPointerVar<CXIdxObjCProtocolRefInfo>>?
get() = memberAt<CPointerVar<CPointerVar<CXIdxObjCProtocolRefInfo>>>(0).value
set(value) { memberAt<CPointerVar<CPointerVar<CXIdxObjCProtocolRefInfo>>>(0).value = value }
var numProtocols: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
}
@CNaturalStruct("containerInfo", "superInfo", "protocols")
class CXIdxObjCInterfaceDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var containerInfo: CPointer<CXIdxObjCContainerDeclInfo>?
get() = memberAt<CPointerVar<CXIdxObjCContainerDeclInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxObjCContainerDeclInfo>>(0).value = value }
var superInfo: CPointer<CXIdxBaseClassInfo>?
get() = memberAt<CPointerVar<CXIdxBaseClassInfo>>(8).value
set(value) { memberAt<CPointerVar<CXIdxBaseClassInfo>>(8).value = value }
var protocols: CPointer<CXIdxObjCProtocolRefListInfo>?
get() = memberAt<CPointerVar<CXIdxObjCProtocolRefListInfo>>(16).value
set(value) { memberAt<CPointerVar<CXIdxObjCProtocolRefListInfo>>(16).value = value }
}
@CNaturalStruct("containerInfo", "objcClass", "classCursor", "classLoc", "protocols")
class CXIdxObjCCategoryDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(80, 8)
var containerInfo: CPointer<CXIdxObjCContainerDeclInfo>?
get() = memberAt<CPointerVar<CXIdxObjCContainerDeclInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxObjCContainerDeclInfo>>(0).value = value }
var objcClass: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(8).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(8).value = value }
val classCursor: CXCursor
get() = memberAt(16)
val classLoc: CXIdxLoc
get() = memberAt(48)
var protocols: CPointer<CXIdxObjCProtocolRefListInfo>?
get() = memberAt<CPointerVar<CXIdxObjCProtocolRefListInfo>>(72).value
set(value) { memberAt<CPointerVar<CXIdxObjCProtocolRefListInfo>>(72).value = value }
}
@CNaturalStruct("declInfo", "getter", "setter")
class CXIdxObjCPropertyDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var declInfo: CPointer<CXIdxDeclInfo>?
get() = memberAt<CPointerVar<CXIdxDeclInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxDeclInfo>>(0).value = value }
var getter: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(8).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(8).value = value }
var setter: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(16).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(16).value = value }
}
@CNaturalStruct("declInfo", "bases", "numBases")
class CXIdxCXXClassDeclInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(24, 8)
var declInfo: CPointer<CXIdxDeclInfo>?
get() = memberAt<CPointerVar<CXIdxDeclInfo>>(0).value
set(value) { memberAt<CPointerVar<CXIdxDeclInfo>>(0).value = value }
var bases: CPointer<CPointerVar<CXIdxBaseClassInfo>>?
get() = memberAt<CPointerVar<CPointerVar<CXIdxBaseClassInfo>>>(8).value
set(value) { memberAt<CPointerVar<CPointerVar<CXIdxBaseClassInfo>>>(8).value = value }
var numBases: Int
get() = memberAt<IntVar>(16).value
set(value) { memberAt<IntVar>(16).value = value }
}
@CNaturalStruct("kind", "cursor", "loc", "referencedEntity", "parentEntity", "container", "role")
class CXIdxEntityRefInfo(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(96, 8)
var kind: CXIdxEntityRefKind
get() = memberAt<CXIdxEntityRefKindVar>(0).value
set(value) { memberAt<CXIdxEntityRefKindVar>(0).value = value }
val cursor: CXCursor
get() = memberAt(8)
val loc: CXIdxLoc
get() = memberAt(40)
var referencedEntity: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(64).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(64).value = value }
var parentEntity: CPointer<CXIdxEntityInfo>?
get() = memberAt<CPointerVar<CXIdxEntityInfo>>(72).value
set(value) { memberAt<CPointerVar<CXIdxEntityInfo>>(72).value = value }
var container: CPointer<CXIdxContainerInfo>?
get() = memberAt<CPointerVar<CXIdxContainerInfo>>(80).value
set(value) { memberAt<CPointerVar<CXIdxContainerInfo>>(80).value = value }
var role: CXSymbolRole
get() = memberAt<CXSymbolRoleVar>(88).value
set(value) { memberAt<CXSymbolRoleVar>(88).value = value }
}
@CNaturalStruct("abortQuery", "diagnostic", "enteredMainFile", "ppIncludedFile", "importedASTFile", "startedTranslationUnit", "indexDeclaration", "indexEntityReference")
class IndexerCallbacks(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(64, 8)
var abortQuery: CPointer<CFunction<(CXClientData?, COpaquePointer?) -> Int>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, COpaquePointer?) -> Int>>>(0).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, COpaquePointer?) -> Int>>>(0).value = value }
var diagnostic: CPointer<CFunction<(CXClientData?, CXDiagnosticSet?, COpaquePointer?) -> Unit>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CXDiagnosticSet?, COpaquePointer?) -> Unit>>>(8).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CXDiagnosticSet?, COpaquePointer?) -> Unit>>>(8).value = value }
var enteredMainFile: CPointer<CFunction<(CXClientData?, CXFile?, COpaquePointer?) -> CXIdxClientFile?>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CXFile?, COpaquePointer?) -> CXIdxClientFile?>>>(16).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CXFile?, COpaquePointer?) -> CXIdxClientFile?>>>(16).value = value }
var ppIncludedFile: CPointer<CFunction<(CXClientData?, CPointer<CXIdxIncludedFileInfo>?) -> CXIdxClientFile?>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxIncludedFileInfo>?) -> CXIdxClientFile?>>>(24).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxIncludedFileInfo>?) -> CXIdxClientFile?>>>(24).value = value }
var importedASTFile: CPointer<CFunction<(CXClientData?, CPointer<CXIdxImportedASTFileInfo>?) -> CXIdxClientASTFile?>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxImportedASTFileInfo>?) -> CXIdxClientASTFile?>>>(32).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxImportedASTFileInfo>?) -> CXIdxClientASTFile?>>>(32).value = value }
var startedTranslationUnit: CPointer<CFunction<(CXClientData?, COpaquePointer?) -> CXIdxClientContainer?>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, COpaquePointer?) -> CXIdxClientContainer?>>>(40).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, COpaquePointer?) -> CXIdxClientContainer?>>>(40).value = value }
var indexDeclaration: CPointer<CFunction<(CXClientData?, CPointer<CXIdxDeclInfo>?) -> Unit>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxDeclInfo>?) -> Unit>>>(48).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxDeclInfo>?) -> Unit>>>(48).value = value }
var indexEntityReference: CPointer<CFunction<(CXClientData?, CPointer<CXIdxEntityRefInfo>?) -> Unit>>?
get() = memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxEntityRefInfo>?) -> Unit>>>(56).value
set(value) { memberAt<CPointerVar<CFunction<(CXClientData?, CPointer<CXIdxEntityRefInfo>?) -> Unit>>>(56).value = value }
}
@CNaturalStruct("typeOpaquePtr")
class CXTypeAttributes(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : CStructVar.Type(8, 8)
var typeOpaquePtr: COpaquePointer?
get() = memberAt<COpaquePointerVar>(0).value
set(value) { memberAt<COpaquePointerVar>(0).value = value }
}
enum class CXErrorCode(override val value: Int) : CEnum {
CXError_Success(0),
CXError_Failure(1),
CXError_Crashed(2),
CXError_InvalidArguments(3),
CXError_ASTReadError(4),
CXError_RefactoringActionUnavailable(5),
CXError_RefactoringNameSizeMismatch(6),
CXError_RefactoringNameInvalid(7),
;
companion object {
fun byValue(value: Int) = CXErrorCode.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXErrorCode
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXAvailabilityKind(override val value: Int) : CEnum {
CXAvailability_Available(0),
CXAvailability_Deprecated(1),
CXAvailability_NotAvailable(2),
CXAvailability_NotAccessible(3),
;
companion object {
fun byValue(value: Int) = CXAvailabilityKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXAvailabilityKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXCursor_ExceptionSpecificationKind(override val value: Int) : CEnum {
CXCursor_ExceptionSpecificationKind_None(0),
CXCursor_ExceptionSpecificationKind_DynamicNone(1),
CXCursor_ExceptionSpecificationKind_Dynamic(2),
CXCursor_ExceptionSpecificationKind_MSAny(3),
CXCursor_ExceptionSpecificationKind_BasicNoexcept(4),
CXCursor_ExceptionSpecificationKind_ComputedNoexcept(5),
CXCursor_ExceptionSpecificationKind_Unevaluated(6),
CXCursor_ExceptionSpecificationKind_Uninstantiated(7),
CXCursor_ExceptionSpecificationKind_Unparsed(8),
;
companion object {
fun byValue(value: Int) = CXCursor_ExceptionSpecificationKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXCursor_ExceptionSpecificationKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXDiagnosticSeverity(override val value: Int) : CEnum {
CXDiagnostic_Ignored(0),
CXDiagnostic_Note(1),
CXDiagnostic_Warning(2),
CXDiagnostic_Error(3),
CXDiagnostic_Fatal(4),
;
companion object {
fun byValue(value: Int) = CXDiagnosticSeverity.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXDiagnosticSeverity
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXLoadDiag_Error(override val value: Int) : CEnum {
CXLoadDiag_None(0),
CXLoadDiag_Unknown(1),
CXLoadDiag_CannotLoad(2),
CXLoadDiag_InvalidFile(3),
;
companion object {
fun byValue(value: Int) = CXLoadDiag_Error.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXLoadDiag_Error
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXSaveError(override val value: Int) : CEnum {
CXSaveError_None(0),
CXSaveError_Unknown(1),
CXSaveError_TranslationErrors(2),
CXSaveError_InvalidTU(3),
;
companion object {
fun byValue(value: Int) = CXSaveError.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXSaveError
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXTUResourceUsageKind(override val value: Int) : CEnum {
CXTUResourceUsage_AST(1),
CXTUResourceUsage_Identifiers(2),
CXTUResourceUsage_Selectors(3),
CXTUResourceUsage_GlobalCompletionResults(4),
CXTUResourceUsage_SourceManagerContentCache(5),
CXTUResourceUsage_AST_SideTables(6),
CXTUResourceUsage_SourceManager_Membuffer_Malloc(7),
CXTUResourceUsage_SourceManager_Membuffer_MMap(8),
CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc(9),
CXTUResourceUsage_ExternalASTSource_Membuffer_MMap(10),
CXTUResourceUsage_Preprocessor(11),
CXTUResourceUsage_PreprocessingRecord(12),
CXTUResourceUsage_SourceManager_DataStructures(13),
CXTUResourceUsage_Preprocessor_HeaderSearch(14),
;
companion object {
val CXTUResourceUsage_MEMORY_IN_BYTES_BEGIN = CXTUResourceUsage_AST
val CXTUResourceUsage_First = CXTUResourceUsage_AST
val CXTUResourceUsage_MEMORY_IN_BYTES_END = CXTUResourceUsage_Preprocessor_HeaderSearch
val CXTUResourceUsage_Last = CXTUResourceUsage_Preprocessor_HeaderSearch
fun byValue(value: Int) = CXTUResourceUsageKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXTUResourceUsageKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXCursorKind(override val value: Int) : CEnum {
CXCursor_UnexposedDecl(1),
CXCursor_StructDecl(2),
CXCursor_UnionDecl(3),
CXCursor_ClassDecl(4),
CXCursor_EnumDecl(5),
CXCursor_FieldDecl(6),
CXCursor_EnumConstantDecl(7),
CXCursor_FunctionDecl(8),
CXCursor_VarDecl(9),
CXCursor_ParmDecl(10),
CXCursor_ObjCInterfaceDecl(11),
CXCursor_ObjCCategoryDecl(12),
CXCursor_ObjCProtocolDecl(13),
CXCursor_ObjCPropertyDecl(14),
CXCursor_ObjCIvarDecl(15),
CXCursor_ObjCInstanceMethodDecl(16),
CXCursor_ObjCClassMethodDecl(17),
CXCursor_ObjCImplementationDecl(18),
CXCursor_ObjCCategoryImplDecl(19),
CXCursor_TypedefDecl(20),
CXCursor_CXXMethod(21),
CXCursor_Namespace(22),
CXCursor_LinkageSpec(23),
CXCursor_Constructor(24),
CXCursor_Destructor(25),
CXCursor_ConversionFunction(26),
CXCursor_TemplateTypeParameter(27),
CXCursor_NonTypeTemplateParameter(28),
CXCursor_TemplateTemplateParameter(29),
CXCursor_FunctionTemplate(30),
CXCursor_ClassTemplate(31),
CXCursor_ClassTemplatePartialSpecialization(32),
CXCursor_NamespaceAlias(33),
CXCursor_UsingDirective(34),
CXCursor_UsingDeclaration(35),
CXCursor_TypeAliasDecl(36),
CXCursor_ObjCSynthesizeDecl(37),
CXCursor_ObjCDynamicDecl(38),
CXCursor_CXXAccessSpecifier(39),
CXCursor_ObjCSuperClassRef(40),
CXCursor_ObjCProtocolRef(41),
CXCursor_ObjCClassRef(42),
CXCursor_TypeRef(43),
CXCursor_CXXBaseSpecifier(44),
CXCursor_TemplateRef(45),
CXCursor_NamespaceRef(46),
CXCursor_MemberRef(47),
CXCursor_LabelRef(48),
CXCursor_OverloadedDeclRef(49),
CXCursor_VariableRef(50),
CXCursor_InvalidFile(70),
CXCursor_NoDeclFound(71),
CXCursor_NotImplemented(72),
CXCursor_InvalidCode(73),
CXCursor_UnexposedExpr(100),
CXCursor_DeclRefExpr(101),
CXCursor_MemberRefExpr(102),
CXCursor_CallExpr(103),
CXCursor_ObjCMessageExpr(104),
CXCursor_BlockExpr(105),
CXCursor_IntegerLiteral(106),
CXCursor_FloatingLiteral(107),
CXCursor_ImaginaryLiteral(108),
CXCursor_StringLiteral(109),
CXCursor_CharacterLiteral(110),
CXCursor_ParenExpr(111),
CXCursor_UnaryOperator(112),
CXCursor_ArraySubscriptExpr(113),
CXCursor_BinaryOperator(114),
CXCursor_CompoundAssignOperator(115),
CXCursor_ConditionalOperator(116),
CXCursor_CStyleCastExpr(117),
CXCursor_CompoundLiteralExpr(118),
CXCursor_InitListExpr(119),
CXCursor_AddrLabelExpr(120),
CXCursor_StmtExpr(121),
CXCursor_GenericSelectionExpr(122),
CXCursor_GNUNullExpr(123),
CXCursor_CXXStaticCastExpr(124),
CXCursor_CXXDynamicCastExpr(125),
CXCursor_CXXReinterpretCastExpr(126),
CXCursor_CXXConstCastExpr(127),
CXCursor_CXXFunctionalCastExpr(128),
CXCursor_CXXTypeidExpr(129),
CXCursor_CXXBoolLiteralExpr(130),
CXCursor_CXXNullPtrLiteralExpr(131),
CXCursor_CXXThisExpr(132),
CXCursor_CXXThrowExpr(133),
CXCursor_CXXNewExpr(134),
CXCursor_CXXDeleteExpr(135),
CXCursor_UnaryExpr(136),
CXCursor_ObjCStringLiteral(137),
CXCursor_ObjCEncodeExpr(138),
CXCursor_ObjCSelectorExpr(139),
CXCursor_ObjCProtocolExpr(140),
CXCursor_ObjCBridgedCastExpr(141),
CXCursor_PackExpansionExpr(142),
CXCursor_SizeOfPackExpr(143),
CXCursor_LambdaExpr(144),
CXCursor_ObjCBoolLiteralExpr(145),
CXCursor_ObjCSelfExpr(146),
CXCursor_OMPArraySectionExpr(147),
CXCursor_ObjCAvailabilityCheckExpr(148),
CXCursor_FixedPointLiteral(149),
CXCursor_UnexposedStmt(200),
CXCursor_LabelStmt(201),
CXCursor_CompoundStmt(202),
CXCursor_CaseStmt(203),
CXCursor_DefaultStmt(204),
CXCursor_IfStmt(205),
CXCursor_SwitchStmt(206),
CXCursor_WhileStmt(207),
CXCursor_DoStmt(208),
CXCursor_ForStmt(209),
CXCursor_GotoStmt(210),
CXCursor_IndirectGotoStmt(211),
CXCursor_ContinueStmt(212),
CXCursor_BreakStmt(213),
CXCursor_ReturnStmt(214),
CXCursor_GCCAsmStmt(215),
CXCursor_ObjCAtTryStmt(216),
CXCursor_ObjCAtCatchStmt(217),
CXCursor_ObjCAtFinallyStmt(218),
CXCursor_ObjCAtThrowStmt(219),
CXCursor_ObjCAtSynchronizedStmt(220),
CXCursor_ObjCAutoreleasePoolStmt(221),
CXCursor_ObjCForCollectionStmt(222),
CXCursor_CXXCatchStmt(223),
CXCursor_CXXTryStmt(224),
CXCursor_CXXForRangeStmt(225),
CXCursor_SEHTryStmt(226),
CXCursor_SEHExceptStmt(227),
CXCursor_SEHFinallyStmt(228),
CXCursor_MSAsmStmt(229),
CXCursor_NullStmt(230),
CXCursor_DeclStmt(231),
CXCursor_OMPParallelDirective(232),
CXCursor_OMPSimdDirective(233),
CXCursor_OMPForDirective(234),
CXCursor_OMPSectionsDirective(235),
CXCursor_OMPSectionDirective(236),
CXCursor_OMPSingleDirective(237),
CXCursor_OMPParallelForDirective(238),
CXCursor_OMPParallelSectionsDirective(239),
CXCursor_OMPTaskDirective(240),
CXCursor_OMPMasterDirective(241),
CXCursor_OMPCriticalDirective(242),
CXCursor_OMPTaskyieldDirective(243),
CXCursor_OMPBarrierDirective(244),
CXCursor_OMPTaskwaitDirective(245),
CXCursor_OMPFlushDirective(246),
CXCursor_SEHLeaveStmt(247),
CXCursor_OMPOrderedDirective(248),
CXCursor_OMPAtomicDirective(249),
CXCursor_OMPForSimdDirective(250),
CXCursor_OMPParallelForSimdDirective(251),
CXCursor_OMPTargetDirective(252),
CXCursor_OMPTeamsDirective(253),
CXCursor_OMPTaskgroupDirective(254),
CXCursor_OMPCancellationPointDirective(255),
CXCursor_OMPCancelDirective(256),
CXCursor_OMPTargetDataDirective(257),
CXCursor_OMPTaskLoopDirective(258),
CXCursor_OMPTaskLoopSimdDirective(259),
CXCursor_OMPDistributeDirective(260),
CXCursor_OMPTargetEnterDataDirective(261),
CXCursor_OMPTargetExitDataDirective(262),
CXCursor_OMPTargetParallelDirective(263),
CXCursor_OMPTargetParallelForDirective(264),
CXCursor_OMPTargetUpdateDirective(265),
CXCursor_OMPDistributeParallelForDirective(266),
CXCursor_OMPDistributeParallelForSimdDirective(267),
CXCursor_OMPDistributeSimdDirective(268),
CXCursor_OMPTargetParallelForSimdDirective(269),
CXCursor_OMPTargetSimdDirective(270),
CXCursor_OMPTeamsDistributeDirective(271),
CXCursor_OMPTeamsDistributeSimdDirective(272),
CXCursor_OMPTeamsDistributeParallelForSimdDirective(273),
CXCursor_OMPTeamsDistributeParallelForDirective(274),
CXCursor_OMPTargetTeamsDirective(275),
CXCursor_OMPTargetTeamsDistributeDirective(276),
CXCursor_OMPTargetTeamsDistributeParallelForDirective(277),
CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective(278),
CXCursor_OMPTargetTeamsDistributeSimdDirective(279),
CXCursor_TranslationUnit(300),
CXCursor_UnexposedAttr(400),
CXCursor_IBActionAttr(401),
CXCursor_IBOutletAttr(402),
CXCursor_IBOutletCollectionAttr(403),
CXCursor_CXXFinalAttr(404),
CXCursor_CXXOverrideAttr(405),
CXCursor_AnnotateAttr(406),
CXCursor_AsmLabelAttr(407),
CXCursor_PackedAttr(408),
CXCursor_PureAttr(409),
CXCursor_ConstAttr(410),
CXCursor_NoDuplicateAttr(411),
CXCursor_CUDAConstantAttr(412),
CXCursor_CUDADeviceAttr(413),
CXCursor_CUDAGlobalAttr(414),
CXCursor_CUDAHostAttr(415),
CXCursor_CUDASharedAttr(416),
CXCursor_VisibilityAttr(417),
CXCursor_DLLExport(418),
CXCursor_DLLImport(419),
CXCursor_NSReturnsRetained(420),
CXCursor_NSReturnsNotRetained(421),
CXCursor_NSReturnsAutoreleased(422),
CXCursor_NSConsumesSelf(423),
CXCursor_NSConsumed(424),
CXCursor_ObjCException(425),
CXCursor_ObjCNSObject(426),
CXCursor_ObjCIndependentClass(427),
CXCursor_ObjCPreciseLifetime(428),
CXCursor_ObjCReturnsInnerPointer(429),
CXCursor_ObjCRequiresSuper(430),
CXCursor_ObjCRootClass(431),
CXCursor_ObjCSubclassingRestricted(432),
CXCursor_ObjCExplicitProtocolImpl(433),
CXCursor_ObjCDesignatedInitializer(434),
CXCursor_ObjCRuntimeVisible(435),
CXCursor_ObjCBoxable(436),
CXCursor_FlagEnum(437),
CXCursor_PreprocessingDirective(500),
CXCursor_MacroDefinition(501),
CXCursor_MacroExpansion(502),
CXCursor_InclusionDirective(503),
CXCursor_ModuleImportDecl(600),
CXCursor_TypeAliasTemplateDecl(601),
CXCursor_StaticAssert(602),
CXCursor_LastExtraDecl(603),
CXCursor_OverloadCandidate(700),
;
companion object {
val CXCursor_FirstDecl = CXCursor_UnexposedDecl
val CXCursor_LastDecl = CXCursor_CXXAccessSpecifier
val CXCursor_FirstRef = CXCursor_ObjCSuperClassRef
val CXCursor_LastRef = CXCursor_VariableRef
val CXCursor_FirstInvalid = CXCursor_InvalidFile
val CXCursor_LastInvalid = CXCursor_InvalidCode
val CXCursor_FirstExpr = CXCursor_UnexposedExpr
val CXCursor_LastExpr = CXCursor_FixedPointLiteral
val CXCursor_FirstStmt = CXCursor_UnexposedStmt
val CXCursor_AsmStmt = CXCursor_GCCAsmStmt
val CXCursor_LastStmt = CXCursor_OMPTargetTeamsDistributeSimdDirective
val CXCursor_FirstAttr = CXCursor_UnexposedAttr
val CXCursor_LastAttr = CXCursor_FlagEnum
val CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective
val CXCursor_MacroInstantiation = CXCursor_MacroExpansion
val CXCursor_LastPreprocessing = CXCursor_InclusionDirective
val CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl
val CXCursor_FriendDecl = CXCursor_LastExtraDecl
fun byValue(value: Int) = CXCursorKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXCursorKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXLinkageKind(override val value: Int) : CEnum {
CXLinkage_Invalid(0),
CXLinkage_NoLinkage(1),
CXLinkage_Internal(2),
CXLinkage_UniqueExternal(3),
CXLinkage_External(4),
;
companion object {
fun byValue(value: Int) = CXLinkageKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXLinkageKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXVisibilityKind(override val value: Int) : CEnum {
CXVisibility_Invalid(0),
CXVisibility_Hidden(1),
CXVisibility_Protected(2),
CXVisibility_Default(3),
;
companion object {
fun byValue(value: Int) = CXVisibilityKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXVisibilityKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXLanguageKind(override val value: Int) : CEnum {
CXLanguage_Invalid(0),
CXLanguage_C(1),
CXLanguage_ObjC(2),
CXLanguage_CPlusPlus(3),
;
companion object {
fun byValue(value: Int) = CXLanguageKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXLanguageKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXTypeKind(override val value: Int) : CEnum {
CXType_Invalid(0),
CXType_Unexposed(1),
CXType_Void(2),
CXType_Bool(3),
CXType_Char_U(4),
CXType_UChar(5),
CXType_Char16(6),
CXType_Char32(7),
CXType_UShort(8),
CXType_UInt(9),
CXType_ULong(10),
CXType_ULongLong(11),
CXType_UInt128(12),
CXType_Char_S(13),
CXType_SChar(14),
CXType_WChar(15),
CXType_Short(16),
CXType_Int(17),
CXType_Long(18),
CXType_LongLong(19),
CXType_Int128(20),
CXType_Float(21),
CXType_Double(22),
CXType_LongDouble(23),
CXType_NullPtr(24),
CXType_Overload(25),
CXType_Dependent(26),
CXType_ObjCId(27),
CXType_ObjCClass(28),
CXType_ObjCSel(29),
CXType_Float128(30),
CXType_Half(31),
CXType_Float16(32),
CXType_ShortAccum(33),
CXType_Accum(34),
CXType_LongAccum(35),
CXType_UShortAccum(36),
CXType_UAccum(37),
CXType_ULongAccum(38),
CXType_Complex(100),
CXType_Pointer(101),
CXType_BlockPointer(102),
CXType_LValueReference(103),
CXType_RValueReference(104),
CXType_Record(105),
CXType_Enum(106),
CXType_Typedef(107),
CXType_ObjCInterface(108),
CXType_ObjCObjectPointer(109),
CXType_FunctionNoProto(110),
CXType_FunctionProto(111),
CXType_ConstantArray(112),
CXType_Vector(113),
CXType_IncompleteArray(114),
CXType_VariableArray(115),
CXType_DependentSizedArray(116),
CXType_MemberPointer(117),
CXType_Auto(118),
CXType_Elaborated(119),
CXType_Pipe(120),
CXType_OCLImage1dRO(121),
CXType_OCLImage1dArrayRO(122),
CXType_OCLImage1dBufferRO(123),
CXType_OCLImage2dRO(124),
CXType_OCLImage2dArrayRO(125),
CXType_OCLImage2dDepthRO(126),
CXType_OCLImage2dArrayDepthRO(127),
CXType_OCLImage2dMSAARO(128),
CXType_OCLImage2dArrayMSAARO(129),
CXType_OCLImage2dMSAADepthRO(130),
CXType_OCLImage2dArrayMSAADepthRO(131),
CXType_OCLImage3dRO(132),
CXType_OCLImage1dWO(133),
CXType_OCLImage1dArrayWO(134),
CXType_OCLImage1dBufferWO(135),
CXType_OCLImage2dWO(136),
CXType_OCLImage2dArrayWO(137),
CXType_OCLImage2dDepthWO(138),
CXType_OCLImage2dArrayDepthWO(139),
CXType_OCLImage2dMSAAWO(140),
CXType_OCLImage2dArrayMSAAWO(141),
CXType_OCLImage2dMSAADepthWO(142),
CXType_OCLImage2dArrayMSAADepthWO(143),
CXType_OCLImage3dWO(144),
CXType_OCLImage1dRW(145),
CXType_OCLImage1dArrayRW(146),
CXType_OCLImage1dBufferRW(147),
CXType_OCLImage2dRW(148),
CXType_OCLImage2dArrayRW(149),
CXType_OCLImage2dDepthRW(150),
CXType_OCLImage2dArrayDepthRW(151),
CXType_OCLImage2dMSAARW(152),
CXType_OCLImage2dArrayMSAARW(153),
CXType_OCLImage2dMSAADepthRW(154),
CXType_OCLImage2dArrayMSAADepthRW(155),
CXType_OCLImage3dRW(156),
CXType_OCLSampler(157),
CXType_OCLEvent(158),
CXType_OCLQueue(159),
CXType_OCLReserveID(160),
CXType_ObjCObject(161),
CXType_ObjCTypeParam(162),
CXType_Attributed(163),
CXType_OCLIntelSubgroupAVCMcePayload(164),
CXType_OCLIntelSubgroupAVCImePayload(165),
CXType_OCLIntelSubgroupAVCRefPayload(166),
CXType_OCLIntelSubgroupAVCSicPayload(167),
CXType_OCLIntelSubgroupAVCMceResult(168),
CXType_OCLIntelSubgroupAVCImeResult(169),
CXType_OCLIntelSubgroupAVCRefResult(170),
CXType_OCLIntelSubgroupAVCSicResult(171),
CXType_OCLIntelSubgroupAVCImeResultSingleRefStreamout(172),
CXType_OCLIntelSubgroupAVCImeResultDualRefStreamout(173),
CXType_OCLIntelSubgroupAVCImeSingleRefStreamin(174),
CXType_OCLIntelSubgroupAVCImeDualRefStreamin(175),
;
companion object {
val CXType_FirstBuiltin = CXType_Void
val CXType_LastBuiltin = CXType_ULongAccum
fun byValue(value: Int) = CXTypeKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXTypeKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXCallingConv(override val value: Int) : CEnum {
CXCallingConv_Default(0),
CXCallingConv_C(1),
CXCallingConv_X86StdCall(2),
CXCallingConv_X86FastCall(3),
CXCallingConv_X86ThisCall(4),
CXCallingConv_X86Pascal(5),
CXCallingConv_AAPCS(6),
CXCallingConv_AAPCS_VFP(7),
CXCallingConv_X86RegCall(8),
CXCallingConv_IntelOclBicc(9),
CXCallingConv_Win64(10),
CXCallingConv_X86_64SysV(11),
CXCallingConv_X86VectorCall(12),
CXCallingConv_Swift(13),
CXCallingConv_PreserveMost(14),
CXCallingConv_PreserveAll(15),
CXCallingConv_AArch64VectorCall(16),
CXCallingConv_Invalid(100),
CXCallingConv_Unexposed(200),
;
companion object {
val CXCallingConv_X86_64Win64 = CXCallingConv_Win64
fun byValue(value: Int) = CXCallingConv.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXCallingConv
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXTemplateArgumentKind(override val value: Int) : CEnum {
CXTemplateArgumentKind_Null(0),
CXTemplateArgumentKind_Type(1),
CXTemplateArgumentKind_Declaration(2),
CXTemplateArgumentKind_NullPtr(3),
CXTemplateArgumentKind_Integral(4),
CXTemplateArgumentKind_Template(5),
CXTemplateArgumentKind_TemplateExpansion(6),
CXTemplateArgumentKind_Expression(7),
CXTemplateArgumentKind_Pack(8),
CXTemplateArgumentKind_Invalid(9),
;
companion object {
fun byValue(value: Int) = CXTemplateArgumentKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXTemplateArgumentKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CX_CXXAccessSpecifier(override val value: Int) : CEnum {
CX_CXXInvalidAccessSpecifier(0),
CX_CXXPublic(1),
CX_CXXProtected(2),
CX_CXXPrivate(3),
;
companion object {
fun byValue(value: Int) = CX_CXXAccessSpecifier.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CX_CXXAccessSpecifier
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CX_StorageClass(override val value: Int) : CEnum {
CX_SC_Invalid(0),
CX_SC_None(1),
CX_SC_Extern(2),
CX_SC_Static(3),
CX_SC_PrivateExtern(4),
CX_SC_OpenCLWorkGroupLocal(5),
CX_SC_Auto(6),
CX_SC_Register(7),
;
companion object {
fun byValue(value: Int) = CX_StorageClass.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CX_StorageClass
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXChildVisitResult(override val value: Int) : CEnum {
CXChildVisit_Break(0),
CXChildVisit_Continue(1),
CXChildVisit_Recurse(2),
;
companion object {
fun byValue(value: Int) = CXChildVisitResult.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXChildVisitResult
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXTokenKind(override val value: Int) : CEnum {
CXToken_Punctuation(0),
CXToken_Keyword(1),
CXToken_Identifier(2),
CXToken_Literal(3),
CXToken_Comment(4),
;
companion object {
fun byValue(value: Int) = CXTokenKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXTokenKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXCompletionChunkKind(override val value: Int) : CEnum {
CXCompletionChunk_Optional(0),
CXCompletionChunk_TypedText(1),
CXCompletionChunk_Text(2),
CXCompletionChunk_Placeholder(3),
CXCompletionChunk_Informative(4),
CXCompletionChunk_CurrentParameter(5),
CXCompletionChunk_LeftParen(6),
CXCompletionChunk_RightParen(7),
CXCompletionChunk_LeftBracket(8),
CXCompletionChunk_RightBracket(9),
CXCompletionChunk_LeftBrace(10),
CXCompletionChunk_RightBrace(11),
CXCompletionChunk_LeftAngle(12),
CXCompletionChunk_RightAngle(13),
CXCompletionChunk_Comma(14),
CXCompletionChunk_ResultType(15),
CXCompletionChunk_Colon(16),
CXCompletionChunk_SemiColon(17),
CXCompletionChunk_Equal(18),
CXCompletionChunk_HorizontalSpace(19),
CXCompletionChunk_VerticalSpace(20),
;
companion object {
fun byValue(value: Int) = CXCompletionChunkKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXCompletionChunkKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXEvalResultKind(override val value: Int) : CEnum {
CXEval_Int(1),
CXEval_Float(2),
CXEval_ObjCStrLiteral(3),
CXEval_StrLiteral(4),
CXEval_CFStr(5),
CXEval_Other(6),
CXEval_UnExposed(0),
;
companion object {
fun byValue(value: Int) = CXEvalResultKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXEvalResultKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXVisitorResult(override val value: Int) : CEnum {
CXVisit_Break(0),
CXVisit_Continue(1),
;
companion object {
fun byValue(value: Int) = CXVisitorResult.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXVisitorResult
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXResult(override val value: Int) : CEnum {
CXResult_Success(0),
CXResult_Invalid(1),
CXResult_VisitBreak(2),
;
companion object {
fun byValue(value: Int) = CXResult.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXResult
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXIdxEntityKind(override val value: Int) : CEnum {
CXIdxEntity_Unexposed(0),
CXIdxEntity_Typedef(1),
CXIdxEntity_Function(2),
CXIdxEntity_Variable(3),
CXIdxEntity_Field(4),
CXIdxEntity_EnumConstant(5),
CXIdxEntity_ObjCClass(6),
CXIdxEntity_ObjCProtocol(7),
CXIdxEntity_ObjCCategory(8),
CXIdxEntity_ObjCInstanceMethod(9),
CXIdxEntity_ObjCClassMethod(10),
CXIdxEntity_ObjCProperty(11),
CXIdxEntity_ObjCIvar(12),
CXIdxEntity_Enum(13),
CXIdxEntity_Struct(14),
CXIdxEntity_Union(15),
CXIdxEntity_CXXClass(16),
CXIdxEntity_CXXNamespace(17),
CXIdxEntity_CXXNamespaceAlias(18),
CXIdxEntity_CXXStaticVariable(19),
CXIdxEntity_CXXStaticMethod(20),
CXIdxEntity_CXXInstanceMethod(21),
CXIdxEntity_CXXConstructor(22),
CXIdxEntity_CXXDestructor(23),
CXIdxEntity_CXXConversionFunction(24),
CXIdxEntity_CXXTypeAlias(25),
CXIdxEntity_CXXInterface(26),
;
companion object {
fun byValue(value: Int) = CXIdxEntityKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXIdxEntityKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
enum class CXNullabilityKind(override val value: Int) : CEnum {
CXNullabilityKind_Nullable(0),
CXNullabilityKind_NonNull(1),
CXNullabilityKind_Unspecified(2),
;
companion object {
fun byValue(value: Int) = CXNullabilityKind.values().find { it.value == value }!!
}
class Var(rawPtr: NativePtr) : CEnumVar(rawPtr) {
companion object : Type(IntVar.size.toInt())
var value: CXNullabilityKind
get() = byValue(this.reinterpret<IntVar>().value)
set(value) { this.reinterpret<IntVar>().value = value.value }
}
}
fun clang_getCString(string: CValue<CXString>): CPointer<ByteVar>? {
memScoped {
return interpretCPointer<ByteVar>(kniBridge0(string.getPointer(memScope).rawValue))
}
}
fun clang_disposeString(string: CValue<CXString>): Unit {
memScoped {
return kniBridge1(string.getPointer(memScope).rawValue)
}
}
fun clang_disposeStringSet(set: CValuesRef<CXStringSet>?): Unit {
memScoped {
return kniBridge2(set?.getPointer(memScope).rawValue)
}
}
fun clang_getBuildSessionTimestamp(): Long {
return kniBridge3()
}
fun clang_VirtualFileOverlay_create(options: Int): CXVirtualFileOverlay? {
return interpretCPointer<CXVirtualFileOverlayImpl>(kniBridge4(options))
}
fun clang_VirtualFileOverlay_addFileMapping(arg0: CXVirtualFileOverlay?, virtualPath: String?, realPath: String?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge5(arg0.rawValue, virtualPath?.cstr?.getPointer(memScope).rawValue, realPath?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_VirtualFileOverlay_setCaseSensitivity(arg0: CXVirtualFileOverlay?, caseSensitive: Int): CXErrorCode {
return CXErrorCode.byValue(kniBridge6(arg0.rawValue, caseSensitive))
}
fun clang_VirtualFileOverlay_writeToBuffer(arg0: CXVirtualFileOverlay?, options: Int, out_buffer_ptr: CValuesRef<CPointerVar<ByteVar>>?, out_buffer_size: CValuesRef<IntVar>?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge7(arg0.rawValue, options, out_buffer_ptr?.getPointer(memScope).rawValue, out_buffer_size?.getPointer(memScope).rawValue))
}
}
fun clang_free(buffer: CValuesRef<*>?): Unit {
memScoped {
return kniBridge8(buffer?.getPointer(memScope).rawValue)
}
}
fun clang_VirtualFileOverlay_dispose(arg0: CXVirtualFileOverlay?): Unit {
return kniBridge9(arg0.rawValue)
}
fun clang_ModuleMapDescriptor_create(options: Int): CXModuleMapDescriptor? {
return interpretCPointer<CXModuleMapDescriptorImpl>(kniBridge10(options))
}
fun clang_ModuleMapDescriptor_setFrameworkModuleName(arg0: CXModuleMapDescriptor?, name: String?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge11(arg0.rawValue, name?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_ModuleMapDescriptor_setUmbrellaHeader(arg0: CXModuleMapDescriptor?, name: String?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge12(arg0.rawValue, name?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_ModuleMapDescriptor_writeToBuffer(arg0: CXModuleMapDescriptor?, options: Int, out_buffer_ptr: CValuesRef<CPointerVar<ByteVar>>?, out_buffer_size: CValuesRef<IntVar>?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge13(arg0.rawValue, options, out_buffer_ptr?.getPointer(memScope).rawValue, out_buffer_size?.getPointer(memScope).rawValue))
}
}
fun clang_ModuleMapDescriptor_dispose(arg0: CXModuleMapDescriptor?): Unit {
return kniBridge14(arg0.rawValue)
}
fun clang_createIndex(excludeDeclarationsFromPCH: Int, displayDiagnostics: Int): CXIndex? {
return interpretCPointer<COpaque>(kniBridge15(excludeDeclarationsFromPCH, displayDiagnostics))
}
fun clang_disposeIndex(index: CXIndex?): Unit {
return kniBridge16(index.rawValue)
}
fun clang_CXIndex_setGlobalOptions(arg0: CXIndex?, options: Int): Unit {
return kniBridge17(arg0.rawValue, options)
}
fun clang_CXIndex_getGlobalOptions(arg0: CXIndex?): Int {
return kniBridge18(arg0.rawValue)
}
fun clang_CXIndex_setInvocationEmissionPathOption(arg0: CXIndex?, Path: String?): Unit {
memScoped {
return kniBridge19(arg0.rawValue, Path?.cstr?.getPointer(memScope).rawValue)
}
}
fun clang_getFileName(SFile: CXFile?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge20(SFile.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getFileTime(SFile: CXFile?): time_t {
return kniBridge21(SFile.rawValue)
}
fun clang_getFileUniqueID(file: CXFile?, outID: CValuesRef<CXFileUniqueID>?): Int {
memScoped {
return kniBridge22(file.rawValue, outID?.getPointer(memScope).rawValue)
}
}
fun clang_isFileMultipleIncludeGuarded(tu: CXTranslationUnit?, file: CXFile?): Int {
return kniBridge23(tu.rawValue, file.rawValue)
}
fun clang_getFile(tu: CXTranslationUnit?, file_name: String?): CXFile? {
memScoped {
return interpretCPointer<COpaque>(kniBridge24(tu.rawValue, file_name?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_getFileContents(tu: CXTranslationUnit?, file: CXFile?, size: CValuesRef<size_tVar>?): CPointer<ByteVar>? {
memScoped {
return interpretCPointer<ByteVar>(kniBridge25(tu.rawValue, file.rawValue, size?.getPointer(memScope).rawValue))
}
}
fun clang_File_isEqual(file1: CXFile?, file2: CXFile?): Int {
return kniBridge26(file1.rawValue, file2.rawValue)
}
fun clang_File_tryGetRealPathName(file: CXFile?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge27(file.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getNullLocation(): CValue<CXSourceLocation> {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge28(kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_equalLocations(loc1: CValue<CXSourceLocation>, loc2: CValue<CXSourceLocation>): Int {
memScoped {
return kniBridge29(loc1.getPointer(memScope).rawValue, loc2.getPointer(memScope).rawValue)
}
}
fun clang_getLocation(tu: CXTranslationUnit?, file: CXFile?, line: Int, column: Int): CValue<CXSourceLocation> {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge30(tu.rawValue, file.rawValue, line, column, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getLocationForOffset(tu: CXTranslationUnit?, file: CXFile?, offset: Int): CValue<CXSourceLocation> {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge31(tu.rawValue, file.rawValue, offset, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_Location_isInSystemHeader(location: CValue<CXSourceLocation>): Int {
memScoped {
return kniBridge32(location.getPointer(memScope).rawValue)
}
}
fun clang_Location_isFromMainFile(location: CValue<CXSourceLocation>): Int {
memScoped {
return kniBridge33(location.getPointer(memScope).rawValue)
}
}
fun clang_getNullRange(): CValue<CXSourceRange> {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge34(kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getRange(begin: CValue<CXSourceLocation>, end: CValue<CXSourceLocation>): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge35(begin.getPointer(memScope).rawValue, end.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_equalRanges(range1: CValue<CXSourceRange>, range2: CValue<CXSourceRange>): Int {
memScoped {
return kniBridge36(range1.getPointer(memScope).rawValue, range2.getPointer(memScope).rawValue)
}
}
fun clang_Range_isNull(range: CValue<CXSourceRange>): Int {
memScoped {
return kniBridge37(range.getPointer(memScope).rawValue)
}
}
fun clang_getExpansionLocation(location: CValue<CXSourceLocation>, file: CValuesRef<CXFileVar>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?, offset: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge38(location.getPointer(memScope).rawValue, file?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue, offset?.getPointer(memScope).rawValue)
}
}
fun clang_getPresumedLocation(location: CValue<CXSourceLocation>, filename: CValuesRef<CXString>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge39(location.getPointer(memScope).rawValue, filename?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue)
}
}
fun clang_getInstantiationLocation(location: CValue<CXSourceLocation>, file: CValuesRef<CXFileVar>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?, offset: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge40(location.getPointer(memScope).rawValue, file?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue, offset?.getPointer(memScope).rawValue)
}
}
fun clang_getSpellingLocation(location: CValue<CXSourceLocation>, file: CValuesRef<CXFileVar>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?, offset: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge41(location.getPointer(memScope).rawValue, file?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue, offset?.getPointer(memScope).rawValue)
}
}
fun clang_getFileLocation(location: CValue<CXSourceLocation>, file: CValuesRef<CXFileVar>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?, offset: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge42(location.getPointer(memScope).rawValue, file?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue, offset?.getPointer(memScope).rawValue)
}
}
fun clang_getRangeStart(range: CValue<CXSourceRange>): CValue<CXSourceLocation> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge43(range.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getRangeEnd(range: CValue<CXSourceRange>): CValue<CXSourceLocation> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge44(range.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getSkippedRanges(tu: CXTranslationUnit?, file: CXFile?): CPointer<CXSourceRangeList>? {
return interpretCPointer<CXSourceRangeList>(kniBridge45(tu.rawValue, file.rawValue))
}
fun clang_getAllSkippedRanges(tu: CXTranslationUnit?): CPointer<CXSourceRangeList>? {
return interpretCPointer<CXSourceRangeList>(kniBridge46(tu.rawValue))
}
fun clang_disposeSourceRangeList(ranges: CValuesRef<CXSourceRangeList>?): Unit {
memScoped {
return kniBridge47(ranges?.getPointer(memScope).rawValue)
}
}
fun clang_getNumDiagnosticsInSet(Diags: CXDiagnosticSet?): Int {
return kniBridge48(Diags.rawValue)
}
fun clang_getDiagnosticInSet(Diags: CXDiagnosticSet?, Index: Int): CXDiagnostic? {
return interpretCPointer<COpaque>(kniBridge49(Diags.rawValue, Index))
}
fun clang_loadDiagnostics(file: String?, error: CValuesRef<CXLoadDiag_Error.Var>?, errorString: CValuesRef<CXString>?): CXDiagnosticSet? {
memScoped {
return interpretCPointer<COpaque>(kniBridge50(file?.cstr?.getPointer(memScope).rawValue, error?.getPointer(memScope).rawValue, errorString?.getPointer(memScope).rawValue))
}
}
fun clang_disposeDiagnosticSet(Diags: CXDiagnosticSet?): Unit {
return kniBridge51(Diags.rawValue)
}
fun clang_getChildDiagnostics(D: CXDiagnostic?): CXDiagnosticSet? {
return interpretCPointer<COpaque>(kniBridge52(D.rawValue))
}
fun clang_getNumDiagnostics(Unit: CXTranslationUnit?): Int {
return kniBridge53(Unit.rawValue)
}
fun clang_getDiagnostic(Unit: CXTranslationUnit?, Index: Int): CXDiagnostic? {
return interpretCPointer<COpaque>(kniBridge54(Unit.rawValue, Index))
}
fun clang_getDiagnosticSetFromTU(Unit: CXTranslationUnit?): CXDiagnosticSet? {
return interpretCPointer<COpaque>(kniBridge55(Unit.rawValue))
}
fun clang_disposeDiagnostic(Diagnostic: CXDiagnostic?): Unit {
return kniBridge56(Diagnostic.rawValue)
}
fun clang_formatDiagnostic(Diagnostic: CXDiagnostic?, Options: Int): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge57(Diagnostic.rawValue, Options, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_defaultDiagnosticDisplayOptions(): Int {
return kniBridge58()
}
fun clang_getDiagnosticSeverity(arg0: CXDiagnostic?): CXDiagnosticSeverity {
return CXDiagnosticSeverity.byValue(kniBridge59(arg0.rawValue))
}
fun clang_getDiagnosticLocation(arg0: CXDiagnostic?): CValue<CXSourceLocation> {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge60(arg0.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDiagnosticSpelling(arg0: CXDiagnostic?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge61(arg0.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDiagnosticOption(Diag: CXDiagnostic?, Disable: CValuesRef<CXString>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge62(Diag.rawValue, Disable?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getDiagnosticCategory(arg0: CXDiagnostic?): Int {
return kniBridge63(arg0.rawValue)
}
fun clang_getDiagnosticCategoryName(Category: Int): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge64(Category, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDiagnosticCategoryText(arg0: CXDiagnostic?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge65(arg0.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDiagnosticNumRanges(arg0: CXDiagnostic?): Int {
return kniBridge66(arg0.rawValue)
}
fun clang_getDiagnosticRange(Diagnostic: CXDiagnostic?, Range: Int): CValue<CXSourceRange> {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge67(Diagnostic.rawValue, Range, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDiagnosticNumFixIts(Diagnostic: CXDiagnostic?): Int {
return kniBridge68(Diagnostic.rawValue)
}
fun clang_getDiagnosticFixIt(Diagnostic: CXDiagnostic?, FixIt: Int, ReplacementRange: CValuesRef<CXSourceRange>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge69(Diagnostic.rawValue, FixIt, ReplacementRange?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTranslationUnitSpelling(CTUnit: CXTranslationUnit?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge70(CTUnit.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_createTranslationUnitFromSourceFile(CIdx: CXIndex?, source_filename: String?, num_clang_command_line_args: Int, clang_command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_unsaved_files: Int, unsaved_files: CValuesRef<CXUnsavedFile>?): CXTranslationUnit? {
memScoped {
return interpretCPointer<CXTranslationUnitImpl>(kniBridge71(CIdx.rawValue, source_filename?.cstr?.getPointer(memScope).rawValue, num_clang_command_line_args, clang_command_line_args?.getPointer(memScope).rawValue, num_unsaved_files, unsaved_files?.getPointer(memScope).rawValue))
}
}
fun clang_createTranslationUnit(CIdx: CXIndex?, ast_filename: String?): CXTranslationUnit? {
memScoped {
return interpretCPointer<CXTranslationUnitImpl>(kniBridge72(CIdx.rawValue, ast_filename?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_createTranslationUnit2(CIdx: CXIndex?, ast_filename: String?, out_TU: CValuesRef<CXTranslationUnitVar>?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge73(CIdx.rawValue, ast_filename?.cstr?.getPointer(memScope).rawValue, out_TU?.getPointer(memScope).rawValue))
}
}
fun clang_defaultEditingTranslationUnitOptions(): Int {
return kniBridge74()
}
fun clang_parseTranslationUnit(CIdx: CXIndex?, source_filename: String?, command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_command_line_args: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, options: Int): CXTranslationUnit? {
memScoped {
return interpretCPointer<CXTranslationUnitImpl>(kniBridge75(CIdx.rawValue, source_filename?.cstr?.getPointer(memScope).rawValue, command_line_args?.getPointer(memScope).rawValue, num_command_line_args, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, options))
}
}
fun clang_parseTranslationUnit2(CIdx: CXIndex?, source_filename: String?, command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_command_line_args: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, options: Int, out_TU: CValuesRef<CXTranslationUnitVar>?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge76(CIdx.rawValue, source_filename?.cstr?.getPointer(memScope).rawValue, command_line_args?.getPointer(memScope).rawValue, num_command_line_args, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, options, out_TU?.getPointer(memScope).rawValue))
}
}
fun clang_parseTranslationUnit2FullArgv(CIdx: CXIndex?, source_filename: String?, command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_command_line_args: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, options: Int, out_TU: CValuesRef<CXTranslationUnitVar>?): CXErrorCode {
memScoped {
return CXErrorCode.byValue(kniBridge77(CIdx.rawValue, source_filename?.cstr?.getPointer(memScope).rawValue, command_line_args?.getPointer(memScope).rawValue, num_command_line_args, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, options, out_TU?.getPointer(memScope).rawValue))
}
}
fun clang_defaultSaveOptions(TU: CXTranslationUnit?): Int {
return kniBridge78(TU.rawValue)
}
fun clang_saveTranslationUnit(TU: CXTranslationUnit?, FileName: String?, options: Int): Int {
memScoped {
return kniBridge79(TU.rawValue, FileName?.cstr?.getPointer(memScope).rawValue, options)
}
}
fun clang_suspendTranslationUnit(arg0: CXTranslationUnit?): Int {
return kniBridge80(arg0.rawValue)
}
fun clang_disposeTranslationUnit(arg0: CXTranslationUnit?): Unit {
return kniBridge81(arg0.rawValue)
}
fun clang_defaultReparseOptions(TU: CXTranslationUnit?): Int {
return kniBridge82(TU.rawValue)
}
fun clang_reparseTranslationUnit(TU: CXTranslationUnit?, num_unsaved_files: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, options: Int): Int {
memScoped {
return kniBridge83(TU.rawValue, num_unsaved_files, unsaved_files?.getPointer(memScope).rawValue, options)
}
}
fun clang_getTUResourceUsageName(kind: CXTUResourceUsageKind): CPointer<ByteVar>? {
return interpretCPointer<ByteVar>(kniBridge84(kind.value))
}
fun clang_getCXTUResourceUsage(TU: CXTranslationUnit?): CValue<CXTUResourceUsage> {
val kniRetVal = nativeHeap.alloc<CXTUResourceUsage>()
try {
kniBridge85(TU.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_disposeCXTUResourceUsage(usage: CValue<CXTUResourceUsage>): Unit {
memScoped {
return kniBridge86(usage.getPointer(memScope).rawValue)
}
}
fun clang_getTranslationUnitTargetInfo(CTUnit: CXTranslationUnit?): CXTargetInfo? {
return interpretCPointer<CXTargetInfoImpl>(kniBridge87(CTUnit.rawValue))
}
fun clang_TargetInfo_dispose(Info: CXTargetInfo?): Unit {
return kniBridge88(Info.rawValue)
}
fun clang_TargetInfo_getTriple(Info: CXTargetInfo?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge89(Info.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_TargetInfo_getPointerWidth(Info: CXTargetInfo?): Int {
return kniBridge90(Info.rawValue)
}
fun clang_getNullCursor(): CValue<CXCursor> {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge91(kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getTranslationUnitCursor(arg0: CXTranslationUnit?): CValue<CXCursor> {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge92(arg0.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_equalCursors(arg0: CValue<CXCursor>, arg1: CValue<CXCursor>): Int {
memScoped {
return kniBridge93(arg0.getPointer(memScope).rawValue, arg1.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isNull(cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge94(cursor.getPointer(memScope).rawValue)
}
}
fun clang_hashCursor(arg0: CValue<CXCursor>): Int {
memScoped {
return kniBridge95(arg0.getPointer(memScope).rawValue)
}
}
fun clang_getCursorKind(arg0: CValue<CXCursor>): CXCursorKind {
memScoped {
return CXCursorKind.byValue(kniBridge96(arg0.getPointer(memScope).rawValue))
}
}
fun clang_isDeclaration(arg0: CXCursorKind): Int {
return kniBridge97(arg0.value)
}
fun clang_isInvalidDeclaration(arg0: CValue<CXCursor>): Int {
memScoped {
return kniBridge98(arg0.getPointer(memScope).rawValue)
}
}
fun clang_isReference(arg0: CXCursorKind): Int {
return kniBridge99(arg0.value)
}
fun clang_isExpression(arg0: CXCursorKind): Int {
return kniBridge100(arg0.value)
}
fun clang_isStatement(arg0: CXCursorKind): Int {
return kniBridge101(arg0.value)
}
fun clang_isAttribute(arg0: CXCursorKind): Int {
return kniBridge102(arg0.value)
}
fun clang_Cursor_hasAttrs(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge103(C.getPointer(memScope).rawValue)
}
}
fun clang_isInvalid(arg0: CXCursorKind): Int {
return kniBridge104(arg0.value)
}
fun clang_isTranslationUnit(arg0: CXCursorKind): Int {
return kniBridge105(arg0.value)
}
fun clang_isPreprocessing(arg0: CXCursorKind): Int {
return kniBridge106(arg0.value)
}
fun clang_isUnexposed(arg0: CXCursorKind): Int {
return kniBridge107(arg0.value)
}
fun clang_getCursorLinkage(cursor: CValue<CXCursor>): CXLinkageKind {
memScoped {
return CXLinkageKind.byValue(kniBridge108(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCursorVisibility(cursor: CValue<CXCursor>): CXVisibilityKind {
memScoped {
return CXVisibilityKind.byValue(kniBridge109(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCursorAvailability(cursor: CValue<CXCursor>): CXAvailabilityKind {
memScoped {
return CXAvailabilityKind.byValue(kniBridge110(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCursorPlatformAvailability(cursor: CValue<CXCursor>, always_deprecated: CValuesRef<IntVar>?, deprecated_message: CValuesRef<CXString>?, always_unavailable: CValuesRef<IntVar>?, unavailable_message: CValuesRef<CXString>?, availability: CValuesRef<CXPlatformAvailability>?, availability_size: Int): Int {
memScoped {
return kniBridge111(cursor.getPointer(memScope).rawValue, always_deprecated?.getPointer(memScope).rawValue, deprecated_message?.getPointer(memScope).rawValue, always_unavailable?.getPointer(memScope).rawValue, unavailable_message?.getPointer(memScope).rawValue, availability?.getPointer(memScope).rawValue, availability_size)
}
}
fun clang_disposeCXPlatformAvailability(availability: CValuesRef<CXPlatformAvailability>?): Unit {
memScoped {
return kniBridge112(availability?.getPointer(memScope).rawValue)
}
}
fun clang_getCursorLanguage(cursor: CValue<CXCursor>): CXLanguageKind {
memScoped {
return CXLanguageKind.byValue(kniBridge113(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCursorTLSKind(cursor: CValue<CXCursor>): CXTLSKind {
memScoped {
return kniBridge114(cursor.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getTranslationUnit(arg0: CValue<CXCursor>): CXTranslationUnit? {
memScoped {
return interpretCPointer<CXTranslationUnitImpl>(kniBridge115(arg0.getPointer(memScope).rawValue))
}
}
fun clang_createCXCursorSet(): CXCursorSet? {
return interpretCPointer<CXCursorSetImpl>(kniBridge116())
}
fun clang_disposeCXCursorSet(cset: CXCursorSet?): Unit {
return kniBridge117(cset.rawValue)
}
fun clang_CXCursorSet_contains(cset: CXCursorSet?, cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge118(cset.rawValue, cursor.getPointer(memScope).rawValue)
}
}
fun clang_CXCursorSet_insert(cset: CXCursorSet?, cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge119(cset.rawValue, cursor.getPointer(memScope).rawValue)
}
}
fun clang_getCursorSemanticParent(cursor: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge120(cursor.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorLexicalParent(cursor: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge121(cursor.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getOverriddenCursors(cursor: CValue<CXCursor>, overridden: CValuesRef<CPointerVar<CXCursor>>?, num_overridden: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge122(cursor.getPointer(memScope).rawValue, overridden?.getPointer(memScope).rawValue, num_overridden?.getPointer(memScope).rawValue)
}
}
fun clang_disposeOverriddenCursors(overridden: CValuesRef<CXCursor>?): Unit {
memScoped {
return kniBridge123(overridden?.getPointer(memScope).rawValue)
}
}
fun clang_getIncludedFile(cursor: CValue<CXCursor>): CXFile? {
memScoped {
return interpretCPointer<COpaque>(kniBridge124(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCursor(arg0: CXTranslationUnit?, arg1: CValue<CXSourceLocation>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge125(arg0.rawValue, arg1.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorLocation(arg0: CValue<CXCursor>): CValue<CXSourceLocation> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge126(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorExtent(arg0: CValue<CXCursor>): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge127(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorType(C: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge128(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTypeSpelling(CT: CValue<CXType>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge129(CT.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTypedefDeclUnderlyingType(C: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge130(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getEnumDeclIntegerType(C: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge131(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getEnumConstantDeclValue(C: CValue<CXCursor>): Long {
memScoped {
return kniBridge132(C.getPointer(memScope).rawValue)
}
}
fun clang_getEnumConstantDeclUnsignedValue(C: CValue<CXCursor>): Long {
memScoped {
return kniBridge133(C.getPointer(memScope).rawValue)
}
}
fun clang_getFieldDeclBitWidth(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge134(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getNumArguments(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge135(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getArgument(C: CValue<CXCursor>, i: Int): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge136(C.getPointer(memScope).rawValue, i, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getNumTemplateArguments(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge137(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getTemplateArgumentKind(C: CValue<CXCursor>, I: Int): CXTemplateArgumentKind {
memScoped {
return CXTemplateArgumentKind.byValue(kniBridge138(C.getPointer(memScope).rawValue, I))
}
}
fun clang_Cursor_getTemplateArgumentType(C: CValue<CXCursor>, I: Int): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge139(C.getPointer(memScope).rawValue, I, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getTemplateArgumentValue(C: CValue<CXCursor>, I: Int): Long {
memScoped {
return kniBridge140(C.getPointer(memScope).rawValue, I)
}
}
fun clang_Cursor_getTemplateArgumentUnsignedValue(C: CValue<CXCursor>, I: Int): Long {
memScoped {
return kniBridge141(C.getPointer(memScope).rawValue, I)
}
}
fun clang_equalTypes(A: CValue<CXType>, B: CValue<CXType>): Int {
memScoped {
return kniBridge142(A.getPointer(memScope).rawValue, B.getPointer(memScope).rawValue)
}
}
fun clang_getCanonicalType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge143(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_isConstQualifiedType(T: CValue<CXType>): Int {
memScoped {
return kniBridge144(T.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isMacroFunctionLike(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge145(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isMacroBuiltin(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge146(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isFunctionInlined(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge147(C.getPointer(memScope).rawValue)
}
}
fun clang_isVolatileQualifiedType(T: CValue<CXType>): Int {
memScoped {
return kniBridge148(T.getPointer(memScope).rawValue)
}
}
fun clang_isRestrictQualifiedType(T: CValue<CXType>): Int {
memScoped {
return kniBridge149(T.getPointer(memScope).rawValue)
}
}
fun clang_getAddressSpace(T: CValue<CXType>): Int {
memScoped {
return kniBridge150(T.getPointer(memScope).rawValue)
}
}
fun clang_getTypedefName(CT: CValue<CXType>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge151(CT.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getPointeeType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge152(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTypeDeclaration(T: CValue<CXType>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge153(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getDeclObjCTypeEncoding(C: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge154(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getObjCEncoding(type: CValue<CXType>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge155(type.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTypeKindSpelling(K: CXTypeKind): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge156(K.value, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getFunctionTypeCallingConv(T: CValue<CXType>): CXCallingConv {
memScoped {
return CXCallingConv.byValue(kniBridge157(T.getPointer(memScope).rawValue))
}
}
fun clang_getResultType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge158(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getExceptionSpecificationType(T: CValue<CXType>): Int {
memScoped {
return kniBridge159(T.getPointer(memScope).rawValue)
}
}
fun clang_getNumArgTypes(T: CValue<CXType>): Int {
memScoped {
return kniBridge160(T.getPointer(memScope).rawValue)
}
}
fun clang_getArgType(T: CValue<CXType>, i: Int): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge161(T.getPointer(memScope).rawValue, i, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getObjCObjectBaseType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge162(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getNumObjCProtocolRefs(T: CValue<CXType>): Int {
memScoped {
return kniBridge163(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getObjCProtocolDecl(T: CValue<CXType>, i: Int): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge164(T.getPointer(memScope).rawValue, i, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getNumObjCTypeArgs(T: CValue<CXType>): Int {
memScoped {
return kniBridge165(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getObjCTypeArg(T: CValue<CXType>, i: Int): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge166(T.getPointer(memScope).rawValue, i, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_isFunctionTypeVariadic(T: CValue<CXType>): Int {
memScoped {
return kniBridge167(T.getPointer(memScope).rawValue)
}
}
fun clang_getCursorResultType(C: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge168(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorExceptionSpecificationType(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge169(C.getPointer(memScope).rawValue)
}
}
fun clang_isPODType(T: CValue<CXType>): Int {
memScoped {
return kniBridge170(T.getPointer(memScope).rawValue)
}
}
fun clang_getElementType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge171(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getNumElements(T: CValue<CXType>): Long {
memScoped {
return kniBridge172(T.getPointer(memScope).rawValue)
}
}
fun clang_getArrayElementType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge173(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getArraySize(T: CValue<CXType>): Long {
memScoped {
return kniBridge174(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getNamedType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge175(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_isTransparentTagTypedef(T: CValue<CXType>): Int {
memScoped {
return kniBridge176(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getNullability(T: CValue<CXType>): CXTypeNullabilityKind {
memScoped {
return kniBridge177(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getAlignOf(T: CValue<CXType>): Long {
memScoped {
return kniBridge178(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getClassType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge179(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getSizeOf(T: CValue<CXType>): Long {
memScoped {
return kniBridge180(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getOffsetOf(T: CValue<CXType>, S: String?): Long {
memScoped {
return kniBridge181(T.getPointer(memScope).rawValue, S?.cstr?.getPointer(memScope).rawValue)
}
}
fun clang_Type_getModifiedType(T: CValue<CXType>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge182(T.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getOffsetOfField(C: CValue<CXCursor>): Long {
memScoped {
return kniBridge183(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isAnonymous(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge184(C.getPointer(memScope).rawValue)
}
}
fun clang_Type_getNumTemplateArguments(T: CValue<CXType>): Int {
memScoped {
return kniBridge185(T.getPointer(memScope).rawValue)
}
}
fun clang_Type_getTemplateArgumentAsType(T: CValue<CXType>, i: Int): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge186(T.getPointer(memScope).rawValue, i, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getCXXRefQualifier(T: CValue<CXType>): CXRefQualifierKind {
memScoped {
return kniBridge187(T.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isBitField(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge188(C.getPointer(memScope).rawValue)
}
}
fun clang_isVirtualBase(arg0: CValue<CXCursor>): Int {
memScoped {
return kniBridge189(arg0.getPointer(memScope).rawValue)
}
}
fun clang_getCXXAccessSpecifier(arg0: CValue<CXCursor>): CX_CXXAccessSpecifier {
memScoped {
return CX_CXXAccessSpecifier.byValue(kniBridge190(arg0.getPointer(memScope).rawValue))
}
}
fun clang_Cursor_getStorageClass(arg0: CValue<CXCursor>): CX_StorageClass {
memScoped {
return CX_StorageClass.byValue(kniBridge191(arg0.getPointer(memScope).rawValue))
}
}
fun clang_getNumOverloadedDecls(cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge192(cursor.getPointer(memScope).rawValue)
}
}
fun clang_getOverloadedDecl(cursor: CValue<CXCursor>, index: Int): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge193(cursor.getPointer(memScope).rawValue, index, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getIBOutletCollectionType(arg0: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge194(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_visitChildren(parent: CValue<CXCursor>, visitor: CXCursorVisitor?, client_data: CXClientData?): Int {
memScoped {
return kniBridge195(parent.getPointer(memScope).rawValue, visitor.rawValue, client_data.rawValue)
}
}
fun clang_getCursorUSR(arg0: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge196(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCClass(class_name: String?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge197(class_name?.cstr?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCCategory(class_name: String?, category_name: String?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge198(class_name?.cstr?.getPointer(memScope).rawValue, category_name?.cstr?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCProtocol(protocol_name: String?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge199(protocol_name?.cstr?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCIvar(name: String?, classUSR: CValue<CXString>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge200(name?.cstr?.getPointer(memScope).rawValue, classUSR.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCMethod(name: String?, isInstanceMethod: Int, classUSR: CValue<CXString>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge201(name?.cstr?.getPointer(memScope).rawValue, isInstanceMethod, classUSR.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_constructUSR_ObjCProperty(property: String?, classUSR: CValue<CXString>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge202(property?.cstr?.getPointer(memScope).rawValue, classUSR.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorSpelling(arg0: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge203(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getSpellingNameRange(arg0: CValue<CXCursor>, pieceIndex: Int, options: Int): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge204(arg0.getPointer(memScope).rawValue, pieceIndex, options, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_PrintingPolicy_getProperty(Policy: CXPrintingPolicy?, Property: CXPrintingPolicyProperty): Int {
return kniBridge205(Policy.rawValue, Property)
}
fun clang_PrintingPolicy_setProperty(Policy: CXPrintingPolicy?, Property: CXPrintingPolicyProperty, Value: Int): Unit {
return kniBridge206(Policy.rawValue, Property, Value)
}
fun clang_getCursorPrintingPolicy(arg0: CValue<CXCursor>): CXPrintingPolicy? {
memScoped {
return interpretCPointer<COpaque>(kniBridge207(arg0.getPointer(memScope).rawValue))
}
}
fun clang_PrintingPolicy_dispose(Policy: CXPrintingPolicy?): Unit {
return kniBridge208(Policy.rawValue)
}
fun clang_getCursorPrettyPrinted(Cursor: CValue<CXCursor>, Policy: CXPrintingPolicy?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge209(Cursor.getPointer(memScope).rawValue, Policy.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorDisplayName(arg0: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge210(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorReferenced(arg0: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge211(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorDefinition(arg0: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge212(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_isCursorDefinition(arg0: CValue<CXCursor>): Int {
memScoped {
return kniBridge213(arg0.getPointer(memScope).rawValue)
}
}
fun clang_getCanonicalCursor(arg0: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge214(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getObjCSelectorIndex(arg0: CValue<CXCursor>): Int {
memScoped {
return kniBridge215(arg0.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isDynamicCall(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge216(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getReceiverType(C: CValue<CXCursor>): CValue<CXType> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXType>()
try {
kniBridge217(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getObjCPropertyAttributes(C: CValue<CXCursor>, reserved: Int): Int {
memScoped {
return kniBridge218(C.getPointer(memScope).rawValue, reserved)
}
}
fun clang_Cursor_getObjCPropertyGetterName(C: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge219(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getObjCPropertySetterName(C: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge220(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getObjCDeclQualifiers(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge221(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isObjCOptional(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge222(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isVariadic(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge223(C.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isExternalSymbol(C: CValue<CXCursor>, language: CValuesRef<CXString>?, definedIn: CValuesRef<CXString>?, isGenerated: CValuesRef<IntVar>?): Int {
memScoped {
return kniBridge224(C.getPointer(memScope).rawValue, language?.getPointer(memScope).rawValue, definedIn?.getPointer(memScope).rawValue, isGenerated?.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_getCommentRange(C: CValue<CXCursor>): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge225(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getRawCommentText(C: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge226(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getBriefCommentText(C: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge227(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getMangling(arg0: CValue<CXCursor>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge228(arg0.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_getCXXManglings(arg0: CValue<CXCursor>): CPointer<CXStringSet>? {
memScoped {
return interpretCPointer<CXStringSet>(kniBridge229(arg0.getPointer(memScope).rawValue))
}
}
fun clang_Cursor_getObjCManglings(arg0: CValue<CXCursor>): CPointer<CXStringSet>? {
memScoped {
return interpretCPointer<CXStringSet>(kniBridge230(arg0.getPointer(memScope).rawValue))
}
}
fun clang_Cursor_getModule(C: CValue<CXCursor>): CXModule? {
memScoped {
return interpretCPointer<COpaque>(kniBridge231(C.getPointer(memScope).rawValue))
}
}
fun clang_getModuleForFile(arg0: CXTranslationUnit?, arg1: CXFile?): CXModule? {
return interpretCPointer<COpaque>(kniBridge232(arg0.rawValue, arg1.rawValue))
}
fun clang_Module_getASTFile(Module: CXModule?): CXFile? {
return interpretCPointer<COpaque>(kniBridge233(Module.rawValue))
}
fun clang_Module_getParent(Module: CXModule?): CXModule? {
return interpretCPointer<COpaque>(kniBridge234(Module.rawValue))
}
fun clang_Module_getName(Module: CXModule?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge235(Module.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_Module_getFullName(Module: CXModule?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge236(Module.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_Module_isSystem(Module: CXModule?): Int {
return kniBridge237(Module.rawValue)
}
fun clang_Module_getNumTopLevelHeaders(arg0: CXTranslationUnit?, Module: CXModule?): Int {
return kniBridge238(arg0.rawValue, Module.rawValue)
}
fun clang_Module_getTopLevelHeader(arg0: CXTranslationUnit?, Module: CXModule?, Index: Int): CXFile? {
return interpretCPointer<COpaque>(kniBridge239(arg0.rawValue, Module.rawValue, Index))
}
fun clang_CXXConstructor_isConvertingConstructor(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge240(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXConstructor_isCopyConstructor(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge241(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXConstructor_isDefaultConstructor(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge242(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXConstructor_isMoveConstructor(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge243(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXField_isMutable(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge244(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXMethod_isDefaulted(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge245(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXMethod_isPureVirtual(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge246(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXMethod_isStatic(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge247(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXMethod_isVirtual(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge248(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXRecord_isAbstract(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge249(C.getPointer(memScope).rawValue)
}
}
fun clang_EnumDecl_isScoped(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge250(C.getPointer(memScope).rawValue)
}
}
fun clang_CXXMethod_isConst(C: CValue<CXCursor>): Int {
memScoped {
return kniBridge251(C.getPointer(memScope).rawValue)
}
}
fun clang_getTemplateCursorKind(C: CValue<CXCursor>): CXCursorKind {
memScoped {
return CXCursorKind.byValue(kniBridge252(C.getPointer(memScope).rawValue))
}
}
fun clang_getSpecializedCursorTemplate(C: CValue<CXCursor>): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge253(C.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorReferenceNameRange(C: CValue<CXCursor>, NameFlags: Int, PieceIndex: Int): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge254(C.getPointer(memScope).rawValue, NameFlags, PieceIndex, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getToken(TU: CXTranslationUnit?, Location: CValue<CXSourceLocation>): CPointer<CXToken>? {
memScoped {
return interpretCPointer<CXToken>(kniBridge255(TU.rawValue, Location.getPointer(memScope).rawValue))
}
}
fun clang_getTokenKind(arg0: CValue<CXToken>): CXTokenKind {
memScoped {
return CXTokenKind.byValue(kniBridge256(arg0.getPointer(memScope).rawValue))
}
}
fun clang_getTokenSpelling(arg0: CXTranslationUnit?, arg1: CValue<CXToken>): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge257(arg0.rawValue, arg1.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTokenLocation(arg0: CXTranslationUnit?, arg1: CValue<CXToken>): CValue<CXSourceLocation> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge258(arg0.rawValue, arg1.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getTokenExtent(arg0: CXTranslationUnit?, arg1: CValue<CXToken>): CValue<CXSourceRange> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceRange>()
try {
kniBridge259(arg0.rawValue, arg1.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_tokenize(TU: CXTranslationUnit?, Range: CValue<CXSourceRange>, Tokens: CValuesRef<CPointerVar<CXToken>>?, NumTokens: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge260(TU.rawValue, Range.getPointer(memScope).rawValue, Tokens?.getPointer(memScope).rawValue, NumTokens?.getPointer(memScope).rawValue)
}
}
fun clang_annotateTokens(TU: CXTranslationUnit?, Tokens: CValuesRef<CXToken>?, NumTokens: Int, Cursors: CValuesRef<CXCursor>?): Unit {
memScoped {
return kniBridge261(TU.rawValue, Tokens?.getPointer(memScope).rawValue, NumTokens, Cursors?.getPointer(memScope).rawValue)
}
}
fun clang_disposeTokens(TU: CXTranslationUnit?, Tokens: CValuesRef<CXToken>?, NumTokens: Int): Unit {
memScoped {
return kniBridge262(TU.rawValue, Tokens?.getPointer(memScope).rawValue, NumTokens)
}
}
fun clang_getCursorKindSpelling(Kind: CXCursorKind): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge263(Kind.value, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getDefinitionSpellingAndExtent(arg0: CValue<CXCursor>, startBuf: CValuesRef<CPointerVar<ByteVar>>?, endBuf: CValuesRef<CPointerVar<ByteVar>>?, startLine: CValuesRef<IntVar>?, startColumn: CValuesRef<IntVar>?, endLine: CValuesRef<IntVar>?, endColumn: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge264(arg0.getPointer(memScope).rawValue, startBuf?.getPointer(memScope).rawValue, endBuf?.getPointer(memScope).rawValue, startLine?.getPointer(memScope).rawValue, startColumn?.getPointer(memScope).rawValue, endLine?.getPointer(memScope).rawValue, endColumn?.getPointer(memScope).rawValue)
}
}
fun clang_enableStackTraces(): Unit {
return kniBridge265()
}
fun clang_executeOnThread(fn: CPointer<CFunction<(COpaquePointer?) -> Unit>>?, user_data: CValuesRef<*>?, stack_size: Int): Unit {
memScoped {
return kniBridge266(fn.rawValue, user_data?.getPointer(memScope).rawValue, stack_size)
}
}
fun clang_getCompletionChunkKind(completion_string: CXCompletionString?, chunk_number: Int): CXCompletionChunkKind {
return CXCompletionChunkKind.byValue(kniBridge267(completion_string.rawValue, chunk_number))
}
fun clang_getCompletionChunkText(completion_string: CXCompletionString?, chunk_number: Int): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge268(completion_string.rawValue, chunk_number, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getCompletionChunkCompletionString(completion_string: CXCompletionString?, chunk_number: Int): CXCompletionString? {
return interpretCPointer<COpaque>(kniBridge269(completion_string.rawValue, chunk_number))
}
fun clang_getNumCompletionChunks(completion_string: CXCompletionString?): Int {
return kniBridge270(completion_string.rawValue)
}
fun clang_getCompletionPriority(completion_string: CXCompletionString?): Int {
return kniBridge271(completion_string.rawValue)
}
fun clang_getCompletionAvailability(completion_string: CXCompletionString?): CXAvailabilityKind {
return CXAvailabilityKind.byValue(kniBridge272(completion_string.rawValue))
}
fun clang_getCompletionNumAnnotations(completion_string: CXCompletionString?): Int {
return kniBridge273(completion_string.rawValue)
}
fun clang_getCompletionAnnotation(completion_string: CXCompletionString?, annotation_number: Int): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge274(completion_string.rawValue, annotation_number, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getCompletionParent(completion_string: CXCompletionString?, kind: CValuesRef<CXCursorKind.Var>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge275(completion_string.rawValue, kind?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCompletionBriefComment(completion_string: CXCompletionString?): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge276(completion_string.rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_getCursorCompletionString(cursor: CValue<CXCursor>): CXCompletionString? {
memScoped {
return interpretCPointer<COpaque>(kniBridge277(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getCompletionNumFixIts(results: CValuesRef<CXCodeCompleteResults>?, completion_index: Int): Int {
memScoped {
return kniBridge278(results?.getPointer(memScope).rawValue, completion_index)
}
}
fun clang_getCompletionFixIt(results: CValuesRef<CXCodeCompleteResults>?, completion_index: Int, fixit_index: Int, replacement_range: CValuesRef<CXSourceRange>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge279(results?.getPointer(memScope).rawValue, completion_index, fixit_index, replacement_range?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_defaultCodeCompleteOptions(): Int {
return kniBridge280()
}
fun clang_codeCompleteAt(TU: CXTranslationUnit?, complete_filename: String?, complete_line: Int, complete_column: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, options: Int): CPointer<CXCodeCompleteResults>? {
memScoped {
return interpretCPointer<CXCodeCompleteResults>(kniBridge281(TU.rawValue, complete_filename?.cstr?.getPointer(memScope).rawValue, complete_line, complete_column, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, options))
}
}
fun clang_sortCodeCompletionResults(Results: CValuesRef<CXCompletionResult>?, NumResults: Int): Unit {
memScoped {
return kniBridge282(Results?.getPointer(memScope).rawValue, NumResults)
}
}
fun clang_disposeCodeCompleteResults(Results: CValuesRef<CXCodeCompleteResults>?): Unit {
memScoped {
return kniBridge283(Results?.getPointer(memScope).rawValue)
}
}
fun clang_codeCompleteGetNumDiagnostics(Results: CValuesRef<CXCodeCompleteResults>?): Int {
memScoped {
return kniBridge284(Results?.getPointer(memScope).rawValue)
}
}
fun clang_codeCompleteGetDiagnostic(Results: CValuesRef<CXCodeCompleteResults>?, Index: Int): CXDiagnostic? {
memScoped {
return interpretCPointer<COpaque>(kniBridge285(Results?.getPointer(memScope).rawValue, Index))
}
}
fun clang_codeCompleteGetContexts(Results: CValuesRef<CXCodeCompleteResults>?): Long {
memScoped {
return kniBridge286(Results?.getPointer(memScope).rawValue)
}
}
fun clang_codeCompleteGetContainerKind(Results: CValuesRef<CXCodeCompleteResults>?, IsIncomplete: CValuesRef<IntVar>?): CXCursorKind {
memScoped {
return CXCursorKind.byValue(kniBridge287(Results?.getPointer(memScope).rawValue, IsIncomplete?.getPointer(memScope).rawValue))
}
}
fun clang_codeCompleteGetContainerUSR(Results: CValuesRef<CXCodeCompleteResults>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge288(Results?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_codeCompleteGetObjCSelector(Results: CValuesRef<CXCodeCompleteResults>?): CValue<CXString> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge289(Results?.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getClangVersion(): CValue<CXString> {
val kniRetVal = nativeHeap.alloc<CXString>()
try {
kniBridge290(kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
fun clang_toggleCrashRecovery(isEnabled: Int): Unit {
return kniBridge291(isEnabled)
}
fun clang_getInclusions(tu: CXTranslationUnit?, visitor: CXInclusionVisitor?, client_data: CXClientData?): Unit {
return kniBridge292(tu.rawValue, visitor.rawValue, client_data.rawValue)
}
fun clang_Cursor_Evaluate(C: CValue<CXCursor>): CXEvalResult? {
memScoped {
return interpretCPointer<COpaque>(kniBridge293(C.getPointer(memScope).rawValue))
}
}
fun clang_EvalResult_getKind(E: CXEvalResult?): CXEvalResultKind {
return CXEvalResultKind.byValue(kniBridge294(E.rawValue))
}
fun clang_EvalResult_getAsInt(E: CXEvalResult?): Int {
return kniBridge295(E.rawValue)
}
fun clang_EvalResult_getAsLongLong(E: CXEvalResult?): Long {
return kniBridge296(E.rawValue)
}
fun clang_EvalResult_isUnsignedInt(E: CXEvalResult?): Int {
return kniBridge297(E.rawValue)
}
fun clang_EvalResult_getAsUnsigned(E: CXEvalResult?): Long {
return kniBridge298(E.rawValue)
}
fun clang_EvalResult_getAsDouble(E: CXEvalResult?): Double {
return kniBridge299(E.rawValue)
}
fun clang_EvalResult_getAsStr(E: CXEvalResult?): CPointer<ByteVar>? {
return interpretCPointer<ByteVar>(kniBridge300(E.rawValue))
}
fun clang_EvalResult_dispose(E: CXEvalResult?): Unit {
return kniBridge301(E.rawValue)
}
fun clang_getRemappings(path: String?): CXRemapping? {
memScoped {
return interpretCPointer<COpaque>(kniBridge302(path?.cstr?.getPointer(memScope).rawValue))
}
}
fun clang_getRemappingsFromFileList(filePaths: CValuesRef<CPointerVar<ByteVar>>?, numFiles: Int): CXRemapping? {
memScoped {
return interpretCPointer<COpaque>(kniBridge303(filePaths?.getPointer(memScope).rawValue, numFiles))
}
}
fun clang_remap_getNumFiles(arg0: CXRemapping?): Int {
return kniBridge304(arg0.rawValue)
}
fun clang_remap_getFilenames(arg0: CXRemapping?, index: Int, original: CValuesRef<CXString>?, transformed: CValuesRef<CXString>?): Unit {
memScoped {
return kniBridge305(arg0.rawValue, index, original?.getPointer(memScope).rawValue, transformed?.getPointer(memScope).rawValue)
}
}
fun clang_remap_dispose(arg0: CXRemapping?): Unit {
return kniBridge306(arg0.rawValue)
}
fun clang_findReferencesInFile(cursor: CValue<CXCursor>, file: CXFile?, visitor: CValue<CXCursorAndRangeVisitor>): CXResult {
memScoped {
return CXResult.byValue(kniBridge307(cursor.getPointer(memScope).rawValue, file.rawValue, visitor.getPointer(memScope).rawValue))
}
}
fun clang_findIncludesInFile(TU: CXTranslationUnit?, file: CXFile?, visitor: CValue<CXCursorAndRangeVisitor>): CXResult {
memScoped {
return CXResult.byValue(kniBridge308(TU.rawValue, file.rawValue, visitor.getPointer(memScope).rawValue))
}
}
fun clang_index_isEntityObjCContainerKind(arg0: CXIdxEntityKind): Int {
return kniBridge309(arg0.value)
}
fun clang_index_getObjCContainerDeclInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxObjCContainerDeclInfo>? {
memScoped {
return interpretCPointer<CXIdxObjCContainerDeclInfo>(kniBridge310(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getObjCInterfaceDeclInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxObjCInterfaceDeclInfo>? {
memScoped {
return interpretCPointer<CXIdxObjCInterfaceDeclInfo>(kniBridge311(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getObjCCategoryDeclInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxObjCCategoryDeclInfo>? {
memScoped {
return interpretCPointer<CXIdxObjCCategoryDeclInfo>(kniBridge312(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getObjCProtocolRefListInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxObjCProtocolRefListInfo>? {
memScoped {
return interpretCPointer<CXIdxObjCProtocolRefListInfo>(kniBridge313(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getObjCPropertyDeclInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxObjCPropertyDeclInfo>? {
memScoped {
return interpretCPointer<CXIdxObjCPropertyDeclInfo>(kniBridge314(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getIBOutletCollectionAttrInfo(arg0: CValuesRef<CXIdxAttrInfo>?): CPointer<CXIdxIBOutletCollectionAttrInfo>? {
memScoped {
return interpretCPointer<CXIdxIBOutletCollectionAttrInfo>(kniBridge315(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getCXXClassDeclInfo(arg0: CValuesRef<CXIdxDeclInfo>?): CPointer<CXIdxCXXClassDeclInfo>? {
memScoped {
return interpretCPointer<CXIdxCXXClassDeclInfo>(kniBridge316(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_getClientContainer(arg0: CValuesRef<CXIdxContainerInfo>?): CXIdxClientContainer? {
memScoped {
return interpretCPointer<COpaque>(kniBridge317(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_setClientContainer(arg0: CValuesRef<CXIdxContainerInfo>?, arg1: CXIdxClientContainer?): Unit {
memScoped {
return kniBridge318(arg0?.getPointer(memScope).rawValue, arg1.rawValue)
}
}
fun clang_index_getClientEntity(arg0: CValuesRef<CXIdxEntityInfo>?): CXIdxClientEntity? {
memScoped {
return interpretCPointer<COpaque>(kniBridge319(arg0?.getPointer(memScope).rawValue))
}
}
fun clang_index_setClientEntity(arg0: CValuesRef<CXIdxEntityInfo>?, arg1: CXIdxClientEntity?): Unit {
memScoped {
return kniBridge320(arg0?.getPointer(memScope).rawValue, arg1.rawValue)
}
}
fun clang_IndexAction_create(CIdx: CXIndex?): CXIndexAction? {
return interpretCPointer<COpaque>(kniBridge321(CIdx.rawValue))
}
fun clang_IndexAction_dispose(arg0: CXIndexAction?): Unit {
return kniBridge322(arg0.rawValue)
}
fun clang_indexSourceFile(arg0: CXIndexAction?, client_data: CXClientData?, index_callbacks: CValuesRef<IndexerCallbacks>?, index_callbacks_size: Int, index_options: Int, source_filename: String?, command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_command_line_args: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, out_TU: CValuesRef<CXTranslationUnitVar>?, TU_options: Int): Int {
memScoped {
return kniBridge323(arg0.rawValue, client_data.rawValue, index_callbacks?.getPointer(memScope).rawValue, index_callbacks_size, index_options, source_filename?.cstr?.getPointer(memScope).rawValue, command_line_args?.getPointer(memScope).rawValue, num_command_line_args, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, out_TU?.getPointer(memScope).rawValue, TU_options)
}
}
fun clang_indexSourceFileFullArgv(arg0: CXIndexAction?, client_data: CXClientData?, index_callbacks: CValuesRef<IndexerCallbacks>?, index_callbacks_size: Int, index_options: Int, source_filename: String?, command_line_args: CValuesRef<CPointerVar<ByteVar>>?, num_command_line_args: Int, unsaved_files: CValuesRef<CXUnsavedFile>?, num_unsaved_files: Int, out_TU: CValuesRef<CXTranslationUnitVar>?, TU_options: Int): Int {
memScoped {
return kniBridge324(arg0.rawValue, client_data.rawValue, index_callbacks?.getPointer(memScope).rawValue, index_callbacks_size, index_options, source_filename?.cstr?.getPointer(memScope).rawValue, command_line_args?.getPointer(memScope).rawValue, num_command_line_args, unsaved_files?.getPointer(memScope).rawValue, num_unsaved_files, out_TU?.getPointer(memScope).rawValue, TU_options)
}
}
fun clang_indexTranslationUnit(arg0: CXIndexAction?, client_data: CXClientData?, index_callbacks: CValuesRef<IndexerCallbacks>?, index_callbacks_size: Int, index_options: Int, arg5: CXTranslationUnit?): Int {
memScoped {
return kniBridge325(arg0.rawValue, client_data.rawValue, index_callbacks?.getPointer(memScope).rawValue, index_callbacks_size, index_options, arg5.rawValue)
}
}
fun clang_indexLoc_getFileLocation(loc: CValue<CXIdxLoc>, indexFile: CValuesRef<CXIdxClientFileVar>?, file: CValuesRef<CXFileVar>?, line: CValuesRef<IntVar>?, column: CValuesRef<IntVar>?, offset: CValuesRef<IntVar>?): Unit {
memScoped {
return kniBridge326(loc.getPointer(memScope).rawValue, indexFile?.getPointer(memScope).rawValue, file?.getPointer(memScope).rawValue, line?.getPointer(memScope).rawValue, column?.getPointer(memScope).rawValue, offset?.getPointer(memScope).rawValue)
}
}
fun clang_indexLoc_getCXSourceLocation(loc: CValue<CXIdxLoc>): CValue<CXSourceLocation> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXSourceLocation>()
try {
kniBridge327(loc.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_visitFields(T: CValue<CXType>, visitor: CXFieldVisitor?, client_data: CXClientData?): Int {
memScoped {
return kniBridge328(T.getPointer(memScope).rawValue, visitor.rawValue, client_data.rawValue)
}
}
fun clang_Cursor_getAttributeSpelling(cursor: CValue<CXCursor>): CPointer<ByteVar>? {
memScoped {
return interpretCPointer<ByteVar>(kniBridge329(cursor.getPointer(memScope).rawValue))
}
}
fun clang_getDeclTypeAttributes(cursor: CValue<CXCursor>): CValue<CXTypeAttributes> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXTypeAttributes>()
try {
kniBridge330(cursor.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getResultTypeAttributes(typeAttributes: CValue<CXTypeAttributes>): CValue<CXTypeAttributes> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXTypeAttributes>()
try {
kniBridge331(typeAttributes.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_getCursorResultTypeAttributes(cursor: CValue<CXCursor>): CValue<CXTypeAttributes> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXTypeAttributes>()
try {
kniBridge332(cursor.getPointer(memScope).rawValue, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Type_getNullabilityKind(type: CValue<CXType>, attributes: CValue<CXTypeAttributes>): CXNullabilityKind {
memScoped {
return CXNullabilityKind.byValue(kniBridge333(type.getPointer(memScope).rawValue, attributes.getPointer(memScope).rawValue))
}
}
fun clang_Type_getNumProtocols(type: CValue<CXType>): Int {
memScoped {
return kniBridge334(type.getPointer(memScope).rawValue)
}
}
fun clang_Type_getProtocol(type: CValue<CXType>, index: Int): CValue<CXCursor> {
memScoped {
val kniRetVal = nativeHeap.alloc<CXCursor>()
try {
kniBridge335(type.getPointer(memScope).rawValue, index, kniRetVal.rawPtr)
return kniRetVal.readValue()
} finally { nativeHeap.free(kniRetVal) }
}
}
fun clang_Cursor_isObjCInitMethod(cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge336(cursor.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isObjCReturningRetainedMethod(cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge337(cursor.getPointer(memScope).rawValue)
}
}
fun clang_Cursor_isObjCConsumingSelfMethod(cursor: CValue<CXCursor>): Int {
memScoped {
return kniBridge338(cursor.getPointer(memScope).rawValue)
}
}
fun clang_isExtVectorType(type: CValue<CXType>): Int {
memScoped {
return kniBridge339(type.getPointer(memScope).rawValue)
}
}
val CINDEX_VERSION_MAJOR: Int get() = 0
val CINDEX_VERSION_MINOR: Int get() = 50
val CINDEX_VERSION: Int get() = 50
val CINDEX_VERSION_STRING: String get() = "0.50"
typealias CXVirtualFileOverlayVar = CPointerVarOf<CXVirtualFileOverlay>
typealias CXVirtualFileOverlay = CPointer<CXVirtualFileOverlayImpl>
typealias CXModuleMapDescriptorVar = CPointerVarOf<CXModuleMapDescriptor>
typealias CXModuleMapDescriptor = CPointer<CXModuleMapDescriptorImpl>
typealias CXIndexVar = CPointerVarOf<CXIndex>
typealias CXIndex = COpaquePointer
typealias CXTargetInfoVar = CPointerVarOf<CXTargetInfo>
typealias CXTargetInfo = CPointer<CXTargetInfoImpl>
typealias CXTranslationUnitVar = CPointerVarOf<CXTranslationUnit>
typealias CXTranslationUnit = CPointer<CXTranslationUnitImpl>
typealias CXClientDataVar = CPointerVarOf<CXClientData>
typealias CXClientData = COpaquePointer
typealias CXFileVar = CPointerVarOf<CXFile>
typealias CXFile = COpaquePointer
typealias __darwin_time_tVar = LongVarOf<__darwin_time_t>
typealias __darwin_time_t = Long
typealias time_tVar = LongVarOf<time_t>
typealias time_t = __darwin_time_t
typealias __darwin_size_tVar = LongVarOf<__darwin_size_t>
typealias __darwin_size_t = Long
typealias size_tVar = LongVarOf<size_t>
typealias size_t = __darwin_size_t
typealias CXDiagnosticVar = CPointerVarOf<CXDiagnostic>
typealias CXDiagnostic = COpaquePointer
typealias CXDiagnosticSetVar = CPointerVarOf<CXDiagnosticSet>
typealias CXDiagnosticSet = COpaquePointer
typealias CXCursorSetVar = CPointerVarOf<CXCursorSet>
typealias CXCursorSet = CPointer<CXCursorSetImpl>
typealias CXCursorVisitorVar = CPointerVarOf<CXCursorVisitor>
typealias CXCursorVisitor = CPointer<CFunction<(CValue<CXCursor>, CValue<CXCursor>, CXClientData?) -> CXChildVisitResult>>
typealias CXPrintingPolicyVar = CPointerVarOf<CXPrintingPolicy>
typealias CXPrintingPolicy = COpaquePointer
typealias CXModuleVar = CPointerVarOf<CXModule>
typealias CXModule = COpaquePointer
typealias CXCompletionStringVar = CPointerVarOf<CXCompletionString>
typealias CXCompletionString = COpaquePointer
typealias CXInclusionVisitorVar = CPointerVarOf<CXInclusionVisitor>
typealias CXInclusionVisitor = CPointer<CFunction<(CXFile?, CPointer<CXSourceLocation>?, Int, CXClientData?) -> Unit>>
typealias CXEvalResultVar = CPointerVarOf<CXEvalResult>
typealias CXEvalResult = COpaquePointer
typealias CXRemappingVar = CPointerVarOf<CXRemapping>
typealias CXRemapping = COpaquePointer
typealias CXIdxClientFileVar = CPointerVarOf<CXIdxClientFile>
typealias CXIdxClientFile = COpaquePointer
typealias CXIdxClientEntityVar = CPointerVarOf<CXIdxClientEntity>
typealias CXIdxClientEntity = COpaquePointer
typealias CXIdxClientContainerVar = CPointerVarOf<CXIdxClientContainer>
typealias CXIdxClientContainer = COpaquePointer
typealias CXIdxClientASTFileVar = CPointerVarOf<CXIdxClientASTFile>
typealias CXIdxClientASTFile = COpaquePointer
typealias CXIndexActionVar = CPointerVarOf<CXIndexAction>
typealias CXIndexAction = COpaquePointer
typealias CXFieldVisitorVar = CPointerVarOf<CXFieldVisitor>
typealias CXFieldVisitor = CPointer<CFunction<(CValue<CXCursor>, CXClientData?) -> CXVisitorResult>>
val CXGlobalOpt_None: CXGlobalOptFlags get() = 0
val CXGlobalOpt_ThreadBackgroundPriorityForIndexing: CXGlobalOptFlags get() = 1
val CXGlobalOpt_ThreadBackgroundPriorityForEditing: CXGlobalOptFlags get() = 2
val CXGlobalOpt_ThreadBackgroundPriorityForAll: CXGlobalOptFlags get() = 3
typealias CXGlobalOptFlagsVar = IntVarOf<CXGlobalOptFlags>
typealias CXGlobalOptFlags = Int
val CXDiagnostic_DisplaySourceLocation: CXDiagnosticDisplayOptions get() = 1
val CXDiagnostic_DisplayColumn: CXDiagnosticDisplayOptions get() = 2
val CXDiagnostic_DisplaySourceRanges: CXDiagnosticDisplayOptions get() = 4
val CXDiagnostic_DisplayOption: CXDiagnosticDisplayOptions get() = 8
val CXDiagnostic_DisplayCategoryId: CXDiagnosticDisplayOptions get() = 16
val CXDiagnostic_DisplayCategoryName: CXDiagnosticDisplayOptions get() = 32
typealias CXDiagnosticDisplayOptionsVar = IntVarOf<CXDiagnosticDisplayOptions>
typealias CXDiagnosticDisplayOptions = Int
val CXTranslationUnit_None: CXTranslationUnit_Flags get() = 0
val CXTranslationUnit_DetailedPreprocessingRecord: CXTranslationUnit_Flags get() = 1
val CXTranslationUnit_Incomplete: CXTranslationUnit_Flags get() = 2
val CXTranslationUnit_PrecompiledPreamble: CXTranslationUnit_Flags get() = 4
val CXTranslationUnit_CacheCompletionResults: CXTranslationUnit_Flags get() = 8
val CXTranslationUnit_ForSerialization: CXTranslationUnit_Flags get() = 16
val CXTranslationUnit_CXXChainedPCH: CXTranslationUnit_Flags get() = 32
val CXTranslationUnit_SkipFunctionBodies: CXTranslationUnit_Flags get() = 64
val CXTranslationUnit_IncludeBriefCommentsInCodeCompletion: CXTranslationUnit_Flags get() = 128
val CXTranslationUnit_CreatePreambleOnFirstParse: CXTranslationUnit_Flags get() = 256
val CXTranslationUnit_KeepGoing: CXTranslationUnit_Flags get() = 512
val CXTranslationUnit_SingleFileParse: CXTranslationUnit_Flags get() = 1024
val CXTranslationUnit_LimitSkipFunctionBodiesToPreamble: CXTranslationUnit_Flags get() = 2048
val CXTranslationUnit_IncludeAttributedTypes: CXTranslationUnit_Flags get() = 4096
val CXTranslationUnit_VisitImplicitAttributes: CXTranslationUnit_Flags get() = 8192
typealias CXTranslationUnit_FlagsVar = IntVarOf<CXTranslationUnit_Flags>
typealias CXTranslationUnit_Flags = Int
val CXSaveTranslationUnit_None: CXSaveTranslationUnit_Flags get() = 0
typealias CXSaveTranslationUnit_FlagsVar = IntVarOf<CXSaveTranslationUnit_Flags>
typealias CXSaveTranslationUnit_Flags = Int
val CXReparse_None: CXReparse_Flags get() = 0
typealias CXReparse_FlagsVar = IntVarOf<CXReparse_Flags>
typealias CXReparse_Flags = Int
val CXTLS_None: CXTLSKind get() = 0
val CXTLS_Dynamic: CXTLSKind get() = 1
val CXTLS_Static: CXTLSKind get() = 2
typealias CXTLSKindVar = IntVarOf<CXTLSKind>
typealias CXTLSKind = Int
val CXTypeNullability_NonNull: CXTypeNullabilityKind get() = 0
val CXTypeNullability_Nullable: CXTypeNullabilityKind get() = 1
val CXTypeNullability_Unspecified: CXTypeNullabilityKind get() = 2
val CXTypeNullability_Invalid: CXTypeNullabilityKind get() = 3
typealias CXTypeNullabilityKindVar = IntVarOf<CXTypeNullabilityKind>
typealias CXTypeNullabilityKind = Int
val CXTypeLayoutError_Invalid: CXTypeLayoutError get() = -1
val CXTypeLayoutError_Incomplete: CXTypeLayoutError get() = -2
val CXTypeLayoutError_Dependent: CXTypeLayoutError get() = -3
val CXTypeLayoutError_NotConstantSize: CXTypeLayoutError get() = -4
val CXTypeLayoutError_InvalidFieldName: CXTypeLayoutError get() = -5
typealias CXTypeLayoutErrorVar = IntVarOf<CXTypeLayoutError>
typealias CXTypeLayoutError = Int
val CXRefQualifier_None: CXRefQualifierKind get() = 0
val CXRefQualifier_LValue: CXRefQualifierKind get() = 1
val CXRefQualifier_RValue: CXRefQualifierKind get() = 2
typealias CXRefQualifierKindVar = IntVarOf<CXRefQualifierKind>
typealias CXRefQualifierKind = Int
val CXPrintingPolicy_Indentation: CXPrintingPolicyProperty get() = 0
val CXPrintingPolicy_SuppressSpecifiers: CXPrintingPolicyProperty get() = 1
val CXPrintingPolicy_SuppressTagKeyword: CXPrintingPolicyProperty get() = 2
val CXPrintingPolicy_IncludeTagDefinition: CXPrintingPolicyProperty get() = 3
val CXPrintingPolicy_SuppressScope: CXPrintingPolicyProperty get() = 4
val CXPrintingPolicy_SuppressUnwrittenScope: CXPrintingPolicyProperty get() = 5
val CXPrintingPolicy_SuppressInitializers: CXPrintingPolicyProperty get() = 6
val CXPrintingPolicy_ConstantArraySizeAsWritten: CXPrintingPolicyProperty get() = 7
val CXPrintingPolicy_AnonymousTagLocations: CXPrintingPolicyProperty get() = 8
val CXPrintingPolicy_SuppressStrongLifetime: CXPrintingPolicyProperty get() = 9
val CXPrintingPolicy_SuppressLifetimeQualifiers: CXPrintingPolicyProperty get() = 10
val CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors: CXPrintingPolicyProperty get() = 11
val CXPrintingPolicy_Bool: CXPrintingPolicyProperty get() = 12
val CXPrintingPolicy_Restrict: CXPrintingPolicyProperty get() = 13
val CXPrintingPolicy_Alignof: CXPrintingPolicyProperty get() = 14
val CXPrintingPolicy_UnderscoreAlignof: CXPrintingPolicyProperty get() = 15
val CXPrintingPolicy_UseVoidForZeroParams: CXPrintingPolicyProperty get() = 16
val CXPrintingPolicy_TerseOutput: CXPrintingPolicyProperty get() = 17
val CXPrintingPolicy_PolishForDeclaration: CXPrintingPolicyProperty get() = 18
val CXPrintingPolicy_Half: CXPrintingPolicyProperty get() = 19
val CXPrintingPolicy_MSWChar: CXPrintingPolicyProperty get() = 20
val CXPrintingPolicy_IncludeNewlines: CXPrintingPolicyProperty get() = 21
val CXPrintingPolicy_MSVCFormatting: CXPrintingPolicyProperty get() = 22
val CXPrintingPolicy_ConstantsAsWritten: CXPrintingPolicyProperty get() = 23
val CXPrintingPolicy_SuppressImplicitBase: CXPrintingPolicyProperty get() = 24
val CXPrintingPolicy_FullyQualifiedName: CXPrintingPolicyProperty get() = 25
val CXPrintingPolicy_LastProperty: CXPrintingPolicyProperty get() = 25
typealias CXPrintingPolicyPropertyVar = IntVarOf<CXPrintingPolicyProperty>
typealias CXPrintingPolicyProperty = Int
val CXObjCPropertyAttr_noattr: CXObjCPropertyAttrKind get() = 0
val CXObjCPropertyAttr_readonly: CXObjCPropertyAttrKind get() = 1
val CXObjCPropertyAttr_getter: CXObjCPropertyAttrKind get() = 2
val CXObjCPropertyAttr_assign: CXObjCPropertyAttrKind get() = 4
val CXObjCPropertyAttr_readwrite: CXObjCPropertyAttrKind get() = 8
val CXObjCPropertyAttr_retain: CXObjCPropertyAttrKind get() = 16
val CXObjCPropertyAttr_copy: CXObjCPropertyAttrKind get() = 32
val CXObjCPropertyAttr_nonatomic: CXObjCPropertyAttrKind get() = 64
val CXObjCPropertyAttr_setter: CXObjCPropertyAttrKind get() = 128
val CXObjCPropertyAttr_atomic: CXObjCPropertyAttrKind get() = 256
val CXObjCPropertyAttr_weak: CXObjCPropertyAttrKind get() = 512
val CXObjCPropertyAttr_strong: CXObjCPropertyAttrKind get() = 1024
val CXObjCPropertyAttr_unsafe_unretained: CXObjCPropertyAttrKind get() = 2048
val CXObjCPropertyAttr_class: CXObjCPropertyAttrKind get() = 4096
typealias CXObjCPropertyAttrKindVar = IntVarOf<CXObjCPropertyAttrKind>
typealias CXObjCPropertyAttrKind = Int
val CXObjCDeclQualifier_None: CXObjCDeclQualifierKind get() = 0
val CXObjCDeclQualifier_In: CXObjCDeclQualifierKind get() = 1
val CXObjCDeclQualifier_Inout: CXObjCDeclQualifierKind get() = 2
val CXObjCDeclQualifier_Out: CXObjCDeclQualifierKind get() = 4
val CXObjCDeclQualifier_Bycopy: CXObjCDeclQualifierKind get() = 8
val CXObjCDeclQualifier_Byref: CXObjCDeclQualifierKind get() = 16
val CXObjCDeclQualifier_Oneway: CXObjCDeclQualifierKind get() = 32
typealias CXObjCDeclQualifierKindVar = IntVarOf<CXObjCDeclQualifierKind>
typealias CXObjCDeclQualifierKind = Int
val CXNameRange_WantQualifier: CXNameRefFlags get() = 1
val CXNameRange_WantTemplateArgs: CXNameRefFlags get() = 2
val CXNameRange_WantSinglePiece: CXNameRefFlags get() = 4
typealias CXNameRefFlagsVar = IntVarOf<CXNameRefFlags>
typealias CXNameRefFlags = Int
val CXCodeComplete_IncludeMacros: CXCodeComplete_Flags get() = 1
val CXCodeComplete_IncludeCodePatterns: CXCodeComplete_Flags get() = 2
val CXCodeComplete_IncludeBriefComments: CXCodeComplete_Flags get() = 4
val CXCodeComplete_SkipPreamble: CXCodeComplete_Flags get() = 8
val CXCodeComplete_IncludeCompletionsWithFixIts: CXCodeComplete_Flags get() = 16
typealias CXCodeComplete_FlagsVar = IntVarOf<CXCodeComplete_Flags>
typealias CXCodeComplete_Flags = Int
val CXCompletionContext_Unexposed: CXCompletionContext get() = 0
val CXCompletionContext_AnyType: CXCompletionContext get() = 1
val CXCompletionContext_AnyValue: CXCompletionContext get() = 2
val CXCompletionContext_ObjCObjectValue: CXCompletionContext get() = 4
val CXCompletionContext_ObjCSelectorValue: CXCompletionContext get() = 8
val CXCompletionContext_CXXClassTypeValue: CXCompletionContext get() = 16
val CXCompletionContext_DotMemberAccess: CXCompletionContext get() = 32
val CXCompletionContext_ArrowMemberAccess: CXCompletionContext get() = 64
val CXCompletionContext_ObjCPropertyAccess: CXCompletionContext get() = 128
val CXCompletionContext_EnumTag: CXCompletionContext get() = 256
val CXCompletionContext_UnionTag: CXCompletionContext get() = 512
val CXCompletionContext_StructTag: CXCompletionContext get() = 1024
val CXCompletionContext_ClassTag: CXCompletionContext get() = 2048
val CXCompletionContext_Namespace: CXCompletionContext get() = 4096
val CXCompletionContext_NestedNameSpecifier: CXCompletionContext get() = 8192
val CXCompletionContext_ObjCInterface: CXCompletionContext get() = 16384
val CXCompletionContext_ObjCProtocol: CXCompletionContext get() = 32768
val CXCompletionContext_ObjCCategory: CXCompletionContext get() = 65536
val CXCompletionContext_ObjCInstanceMessage: CXCompletionContext get() = 131072
val CXCompletionContext_ObjCClassMessage: CXCompletionContext get() = 262144
val CXCompletionContext_ObjCSelectorName: CXCompletionContext get() = 524288
val CXCompletionContext_MacroName: CXCompletionContext get() = 1048576
val CXCompletionContext_NaturalLanguage: CXCompletionContext get() = 2097152
val CXCompletionContext_IncludedFile: CXCompletionContext get() = 4194304
val CXCompletionContext_Unknown: CXCompletionContext get() = 8388607
typealias CXCompletionContextVar = IntVarOf<CXCompletionContext>
typealias CXCompletionContext = Int
val CXIdxEntityLang_None: CXIdxEntityLanguage get() = 0
val CXIdxEntityLang_C: CXIdxEntityLanguage get() = 1
val CXIdxEntityLang_ObjC: CXIdxEntityLanguage get() = 2
val CXIdxEntityLang_CXX: CXIdxEntityLanguage get() = 3
val CXIdxEntityLang_Swift: CXIdxEntityLanguage get() = 4
typealias CXIdxEntityLanguageVar = IntVarOf<CXIdxEntityLanguage>
typealias CXIdxEntityLanguage = Int
val CXIdxEntity_NonTemplate: CXIdxEntityCXXTemplateKind get() = 0
val CXIdxEntity_Template: CXIdxEntityCXXTemplateKind get() = 1
val CXIdxEntity_TemplatePartialSpecialization: CXIdxEntityCXXTemplateKind get() = 2
val CXIdxEntity_TemplateSpecialization: CXIdxEntityCXXTemplateKind get() = 3
typealias CXIdxEntityCXXTemplateKindVar = IntVarOf<CXIdxEntityCXXTemplateKind>
typealias CXIdxEntityCXXTemplateKind = Int
val CXIdxAttr_Unexposed: CXIdxAttrKind get() = 0
val CXIdxAttr_IBAction: CXIdxAttrKind get() = 1
val CXIdxAttr_IBOutlet: CXIdxAttrKind get() = 2
val CXIdxAttr_IBOutletCollection: CXIdxAttrKind get() = 3
typealias CXIdxAttrKindVar = IntVarOf<CXIdxAttrKind>
typealias CXIdxAttrKind = Int
val CXIdxDeclFlag_Skipped: CXIdxDeclInfoFlags get() = 1
typealias CXIdxDeclInfoFlagsVar = IntVarOf<CXIdxDeclInfoFlags>
typealias CXIdxDeclInfoFlags = Int
val CXIdxObjCContainer_ForwardRef: CXIdxObjCContainerKind get() = 0
val CXIdxObjCContainer_Interface: CXIdxObjCContainerKind get() = 1
val CXIdxObjCContainer_Implementation: CXIdxObjCContainerKind get() = 2
typealias CXIdxObjCContainerKindVar = IntVarOf<CXIdxObjCContainerKind>
typealias CXIdxObjCContainerKind = Int
val CXIdxEntityRef_Direct: CXIdxEntityRefKind get() = 1
val CXIdxEntityRef_Implicit: CXIdxEntityRefKind get() = 2
typealias CXIdxEntityRefKindVar = IntVarOf<CXIdxEntityRefKind>
typealias CXIdxEntityRefKind = Int
val CXSymbolRole_None: CXSymbolRole get() = 0
val CXSymbolRole_Declaration: CXSymbolRole get() = 1
val CXSymbolRole_Definition: CXSymbolRole get() = 2
val CXSymbolRole_Reference: CXSymbolRole get() = 4
val CXSymbolRole_Read: CXSymbolRole get() = 8
val CXSymbolRole_Write: CXSymbolRole get() = 16
val CXSymbolRole_Call: CXSymbolRole get() = 32
val CXSymbolRole_Dynamic: CXSymbolRole get() = 64
val CXSymbolRole_AddressOf: CXSymbolRole get() = 128
val CXSymbolRole_Implicit: CXSymbolRole get() = 256
typealias CXSymbolRoleVar = IntVarOf<CXSymbolRole>
typealias CXSymbolRole = Int
val CXIndexOpt_None: CXIndexOptFlags get() = 0
val CXIndexOpt_SuppressRedundantRefs: CXIndexOptFlags get() = 1
val CXIndexOpt_IndexFunctionLocalSymbols: CXIndexOptFlags get() = 2
val CXIndexOpt_IndexImplicitTemplateInstantiations: CXIndexOptFlags get() = 4
val CXIndexOpt_SuppressWarnings: CXIndexOptFlags get() = 8
val CXIndexOpt_SkipParsedBodiesInSession: CXIndexOptFlags get() = 16
typealias CXIndexOptFlagsVar = IntVarOf<CXIndexOptFlags>
typealias CXIndexOptFlags = Int
private external fun kniBridge0(p0: NativePtr): NativePtr
private external fun kniBridge1(p0: NativePtr): Unit
private external fun kniBridge2(p0: NativePtr): Unit
private external fun kniBridge3(): Long
private external fun kniBridge4(p0: Int): NativePtr
private external fun kniBridge5(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge6(p0: NativePtr, p1: Int): Int
private external fun kniBridge7(p0: NativePtr, p1: Int, p2: NativePtr, p3: NativePtr): Int
private external fun kniBridge8(p0: NativePtr): Unit
private external fun kniBridge9(p0: NativePtr): Unit
private external fun kniBridge10(p0: Int): NativePtr
private external fun kniBridge11(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge12(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge13(p0: NativePtr, p1: Int, p2: NativePtr, p3: NativePtr): Int
private external fun kniBridge14(p0: NativePtr): Unit
private external fun kniBridge15(p0: Int, p1: Int): NativePtr
private external fun kniBridge16(p0: NativePtr): Unit
private external fun kniBridge17(p0: NativePtr, p1: Int): Unit
private external fun kniBridge18(p0: NativePtr): Int
private external fun kniBridge19(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge20(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge21(p0: NativePtr): Long
private external fun kniBridge22(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge23(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge24(p0: NativePtr, p1: NativePtr): NativePtr
private external fun kniBridge25(p0: NativePtr, p1: NativePtr, p2: NativePtr): NativePtr
private external fun kniBridge26(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge27(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge28(p0: NativePtr): Unit
private external fun kniBridge29(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge30(p0: NativePtr, p1: NativePtr, p2: Int, p3: Int, p4: NativePtr): Unit
private external fun kniBridge31(p0: NativePtr, p1: NativePtr, p2: Int, p3: NativePtr): Unit
private external fun kniBridge32(p0: NativePtr): Int
private external fun kniBridge33(p0: NativePtr): Int
private external fun kniBridge34(p0: NativePtr): Unit
private external fun kniBridge35(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge36(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge37(p0: NativePtr): Int
private external fun kniBridge38(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr): Unit
private external fun kniBridge39(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr): Unit
private external fun kniBridge40(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr): Unit
private external fun kniBridge41(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr): Unit
private external fun kniBridge42(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr): Unit
private external fun kniBridge43(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge44(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge45(p0: NativePtr, p1: NativePtr): NativePtr
private external fun kniBridge46(p0: NativePtr): NativePtr
private external fun kniBridge47(p0: NativePtr): Unit
private external fun kniBridge48(p0: NativePtr): Int
private external fun kniBridge49(p0: NativePtr, p1: Int): NativePtr
private external fun kniBridge50(p0: NativePtr, p1: NativePtr, p2: NativePtr): NativePtr
private external fun kniBridge51(p0: NativePtr): Unit
private external fun kniBridge52(p0: NativePtr): NativePtr
private external fun kniBridge53(p0: NativePtr): Int
private external fun kniBridge54(p0: NativePtr, p1: Int): NativePtr
private external fun kniBridge55(p0: NativePtr): NativePtr
private external fun kniBridge56(p0: NativePtr): Unit
private external fun kniBridge57(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge58(): Int
private external fun kniBridge59(p0: NativePtr): Int
private external fun kniBridge60(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge61(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge62(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge63(p0: NativePtr): Int
private external fun kniBridge64(p0: Int, p1: NativePtr): Unit
private external fun kniBridge65(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge66(p0: NativePtr): Int
private external fun kniBridge67(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge68(p0: NativePtr): Int
private external fun kniBridge69(p0: NativePtr, p1: Int, p2: NativePtr, p3: NativePtr): Unit
private external fun kniBridge70(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge71(p0: NativePtr, p1: NativePtr, p2: Int, p3: NativePtr, p4: Int, p5: NativePtr): NativePtr
private external fun kniBridge72(p0: NativePtr, p1: NativePtr): NativePtr
private external fun kniBridge73(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge74(): Int
private external fun kniBridge75(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: NativePtr, p5: Int, p6: Int): NativePtr
private external fun kniBridge76(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: NativePtr, p5: Int, p6: Int, p7: NativePtr): Int
private external fun kniBridge77(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: NativePtr, p5: Int, p6: Int, p7: NativePtr): Int
private external fun kniBridge78(p0: NativePtr): Int
private external fun kniBridge79(p0: NativePtr, p1: NativePtr, p2: Int): Int
private external fun kniBridge80(p0: NativePtr): Int
private external fun kniBridge81(p0: NativePtr): Unit
private external fun kniBridge82(p0: NativePtr): Int
private external fun kniBridge83(p0: NativePtr, p1: Int, p2: NativePtr, p3: Int): Int
private external fun kniBridge84(p0: Int): NativePtr
private external fun kniBridge85(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge86(p0: NativePtr): Unit
private external fun kniBridge87(p0: NativePtr): NativePtr
private external fun kniBridge88(p0: NativePtr): Unit
private external fun kniBridge89(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge90(p0: NativePtr): Int
private external fun kniBridge91(p0: NativePtr): Unit
private external fun kniBridge92(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge93(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge94(p0: NativePtr): Int
private external fun kniBridge95(p0: NativePtr): Int
private external fun kniBridge96(p0: NativePtr): Int
private external fun kniBridge97(p0: Int): Int
private external fun kniBridge98(p0: NativePtr): Int
private external fun kniBridge99(p0: Int): Int
private external fun kniBridge100(p0: Int): Int
private external fun kniBridge101(p0: Int): Int
private external fun kniBridge102(p0: Int): Int
private external fun kniBridge103(p0: NativePtr): Int
private external fun kniBridge104(p0: Int): Int
private external fun kniBridge105(p0: Int): Int
private external fun kniBridge106(p0: Int): Int
private external fun kniBridge107(p0: Int): Int
private external fun kniBridge108(p0: NativePtr): Int
private external fun kniBridge109(p0: NativePtr): Int
private external fun kniBridge110(p0: NativePtr): Int
private external fun kniBridge111(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr, p5: NativePtr, p6: Int): Int
private external fun kniBridge112(p0: NativePtr): Unit
private external fun kniBridge113(p0: NativePtr): Int
private external fun kniBridge114(p0: NativePtr): Int
private external fun kniBridge115(p0: NativePtr): NativePtr
private external fun kniBridge116(): NativePtr
private external fun kniBridge117(p0: NativePtr): Unit
private external fun kniBridge118(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge119(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge120(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge121(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge122(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge123(p0: NativePtr): Unit
private external fun kniBridge124(p0: NativePtr): NativePtr
private external fun kniBridge125(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge126(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge127(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge128(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge129(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge130(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge131(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge132(p0: NativePtr): Long
private external fun kniBridge133(p0: NativePtr): Long
private external fun kniBridge134(p0: NativePtr): Int
private external fun kniBridge135(p0: NativePtr): Int
private external fun kniBridge136(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge137(p0: NativePtr): Int
private external fun kniBridge138(p0: NativePtr, p1: Int): Int
private external fun kniBridge139(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge140(p0: NativePtr, p1: Int): Long
private external fun kniBridge141(p0: NativePtr, p1: Int): Long
private external fun kniBridge142(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge143(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge144(p0: NativePtr): Int
private external fun kniBridge145(p0: NativePtr): Int
private external fun kniBridge146(p0: NativePtr): Int
private external fun kniBridge147(p0: NativePtr): Int
private external fun kniBridge148(p0: NativePtr): Int
private external fun kniBridge149(p0: NativePtr): Int
private external fun kniBridge150(p0: NativePtr): Int
private external fun kniBridge151(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge152(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge153(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge154(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge155(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge156(p0: Int, p1: NativePtr): Unit
private external fun kniBridge157(p0: NativePtr): Int
private external fun kniBridge158(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge159(p0: NativePtr): Int
private external fun kniBridge160(p0: NativePtr): Int
private external fun kniBridge161(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge162(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge163(p0: NativePtr): Int
private external fun kniBridge164(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge165(p0: NativePtr): Int
private external fun kniBridge166(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge167(p0: NativePtr): Int
private external fun kniBridge168(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge169(p0: NativePtr): Int
private external fun kniBridge170(p0: NativePtr): Int
private external fun kniBridge171(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge172(p0: NativePtr): Long
private external fun kniBridge173(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge174(p0: NativePtr): Long
private external fun kniBridge175(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge176(p0: NativePtr): Int
private external fun kniBridge177(p0: NativePtr): Int
private external fun kniBridge178(p0: NativePtr): Long
private external fun kniBridge179(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge180(p0: NativePtr): Long
private external fun kniBridge181(p0: NativePtr, p1: NativePtr): Long
private external fun kniBridge182(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge183(p0: NativePtr): Long
private external fun kniBridge184(p0: NativePtr): Int
private external fun kniBridge185(p0: NativePtr): Int
private external fun kniBridge186(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge187(p0: NativePtr): Int
private external fun kniBridge188(p0: NativePtr): Int
private external fun kniBridge189(p0: NativePtr): Int
private external fun kniBridge190(p0: NativePtr): Int
private external fun kniBridge191(p0: NativePtr): Int
private external fun kniBridge192(p0: NativePtr): Int
private external fun kniBridge193(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge194(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge195(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge196(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge197(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge198(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge199(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge200(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge201(p0: NativePtr, p1: Int, p2: NativePtr, p3: NativePtr): Unit
private external fun kniBridge202(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge203(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge204(p0: NativePtr, p1: Int, p2: Int, p3: NativePtr): Unit
private external fun kniBridge205(p0: NativePtr, p1: Int): Int
private external fun kniBridge206(p0: NativePtr, p1: Int, p2: Int): Unit
private external fun kniBridge207(p0: NativePtr): NativePtr
private external fun kniBridge208(p0: NativePtr): Unit
private external fun kniBridge209(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge210(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge211(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge212(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge213(p0: NativePtr): Int
private external fun kniBridge214(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge215(p0: NativePtr): Int
private external fun kniBridge216(p0: NativePtr): Int
private external fun kniBridge217(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge218(p0: NativePtr, p1: Int): Int
private external fun kniBridge219(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge220(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge221(p0: NativePtr): Int
private external fun kniBridge222(p0: NativePtr): Int
private external fun kniBridge223(p0: NativePtr): Int
private external fun kniBridge224(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr): Int
private external fun kniBridge225(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge226(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge227(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge228(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge229(p0: NativePtr): NativePtr
private external fun kniBridge230(p0: NativePtr): NativePtr
private external fun kniBridge231(p0: NativePtr): NativePtr
private external fun kniBridge232(p0: NativePtr, p1: NativePtr): NativePtr
private external fun kniBridge233(p0: NativePtr): NativePtr
private external fun kniBridge234(p0: NativePtr): NativePtr
private external fun kniBridge235(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge236(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge237(p0: NativePtr): Int
private external fun kniBridge238(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge239(p0: NativePtr, p1: NativePtr, p2: Int): NativePtr
private external fun kniBridge240(p0: NativePtr): Int
private external fun kniBridge241(p0: NativePtr): Int
private external fun kniBridge242(p0: NativePtr): Int
private external fun kniBridge243(p0: NativePtr): Int
private external fun kniBridge244(p0: NativePtr): Int
private external fun kniBridge245(p0: NativePtr): Int
private external fun kniBridge246(p0: NativePtr): Int
private external fun kniBridge247(p0: NativePtr): Int
private external fun kniBridge248(p0: NativePtr): Int
private external fun kniBridge249(p0: NativePtr): Int
private external fun kniBridge250(p0: NativePtr): Int
private external fun kniBridge251(p0: NativePtr): Int
private external fun kniBridge252(p0: NativePtr): Int
private external fun kniBridge253(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge254(p0: NativePtr, p1: Int, p2: Int, p3: NativePtr): Unit
private external fun kniBridge255(p0: NativePtr, p1: NativePtr): NativePtr
private external fun kniBridge256(p0: NativePtr): Int
private external fun kniBridge257(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge258(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge259(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge260(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr): Unit
private external fun kniBridge261(p0: NativePtr, p1: NativePtr, p2: Int, p3: NativePtr): Unit
private external fun kniBridge262(p0: NativePtr, p1: NativePtr, p2: Int): Unit
private external fun kniBridge263(p0: Int, p1: NativePtr): Unit
private external fun kniBridge264(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr, p5: NativePtr, p6: NativePtr): Unit
private external fun kniBridge265(): Unit
private external fun kniBridge266(p0: NativePtr, p1: NativePtr, p2: Int): Unit
private external fun kniBridge267(p0: NativePtr, p1: Int): Int
private external fun kniBridge268(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge269(p0: NativePtr, p1: Int): NativePtr
private external fun kniBridge270(p0: NativePtr): Int
private external fun kniBridge271(p0: NativePtr): Int
private external fun kniBridge272(p0: NativePtr): Int
private external fun kniBridge273(p0: NativePtr): Int
private external fun kniBridge274(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge275(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge276(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge277(p0: NativePtr): NativePtr
private external fun kniBridge278(p0: NativePtr, p1: Int): Int
private external fun kniBridge279(p0: NativePtr, p1: Int, p2: Int, p3: NativePtr, p4: NativePtr): Unit
private external fun kniBridge280(): Int
private external fun kniBridge281(p0: NativePtr, p1: NativePtr, p2: Int, p3: Int, p4: NativePtr, p5: Int, p6: Int): NativePtr
private external fun kniBridge282(p0: NativePtr, p1: Int): Unit
private external fun kniBridge283(p0: NativePtr): Unit
private external fun kniBridge284(p0: NativePtr): Int
private external fun kniBridge285(p0: NativePtr, p1: Int): NativePtr
private external fun kniBridge286(p0: NativePtr): Long
private external fun kniBridge287(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge288(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge289(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge290(p0: NativePtr): Unit
private external fun kniBridge291(p0: Int): Unit
private external fun kniBridge292(p0: NativePtr, p1: NativePtr, p2: NativePtr): Unit
private external fun kniBridge293(p0: NativePtr): NativePtr
private external fun kniBridge294(p0: NativePtr): Int
private external fun kniBridge295(p0: NativePtr): Int
private external fun kniBridge296(p0: NativePtr): Long
private external fun kniBridge297(p0: NativePtr): Int
private external fun kniBridge298(p0: NativePtr): Long
private external fun kniBridge299(p0: NativePtr): Double
private external fun kniBridge300(p0: NativePtr): NativePtr
private external fun kniBridge301(p0: NativePtr): Unit
private external fun kniBridge302(p0: NativePtr): NativePtr
private external fun kniBridge303(p0: NativePtr, p1: Int): NativePtr
private external fun kniBridge304(p0: NativePtr): Int
private external fun kniBridge305(p0: NativePtr, p1: Int, p2: NativePtr, p3: NativePtr): Unit
private external fun kniBridge306(p0: NativePtr): Unit
private external fun kniBridge307(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge308(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge309(p0: Int): Int
private external fun kniBridge310(p0: NativePtr): NativePtr
private external fun kniBridge311(p0: NativePtr): NativePtr
private external fun kniBridge312(p0: NativePtr): NativePtr
private external fun kniBridge313(p0: NativePtr): NativePtr
private external fun kniBridge314(p0: NativePtr): NativePtr
private external fun kniBridge315(p0: NativePtr): NativePtr
private external fun kniBridge316(p0: NativePtr): NativePtr
private external fun kniBridge317(p0: NativePtr): NativePtr
private external fun kniBridge318(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge319(p0: NativePtr): NativePtr
private external fun kniBridge320(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge321(p0: NativePtr): NativePtr
private external fun kniBridge322(p0: NativePtr): Unit
private external fun kniBridge323(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: Int, p5: NativePtr, p6: NativePtr, p7: Int, p8: NativePtr, p9: Int, p10: NativePtr, p11: Int): Int
private external fun kniBridge324(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: Int, p5: NativePtr, p6: NativePtr, p7: Int, p8: NativePtr, p9: Int, p10: NativePtr, p11: Int): Int
private external fun kniBridge325(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: Int, p4: Int, p5: NativePtr): Int
private external fun kniBridge326(p0: NativePtr, p1: NativePtr, p2: NativePtr, p3: NativePtr, p4: NativePtr, p5: NativePtr): Unit
private external fun kniBridge327(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge328(p0: NativePtr, p1: NativePtr, p2: NativePtr): Int
private external fun kniBridge329(p0: NativePtr): NativePtr
private external fun kniBridge330(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge331(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge332(p0: NativePtr, p1: NativePtr): Unit
private external fun kniBridge333(p0: NativePtr, p1: NativePtr): Int
private external fun kniBridge334(p0: NativePtr): Int
private external fun kniBridge335(p0: NativePtr, p1: Int, p2: NativePtr): Unit
private external fun kniBridge336(p0: NativePtr): Int
private external fun kniBridge337(p0: NativePtr): Int
private external fun kniBridge338(p0: NativePtr): Int
private external fun kniBridge339(p0: NativePtr): Int
private val loadLibrary = loadKonanLibrary("clangstubs")
| apache-2.0 | 4ac7c288364daeaa562cfef7d146272f | 36.222903 | 420 | 0.722573 | 3.893995 | false | false | false | false |
JetBrains/kotlin-native | endorsedLibraries/kotlinx.cli/src/main/kotlin/kotlinx/cli/Options.kt | 4 | 10776 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlinx.cli
/**
* Base interface for all possible types of options with multiple values.
* Provides limitations for API that is accessible for options with several values.
* Allows to save the way of providing several values in command line.
*
* @see [MultipleOption]
*/
interface MultipleOptionType {
/**
* Type of an option with multiple values allowed to be provided several times in command line.
*/
class Repeated : MultipleOptionType
/**
* Type of an option with multiple values allowed to be provided using delimiter in one command line value.
*/
class Delimited : MultipleOptionType
/**
* Type of an option with multiple values allowed to be provided several times in command line
* both with specifying several values and with delimiter.
*/
class RepeatedDelimited : MultipleOptionType
}
/**
* The base class for command line options.
*
* You can use [ArgParser.option] function to declare an option.
*/
abstract class Option<TResult> internal constructor(delegate: ArgumentValueDelegate<TResult>,
owner: CLIEntityWrapper) : CLIEntity<TResult>(delegate, owner)
/**
* The base class of an option with a single value.
*
* A required option or an option with a default value is represented with the [SingleOption] inheritor.
* An option having nullable value is represented with the [SingleNullableOption] inheritor.
*/
abstract class AbstractSingleOption<T : Any, TResult, DefaultRequired: DefaultRequiredType> internal constructor(
delegate: ArgumentValueDelegate<TResult>,
owner: CLIEntityWrapper) :
Option<TResult>(delegate, owner) {
/**
* Check descriptor for this kind of option.
*/
internal fun checkDescriptor(descriptor: OptionDescriptor<*, *>) {
if (descriptor.multiple || descriptor.delimiter != null) {
failAssertion("Option with single value can't be initialized with descriptor for multiple values.")
}
}
}
/**
* A required option or an option with a default value.
*
* The [value] of such option is non-null.
*/
class SingleOption<T : Any, DefaultType: DefaultRequiredType> internal constructor(descriptor: OptionDescriptor<T, T>,
owner: CLIEntityWrapper) :
AbstractSingleOption<T, T, DefaultRequiredType>(ArgumentSingleValue(descriptor), owner) {
init {
checkDescriptor(descriptor)
}
}
/**
* An option with nullable [value].
*/
class SingleNullableOption<T : Any> internal constructor(descriptor: OptionDescriptor<T, T>, owner: CLIEntityWrapper) :
AbstractSingleOption<T, T?, DefaultRequiredType.None>(ArgumentSingleNullableValue(descriptor), owner) {
init {
checkDescriptor(descriptor)
}
}
/**
* An option that allows several values to be provided in command line string.
*
* The [value] property of such option has type `List<T>`.
*/
class MultipleOption<T : Any, OptionType : MultipleOptionType, DefaultType: DefaultRequiredType> internal constructor(
descriptor: OptionDescriptor<T, List<T>>,
owner: CLIEntityWrapper
) :
Option<List<T>>( ArgumentMultipleValues(descriptor), owner) {
init {
if (!descriptor.multiple && descriptor.delimiter == null) {
failAssertion("Option with multiple values can't be initialized with descriptor for single one.")
}
}
}
/**
* Allows the option to have several values specified in command line string.
* Number of values is unlimited.
*/
fun <T : Any, TResult, DefaultType: DefaultRequiredType> AbstractSingleOption<T, TResult, DefaultType>.multiple():
MultipleOption<T, MultipleOptionType.Repeated, DefaultType> {
val newOption = with((delegate.cast<ParsingValue<T, T>>()).descriptor as OptionDescriptor) {
MultipleOption<T, MultipleOptionType.Repeated, DefaultType>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, listOfNotNull(defaultValue),
required, true, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Allows the option to have several values specified in command line string.
* Number of values is unlimited.
*/
fun <T : Any, DefaultType: DefaultRequiredType> MultipleOption<T, MultipleOptionType.Delimited, DefaultType>.multiple():
MultipleOption<T, MultipleOptionType.RepeatedDelimited, DefaultRequiredType> {
val newOption = with((delegate.cast<ParsingValue<T, List<T>>>()).descriptor as OptionDescriptor) {
if (multiple) {
error("Try to use modifier multiple() twice on option ${fullName ?: ""}")
}
MultipleOption<T, MultipleOptionType.RepeatedDelimited, DefaultRequiredType>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, defaultValue?.toList() ?: listOf(),
required, true, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Specifies the default value for the option, that will be used when no value is provided for it
* in command line string.
*
* @param value the default value.
*/
fun <T : Any> SingleNullableOption<T>.default(value: T): SingleOption<T, DefaultRequiredType.Default> {
val newOption = with((delegate.cast<ParsingValue<T, T>>()).descriptor as OptionDescriptor) {
SingleOption<T, DefaultRequiredType.Default>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, value, required, multiple, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Specifies the default value for the option with multiple values, that will be used when no values are provided
* for it in command line string.
*
* @param value the default value, must be a non-empty collection.
* @throws IllegalArgumentException if provided default value is empty collection.
*/
fun <T : Any, OptionType : MultipleOptionType>
MultipleOption<T, OptionType, DefaultRequiredType.None>.default(value: Collection<T>):
MultipleOption<T, OptionType, DefaultRequiredType.Default> {
val newOption = with((delegate.cast<ParsingValue<T, List<T>>>()).descriptor as OptionDescriptor) {
require(value.isNotEmpty()) { "Default value for option can't be empty collection." }
MultipleOption<T, OptionType, DefaultRequiredType.Default>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName,
shortName, description, value.toList(),
required, multiple, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Requires the option to be always provided in command line.
*/
fun <T : Any> SingleNullableOption<T>.required(): SingleOption<T, DefaultRequiredType.Required> {
val newOption = with((delegate.cast<ParsingValue<T, T>>()).descriptor as OptionDescriptor) {
SingleOption<T, DefaultRequiredType.Required>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName,
shortName, description, defaultValue,
true, multiple, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Requires the option to be always provided in command line.
*/
fun <T : Any, OptionType : MultipleOptionType>
MultipleOption<T, OptionType, DefaultRequiredType.None>.required():
MultipleOption<T, OptionType, DefaultRequiredType.Required> {
val newOption = with((delegate.cast<ParsingValue<T, List<T>>>()).descriptor as OptionDescriptor) {
MultipleOption<T, OptionType, DefaultRequiredType.Required>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, defaultValue?.toList() ?: listOf(),
true, multiple, delimiter, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Allows the option to have several values joined with [delimiter] specified in command line string.
* Number of values is unlimited.
*
* The value of the argument is an empty list in case if no value was specified in command line string.
*
* @param delimiterValue delimiter used to separate string value to option values list.
*/
fun <T : Any, DefaultRequired: DefaultRequiredType> AbstractSingleOption<T, *, DefaultRequired>.delimiter(
delimiterValue: String):
MultipleOption<T, MultipleOptionType.Delimited, DefaultRequired> {
val newOption = with((delegate.cast<ParsingValue<T, T>>()).descriptor as OptionDescriptor) {
MultipleOption<T, MultipleOptionType.Delimited, DefaultRequired>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, listOfNotNull(defaultValue),
required, multiple, delimiterValue, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
}
/**
* Allows the option to have several values joined with [delimiter] specified in command line string.
* Number of values is unlimited.
*
* The value of the argument is an empty list in case if no value was specified in command line string.
*
* @param delimiterValue delimiter used to separate string value to option values list.
*/
fun <T : Any, DefaultRequired: DefaultRequiredType> MultipleOption<T, MultipleOptionType.Repeated, DefaultRequired>.delimiter(
delimiterValue: String):
MultipleOption<T, MultipleOptionType.RepeatedDelimited, DefaultRequired> {
val newOption = with((delegate.cast<ParsingValue<T, List<T>>>()).descriptor as OptionDescriptor) {
MultipleOption<T, MultipleOptionType.RepeatedDelimited, DefaultRequired>(
OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName,
description, defaultValue?.toList() ?: listOf(),
required, multiple, delimiterValue, deprecatedWarning
), owner
)
}
owner.entity = newOption
return newOption
} | apache-2.0 | c390d6d5968b0c8f12f801a72d5b5b92 | 39.515038 | 126 | 0.686433 | 4.749229 | false | false | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/extensions/Context.kt | 1 | 42574 | package com.simplemobiletools.gallery.pro.extensions
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.drawable.PictureDrawable
import android.media.AudioManager
import android.os.Process
import android.provider.MediaStore.Files
import android.provider.MediaStore.Images
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.views.MySquareImageView
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask
import com.simplemobiletools.gallery.pro.databases.GalleryDatabase
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.interfaces.*
import com.simplemobiletools.gallery.pro.models.*
import com.simplemobiletools.gallery.pro.svg.SvgSoftwareLayerSetter
import com.squareup.picasso.Picasso
import pl.droidsonroids.gif.GifDrawable
import java.io.File
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import kotlin.collections.set
val Context.audioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager
fun Context.getHumanizedFilename(path: String): String {
val humanized = humanizePath(path)
return humanized.substring(humanized.lastIndexOf("/") + 1)
}
val Context.config: Config get() = Config.newInstance(applicationContext)
val Context.widgetsDB: WidgetsDao get() = GalleryDatabase.getInstance(applicationContext).WidgetsDao()
val Context.mediaDB: MediumDao get() = GalleryDatabase.getInstance(applicationContext).MediumDao()
val Context.directoryDB: DirectoryDao get() = GalleryDatabase.getInstance(applicationContext).DirectoryDao()
val Context.favoritesDB: FavoritesDao get() = GalleryDatabase.getInstance(applicationContext).FavoritesDao()
val Context.dateTakensDB: DateTakensDao get() = GalleryDatabase.getInstance(applicationContext).DateTakensDao()
val Context.recycleBin: File get() = filesDir
fun Context.movePinnedDirectoriesToFront(dirs: ArrayList<Directory>): ArrayList<Directory> {
val foundFolders = ArrayList<Directory>()
val pinnedFolders = config.pinnedFolders
dirs.forEach {
if (pinnedFolders.contains(it.path)) {
foundFolders.add(it)
}
}
dirs.removeAll(foundFolders)
dirs.addAll(0, foundFolders)
if (config.tempFolderPath.isNotEmpty()) {
val newFolder = dirs.firstOrNull { it.path == config.tempFolderPath }
if (newFolder != null) {
dirs.remove(newFolder)
dirs.add(0, newFolder)
}
}
if (config.showRecycleBinAtFolders && config.showRecycleBinLast) {
val binIndex = dirs.indexOfFirst { it.isRecycleBin() }
if (binIndex != -1) {
val bin = dirs.removeAt(binIndex)
dirs.add(bin)
}
}
return dirs
}
@Suppress("UNCHECKED_CAST")
fun Context.getSortedDirectories(source: ArrayList<Directory>): ArrayList<Directory> {
val sorting = config.directorySorting
val dirs = source.clone() as ArrayList<Directory>
if (sorting and SORT_BY_RANDOM != 0) {
dirs.shuffle()
return movePinnedDirectoriesToFront(dirs)
} else if (sorting and SORT_BY_CUSTOM != 0) {
val newDirsOrdered = ArrayList<Directory>()
config.customFoldersOrder.split("|||").forEach { path ->
val index = dirs.indexOfFirst { it.path == path }
if (index != -1) {
val dir = dirs.removeAt(index)
newDirsOrdered.add(dir)
}
}
dirs.mapTo(newDirsOrdered, { it })
return newDirsOrdered
}
dirs.sortWith(Comparator { o1, o2 ->
o1 as Directory
o2 as Directory
var result = when {
sorting and SORT_BY_NAME != 0 -> {
if (o1.sortValue.isEmpty()) {
o1.sortValue = o1.name.toLowerCase()
}
if (o2.sortValue.isEmpty()) {
o2.sortValue = o2.name.toLowerCase()
}
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.sortValue.normalizeString().toLowerCase(), o2.sortValue.normalizeString().toLowerCase())
} else {
o1.sortValue.normalizeString().toLowerCase().compareTo(o2.sortValue.normalizeString().toLowerCase())
}
}
sorting and SORT_BY_PATH != 0 -> {
if (o1.sortValue.isEmpty()) {
o1.sortValue = o1.path.toLowerCase()
}
if (o2.sortValue.isEmpty()) {
o2.sortValue = o2.path.toLowerCase()
}
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.sortValue.toLowerCase(), o2.sortValue.toLowerCase())
} else {
o1.sortValue.toLowerCase().compareTo(o2.sortValue.toLowerCase())
}
}
sorting and SORT_BY_PATH != 0 -> AlphanumericComparator().compare(o1.sortValue.toLowerCase(), o2.sortValue.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
sorting and SORT_BY_DATE_MODIFIED != 0 -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
else -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
})
return movePinnedDirectoriesToFront(dirs)
}
fun Context.getDirsToShow(dirs: ArrayList<Directory>, allDirs: ArrayList<Directory>, currentPathPrefix: String): ArrayList<Directory> {
return if (config.groupDirectSubfolders) {
dirs.forEach {
it.subfoldersCount = 0
it.subfoldersMediaCount = it.mediaCnt
}
val parentDirs = getDirectParentSubfolders(dirs, currentPathPrefix)
updateSubfolderCounts(dirs, parentDirs)
// show the current folder as an available option too, not just subfolders
if (currentPathPrefix.isNotEmpty()) {
val currentFolder = allDirs.firstOrNull { parentDirs.firstOrNull { it.path == currentPathPrefix } == null && it.path == currentPathPrefix }
currentFolder?.apply {
subfoldersCount = 1
parentDirs.add(this)
}
}
getSortedDirectories(parentDirs)
} else {
dirs.forEach { it.subfoldersMediaCount = it.mediaCnt }
dirs
}
}
fun Context.getDirectParentSubfolders(dirs: ArrayList<Directory>, currentPathPrefix: String): ArrayList<Directory> {
val folders = dirs.map { it.path }.sorted().toMutableSet() as HashSet<String>
val currentPaths = LinkedHashSet<String>()
val foldersWithoutMediaFiles = ArrayList<String>()
var newDirId = 1000L
for (path in folders) {
if (path == RECYCLE_BIN || path == FAVORITES) {
continue
}
if (currentPathPrefix.isNotEmpty()) {
if (!path.startsWith(currentPathPrefix, true)) {
continue
}
if (!File(path).parent.equals(currentPathPrefix, true)) {
continue
}
}
if (currentPathPrefix.isNotEmpty() && path == currentPathPrefix || File(path).parent.equals(currentPathPrefix, true)) {
currentPaths.add(path)
} else if (folders.any { !it.equals(path, true) && (File(path).parent.equals(it, true) || File(it).parent.equals(File(path).parent, true)) }) {
// if we have folders like
// /storage/emulated/0/Pictures/Images and
// /storage/emulated/0/Pictures/Screenshots,
// but /storage/emulated/0/Pictures is empty, still Pictures with the first folders thumbnails and proper other info
val parent = File(path).parent
if (parent != null && !folders.contains(parent) && dirs.none { it.path == parent }) {
currentPaths.add(parent)
val isSortingAscending = config.sorting.isSortingAscending()
val subDirs = dirs.filter { File(it.path).parent.equals(File(path).parent, true) } as ArrayList<Directory>
if (subDirs.isNotEmpty()) {
val lastModified = if (isSortingAscending) {
subDirs.minByOrNull { it.modified }?.modified
} else {
subDirs.maxByOrNull { it.modified }?.modified
} ?: 0
val dateTaken = if (isSortingAscending) {
subDirs.minByOrNull { it.taken }?.taken
} else {
subDirs.maxByOrNull { it.taken }?.taken
} ?: 0
var mediaTypes = 0
subDirs.forEach {
mediaTypes = mediaTypes or it.types
}
val directory = Directory(
newDirId++,
parent,
subDirs.first().tmb,
getFolderNameFromPath(parent),
subDirs.sumBy { it.mediaCnt },
lastModified,
dateTaken,
subDirs.sumByLong { it.size },
getPathLocation(parent),
mediaTypes,
""
)
directory.containsMediaFilesDirectly = false
dirs.add(directory)
currentPaths.add(parent)
foldersWithoutMediaFiles.add(parent)
}
}
} else {
currentPaths.add(path)
}
}
var areDirectSubfoldersAvailable = false
currentPaths.forEach {
val path = it
currentPaths.forEach {
if (!foldersWithoutMediaFiles.contains(it) && !it.equals(path, true) && File(it).parent?.equals(path, true) == true) {
areDirectSubfoldersAvailable = true
}
}
}
if (currentPathPrefix.isEmpty() && folders.contains(RECYCLE_BIN)) {
currentPaths.add(RECYCLE_BIN)
}
if (currentPathPrefix.isEmpty() && folders.contains(FAVORITES)) {
currentPaths.add(FAVORITES)
}
if (folders.size == currentPaths.size) {
return dirs.filter { currentPaths.contains(it.path) } as ArrayList<Directory>
}
folders.clear()
folders.addAll(currentPaths)
val dirsToShow = dirs.filter { folders.contains(it.path) } as ArrayList<Directory>
return if (areDirectSubfoldersAvailable) {
getDirectParentSubfolders(dirsToShow, currentPathPrefix)
} else {
dirsToShow
}
}
fun Context.updateSubfolderCounts(children: ArrayList<Directory>, parentDirs: ArrayList<Directory>) {
for (child in children) {
var longestSharedPath = ""
for (parentDir in parentDirs) {
if (parentDir.path == child.path) {
longestSharedPath = child.path
continue
}
if (child.path.startsWith(parentDir.path, true) && parentDir.path.length > longestSharedPath.length) {
longestSharedPath = parentDir.path
}
}
// make sure we count only the proper direct subfolders, grouped the same way as on the main screen
parentDirs.firstOrNull { it.path == longestSharedPath }?.apply {
if (path.equals(child.path, true) || path.equals(File(child.path).parent, true) || children.any { it.path.equals(File(child.path).parent, true) }) {
if (child.containsMediaFilesDirectly) {
subfoldersCount++
}
if (path != child.path) {
subfoldersMediaCount += child.mediaCnt
}
}
}
}
}
fun Context.getNoMediaFolders(callback: (folders: ArrayList<String>) -> Unit) {
ensureBackgroundThread {
callback(getNoMediaFoldersSync())
}
}
fun Context.getNoMediaFoldersSync(): ArrayList<String> {
val folders = ArrayList<String>()
val uri = Files.getContentUri("external")
val projection = arrayOf(Files.FileColumns.DATA)
val selection = "${Files.FileColumns.MEDIA_TYPE} = ? AND ${Files.FileColumns.TITLE} LIKE ?"
val selectionArgs = arrayOf(Files.FileColumns.MEDIA_TYPE_NONE.toString(), "%$NOMEDIA%")
val sortOrder = "${Files.FileColumns.DATE_MODIFIED} DESC"
val OTGPath = config.OTGPath
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
if (cursor?.moveToFirst() == true) {
do {
val path = cursor.getStringValue(Files.FileColumns.DATA) ?: continue
val noMediaFile = File(path)
if (getDoesFilePathExist(noMediaFile.absolutePath, OTGPath) && noMediaFile.name == NOMEDIA) {
folders.add(noMediaFile.parent)
}
} while (cursor.moveToNext())
}
} catch (ignored: Exception) {
} finally {
cursor?.close()
}
return folders
}
fun Context.rescanFolderMedia(path: String) {
ensureBackgroundThread {
rescanFolderMediaSync(path)
}
}
fun Context.rescanFolderMediaSync(path: String) {
getCachedMedia(path) { cached ->
GetMediaAsynctask(applicationContext, path, isPickImage = false, isPickVideo = false, showAll = false) { newMedia ->
ensureBackgroundThread {
val media = newMedia.filterIsInstance<Medium>() as ArrayList<Medium>
try {
mediaDB.insertAll(media)
cached.forEach { thumbnailItem ->
if (!newMedia.contains(thumbnailItem)) {
val mediumPath = (thumbnailItem as? Medium)?.path
if (mediumPath != null) {
deleteDBPath(mediumPath)
}
}
}
} catch (ignored: Exception) {
}
}
}.execute()
}
}
fun Context.storeDirectoryItems(items: ArrayList<Directory>) {
ensureBackgroundThread {
directoryDB.insertAll(items)
}
}
fun Context.checkAppendingHidden(path: String, hidden: String, includedFolders: MutableSet<String>, noMediaFolders: ArrayList<String>): String {
val dirName = getFolderNameFromPath(path)
val folderNoMediaStatuses = HashMap<String, Boolean>()
noMediaFolders.forEach { folder ->
folderNoMediaStatuses["$folder/$NOMEDIA"] = true
}
return if (path.doesThisOrParentHaveNoMedia(folderNoMediaStatuses, null) && !path.isThisOrParentIncluded(includedFolders)) {
"$dirName $hidden"
} else {
dirName
}
}
fun Context.getFolderNameFromPath(path: String): String {
return when (path) {
internalStoragePath -> getString(R.string.internal)
sdCardPath -> getString(R.string.sd_card)
otgPath -> getString(R.string.usb)
FAVORITES -> getString(R.string.favorites)
RECYCLE_BIN -> getString(R.string.recycle_bin)
else -> path.getFilenameFromPath()
}
}
fun Context.loadImage(
type: Int, path: String, target: MySquareImageView, horizontalScroll: Boolean, animateGifs: Boolean, cropThumbnails: Boolean,
roundCorners: Int, signature: ObjectKey, skipMemoryCacheAtPaths: ArrayList<String>? = null
) {
target.isHorizontalScrolling = horizontalScroll
if (type == TYPE_IMAGES || type == TYPE_VIDEOS || type == TYPE_RAWS || type == TYPE_PORTRAITS) {
if (type == TYPE_IMAGES && path.isPng()) {
loadPng(path, target, cropThumbnails, roundCorners, signature, skipMemoryCacheAtPaths)
} else {
loadJpg(path, target, cropThumbnails, roundCorners, signature, skipMemoryCacheAtPaths)
}
} else if (type == TYPE_GIFS) {
if (!animateGifs) {
loadStaticGIF(path, target, cropThumbnails, roundCorners, signature, skipMemoryCacheAtPaths)
return
}
try {
val gifDrawable = GifDrawable(path)
target.setImageDrawable(gifDrawable)
gifDrawable.start()
target.scaleType = if (cropThumbnails) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
} catch (e: Exception) {
loadStaticGIF(path, target, cropThumbnails, roundCorners, signature, skipMemoryCacheAtPaths)
} catch (e: OutOfMemoryError) {
loadStaticGIF(path, target, cropThumbnails, roundCorners, signature, skipMemoryCacheAtPaths)
}
} else if (type == TYPE_SVGS) {
loadSVG(path, target, cropThumbnails, roundCorners, signature)
}
}
fun Context.addTempFolderIfNeeded(dirs: ArrayList<Directory>): ArrayList<Directory> {
val tempFolderPath = config.tempFolderPath
return if (tempFolderPath.isNotEmpty()) {
val directories = ArrayList<Directory>()
val newFolder = Directory(null, tempFolderPath, "", tempFolderPath.getFilenameFromPath(), 0, 0, 0, 0L, getPathLocation(tempFolderPath), 0, "")
directories.add(newFolder)
directories.addAll(dirs)
directories
} else {
dirs
}
}
fun Context.getPathLocation(path: String): Int {
return when {
isPathOnSD(path) -> LOCATION_SD
isPathOnOTG(path) -> LOCATION_OTG
else -> LOCATION_INTERNAL
}
}
fun Context.loadPng(
path: String,
target: MySquareImageView,
cropThumbnails: Boolean,
roundCorners: Int,
signature: ObjectKey,
skipMemoryCacheAtPaths: ArrayList<String>? = null
) {
val options = RequestOptions()
.signature(signature)
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.priority(Priority.LOW)
.format(DecodeFormat.PREFER_ARGB_8888)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
var builder = Glide.with(applicationContext)
.asBitmap()
.load(path)
.apply(options)
.listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, targetBitmap: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
tryLoadingWithPicasso(path, target, cropThumbnails, roundCorners, signature)
return true
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
targetBitmap: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
return false
}
})
if (roundCorners != ROUNDED_CORNERS_NONE) {
val cornerSize = if (roundCorners == ROUNDED_CORNERS_SMALL) R.dimen.rounded_corner_radius_small else R.dimen.rounded_corner_radius_big
val cornerRadius = resources.getDimension(cornerSize).toInt()
builder = builder.transform(CenterCrop(), RoundedCorners(cornerRadius))
}
builder.into(target)
}
fun Context.loadJpg(
path: String,
target: MySquareImageView,
cropThumbnails: Boolean,
roundCorners: Int,
signature: ObjectKey,
skipMemoryCacheAtPaths: ArrayList<String>? = null
) {
val options = RequestOptions()
.signature(signature)
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.priority(Priority.LOW)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
var builder = Glide.with(applicationContext)
.load(path)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade())
if (roundCorners != ROUNDED_CORNERS_NONE) {
val cornerSize = if (roundCorners == ROUNDED_CORNERS_SMALL) R.dimen.rounded_corner_radius_small else R.dimen.rounded_corner_radius_big
val cornerRadius = resources.getDimension(cornerSize).toInt()
builder = builder.transform(CenterCrop(), RoundedCorners(cornerRadius))
}
builder.into(target)
}
fun Context.loadStaticGIF(
path: String,
target: MySquareImageView,
cropThumbnails: Boolean,
roundCorners: Int,
signature: ObjectKey,
skipMemoryCacheAtPaths: ArrayList<String>? = null
) {
val options = RequestOptions()
.signature(signature)
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.priority(Priority.LOW)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
var builder = Glide.with(applicationContext)
.asBitmap() // make sure the GIF wont animate
.load(path)
.apply(options)
if (roundCorners != ROUNDED_CORNERS_NONE) {
val cornerSize = if (roundCorners == ROUNDED_CORNERS_SMALL) R.dimen.rounded_corner_radius_small else R.dimen.rounded_corner_radius_big
val cornerRadius = resources.getDimension(cornerSize).toInt()
builder = builder.transform(CenterCrop(), RoundedCorners(cornerRadius))
}
builder.into(target)
}
fun Context.loadSVG(path: String, target: MySquareImageView, cropThumbnails: Boolean, roundCorners: Int, signature: ObjectKey) {
target.scaleType = if (cropThumbnails) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
val options = RequestOptions().signature(signature)
var builder = Glide.with(applicationContext)
.`as`(PictureDrawable::class.java)
.listener(SvgSoftwareLayerSetter())
.load(path)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade())
if (roundCorners != ROUNDED_CORNERS_NONE) {
val cornerSize = if (roundCorners == ROUNDED_CORNERS_SMALL) R.dimen.rounded_corner_radius_small else R.dimen.rounded_corner_radius_big
val cornerRadius = resources.getDimension(cornerSize).toInt()
builder = builder.transform(CenterCrop(), RoundedCorners(cornerRadius))
}
builder.into(target)
}
// intended mostly for Android 11 issues, that fail loading PNG files bigger than 10 MB
fun Context.tryLoadingWithPicasso(path: String, view: MySquareImageView, cropThumbnails: Boolean, roundCorners: Int, signature: ObjectKey) {
var pathToLoad = "file://$path"
pathToLoad = pathToLoad.replace("%", "%25").replace("#", "%23")
try {
var builder = Picasso.get()
.load(pathToLoad)
.stableKey(signature.toString())
builder = if (cropThumbnails) {
builder.centerCrop().fit()
} else {
builder.centerInside()
}
if (roundCorners != ROUNDED_CORNERS_NONE) {
val cornerSize = if (roundCorners == ROUNDED_CORNERS_SMALL) R.dimen.rounded_corner_radius_small else R.dimen.rounded_corner_radius_big
val cornerRadius = resources.getDimension(cornerSize).toInt()
builder = builder.transform(PicassoRoundedCornersTransformation(cornerRadius.toFloat()))
}
builder.into(view)
} catch (e: Exception) {
}
}
fun Context.getCachedDirectories(
getVideosOnly: Boolean = false,
getImagesOnly: Boolean = false,
forceShowHidden: Boolean = false,
callback: (ArrayList<Directory>) -> Unit
) {
ensureBackgroundThread {
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE)
} catch (ignored: Exception) {
}
val directories = try {
directoryDB.getAll() as ArrayList<Directory>
} catch (e: Exception) {
ArrayList()
}
if (!config.showRecycleBinAtFolders) {
directories.removeAll { it.isRecycleBin() }
}
val shouldShowHidden = config.shouldShowHidden || forceShowHidden
val excludedPaths = if (config.temporarilyShowExcluded) {
HashSet()
} else {
config.excludedFolders
}
val includedPaths = config.includedFolders
val folderNoMediaStatuses = HashMap<String, Boolean>()
val noMediaFolders = getNoMediaFoldersSync()
noMediaFolders.forEach { folder ->
folderNoMediaStatuses["$folder/$NOMEDIA"] = true
}
var filteredDirectories = directories.filter {
it.path.shouldFolderBeVisible(excludedPaths, includedPaths, shouldShowHidden, folderNoMediaStatuses) { path, hasNoMedia ->
folderNoMediaStatuses[path] = hasNoMedia
}
} as ArrayList<Directory>
val filterMedia = config.filterMedia
filteredDirectories = (when {
getVideosOnly -> filteredDirectories.filter { it.types and TYPE_VIDEOS != 0 }
getImagesOnly -> filteredDirectories.filter { it.types and TYPE_IMAGES != 0 }
else -> filteredDirectories.filter {
(filterMedia and TYPE_IMAGES != 0 && it.types and TYPE_IMAGES != 0) ||
(filterMedia and TYPE_VIDEOS != 0 && it.types and TYPE_VIDEOS != 0) ||
(filterMedia and TYPE_GIFS != 0 && it.types and TYPE_GIFS != 0) ||
(filterMedia and TYPE_RAWS != 0 && it.types and TYPE_RAWS != 0) ||
(filterMedia and TYPE_SVGS != 0 && it.types and TYPE_SVGS != 0) ||
(filterMedia and TYPE_PORTRAITS != 0 && it.types and TYPE_PORTRAITS != 0)
}
}) as ArrayList<Directory>
if (shouldShowHidden) {
val hiddenString = resources.getString(R.string.hidden)
filteredDirectories.forEach {
val noMediaPath = "${it.path}/$NOMEDIA"
val hasNoMedia = if (folderNoMediaStatuses.keys.contains(noMediaPath)) {
folderNoMediaStatuses[noMediaPath]!!
} else {
it.path.doesThisOrParentHaveNoMedia(folderNoMediaStatuses) { path, hasNoMedia ->
val newPath = "$path/$NOMEDIA"
folderNoMediaStatuses[newPath] = hasNoMedia
}
}
it.name = if (hasNoMedia && !it.path.isThisOrParentIncluded(includedPaths)) {
"${it.name.removeSuffix(hiddenString).trim()} $hiddenString"
} else {
it.name.removeSuffix(hiddenString).trim()
}
}
}
val clone = filteredDirectories.clone() as ArrayList<Directory>
callback(clone.distinctBy { it.path.getDistinctPath() } as ArrayList<Directory>)
removeInvalidDBDirectories(filteredDirectories)
}
}
fun Context.getCachedMedia(path: String, getVideosOnly: Boolean = false, getImagesOnly: Boolean = false, callback: (ArrayList<ThumbnailItem>) -> Unit) {
ensureBackgroundThread {
val mediaFetcher = MediaFetcher(this)
val foldersToScan = if (path.isEmpty()) mediaFetcher.getFoldersToScan() else arrayListOf(path)
var media = ArrayList<Medium>()
if (path == FAVORITES) {
media.addAll(mediaDB.getFavorites())
}
if (path == RECYCLE_BIN) {
media.addAll(getUpdatedDeletedMedia())
}
if (config.filterMedia and TYPE_PORTRAITS != 0) {
val foldersToAdd = ArrayList<String>()
for (folder in foldersToScan) {
val allFiles = File(folder).listFiles() ?: continue
allFiles.filter { it.name.startsWith("img_", true) && it.isDirectory }.forEach {
foldersToAdd.add(it.absolutePath)
}
}
foldersToScan.addAll(foldersToAdd)
}
val shouldShowHidden = config.shouldShowHidden
foldersToScan.filter { path.isNotEmpty() || !config.isFolderProtected(it) }.forEach {
try {
val currMedia = mediaDB.getMediaFromPath(it)
media.addAll(currMedia)
} catch (ignored: Exception) {
}
}
if (!shouldShowHidden) {
media = media.filter { !it.path.contains("/.") } as ArrayList<Medium>
}
val filterMedia = config.filterMedia
media = (when {
getVideosOnly -> media.filter { it.type == TYPE_VIDEOS }
getImagesOnly -> media.filter { it.type == TYPE_IMAGES }
else -> media.filter {
(filterMedia and TYPE_IMAGES != 0 && it.type == TYPE_IMAGES) ||
(filterMedia and TYPE_VIDEOS != 0 && it.type == TYPE_VIDEOS) ||
(filterMedia and TYPE_GIFS != 0 && it.type == TYPE_GIFS) ||
(filterMedia and TYPE_RAWS != 0 && it.type == TYPE_RAWS) ||
(filterMedia and TYPE_SVGS != 0 && it.type == TYPE_SVGS) ||
(filterMedia and TYPE_PORTRAITS != 0 && it.type == TYPE_PORTRAITS)
}
}) as ArrayList<Medium>
val pathToUse = if (path.isEmpty()) SHOW_ALL else path
mediaFetcher.sortMedia(media, config.getFolderSorting(pathToUse))
val grouped = mediaFetcher.groupMedia(media, pathToUse)
callback(grouped.clone() as ArrayList<ThumbnailItem>)
val OTGPath = config.OTGPath
try {
val mediaToDelete = ArrayList<Medium>()
// creating a new thread intentionally, do not reuse the common background thread
Thread {
media.filter { !getDoesFilePathExist(it.path, OTGPath) }.forEach {
if (it.path.startsWith(recycleBinPath)) {
deleteDBPath(it.path)
} else {
mediaToDelete.add(it)
}
}
if (mediaToDelete.isNotEmpty()) {
try {
mediaDB.deleteMedia(*mediaToDelete.toTypedArray())
mediaToDelete.filter { it.isFavorite }.forEach {
favoritesDB.deleteFavoritePath(it.path)
}
} catch (ignored: Exception) {
}
}
}.start()
} catch (ignored: Exception) {
}
}
}
fun Context.removeInvalidDBDirectories(dirs: ArrayList<Directory>? = null) {
val dirsToCheck = dirs ?: directoryDB.getAll()
val OTGPath = config.OTGPath
dirsToCheck.filter { !it.areFavorites() && !it.isRecycleBin() && !getDoesFilePathExist(it.path, OTGPath) && it.path != config.tempFolderPath }.forEach {
try {
directoryDB.deleteDirPath(it.path)
} catch (ignored: Exception) {
}
}
}
fun Context.updateDBMediaPath(oldPath: String, newPath: String) {
val newFilename = newPath.getFilenameFromPath()
val newParentPath = newPath.getParentPath()
try {
mediaDB.updateMedium(newFilename, newPath, newParentPath, oldPath)
favoritesDB.updateFavorite(newFilename, newPath, newParentPath, oldPath)
} catch (ignored: Exception) {
}
}
fun Context.updateDBDirectory(directory: Directory) {
try {
directoryDB.updateDirectory(
directory.path,
directory.tmb,
directory.mediaCnt,
directory.modified,
directory.taken,
directory.size,
directory.types,
directory.sortValue
)
} catch (ignored: Exception) {
}
}
fun Context.getOTGFolderChildren(path: String) = getDocumentFile(path)?.listFiles()
fun Context.getOTGFolderChildrenNames(path: String) = getOTGFolderChildren(path)?.map { it.name }?.toMutableList()
fun Context.getFavoritePaths(): ArrayList<String> {
return try {
favoritesDB.getValidFavoritePaths() as ArrayList<String>
} catch (e: Exception) {
ArrayList()
}
}
fun Context.getFavoriteFromPath(path: String) = Favorite(null, path, path.getFilenameFromPath(), path.getParentPath())
fun Context.updateFavorite(path: String, isFavorite: Boolean) {
try {
if (isFavorite) {
favoritesDB.insert(getFavoriteFromPath(path))
} else {
favoritesDB.deleteFavoritePath(path)
}
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
// remove the "recycle_bin" from the file path prefix, replace it with real bin path /data/user...
fun Context.getUpdatedDeletedMedia(): ArrayList<Medium> {
val media = try {
mediaDB.getDeletedMedia() as ArrayList<Medium>
} catch (ignored: Exception) {
ArrayList()
}
media.forEach {
it.path = File(recycleBinPath, it.path.removePrefix(RECYCLE_BIN)).toString()
}
return media
}
fun Context.deleteDBPath(path: String) {
deleteMediumWithPath(path.replaceFirst(recycleBinPath, RECYCLE_BIN))
}
fun Context.deleteMediumWithPath(path: String) {
try {
mediaDB.deleteMediumPath(path)
} catch (ignored: Exception) {
}
}
fun Context.updateWidgets() {
val widgetIDs = AppWidgetManager.getInstance(applicationContext)?.getAppWidgetIds(ComponentName(applicationContext, MyWidgetProvider::class.java))
?: return
if (widgetIDs.isNotEmpty()) {
Intent(applicationContext, MyWidgetProvider::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs)
sendBroadcast(this)
}
}
}
// based on https://github.com/sannies/mp4parser/blob/master/examples/src/main/java/com/google/code/mp4parser/example/PrintStructure.java
fun Context.parseFileChannel(path: String, fc: FileChannel, level: Int, start: Long, end: Long, callback: () -> Unit) {
val FILE_CHANNEL_CONTAINERS = arrayListOf("moov", "trak", "mdia", "minf", "udta", "stbl")
try {
var iteration = 0
var currEnd = end
fc.position(start)
if (currEnd <= 0) {
currEnd = start + fc.size()
}
while (currEnd - fc.position() > 8) {
// just a check to avoid deadloop at some videos
if (iteration++ > 50) {
return
}
val begin = fc.position()
val byteBuffer = ByteBuffer.allocate(8)
fc.read(byteBuffer)
byteBuffer.rewind()
val size = IsoTypeReader.readUInt32(byteBuffer)
val type = IsoTypeReader.read4cc(byteBuffer)
val newEnd = begin + size
if (type == "uuid") {
val fis = FileInputStream(File(path))
fis.skip(begin)
val sb = StringBuilder()
val buffer = ByteArray(1024)
while (sb.length < size) {
val n = fis.read(buffer)
if (n != -1) {
sb.append(String(buffer, 0, n))
} else {
break
}
}
val xmlString = sb.toString().toLowerCase()
if (xmlString.contains("gspherical:projectiontype>equirectangular") || xmlString.contains("gspherical:projectiontype=\"equirectangular\"")) {
callback.invoke()
}
return
}
if (FILE_CHANNEL_CONTAINERS.contains(type)) {
parseFileChannel(path, fc, level + 1, begin + 8, newEnd, callback)
}
fc.position(newEnd)
}
} catch (ignored: Exception) {
}
}
fun Context.addPathToDB(path: String) {
ensureBackgroundThread {
if (!getDoesFilePathExist(path)) {
return@ensureBackgroundThread
}
val type = when {
path.isVideoFast() -> TYPE_VIDEOS
path.isGif() -> TYPE_GIFS
path.isRawFast() -> TYPE_RAWS
path.isSvg() -> TYPE_SVGS
path.isPortrait() -> TYPE_PORTRAITS
else -> TYPE_IMAGES
}
try {
val isFavorite = favoritesDB.isFavorite(path)
val videoDuration = if (type == TYPE_VIDEOS) getDuration(path) ?: 0 else 0
val medium = Medium(
null, path.getFilenameFromPath(), path, path.getParentPath(), System.currentTimeMillis(), System.currentTimeMillis(),
File(path).length(), type, videoDuration, isFavorite, 0L, 0L
)
mediaDB.insert(medium)
} catch (ignored: Exception) {
}
}
}
fun Context.createDirectoryFromMedia(
path: String, curMedia: ArrayList<Medium>, albumCovers: ArrayList<AlbumCover>, hiddenString: String,
includedFolders: MutableSet<String>, getProperFileSize: Boolean, noMediaFolders: ArrayList<String>
): Directory {
val OTGPath = config.OTGPath
val grouped = MediaFetcher(this).groupMedia(curMedia, path)
var thumbnail: String? = null
albumCovers.forEach {
if (it.path == path && getDoesFilePathExist(it.tmb, OTGPath)) {
thumbnail = it.tmb
}
}
if (thumbnail == null) {
val sortedMedia = grouped.filter { it is Medium }.toMutableList() as ArrayList<Medium>
thumbnail = sortedMedia.firstOrNull { getDoesFilePathExist(it.path, OTGPath) }?.path ?: ""
}
if (config.OTGPath.isNotEmpty() && thumbnail!!.startsWith(config.OTGPath)) {
thumbnail = thumbnail!!.getOTGPublicPath(applicationContext)
}
val isSortingAscending = config.directorySorting.isSortingAscending()
val defaultMedium = Medium(0, "", "", "", 0L, 0L, 0L, 0, 0, false, 0L, 0L)
val firstItem = curMedia.firstOrNull() ?: defaultMedium
val lastItem = curMedia.lastOrNull() ?: defaultMedium
val dirName = checkAppendingHidden(path, hiddenString, includedFolders, noMediaFolders)
val lastModified = if (isSortingAscending) Math.min(firstItem.modified, lastItem.modified) else Math.max(firstItem.modified, lastItem.modified)
val dateTaken = if (isSortingAscending) Math.min(firstItem.taken, lastItem.taken) else Math.max(firstItem.taken, lastItem.taken)
val size = if (getProperFileSize) curMedia.sumByLong { it.size } else 0L
val mediaTypes = curMedia.getDirMediaTypes()
val sortValue = getDirectorySortingValue(curMedia, path, dirName, size)
return Directory(null, path, thumbnail!!, dirName, curMedia.size, lastModified, dateTaken, size, getPathLocation(path), mediaTypes, sortValue)
}
fun Context.getDirectorySortingValue(media: ArrayList<Medium>, path: String, name: String, size: Long): String {
val sorting = config.directorySorting
val sorted = when {
sorting and SORT_BY_NAME != 0 -> return name
sorting and SORT_BY_PATH != 0 -> return path
sorting and SORT_BY_SIZE != 0 -> return size.toString()
sorting and SORT_BY_DATE_MODIFIED != 0 -> media.sortedBy { it.modified }
sorting and SORT_BY_DATE_TAKEN != 0 -> media.sortedBy { it.taken }
else -> media
}
val relevantMedium = if (sorting.isSortingAscending()) {
sorted.firstOrNull() ?: return ""
} else {
sorted.lastOrNull() ?: return ""
}
val result: Any = when {
sorting and SORT_BY_DATE_MODIFIED != 0 -> relevantMedium.modified
sorting and SORT_BY_DATE_TAKEN != 0 -> relevantMedium.taken
else -> 0
}
return result.toString()
}
fun Context.updateDirectoryPath(path: String) {
val mediaFetcher = MediaFetcher(applicationContext)
val getImagesOnly = false
val getVideosOnly = false
val hiddenString = getString(R.string.hidden)
val albumCovers = config.parseAlbumCovers()
val includedFolders = config.includedFolders
val noMediaFolders = getNoMediaFoldersSync()
val sorting = config.getFolderSorting(path)
val grouping = config.getFolderGrouping(path)
val getProperDateTaken = config.directorySorting and SORT_BY_DATE_TAKEN != 0 ||
sorting and SORT_BY_DATE_TAKEN != 0 ||
grouping and GROUP_BY_DATE_TAKEN_DAILY != 0 ||
grouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0
val getProperLastModified = config.directorySorting and SORT_BY_DATE_MODIFIED != 0 ||
sorting and SORT_BY_DATE_MODIFIED != 0 ||
grouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 ||
grouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0
val getProperFileSize = config.directorySorting and SORT_BY_SIZE != 0
val lastModifieds = if (getProperLastModified) mediaFetcher.getFolderLastModifieds(path) else HashMap()
val dateTakens = mediaFetcher.getFolderDateTakens(path)
val favoritePaths = getFavoritePaths()
val curMedia = mediaFetcher.getFilesFrom(
path, getImagesOnly, getVideosOnly, getProperDateTaken, getProperLastModified, getProperFileSize,
favoritePaths, false, lastModifieds, dateTakens, null
)
val directory = createDirectoryFromMedia(path, curMedia, albumCovers, hiddenString, includedFolders, getProperFileSize, noMediaFolders)
updateDBDirectory(directory)
}
fun Context.getFileDateTaken(path: String): Long {
val projection = arrayOf(
Images.Media.DATE_TAKEN
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} = ?"
val selectionArgs = arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(Images.Media.DATE_TAKEN)
}
}
} catch (ignored: Exception) {
}
return 0L
}
| gpl-3.0 | 0c3045c975d388b4b5abae73c4549392 | 37.528507 | 160 | 0.623808 | 4.488088 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/CustomSourceRootPropertiesEntityImpl.kt | 2 | 10132 | // 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.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class CustomSourceRootPropertiesEntityImpl(val dataSource: CustomSourceRootPropertiesEntityData) : CustomSourceRootPropertiesEntity, WorkspaceEntityBase() {
companion object {
internal val SOURCEROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java,
CustomSourceRootPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
SOURCEROOT_CONNECTION_ID,
)
}
override val sourceRoot: SourceRootEntity
get() = snapshot.extractOneToOneParent(SOURCEROOT_CONNECTION_ID, this)!!
override val propertiesXmlTag: String
get() = dataSource.propertiesXmlTag
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: CustomSourceRootPropertiesEntityData?) : ModifiableWorkspaceEntityBase<CustomSourceRootPropertiesEntity, CustomSourceRootPropertiesEntityData>(
result), CustomSourceRootPropertiesEntity.Builder {
constructor() : this(CustomSourceRootPropertiesEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity CustomSourceRootPropertiesEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(SOURCEROOT_CONNECTION_ID, this) == null) {
error("Field CustomSourceRootPropertiesEntity#sourceRoot should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] == null) {
error("Field CustomSourceRootPropertiesEntity#sourceRoot should be initialized")
}
}
if (!getEntityData().isPropertiesXmlTagInitialized()) {
error("Field CustomSourceRootPropertiesEntity#propertiesXmlTag should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as CustomSourceRootPropertiesEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.propertiesXmlTag != dataSource.propertiesXmlTag) this.propertiesXmlTag = dataSource.propertiesXmlTag
if (parents != null) {
val sourceRootNew = parents.filterIsInstance<SourceRootEntity>().single()
if ((this.sourceRoot as WorkspaceEntityBase).id != (sourceRootNew as WorkspaceEntityBase).id) {
this.sourceRoot = sourceRootNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var sourceRoot: SourceRootEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(SOURCEROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity
}
else {
this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(SOURCEROOT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] = value
}
changedProperty.add("sourceRoot")
}
override var propertiesXmlTag: String
get() = getEntityData().propertiesXmlTag
set(value) {
checkModificationAllowed()
getEntityData(true).propertiesXmlTag = value
changedProperty.add("propertiesXmlTag")
}
override fun getEntityClass(): Class<CustomSourceRootPropertiesEntity> = CustomSourceRootPropertiesEntity::class.java
}
}
class CustomSourceRootPropertiesEntityData : WorkspaceEntityData<CustomSourceRootPropertiesEntity>() {
lateinit var propertiesXmlTag: String
fun isPropertiesXmlTagInitialized(): Boolean = ::propertiesXmlTag.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<CustomSourceRootPropertiesEntity> {
val modifiable = CustomSourceRootPropertiesEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): CustomSourceRootPropertiesEntity {
return getCached(snapshot) {
val entity = CustomSourceRootPropertiesEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return CustomSourceRootPropertiesEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return CustomSourceRootPropertiesEntity(propertiesXmlTag, entitySource) {
this.sourceRoot = parents.filterIsInstance<SourceRootEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(SourceRootEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as CustomSourceRootPropertiesEntityData
if (this.entitySource != other.entitySource) return false
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as CustomSourceRootPropertiesEntityData
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + propertiesXmlTag.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + propertiesXmlTag.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | f67c204209b44ce4a895c317f53c0ee6 | 38.578125 | 167 | 0.714962 | 5.613296 | false | false | false | false |
GunoH/intellij-community | plugins/gradle-maven/src/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/completion/GradleStringStyleHandler.kt | 2 | 4298 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.Lookup
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil
import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo
import org.jetbrains.idea.maven.statistics.MavenDependencyInsertionCollector
import org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion.MavenDependenciesGradleCompletionContributor.Companion.COMPLETION_DATA_KEY
import org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion.MavenDependenciesGradleCompletionContributor.Companion.CompletionData
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
abstract class ReplaceEndInsertHandler : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val element = getLiteral(context) ?: return
val completed = getCompletedString(item) ?: return
val (completionPrefix, suffix, quote) = item.getUserData(COMPLETION_DATA_KEY) ?: CompletionData("", "", '\'')
val insertedSuffix = if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) "" else suffix.orEmpty()
val newText = completed + insertedSuffix
element.updateText("${quote}$newText${quote}")
postProcess(completed, element.textRange.endOffset - (insertedSuffix.length + 1), context)
context.commitDocument()
val selectedLookupIndex = context.elements.indexOf(item)
val artifactInfo = item.`object` as? MavenRepositoryArtifactInfo ?: return
MavenDependencyInsertionCollector.logPackageAutoCompleted(
groupId = artifactInfo.groupId,
artifactId = artifactInfo.artifactId,
version = artifactInfo.version ?: "",
buildSystem = MavenDependencyInsertionCollector.Companion.BuildSystem.GRADLE,
dependencyDeclarationNotation = MavenDependencyInsertionCollector.Companion.DependencyDeclarationNotation.GRADLE_STRING_STYLE,
completionPrefixLength = completionPrefix.length,
selectedLookupIndex = selectedLookupIndex
)
}
abstract fun getCompletedString(item: LookupElement): String?
open fun postProcess(completedString: String, completedStringEndOffset: Int, context: InsertionContext) {}
}
object GradleStringStyleVersionHandler : ReplaceEndInsertHandler() {
override fun getCompletedString(item: LookupElement): String? {
return (item.`object` as? MavenRepositoryArtifactInfo?)?.version
}
}
object GradleStringStyleGroupAndArtifactHandler : ReplaceEndInsertHandler() {
override fun getCompletedString(item: LookupElement): String? {
val info = item.`object` as? MavenRepositoryArtifactInfo ?: return null
val completed = MavenDependencyCompletionUtil.getPresentableText(info)
val moreCompletionNeeded = completed.count { it == ':' } < 2
return completed + if (moreCompletionNeeded) ":" else ""
}
override fun postProcess(completedString: String, completedStringEndOffset: Int, context: InsertionContext) {
if (!completedString.endsWith(':')) return
context.editor.caretModel.moveToOffset(completedStringEndOffset)
context.setLaterRunnable { CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(context.project, context.editor) }
}
}
private fun getLiteral(context: InsertionContext): GrLiteral? {
val file = context.file as? GroovyFile ?: return null
val psiElement = file.findElementAt(context.startOffset) ?: return null
if (psiElement is GrLiteral && psiElement.parent is GrArgumentList) {
return psiElement
}
val parent = psiElement.parent
if (parent is GrLiteral && parent.parent is GrArgumentList) {
return parent
}
return null
} | apache-2.0 | 99fbabd4bc0dbd5320ac4063863f3563 | 52.7375 | 152 | 0.800605 | 4.884091 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsModuleChecker.kt | 3 | 3218 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.resolve.diagnostics
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.checkers.SimpleDeclarationChecker
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
object JsModuleChecker : SimpleDeclarationChecker {
override fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext
) {
checkSuperClass(bindingContext, diagnosticHolder, descriptor, declaration)
if (AnnotationsUtils.getModuleName(descriptor) == null && !AnnotationsUtils.isNonModule(descriptor)) return
if (descriptor is PropertyDescriptor && descriptor.isVar) {
diagnosticHolder.report(ErrorsJs.JS_MODULE_PROHIBITED_ON_VAR.on(declaration))
}
if (!AnnotationsUtils.isNativeObject(descriptor)) {
diagnosticHolder.report(ErrorsJs.JS_MODULE_PROHIBITED_ON_NON_NATIVE.on(declaration))
}
if (DescriptorUtils.isTopLevelDeclaration(descriptor)) {
val isFileModuleOrNonModule = AnnotationsUtils.getFileModuleName(bindingContext, descriptor) != null ||
AnnotationsUtils.isFromNonModuleFile(bindingContext, descriptor)
if (isFileModuleOrNonModule) {
diagnosticHolder.report(ErrorsJs.NESTED_JS_MODULE_PROHIBITED.on(declaration))
}
}
}
private fun checkSuperClass(
bindingContext: BindingContext,
diagnosticHolder: DiagnosticSink,
descriptor: DeclarationDescriptor,
declaration: KtDeclaration
) {
if (descriptor !is ClassDescriptor) return
val superClass = descriptor.getSuperClassNotAny() ?: return
val psi = (declaration as KtClassOrObject).superTypeListEntries.firstOrNull { entry ->
bindingContext[BindingContext.TYPE, entry.typeReference]?.constructor?.declarationDescriptor == superClass
}
checkJsModuleUsage(bindingContext, diagnosticHolder, descriptor, superClass, psi ?: declaration)
}
}
| apache-2.0 | 52270c64fdfb7bdf21cdef8278f3a613 | 43.082192 | 118 | 0.733375 | 5.051805 | false | false | false | false |
vovagrechka/fucking-everything | attic/alraune/alraune-back/src/TSPile.kt | 1 | 6044 | package alraune.back
import vgrechka.*
import java.io.File
import java.util.*
import kotlin.reflect.full.memberProperties
object TSPile {
// fun spitOutSomeTS() {
// File(AlBackPile0.generatedTSFile).writeText(buildString {
// ln("/*")
// ln(" * (C) Copyright 2017 Vladimir Grechka")
// ln(" *")
// ln(" * YOU DON'T MESS AROUND WITH THIS SHIT, IT WAS GENERATED BY A TOOL SMARTER THAN YOU")
// ln(" */")
// ln("")
// ln("//")
// ln("// Generated on ${Date()}")
// ln("//")
//
// spitDomids(this)
// spitFormPropNames(this)
// spitCommandTypes(this)
// })
// }
//
// private fun spitFormPropNames(buf: StringBuilder) {
// buf.apply {
// ln("")
// ln("const AlFormPropNames = {")
//
// val re = Regex("class\\s+(\\w+)FormPostData\\s*\\(((.|\n)*?)\\)")
// doShitWithClasses(re, AlBackPile0.formPostDataKtSourceFile, {className -> object : DoShitWithClassesPedro {
// override fun shouldGenerateSomething() = true
//
// override fun beforeIteratingProps() {
// val typeName = className.replace(Regex("FormPostData$"), "")
// clog("${this@TSPile::spitFormPropNames.name}: typeName = $typeName")
// ln("")
// ln(" $typeName: {")
// }
//
// override fun onProperty(propName: String, propType: String) {
// ln(" $propName: \"$propName\",")
// }
//
// override fun afterIteratingProps() {
// ln(" },")
// }
// }})
//
// ln("}")
// }
// }
//
// interface DoShitWithClassesPedro {
// fun shouldGenerateSomething(): Boolean
// fun beforeIteratingProps()
// fun onProperty(propName: String, propType: String)
// fun afterIteratingProps()
//
// }
//
// fun doShitWithClasses(re: Regex, srcFileName: String, makePedro: (className: String) -> DoShitWithClassesPedro) {
// val src = File(srcFileName).readText()
// var start = 0
// while (true) {
// val mr = re.find(src, start) ?: break
//
// val className = mr.groupValues[1]
// val pedro = makePedro(className)
// if (pedro.shouldGenerateSomething()) {
// pedro.beforeIteratingProps()
// val propsCode = mr.groupValues[2]
// for (propCode in propsCode.split(",")) {
// val pieces = propCode.split(":")
// check(pieces.size == 2)
// val lhs = pieces[0].trim()
// check(lhs.startsWith("val "))
// val propName = lhs.substring("val ".length).trim()
// val propType = pieces[1].trim()
// clog(" propName = $propName; propType = $propType")
// pedro.onProperty(propName, propType)
// }
// pedro.afterIteratingProps()
// }
//
// start = mr.range.start + 1
// }
// }
//
// private fun spitCommandTypes(buf: StringBuilder) {
// buf.apply {
// ln("")
// ln("namespace AlBackToFrontCommand {")
//
// val typeNames = mutableListOf<String>()
// val re = Regex("class\\s+(\\w+)\\s*\\(((.|\n)*?)\\)\\s*:\\s*AlBackToFrontCommand\\s*\\(\\)")
// doShitWithClasses(re, AlBackPile0.backToFrontCommandsKtSourceFile, {className ->
// object : DoShitWithClassesPedro {
// override fun shouldGenerateSomething() = true
//
// override fun beforeIteratingProps() {
// val typeName = commandClassNameToTSTypeName(className)
// typeNames += typeName
// clog("${this@TSPile::spitCommandTypes.name}: typeName = $typeName")
// ln("")
// ln(" export interface $typeName {")
// ln(" opcode: \"$typeName\"")
// }
//
// override fun onProperty(propName: String, propType: String) {
// val tsType = when {
// propType == "String" -> "string"
// propType.startsWith("List<") -> {
// val closing = propType.lastIndexOfOrNull(">") ?: wtf("358761c8-e7b9-41b2-ac23-7b629bce5137")
// val elementType = propType.subSequence("List<".length, closing)
// val tsElementType = when (elementType) {
// "AlBackToFrontCommand" -> "Type"
// else -> elementType
// }
// "$tsElementType[]"
// }
// else -> wtf("propType = $propType e0a20284-a8ab-44e8-8f17-4a28b1509f4a")
// }
// ln(" $propName: $tsType")
// }
//
// override fun afterIteratingProps() {
// ln(" }")
// }
// }
// })
//
// ln("")
// ln(" export type Type = ${typeNames.joinToString(" | ")}")
//
// ln("}")
// }
// }
//
// private fun spitDomids(buf: StringBuilder) {
// buf.apply {
// ln("")
// ln("const AlDomid = {")
// for (prop in AlDomid::class.memberProperties) {
// val domid = prop.get(AlDomid)
// ln(" $domid: \"$domid\",")
// }
// ln("}")
// }
// }
//
// fun commandClassNameToTSTypeName(className: String) = className.replace(Regex("Command$"), "")
}
| apache-2.0 | 249e9953c6b46d93e62928593b024374 | 33.936416 | 126 | 0.444573 | 4.125597 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/core/PendingStateLongRunTest.kt | 1 | 5725 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.core
import org.ethereum.config.CommonConfig
import org.ethereum.datasource.inmem.HashMapDB
import org.ethereum.db.IndexedBlockStore
import org.ethereum.db.RepositoryRoot
import org.ethereum.listener.EthereumListenerAdapter
import org.ethereum.util.BIUtil
import org.ethereum.validator.DependentBlockHeaderRuleAdapter
import org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.spongycastle.util.encoders.Hex
import java.io.File
import java.io.IOException
import java.net.URISyntaxException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
/**
* @author Mikhail Kalinin
* *
* @since 24.09.2015
*/
@Ignore
class PendingStateLongRunTest {
private var blockchain: Blockchain? = null
private var pendingState: PendingState? = null
private var strData: List<String>? = null
@Before
@Throws(URISyntaxException::class, IOException::class, InterruptedException::class)
fun setup() {
blockchain = createBlockchain(Genesis.instance as Genesis)
pendingState = (blockchain as BlockchainImpl).pendingState
val blocks = ClassLoader.getSystemResource("state/47250.dmp")
val file = File(blocks.toURI())
strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)
for (i in 0..45999) {
val b = Block(Hex.decode(strData!![i]))
blockchain!!.tryToConnect(b)
}
}
@Test // test with real data from the frontier net
fun test_1() {
val b46169 = Block(Hex.decode(strData!![46169]))
val b46170 = Block(Hex.decode(strData!![46170]))
val tx46169 = b46169.transactionsList[0]
val tx46170 = b46170.transactionsList[0]
var pending = pendingState!!.repository
val balanceBefore46169 = pending.getAccountState(tx46169.receiveAddress).balance
val balanceBefore46170 = pending.getAccountState(tx46170.receiveAddress).balance
pendingState!!.addPendingTransaction(tx46169)
pendingState!!.addPendingTransaction(tx46170)
for (i in 46000..46168) {
val b = Block(Hex.decode(strData!![i]))
blockchain!!.tryToConnect(b)
}
pending = pendingState!!.repository
val balanceAfter46169 = balanceBefore46169.add(BIUtil.toBI(tx46169.value))
assertEquals(pendingState!!.pendingTransactions.size.toLong(), 2)
assertEquals(balanceAfter46169, pending.getAccountState(tx46169.receiveAddress).balance)
blockchain!!.tryToConnect(b46169)
pending = pendingState!!.repository
assertEquals(balanceAfter46169, pending.getAccountState(tx46169.receiveAddress).balance)
assertEquals(pendingState!!.pendingTransactions.size.toLong(), 1)
val balanceAfter46170 = balanceBefore46170.add(BIUtil.toBI(tx46170.value))
assertEquals(balanceAfter46170, pending.getAccountState(tx46170.receiveAddress).balance)
blockchain!!.tryToConnect(b46170)
pending = pendingState!!.repository
assertEquals(balanceAfter46170, pending.getAccountState(tx46170.receiveAddress).balance)
assertEquals(pendingState!!.pendingTransactions.size.toLong(), 0)
}
private fun createBlockchain(genesis: Genesis): Blockchain {
val blockStore = IndexedBlockStore()
blockStore.init(HashMapDB<ByteArray>(), HashMapDB<ByteArray>())
val repository = RepositoryRoot(HashMapDB())
val programInvokeFactory = ProgramInvokeFactoryImpl()
val blockchain = BlockchainImpl(blockStore, repository)
.withParentBlockHeaderValidator(CommonConfig().parentHeaderValidator())
blockchain.setParentHeaderValidator(DependentBlockHeaderRuleAdapter())
blockchain.programInvokeFactory = programInvokeFactory
blockchain.byTest = true
val pendingState = PendingStateImpl(EthereumListenerAdapter(), blockchain)
pendingState.setBlockchain(blockchain)
blockchain.pendingState = pendingState
val track = repository.startTracking()
Genesis.populateRepository(track, genesis)
track.commit()
blockStore.saveBlock(Genesis.instance, Genesis.instance.cumulativeDifficulty, true)
blockchain.bestBlock = Genesis.instance
blockchain.totalDifficulty = Genesis.instance.cumulativeDifficulty
return blockchain
}
}
| mit | 94b5b548f5c3f1593709fde3038a9745 | 35.464968 | 96 | 0.73048 | 4.407236 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/EmptyMapLiteralType.kt | 15 | 1950 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.openapi.util.Couple
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.ResolveState
import com.intellij.util.lazyPub
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType
import org.jetbrains.plugins.groovy.lang.psi.impl.getTypeArgumentsFromResult
import org.jetbrains.plugins.groovy.lang.resolve.DiamondResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.asJavaClassResult
import java.util.*
class EmptyMapLiteralType(private val literal: GrListOrMap) : GrMapType(literal) {
override fun isValid(): Boolean = literal.isValid
override fun isEmpty(): Boolean = true
override fun getTypeByStringKey(key: String?): PsiType? = null
override fun getStringKeys(): Set<String> = emptySet()
override fun getOtherEntries(): List<Couple<PsiType>> = emptyList()
override fun getStringEntries(): LinkedHashMap<String, PsiType> = LinkedHashMap()
val resolveResult: DiamondResolveResult? by lazyPub {
resolve()?.let {
DiamondResolveResult(it, literal, ResolveState.initial())
}
}
override fun resolveGenerics(): ClassResolveResult = resolveResult.asJavaClassResult()
override fun getParameters(): Array<out PsiType?> = resolveResult?.getTypeArgumentsFromResult() ?: PsiType.EMPTY_ARRAY
override fun toString(): String = "[:]"
override fun getAllKeyTypes(): Array<PsiType> = error("This method must not be called")
override fun getAllValueTypes(): Array<PsiType> = error("This method must not be called")
override fun setLanguageLevel(languageLevel: LanguageLevel): PsiClassType = error("This method must not be called")
}
| apache-2.0 | 77f7607688409528196720befc2e5bbc | 38 | 140 | 0.783077 | 4.372197 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/CollectionConstructors.kt | 9 | 4079 | // WITH_STDLIB
import kotlin.collections.*
fun simple() {
val list1 = listOf<String>()
if (<warning descr="Condition 'list1.isEmpty()' is always true">list1.isEmpty()</warning>) {}
val list2 = emptyList<String>()
if (<warning descr="Condition 'list2.isNotEmpty()' is always false">list2.isNotEmpty()</warning>) {}
val list3 = listOf(1, 2, 3, 4)
if (<warning descr="Condition 'list3.size == 4' is always true">list3.size == 4</warning>) {}
val list4 = listOfNotNull(1, 2, 3, 4)
if (<warning descr="Condition 'list4.size > 4' is always false">list4.size > 4</warning>) {}
if (list4.size == 4) {}
if (list4.size == 0) {}
val set1 = emptySet<String>()
if (<warning descr="Condition 'set1.isEmpty()' is always true">set1.isEmpty()</warning>) {}
val set2 = setOf<String>()
if (<warning descr="Condition 'set2.isEmpty()' is always true">set2.isEmpty()</warning>) {}
val set3 = setOf(1, 2, 3, 1)
if (<warning descr="Condition 'set3.size > 4' is always false">set3.size > 4</warning>) {}
if (set3.size == 4) {}
if (<warning descr="Condition 'set3.isEmpty()' is always false">set3.isEmpty()</warning>) {}
val map1 = emptyMap<String, String>()
if (<warning descr="Condition 'map1.isEmpty()' is always true">map1.isEmpty()</warning>) {}
val map2 = mapOf<String, String>()
if (<warning descr="Condition 'map2.isNotEmpty()' is always false">map2.isNotEmpty()</warning>) {}
val map3 = mapOf(1 to 2, 3 to 4, 5 to 6, 7 to 8)
if (<warning descr="Condition 'map3.size >= 5' is always false">map3.size >= 5</warning>) {}
if (map3.size >= 4) {}
if (<warning descr="Condition 'map3.size == 0' is always false">map3.size == 0</warning>) {}
}
fun mutableSimple(otherList: MutableList<Int>) {
val list = mutableListOf<Int>()
for(x in otherList) {
list.add(x)
}
if (list.isEmpty()) {}
}
fun mutable(otherList: MutableList<Int>) {
val list = mutableListOf<Int>()
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
otherList.add(1)
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
modifyList(list)
if (list.isEmpty()) {}
}
class MutableField {
var field = mutableListOf<Int>()
fun mutable() {
val list = mutableListOf<Int>()
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
update()
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
field = list
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
update()
if (list.isEmpty()) {}
}
fun update() {
field.add(1)
}
}
fun mutableAndObject() {
val list = mutableListOf<Int>()
val obj = object : Runnable {
override fun run() {
list.add(1)
}
}
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
obj.run()
if (list.isEmpty()) {}
}
fun mutableAndLambda() {
val list = mutableListOf<Int>()
val fn = {
list.add(1)
}
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
fn()
if (list.isEmpty()) {}
}
fun mutableCheckInLambda() {
val list = mutableListOf<Int>()
val fn = {
if (list.size == 0) {}
}
if (<warning descr="Condition 'list.isEmpty()' is always true">list.isEmpty()</warning>) {}
list.add(1)
if (list.isEmpty()) {}
fn()
if (list.isEmpty()) {}
}
fun mutableInMethodReference(x: Int?) {
val set = mutableSetOf<Int>()
x?.let(set::add)
if (set.size == 0) {}
}
fun modifyList(list: MutableList<Int>) {
list.add(2)
}
fun fromArray(arr: Array<Int>) {
val list = mutableListOf(*arr)
if (list.isEmpty()) {}
if (arr.size == 0) return
val list2 = mutableListOf(*arr)
if (<warning descr="Condition 'list2.isEmpty()' is always false">list2.isEmpty()</warning>) {}
}
| apache-2.0 | 006edfb645752756a89dcc8a4bb8811a | 32.991667 | 104 | 0.603824 | 3.553136 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/google/accounts/GoogleAccountsDetailsProvider.kt | 1 | 4264 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.google.accounts
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.collaboration.auth.ui.LoadingAccountsDetailsProvider
import com.intellij.collaboration.util.ProgressIndicatorsProvider
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.concurrency.annotations.RequiresEdt
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.google.GoogleAuthorizedUserException
import org.intellij.plugins.markdown.google.accounts.data.GoogleAccount
import org.intellij.plugins.markdown.google.accounts.data.GoogleUserDetailed
import org.intellij.plugins.markdown.google.accounts.data.GoogleUserInfo
import org.intellij.plugins.markdown.google.authorization.GoogleCredentials
import org.intellij.plugins.markdown.google.authorization.GoogleOAuthService
import org.intellij.plugins.markdown.google.utils.GoogleAccountsUtils.getOrUpdateUserCredentials
import java.net.URL
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeoutException
import javax.imageio.ImageIO
internal class GoogleAccountsDetailsProvider(
progressIndicatorsProvider: ProgressIndicatorsProvider,
private val accountManager: GoogleAccountManager,
private val accountsListModel: GoogleAccountsListModel,
private val oAuthService: GoogleOAuthService,
private val userInfoService: GoogleUserInfoService
) : LoadingAccountsDetailsProvider<GoogleAccount, GoogleUserDetailed>(progressIndicatorsProvider) {
companion object {
private val LOG = logger<GoogleAccountsDetailsProvider>()
}
@RequiresEdt
override fun scheduleLoad(
account: GoogleAccount,
indicator: ProgressIndicator
): CompletableFuture<DetailsLoadingResult<GoogleUserDetailed>> {
val credentials = try {
getUserCredentials(account) ?: return CompletableFuture.completedFuture(noCredentials())
}
catch (e: TimeoutException) {
return CompletableFuture.completedFuture(failedToLoadInfo())
}
return userInfoService.acquireUserInfo(credentials.accessToken, indicator).thenCompose { userInfo ->
loadDetails(account, userInfo, indicator)
}.exceptionally {
when(it.cause) {
is GoogleAuthorizedUserException -> unauthenticatedUser()
is UnrecognizedPropertyException -> {
LOG.debug(it.localizedMessage)
failedToLoadInfo()
}
else -> failedToLoadInfo()
}
}
}
@RequiresEdt
private fun loadDetails(account: GoogleAccount, userInfo: GoogleUserInfo, progressIndicator: ProgressIndicator) =
ProgressManager.getInstance().submitIOTask(progressIndicator) {
val url = URL(userInfo.picture)
val image = ImageIO.read(url)
val details = GoogleUserDetailed(userInfo.name, userInfo.id, userInfo.givenName, userInfo.familyName, userInfo.locale)
DetailsLoadingResult(details, image, null, false)
}.successOnEdt(ModalityState.any()) {
accountsListModel.accountsListModel.contentsChanged(account)
it
}
@RequiresEdt
private fun getUserCredentials(account: GoogleAccount): GoogleCredentials? =
accountsListModel.newCredentials.getOrElse(account) {
getOrUpdateUserCredentials(oAuthService, accountManager, account)
}
private fun noCredentials() =
DetailsLoadingResult<GoogleUserDetailed>(null, null, MarkdownBundle.message("markdown.google.accounts.token.missing"), true)
private fun failedToLoadInfo() =
DetailsLoadingResult<GoogleUserDetailed>(null, null, MarkdownBundle.message("markdown.google.accounts.failed.load.user"), true)
private fun unauthenticatedUser() =
DetailsLoadingResult<GoogleUserDetailed>(null, null, MarkdownBundle.message("markdown.google.accounts.user.unauthenticated.error"), true)
}
| apache-2.0 | 0983fe8e0d7c10ca557b5a6e8f735d19 | 44.849462 | 158 | 0.804409 | 4.912442 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/ProjectAwareWrapper.kt | 7 | 1544 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import java.util.concurrent.atomic.AtomicInteger
class ProjectAwareWrapper(val delegate: ExternalSystemProjectAware,
parentDisposable: Disposable) : ExternalSystemProjectAware by delegate {
val subscribeCounter = AtomicInteger(0)
val unsubscribeCounter = AtomicInteger(0)
val refreshCounter = AtomicInteger(0)
val beforeRefreshCounter = AtomicInteger(0)
val afterRefreshCounter = AtomicInteger(0)
override val settingsFiles = delegate.settingsFiles
init {
delegate.subscribe(object : ExternalSystemProjectListener {
override fun onProjectReloadStart() {
beforeRefreshCounter.incrementAndGet()
}
override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) {
afterRefreshCounter.incrementAndGet()
}
}, parentDisposable)
}
override fun subscribe(listener: ExternalSystemProjectListener, parentDisposable: Disposable) {
delegate.subscribe(listener, parentDisposable)
subscribeCounter.incrementAndGet()
Disposer.register(parentDisposable, Disposable { unsubscribeCounter.incrementAndGet() })
}
override fun reloadProject(context: ExternalSystemProjectReloadContext) {
refreshCounter.incrementAndGet()
delegate.reloadProject(context)
}
} | apache-2.0 | 19afa0111200d884b74aa4424025a96f | 38.615385 | 140 | 0.776554 | 5.475177 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/src/XmlElementStorage.kt | 2 | 16926 | // 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.configurationStore
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.vfs.LargeFileWriteRequestor
import com.intellij.openapi.vfs.SafeWriteRequestor
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.io.delete
import com.intellij.util.io.outputStream
import com.intellij.util.io.safeOutputStream
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
import org.jdom.Attribute
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.io.FileNotFoundException
import java.io.OutputStream
import java.io.Writer
import java.nio.file.Path
import kotlin.math.min
abstract class XmlElementStorage protected constructor(val fileSpec: String,
protected val rootElementName: String?,
private val pathMacroSubstitutor: PathMacroSubstitutor? = null,
roamingType: RoamingType? = RoamingType.DEFAULT,
private val provider: StreamProvider? = null) : StorageBaseEx<StateMap>() {
val roamingType = roamingType ?: RoamingType.DEFAULT
protected abstract fun loadLocalData(): Element?
final override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean) = storageData.getState(componentName, archive)
final override fun archiveState(storageData: StateMap, componentName: String, serializedState: Element?) {
storageData.archive(componentName, serializedState)
}
final override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName)
final override fun loadData() = loadElement()?.let { loadState(it) } ?: StateMap.EMPTY
private fun loadElement(useStreamProvider: Boolean = true): Element? {
var element: Element? = null
try {
val isLoadLocalData: Boolean
if (useStreamProvider && provider != null) {
isLoadLocalData = !provider.read(fileSpec, roamingType) { inputStream ->
inputStream?.let {
element = JDOMUtil.load(inputStream)
providerDataStateChanged(createDataWriterForElement(element!!, toString()), DataStateChanged.LOADED)
}
}
}
else {
isLoadLocalData = true
}
if (isLoadLocalData) {
element = loadLocalData()
}
}
catch (e: FileNotFoundException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot load data for $fileSpec", e)
}
return element
}
protected open fun providerDataStateChanged(writer: DataWriter?, type: DataStateChanged) {
}
private fun loadState(element: Element): StateMap {
beforeElementLoaded(element)
return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor))
}
final override fun createSaveSessionProducer(): SaveSessionProducer? {
return if (checkIsSavingDisabled()) null else createSaveSession(getStorageData())
}
protected abstract fun createSaveSession(states: StateMap): SaveSessionProducer
override fun analyzeExternalChangesAndUpdateIfNeeded(componentNames: MutableSet<in String>) {
val oldData = storageDataRef.get()
val newData = getStorageData(true)
if (oldData == null) {
LOG.debug { "analyzeExternalChangesAndUpdateIfNeeded: old data null, load new for ${toString()}" }
componentNames.addAll(newData.keys())
}
else {
val changedComponentNames = getChangedComponentNames(oldData, newData)
if (changedComponentNames.isNotEmpty()) {
LOG.debug { "analyzeExternalChangesAndUpdateIfNeeded: changedComponentNames $changedComponentNames for ${toString()}" }
componentNames.addAll(changedComponentNames)
}
}
}
private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) {
if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) {
LOG.warn("Old storage data is not equal to current, new storage data was set anyway")
}
}
abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() {
private var copiedStates: MutableMap<String, Any>? = null
private var newLiveStates: MutableMap<String, Element>? = HashMap()
protected open fun isSaveAllowed() = !storage.checkIsSavingDisabled()
final override fun createSaveSession(): SaveSession? {
if (copiedStates == null || !isSaveAllowed()) {
return null
}
val stateMap = StateMap.fromMap(copiedStates!!)
val elements = save(stateMap, newLiveStates ?: throw IllegalStateException("createSaveSession was already called"))
newLiveStates = null
val writer: DataWriter?
if (elements == null) {
writer = null
}
else {
val rootAttributes = LinkedHashMap<String, String>()
storage.beforeElementSaved(elements, rootAttributes)
val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager
writer = XmlDataWriter(storage.rootElementName, elements, rootAttributes, macroManager, storage.toString())
}
// during beforeElementSaved() elements can be modified and so, even if our save() never returns empty list, at this point, elements can be an empty list
return SaveExecutor(elements, writer, stateMap)
}
private inner class SaveExecutor(private val elements: MutableList<Element>?,
private val writer: DataWriter?,
private val stateMap: StateMap) : SaveSession, SafeWriteRequestor, LargeFileWriteRequestor {
override fun save() {
var isSavedLocally = false
val provider = storage.provider
if (elements == null) {
if (provider == null || !provider.delete(storage.fileSpec, storage.roamingType)) {
isSavedLocally = true
saveLocally(writer)
}
}
else if (provider != null && provider.isApplicable(storage.fileSpec, storage.roamingType)) {
// we should use standard line-separator (\n) - stream provider can share file content on any OS
provider.write(storage.fileSpec, writer!!.toBufferExposingByteArray(), storage.roamingType)
}
else {
isSavedLocally = true
saveLocally(writer)
}
if (!isSavedLocally) {
storage.providerDataStateChanged(writer, DataStateChanged.SAVED)
}
storage.setStates(originalStates, stateMap)
}
}
override fun setSerializedState(componentName: String, element: Element?) {
val newLiveStates = newLiveStates ?: throw IllegalStateException("createSaveSession was already called")
val normalized = element?.normalizeRootName()
if (copiedStates == null) {
copiedStates = setStateAndCloneIfNeeded(componentName, normalized, originalStates, newLiveStates)
}
else {
updateState(copiedStates!!, componentName, normalized, newLiveStates)
}
}
protected abstract fun saveLocally(dataWriter: DataWriter?)
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
}
fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) {
updatedFrom(changedComponentNames, deleted, true)
}
fun updatedFrom(changedComponentNames: MutableSet<String>, deleted: Boolean, useStreamProvider: Boolean) {
if (roamingType == RoamingType.DISABLED) {
// storage roaming was changed to DISABLED, but settings repository has old state
return
}
LOG.runAndLogException {
val newElement = if (deleted) null else loadElement(useStreamProvider)
val states = storageDataRef.get()
if (newElement == null) {
// if data was loaded, mark as changed all loaded components
if (states != null) {
changedComponentNames.addAll(states.keys())
setStates(states, null)
}
}
else if (states != null) {
val newStates = loadState(newElement)
changedComponentNames.addAll(getChangedComponentNames(states, newStates))
setStates(states, newStates)
}
}
}
}
internal class XmlDataWriter(private val rootElementName: String?,
private val elements: List<Element>,
private val rootAttributes: Map<String, String>,
private val macroManager: PathMacroManager?,
private val storageFilePathForDebugPurposes: String) : StringDataWriter() {
override fun hasData(filter: DataWriterFilter): Boolean {
return elements.any { filter.hasData(it) }
}
override fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?) {
var lineSeparatorWithIndent = lineSeparator
val hasRootElement = rootElementName != null
val replacePathMap = macroManager?.replacePathMap
val macroFilter = macroManager?.macroFilter
if (hasRootElement) {
lineSeparatorWithIndent += " "
writer.append('<').append(rootElementName)
for (entry in rootAttributes) {
writer.append(' ')
writer.append(entry.key)
writer.append('=')
writer.append('"')
var value = entry.value
if (replacePathMap != null) {
value = replacePathMap.substitute(JDOMUtil.escapeText(value, false, true), SystemInfo.isFileSystemCaseSensitive)
}
writer.append(JDOMUtil.escapeText(value, false, true))
writer.append('"')
}
if (elements.isEmpty()) {
// see note in the save() why elements here can be an empty list
writer.append(" />")
return
}
writer.append('>')
}
val xmlOutputter = JbXmlOutputter(lineSeparatorWithIndent, filter?.toElementFilter(), replacePathMap, macroFilter, storageFilePathForDebugPurposes = storageFilePathForDebugPurposes)
for (element in elements) {
if (hasRootElement) {
writer.append(lineSeparatorWithIndent)
}
xmlOutputter.printElement(writer, element, 0)
}
if (rootElementName != null) {
writer.append(lineSeparator)
writer.append("</").append(rootElementName).append('>')
}
}
}
private fun save(states: StateMap, newLiveStates: Map<String, Element>): MutableList<Element>? {
if (states.isEmpty()) {
return null
}
var result: MutableList<Element>? = null
for (componentName in states.keys()) {
val element: Element
try {
element = states.getElement(componentName, newLiveStates)?.clone() ?: continue
}
catch (e: Exception) {
LOG.error("Cannot save \"$componentName\" data", e)
continue
}
// name attribute should be first
val elementAttributes = element.attributes
var nameAttribute = element.getAttribute(FileStorageCoreUtil.NAME)
@Suppress("SuspiciousEqualsCombination")
if (nameAttribute != null && nameAttribute === elementAttributes[0] && componentName == nameAttribute.value) {
// all is OK
}
else {
if (nameAttribute == null) {
nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName)
elementAttributes.add(0, nameAttribute)
}
else {
nameAttribute.value = componentName
if (elementAttributes[0] != nameAttribute) {
elementAttributes.remove(nameAttribute)
elementAttributes.add(0, nameAttribute)
}
}
}
if (result == null) {
result = SmartList()
}
result.add(element)
}
return result
}
internal fun Element.normalizeRootName(): Element {
if (org.jdom.JDOMInterner.isInterned(this)) {
if (name == FileStorageCoreUtil.COMPONENT) {
return this
}
else {
val clone = clone()
clone.name = FileStorageCoreUtil.COMPONENT
return clone
}
}
else {
if (parent != null) {
LOG.warn("State element must not have a parent: ${JDOMUtil.writeElement(this)}")
detach()
}
name = FileStorageCoreUtil.COMPONENT
return this
}
}
// newStorageData - myStates contains only live (unarchived) states
private fun getChangedComponentNames(oldStateMap: StateMap, newStateMap: StateMap): Set<String> {
val newKeys = newStateMap.keys()
val existingKeys = oldStateMap.keys()
val bothStates = ArrayList<String>(min(newKeys.size, existingKeys.size))
@Suppress("SSBasedInspection")
val existingKeysSet = if (existingKeys.size < 3) existingKeys.asList() else ObjectOpenHashSet(existingKeys)
for (newKey in newKeys) {
if (existingKeysSet.contains(newKey)) {
bothStates.add(newKey)
}
}
val diffs = CollectionFactory.createSmallMemoryFootprintSet<String>(newKeys.size + existingKeys.size)
diffs.addAll(newKeys)
diffs.addAll(existingKeys)
for (state in bothStates) {
diffs.remove(state)
}
for (componentName in bothStates) {
oldStateMap.compare(componentName, newStateMap, diffs)
}
return diffs
}
enum class DataStateChanged {
LOADED, SAVED
}
interface DataWriterFilter {
enum class ElementLevel {
ZERO, FIRST
}
companion object {
fun requireAttribute(name: String, onLevel: ElementLevel): DataWriterFilter {
return object: DataWriterFilter {
override fun toElementFilter(): JDOMUtil.ElementOutputFilter {
return JDOMUtil.ElementOutputFilter { childElement, level -> level != onLevel.ordinal || childElement.getAttribute(name) != null }
}
override fun hasData(element: Element): Boolean {
val elementFilter = toElementFilter()
if (onLevel == ElementLevel.ZERO && elementFilter.accept(element, 0)) {
return true
}
return element.children.any { elementFilter.accept(it, 1) }
}
}
}
}
fun toElementFilter(): JDOMUtil.ElementOutputFilter
fun hasData(element: Element): Boolean
}
interface DataWriter {
// LineSeparator cannot be used because custom (with an indent) line separator can be used
fun write(output: OutputStream, lineSeparator: String = LineSeparator.LF.separatorString, filter: DataWriterFilter? = null)
fun hasData(filter: DataWriterFilter): Boolean
}
internal fun DataWriter?.writeTo(file: Path, requestor: Any?, lineSeparator: String = LineSeparator.LF.separatorString) {
if (this == null) {
file.delete()
}
else {
val safe = SafeWriteRequestor.shouldUseSafeWrite(requestor)
(if (safe) file.safeOutputStream() else file.outputStream()).use {
write(it, lineSeparator)
}
}
}
internal abstract class StringDataWriter : DataWriter {
final override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) {
output.bufferedWriter().use {
write(it, lineSeparator, filter)
}
}
internal abstract fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?)
}
internal fun DataWriter.toBufferExposingByteArray(lineSeparator: LineSeparator = LineSeparator.LF): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(1024)
out.use { write(out, lineSeparator.separatorString) }
return out
}
// use ONLY for non-ordinal usages (default project, deprecated directoryBased storage)
internal fun createDataWriterForElement(element: Element, storageFilePathForDebugPurposes: String): DataWriter {
return object: DataWriter {
override fun hasData(filter: DataWriterFilter) = filter.hasData(element)
override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) {
output.bufferedWriter().use {
JbXmlOutputter(lineSeparator, elementFilter = filter?.toElementFilter(), storageFilePathForDebugPurposes = storageFilePathForDebugPurposes).output(element, it)
}
}
}
}
@ApiStatus.Internal
interface ExternalStorageWithInternalPart {
val internalStorage: StateStorage
} | apache-2.0 | 507272e11a224e0565488bdc7def8a31 | 35.718004 | 185 | 0.696916 | 5.070701 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/util/ChapterSourceSync.kt | 1 | 5176 | package eu.kanade.tachiyomi.util
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.online.HttpSource
import java.util.*
/**
* Helper method for syncing the list of chapters from the source with the ones from the database.
*
* @param db the database.
* @param rawSourceChapters a list of chapters from the source.
* @param manga the manga of the chapters.
* @param source the source of the chapters.
* @return a pair of new insertions and deletions.
*/
fun syncChaptersWithSource(db: DatabaseHelper,
rawSourceChapters: List<SChapter>,
manga: Manga,
source: Source): Pair<List<Chapter>, List<Chapter>> {
if (rawSourceChapters.isEmpty()) {
throw Exception("No chapters found")
}
// Chapters from db.
val dbChapters = db.getChapters(manga).executeAsBlocking()
val sourceChapters = rawSourceChapters.mapIndexed { i, sChapter ->
Chapter.create().apply {
copyFrom(sChapter)
manga_id = manga.id
source_order = i
}
}
// Chapters from the source not in db.
val toAdd = mutableListOf<Chapter>()
// Chapters whose metadata have changed.
val toChange = mutableListOf<Chapter>()
for (sourceChapter in sourceChapters) {
val dbChapter = dbChapters.find { it.url == sourceChapter.url }
// Add the chapter if not in db already, or update if the metadata changed.
if (dbChapter == null) {
toAdd.add(sourceChapter)
} else {
//this forces metadata update for the main viewable things in the chapter list
ChapterRecognition.parseChapterNumber(sourceChapter, manga)
if (shouldUpdateDbChapter(dbChapter, sourceChapter)) {
dbChapter.scanlator = sourceChapter.scanlator
dbChapter.name = sourceChapter.name
dbChapter.date_upload = sourceChapter.date_upload
dbChapter.chapter_number = sourceChapter.chapter_number
toChange.add(dbChapter)
}
}
}
// Recognize number for new chapters.
toAdd.forEach {
if (source is HttpSource) {
source.prepareNewChapter(it, manga)
}
ChapterRecognition.parseChapterNumber(it, manga)
}
// Chapters from the db not in the source.
val toDelete = dbChapters.filterNot { dbChapter ->
sourceChapters.any { sourceChapter ->
dbChapter.url == sourceChapter.url
}
}
// Return if there's nothing to add, delete or change, avoiding unnecessary db transactions.
if (toAdd.isEmpty() && toDelete.isEmpty() && toChange.isEmpty()) {
return Pair(emptyList(), emptyList())
}
val readded = mutableListOf<Chapter>()
db.inTransaction {
val deletedChapterNumbers = TreeSet<Float>()
val deletedReadChapterNumbers = TreeSet<Float>()
if (!toDelete.isEmpty()) {
for (c in toDelete) {
if (c.read) {
deletedReadChapterNumbers.add(c.chapter_number)
}
deletedChapterNumbers.add(c.chapter_number)
}
db.deleteChapters(toDelete).executeAsBlocking()
}
if (!toAdd.isEmpty()) {
// Set the date fetch for new items in reverse order to allow another sorting method.
// Sources MUST return the chapters from most to less recent, which is common.
var now = Date().time
for (i in toAdd.indices.reversed()) {
val c = toAdd[i]
c.date_fetch = now++
// Try to mark already read chapters as read when the source deletes them
if (c.isRecognizedNumber && c.chapter_number in deletedReadChapterNumbers) {
c.read = true
}
if (c.isRecognizedNumber && c.chapter_number in deletedChapterNumbers) {
readded.add(c)
}
}
db.insertChapters(toAdd).executeAsBlocking()
}
if (!toChange.isEmpty()) {
db.insertChapters(toChange).executeAsBlocking()
}
// Fix order in source.
db.fixChaptersSourceOrder(sourceChapters).executeAsBlocking()
// Set this manga as updated since chapters were changed
manga.last_update = Date().time
db.updateLastUpdated(manga).executeAsBlocking()
}
return Pair(toAdd.subtract(readded).toList(), toDelete.subtract(readded).toList())
}
//checks if the chapter in db needs updated
private fun shouldUpdateDbChapter(dbChapter: Chapter, sourceChapter: SChapter): Boolean {
return dbChapter.scanlator != sourceChapter.scanlator || dbChapter.name != sourceChapter.name ||
dbChapter.date_upload != sourceChapter.date_upload ||
dbChapter.chapter_number != sourceChapter.chapter_number
} | apache-2.0 | beb9045019723d5fe9955c2ab16327b1 | 36.244604 | 100 | 0.627318 | 4.709736 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/Game2048/AI2048.kt | 1 | 5254 | package stan.androiddemo.project.Game2048
import stan.androiddemo.tool.Logger
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by stanhu on 22/8/2017.
*/
class AI2048(var grid: Grid) {
val minSearchTime = 150
fun eval():Double{
val emptyCellsNum = grid.getAvailableCells().size
val smoothWeight = 0.1
val monoWeight = 1.0
val emptyWeight = 2.7
val maxWeigh = 1.0
val maxValue = Math.log(grid.maxTileValue().toDouble()) / Math.log(2.0)
val a = grid.smoothness() * smoothWeight
val b = grid.monotonly() * monoWeight
val c = Math.log(emptyCellsNum.toDouble()) * emptyWeight
val d = maxValue * maxWeigh
Logger.e("A:$a---B:$b----C:$c----D:$d")
Logger.e("result:"+(a + b + c + d))
return a + b + c + d
}
fun search(depth:Int,alpha:Double,beta:Double,positions:Int,cutoffs:Int):MoveResult{
var bestScore:Double = 0.0
var bestMove = -1
var result:MoveResult? = null
var position = positions
var cutoff = cutoffs
if (grid.playerTurn) {
bestScore = alpha
(0 until 4).map {
val virtualGrid = grid.clone() //这里里面的东西可能要copy一份
if (virtualGrid.move(it)) {
position++
if (virtualGrid.isWin()) {
return MoveResult(it, 10000.0, position, cutoffs)
}
val ai = AI2048(virtualGrid)
if (depth == 0) {
result = MoveResult(it, ai.eval(), 0, 0)
} else {
result = ai.search(depth - 1, bestScore, beta, position, cutoffs)
if (result!!.score > 9900) {
result!!.score--
}
position = result!!.positions
cutoff = result!!.cutoffs
}
if (result!!.score > bestScore) {
bestScore = result!!.score
bestMove = it
}
if (bestScore > beta) {
cutoff++
return MoveResult(bestMove, beta, position, cutoff)
}
}
}
}
else{
bestScore = beta
var candidates = arrayListOf<Pair<Cell,Int>>()
val cells = grid.getAvailableCells()
var scores = hashMapOf(2 to ArrayList<Double?>(),4 to ArrayList<Double?>())
for (v in scores){
for (c in 0 until cells.size){
v.value.add(null)
val tile = Tile(cells[c],v.key)
grid.insertTile(tile)
v.value[c] = grid.isLands() - grid.smoothness()
grid.removeTile(tile)
}
}
val maxScore = Math.max(scores[2]!!.maxBy { it!! }!!,scores[4]!!.maxBy { it!! }!!)
for (v in scores){
for (i in 0 until scores[v.key]!!.size ){
if (scores[v.key]!![i] == maxScore){
candidates.add(Pair(cells[i],v.key))
}
}
}
for (i in 0 until candidates.size){
val pos = candidates[i].first
val value = candidates[i].second
val newGrid = grid.clone()
val tile = Tile(pos,value)
newGrid.insertTile(tile)
newGrid.playerTurn = true
position ++
val newAI = AI2048(newGrid)
result = newAI.search(depth,alpha,bestScore,position,cutoffs)
position = result!!.positions
cutoff = result!!.cutoffs
if (result!!.score < bestScore){
bestScore = result!!.score
}
if (bestScore < alpha){
cutoff++
return MoveResult(null, beta, position, cutoff)
}
}
}
return MoveResult(bestMove,bestScore,position,cutoff)
}
fun getBest():MoveResult?{
return iterativeDeep()
}
fun iterativeDeep():MoveResult?{
val start = Date()
var depth = 0
var best:MoveResult? = null
do {
val newBest = search(depth,-10000.0,10000.0,0,0)
if (newBest.move == -1){
break
}
else{
best = newBest
}
depth++
}while (Date().time - start.time < minSearchTime)
Logger.e("结果是"+best.toString())
return best
}
}
class MoveResult{
constructor(move:Int?,score:Double,positions:Int,cutoffs: Int){
this.move = move
this.score = score
this.positions = positions
this.cutoffs = cutoffs
}
var move:Int? = 0
var score:Double = 0.0
var positions = 0
var cutoffs = 0
override fun toString(): String {
return "MoveResult(move=$move, score=$score, positions=$positions, cutoffs=$cutoffs)"
}
} | mit | 8400d207ee3f8305d1a6641e025b646f | 32.49359 | 94 | 0.473583 | 4.33887 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/security/UserSessionListener.kt | 2 | 1041 | package com.github.kerubistan.kerub.security
import com.github.kerubistan.kerub.controller.InterController
import com.github.kerubistan.kerub.model.messages.SessionEventMessage
import com.github.kerubistan.kerub.utils.getLogger
import org.springframework.web.context.support.WebApplicationContextUtils
import javax.servlet.http.HttpSessionEvent
import javax.servlet.http.HttpSessionListener
class UserSessionListener : HttpSessionListener {
companion object {
private val logger = getLogger()
}
override fun sessionDestroyed(se: HttpSessionEvent) {
val applicationContext = WebApplicationContextUtils.getWebApplicationContext(se.session.servletContext)
val interController: InterController =
applicationContext.getBean("interController", InterController::class.java)
interController.broadcast(SessionEventMessage(closed = true, sessionId = se.session.id))
logger.info("session destroy: {}", se.session.id)
}
override fun sessionCreated(se: HttpSessionEvent) {
logger.debug("session created: {}", se.session.id)
}
} | apache-2.0 | 07446532c20b2b2ac2b4d74868871053 | 37.592593 | 105 | 0.818444 | 4.180723 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/drink/RPKDrinkProviderImpl.kt | 1 | 2966 | package com.rpkit.drinks.bukkit.drink
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.drink.bukkit.drink.RPKDrink
import com.rpkit.drink.bukkit.drink.RPKDrinkProvider
import com.rpkit.drink.bukkit.event.drink.RPKBukkitDrunkennessChangeEvent
import com.rpkit.drinks.bukkit.RPKDrinksBukkit
import com.rpkit.drinks.bukkit.database.table.RPKDrunkennessTable
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ShapelessRecipe
class RPKDrinkProviderImpl(private val plugin: RPKDrinksBukkit): RPKDrinkProvider {
override val drinks: List<RPKDrink> = plugin.config.getConfigurationSection("drinks")
?.getKeys(false)
?.mapNotNull { name ->
val drinkItem = plugin.config.getItemStack("drinks.$name.item") ?: return@mapNotNull null
val recipe = ShapelessRecipe(NamespacedKey(plugin, name), drinkItem)
plugin.config.getConfigurationSection("drinks.$name.recipe")
?.getKeys(false)
?.forEach { item ->
recipe.addIngredient(plugin.config.getInt("drinks.$name.recipe.$item"),
Material.matchMaterial(item)
?: Material.matchMaterial(item, true)
?: throw IllegalArgumentException("Invalid material $item in recipe for $name")
)
}
RPKDrinkImpl(
name,
drinkItem,
recipe,
plugin.config.getInt("drinks.$name.drunkenness")
)
}
?: listOf()
override fun getDrunkenness(character: RPKCharacter): Int {
return plugin.core.database.getTable(RPKDrunkennessTable::class).get(character)?.drunkenness?:0
}
override fun setDrunkenness(character: RPKCharacter, drunkenness: Int) {
val event = RPKBukkitDrunkennessChangeEvent(character, getDrunkenness(character), drunkenness)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
val drunkennessTable = plugin.core.database.getTable(RPKDrunkennessTable::class)
var charDrunkenness = drunkennessTable.get(character)
if (charDrunkenness != null) {
charDrunkenness.drunkenness = drunkenness
drunkennessTable.update(charDrunkenness)
} else {
charDrunkenness = RPKDrunkenness(character = character, drunkenness = drunkenness)
drunkennessTable.insert(charDrunkenness)
}
}
override fun getDrink(name: String): RPKDrink? {
return drinks.firstOrNull { it.name == name }
}
override fun getDrink(item: ItemStack): RPKDrink? {
return drinks.firstOrNull { it.item.isSimilar(item) }
}
} | apache-2.0 | 316b34d9b06a6a9f3abf51cd085461c5 | 43.283582 | 123 | 0.633513 | 4.984874 | false | true | false | false |
Doist/TodoistPojos | src/main/java/com/todoist/pojo/Model.kt | 1 | 330 | package com.todoist.pojo
open class Model(open var id: String, open var isDeleted: Boolean) {
override fun equals(other: Any?) = when {
this === other -> true
other == null || javaClass != other.javaClass -> false
else -> id == (other as Model).id
}
override fun hashCode() = id.hashCode()
}
| mit | 038b57a2b52d81a7617bdd0231a9c2e3 | 29 | 68 | 0.609091 | 4.074074 | false | false | false | false |
VerifAPS/verifaps-lib | aps-rvt/src/main/kotlin/edu/kit/iti/formal/automation/rvt/rvt.kt | 1 | 9250 | package edu.kit.iti.formal.automation.rvt
import edu.kit.iti.formal.smv.ModuleType
import edu.kit.iti.formal.smv.SMVFacade
import edu.kit.iti.formal.smv.SMVPrinter
import edu.kit.iti.formal.smv.ast.*
import edu.kit.iti.formal.util.CodeWriter
import edu.kit.iti.formal.util.info
import java.io.Writer
/**
*
*/
fun commonVariables(a: Collection<SVariable>,
b: Collection<SVariable>,
pred: SVarEquals)
: Set<Pair<SVariable, SVariable>> {
val set = HashSet<Pair<SVariable, SVariable>>()
for (oldVar in a) {
for (newVar in b) {
if (pred(oldVar, newVar)) {
set.add(Pair(oldVar, newVar))
}
}
}
return set
}
/**
*
*/
typealias SVarEquals = (SVariable, SVariable) -> Boolean
val nameEqual: SVarEquals = { a, b -> a.name == b.name }
/**
*
* @author Alexander Weigl
* @version 1 (12.06.17)
*/
open class RegressionVerification(
var newVersion: SMVModule,
var oldVersion: SMVModule) {
val glueModule = SMVModule("main")
var oldModuleType: ModuleType? = null
var newModuleType: ModuleType? = null
val oldInstanceName = "__old__"
val newInstanceName = "__new__"
protected open fun commonInputVariables(): Set<Pair<SVariable, SVariable>> {
return commonVariables(oldVersion.moduleParameters, newVersion.moduleParameters, nameEqual)
}
protected open fun commonOutputVariables(): Set<Pair<SVariable, SVariable>> {
return commonOutputVariables(oldVersion, newVersion, nameEqual)
}
protected open fun staticInitModule() {
glueModule.name = "main"
if (newVersion.name == oldVersion.name) {
newVersion.name += "_new"
oldVersion.name += "_old"
info("modules renamed due to collision")
}
newModuleType = ModuleType(newVersion.name, newVersion.moduleParameters)
oldModuleType = ModuleType(oldVersion.name, oldVersion.moduleParameters)
}
protected open fun addInputVariables() {
val commonInput = commonInputVariables()
val uncoveredOld = ArrayList<SVariable>(oldVersion.moduleParameters)
val uncoveredNew = ArrayList<SVariable>(newVersion.moduleParameters)
info("Common input variables: %s", commonInput.joinToString {
"(${it.first.name}, ${it.second.name})"
})
for ((first, second) in commonInput) {
assert(first.dataType == second.dataType) { "Datatypes are not equal for ${first} and ${second}" }
glueModule.inputVars.add(first)
uncoveredOld.remove(first)
uncoveredNew.remove(second)
}
info("Old exclusive variables: %s", uncoveredOld.joinToString { it.name })
info("New exclusive variables: %s", uncoveredNew.joinToString { it.name })
handleSpecialInputVariables(uncoveredOld, uncoveredNew);
}
/**
* @param uncoveredOld
* @param uncoveredNew
*/
protected open fun handleSpecialInputVariables(uncoveredOld: List<SVariable>, uncoveredNew: List<SVariable>) {
uncoveredNew.forEach { glueModule.inputVars.add(it) }
uncoveredOld.forEach { glueModule.inputVars.add(it) }
}
protected open fun addStateVariables() {
val oldModuleInstance = SVariable.create("__old__").with(oldModuleType)
val newModuleInstance = SVariable.create("__new__").with(newModuleType)
glueModule.stateVars.add(oldModuleInstance)
glueModule.stateVars.add(newModuleInstance)
}
protected open fun addProofObligation(oldName: String, newName: String) {
val output = commonOutputVariables()
val list = ArrayList<SMVExpr>()
for ((fst, snd) in output) {
val eq = SVariable.bool("eq_${fst.name}_${snd.name}")
glueModule.definitions.add(
SAssignment(eq, fst.inModule(oldName).equal(snd.inModule(newName))))
list.add(eq)
}
val equalOutputExpr = if (list.isEmpty()) SLiteral.TRUE
else SMVFacade.combine(SBinaryOperator.AND, list)
glueModule.ltlSpec.add(equalOutputExpr.globally())
glueModule.invariantSpecs.add(equalOutputExpr)
}
public fun run() {
staticInitModule()
addInputVariables()
addStateVariables()
addProofObligation(oldInstanceName, newInstanceName)
}
open fun writeTo(writer: Writer) {
val sep = "-".repeat(80) + "\n"
with(writer) {
val p = SMVPrinter(CodeWriter(writer))
glueModule.accept(p);
this.write(sep)
oldVersion.accept(p)
this.write(sep)
newVersion.accept(p)
this.write(sep)
}
}
}
private fun commonOutputVariables(oldVersion: SMVModule, newVersion: SMVModule, pred: SVarEquals):
Set<Pair<SVariable, SVariable>> {
return commonVariables(oldVersion.outputVars, newVersion.outputVars, pred)
}
val filterOutput = { k: SVariable -> k.isOutput }
private val SMVModule.outputVars: Collection<SVariable>
get() {
return this.stateVars.filter(filterOutput)
}
abstract class Miter(val oldVersion: SMVModule, val newVersion: SMVModule) {
var module = SMVModule("miter")
val parameterIsNew: MutableList<Pair<SVariable, Boolean>> = arrayListOf()
var varSystemEq: SVariable? = null
val oldPrefix = "o_"
val newPrefix = "n_"
var ltlSpec: SQuantified? = null
var invarSpec: SMVExpr? = null
abstract fun build()
open fun writeTo(writer: Writer) {
val p = CodeWriter(writer)
module.accept(SMVPrinter(p))
}
}
open class ReVeWithMiter(oldVersion: SMVModule, newVersion: SMVModule, val miter: Miter)
: RegressionVerification(newVersion, oldVersion) {
var miterInstanceName = "__miter__"
override fun addProofObligation(oldName: String, newName: String) {
miter.build()
val parameters =
miter.parameterIsNew
.map {
it.first.inModule(if (it.second) newName
else oldName)
}
val miterVar = SVariable.create(miterInstanceName).with(
ModuleType(miter.module.name, parameters)
)
glueModule.stateVars.add(miterVar)
if (miter.ltlSpec != null)
glueModule.ltlSpec.add(miter.ltlSpec?.inModule(miterInstanceName)!!)
if (miter.invarSpec != null)
glueModule.invariantSpecs.add(miter.invarSpec?.inModule(miterInstanceName)!!)
}
override fun writeTo(writer: Writer) {
super.writeTo(writer)
miter.writeTo(writer)
}
}
open class GloballyMiter(oldVersion: SMVModule, newVersion: SMVModule)
: Miter(oldVersion, newVersion) {
override fun build() {
module.name = "GloballyMiter"
val output = commonOutputVariables(oldVersion, newVersion, nameEqual)
val list = ArrayList<SMVExpr>()
for (v in oldVersion.moduleParameters + oldVersion.stateVars) {
module.moduleParameters.add(v.prefix(oldPrefix))
parameterIsNew += Pair(v, false)
}
for (v in newVersion.moduleParameters + newVersion.stateVars) {
module.moduleParameters.add(v.prefix(newPrefix))
parameterIsNew += Pair(v, true)
}
for ((fst, snd) in output) {
val eq = SVariable.bool("eq_${fst.name}_${snd.name}")
val old = fst.prefix(oldPrefix)
val new = snd.prefix(newPrefix)
module.definitions[eq] = old.equal(new)
list.add(eq)
}
val equalOutputExpr = if (list.isEmpty()) SLiteral.TRUE
else SMVFacade.combine(SBinaryOperator.AND, list)
ltlSpec = equalOutputExpr.globally()
invarSpec = equalOutputExpr
}
}
private fun SVariable.prefix(prefix: String): SVariable {
return SVariable(prefix + this.name, this.dataType!!)
}
open class UntilMiter(
val endCondtion: SMVExpr,
oldVersion: SMVModule, newVersion: SMVModule, val inner: Miter)
: Miter(oldVersion, newVersion) {
var triggerCondition = SVariable.bool("END_TRIGGER_POINT")
open fun event() {
module.definitions[triggerCondition] = endCondtion
}
override fun build() {
inner.build()
module.name = "UntilMiter"
module.moduleParameters.addAll(inner.module.moduleParameters)
parameterIsNew.addAll(inner.parameterIsNew)
event()
module.stateVars.add(
SVariable.create("inner")
.with(ModuleType(inner.module.name,
inner.module.moduleParameters))
)
val end = SVariable.bool("premise")
module.stateVars.add(end)
module.initAssignments.add(
SAssignment(end, SLiteral.TRUE))
module.nextAssignments.add(
// next(premise) = premise & !EVENT
SAssignment(end, end.and(triggerCondition.not())))
invarSpec = end.implies(inner.invarSpec?.inModule("inner")!!)
}
override fun writeTo(writer: Writer) {
super.writeTo(writer)
inner.writeTo(writer)
}
}
| gpl-3.0 | 42dfeaee9e14f27a1a8fe238a4712f09 | 30.896552 | 114 | 0.629405 | 4.078483 | false | false | false | false |
Alfresco/activiti-android-app | auth-library/src/main/kotlin/com/alfresco/auth/fragments/HelpFragment.kt | 1 | 3164 | package com.alfresco.auth.fragments
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.Button
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.alfresco.android.aims.R
import com.alfresco.common.FragmentBuilder
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class HelpFragment : BottomSheetDialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_auth_help, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val view = view ?: return
arguments?.let {
val messageResId = it.getInt(ARG_MESSAGE_RES_ID, -1)
val bodyTv: TextView = view.findViewById(R.id.bodyTxt)
val value = resources.getString(messageResId)
bodyTv.setText(HtmlCompat.fromHtml(value, HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE)
}
val closeBtn: Button = view.findViewById(R.id.btnClose)
closeBtn.setOnClickListener { dismiss() }
// Fix for https://issuetracker.google.com/issues/37132390
view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val bottomSheet = (dialog as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
bottomSheet?.let {
BottomSheetBehavior.from<View>(it).apply {
state = BottomSheetBehavior.STATE_EXPANDED
peekHeight = bottomSheet.height
}
}
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
class Builder(parent: FragmentActivity) : FragmentBuilder(parent) {
override val fragmentTag = TAG
override fun build(args: Bundle): Fragment {
val fragment = HelpFragment()
fragment.arguments = args
return fragment
}
fun message(@StringRes msgResId: Int) : Builder {
extraConfiguration.putInt(ARG_MESSAGE_RES_ID, msgResId)
return this
}
fun show() {
(build(extraConfiguration) as BottomSheetDialogFragment).show(parent.supportFragmentManager, TAG)
}
}
companion object {
private val TAG = AdvancedSettingsFragment::class.java.name
private const val ARG_MESSAGE_RES_ID = "message_res_id"
fun with(activity: FragmentActivity): HelpFragment.Builder = HelpFragment.Builder(activity)
}
}
| lgpl-3.0 | 0a211e4a1b0dfe828f4cd570f32be450 | 37.585366 | 136 | 0.692478 | 5.006329 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/dev/editor/EntityInspector.kt | 1 | 8440 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dev.editor
import com.almasb.fxgl.core.reflect.ReflectionUtils
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.dsl.components.HealthIntComponent
import com.almasb.fxgl.dsl.components.LiftComponent
import com.almasb.fxgl.dsl.components.ProjectileComponent
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.component.ComponentListener
import com.almasb.fxgl.entity.component.CopyableComponent
import com.almasb.fxgl.entity.components.CollidableComponent
import com.almasb.fxgl.ui.FXGLButton
import com.almasb.fxgl.ui.FXGLScrollPane
import com.almasb.fxgl.ui.property.DoublePropertyView
import javafx.beans.binding.*
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.scene.control.*
import javafx.scene.input.KeyCode
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.GridPane
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.text.Text
import javafx.stage.FileChooser
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import java.nio.file.Paths
/**
* TODO: how are going to modify each component data, e.g. ViewComponent add new view?
*
* @author Almas Baimagambetov ([email protected])
*/
class EntityInspector : FXGLScrollPane(), ComponentListener {
private val innerBox = VBox(5.0)
// TODO: experimental
private val componentTypes = arrayListOf<Class<out Component>>(
DevSpinComponent::class.java,
ProjectileComponent::class.java,
HealthIntComponent::class.java,
CollidableComponent::class.java
)
private val addViewButton = FXGLButton("Add View")
private val addComponentButton = FXGLButton("Add Component")
private val addCustomComponentButton = FXGLButton("Add Custom Component")
var entity: Entity? = null
set(value) {
if (field != null) {
field!!.removeComponentListener(this)
}
field = value
updateView()
}
init {
background = Background(BackgroundFill(Color.BLACK, null, null))
innerBox.background = Background(BackgroundFill(Color.BLACK, null, null))
innerBox.padding = Insets(5.0)
addViewButton.setOnAction {
entity?.let {
val viewComp = it.viewComponent
val chooser = FileChooser()
chooser.initialDirectory = File(System.getProperty("user.dir"))
chooser.title = "Select image"
chooser.extensionFilters.addAll(FileChooser.ExtensionFilter("Images", "*.png", "*.jpg"))
val file = chooser.showOpenDialog(null)
file?.let {
viewComp.addChild(getAssetLoader().loadTexture(it.toURI().toURL()))
}
}
}
addComponentButton.setOnAction {
entity?.let { selectedEntity ->
val box = ComboBox(FXCollections.observableList(componentTypes))
box.selectionModel.selectFirst()
val dialog = Dialog<ButtonType>()
dialog.dialogPane.buttonTypes.addAll(ButtonType.OK, ButtonType.CANCEL)
dialog.dialogPane.content = box
dialog.showAndWait().ifPresent {
if (it == ButtonType.OK) {
box.selectionModel.selectedItem?.let { item ->
val comp = ReflectionUtils.newInstance(item)
selectedEntity.addComponent(comp)
}
}
}
}
}
addCustomComponentButton.setOnAction {
// val chooser = FileChooser()
// chooser.initialDirectory = File(System.getProperty("user.dir"))
// chooser.title = "Select java Component"
// chooser.extensionFilters.addAll(FileChooser.ExtensionFilter("Java Source", "*.java"))
// val file = chooser.showOpenDialog(null)
try {
val file = Paths.get("fxgl-samples/target/classes/")
file?.let {
val url: URL = it.toFile().toURI().toURL()
val urls: Array<URL> = arrayOf<URL>(url)
// Create a new class loader with the directory
val cl: ClassLoader = URLClassLoader(urls)
val cls = cl.loadClass("sandbox.CustomComponent")
val instance = cls.getDeclaredConstructor().newInstance() as Component
println(instance)
entity?.let {
it.addComponent(instance)
updateView()
}
}
} catch (e : Exception) {
e.printStackTrace()
}
}
maxWidth = 460.0
content = innerBox
}
private fun updateView() {
innerBox.children.clear()
if (entity == null)
return
innerBox.children += addViewButton
innerBox.children += addComponentButton
innerBox.children += addCustomComponentButton
// TODO: this is just a placeholder and needs to be updated
entity!!.components.sortedBy { it.javaClass.simpleName }
.forEach { comp ->
innerBox.children += generateView(comp)
}
entity!!.addComponentListener(this)
}
private fun generateView(component: Component): GridPane {
val pane = GridPane()
pane.hgap = 25.0
pane.vgap = 10.0
var index = 0
val title = FXGL.getUIFactoryService().newText(component.javaClass.simpleName.removeSuffix("Component"), Color.ANTIQUEWHITE, 22.0)
pane.addRow(index++, title)
pane.addRow(index++, Rectangle(165.0, 2.0, Color.ANTIQUEWHITE))
// add property based values
component.javaClass.methods
.filter { it.name.endsWith("Property") }
.sortedBy { it.name }
.forEach { method ->
// val textKey = FXGL.getUIFactoryService().newText(method.name.removeSuffix("Property"), Color.WHITE, 18.0)
val value = method.invoke(component)
val view = getUIFactoryService().newPropertyView(method.name.removeSuffix("Property"), value)
pane.addRow(index++, view)
}
pane.addRow(index++, Text(""))
return pane
}
override fun onAdded(component: Component) {
innerBox.children += generateView(component)
}
override fun onRemoved(component: Component) {
// TODO:
}
}
// add callable methods
// TODO: only allow void methods with 0 params for now
// comp.javaClass.declaredMethods
// .filter { !it.name.endsWith("Property") }
// .sortedBy { it.name }
// .forEach { method ->
//
// val btnMethod = FXGL.getUIFactoryService().newButton(method.name + "()")
// btnMethod.setOnAction {
// getDialogService().showInputBoxWithCancel("Input key", { true }) { input ->
//
// onKeyDown(KeyCode.valueOf(input)) {
// println("Invoking: $method")
//
// method.invoke(comp)
// }
// }
// }
//
// //val textKey = FXGL.getUIFactoryService().newText(method.name + "()", Color.WHITE, 18.0)
//
// pane.addRow(index++, btnMethod)
// }
internal class DevSpinComponent : Component(), CopyableComponent<DevSpinComponent> {
override fun onUpdate(tpf: Double) {
entity.rotateBy(90 * tpf)
}
override fun copy(): DevSpinComponent {
return DevSpinComponent()
}
} | mit | 0acbc90e6ed55327c8f5f2c4c812d7cb | 32.629482 | 138 | 0.577844 | 4.912689 | false | false | false | false |
jamming/FrameworkBenchmarks | frameworks/Kotlin/ktor/ktor/src/main/kotlin/org/jetbrains/ktor/benchmarks/Hello.kt | 4 | 6693 | package org.jetbrains.ktor.benchmarks
import com.zaxxer.hikari.*
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.html.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.response.*
import io.ktor.routing.*
import kotlinx.coroutines.*
import kotlinx.html.*
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.json.*
import java.util.concurrent.*
@Serializable
data class Message(val message: String)
@Serializable
data class World(val id: Int, var randomNumber: Int)
@Serializable
data class Fortune(val id: Int, var message: String)
fun Application.main() {
val worldSerializer = World.serializer()
val worldListSerializer = ListSerializer(World.serializer())
val dbRows = 10000
val poolSize = 48
val pool by lazy { HikariDataSource(HikariConfig().apply { configurePostgres(poolSize) }) }
val databaseDispatcher = Dispatchers.IO
install(DefaultHeaders)
val okContent = TextContent("Hello, World!", ContentType.Text.Plain, HttpStatusCode.OK).also { it.contentLength }
routing {
get("/plaintext") {
call.respond(okContent)
}
get("/json") {
call.respondText(
Json.encodeToString(Message("Hello, world!")),
ContentType.Application.Json,
HttpStatusCode.OK
)
}
get("/db") {
val random = ThreadLocalRandom.current()
val queries = call.queries()
val result = ArrayList<World>(queries ?: 1)
withContext(databaseDispatcher) {
pool.connection.use { connection ->
connection.prepareStatement("SELECT id, randomNumber FROM World WHERE id = ?").use { statement ->
for (i in 1..(queries ?: 1)) {
statement.setInt(1, random.nextInt(dbRows) + 1)
statement.executeQuery().use { rs ->
while (rs.next()) {
result += World(rs.getInt(1), rs.getInt(2))
}
}
}
}
}
}
call.respondText(
when (queries) {
null -> Json.encodeToString(worldSerializer, result.single())
else -> Json.encodeToString(worldListSerializer, result)
}, ContentType.Application.Json, HttpStatusCode.OK
)
}
get("/fortunes") {
val result = mutableListOf<Fortune>()
withContext(databaseDispatcher) {
pool.connection.use { connection ->
connection.prepareStatement("SELECT id, message FROM fortune").use { statement ->
statement.executeQuery().use { rs ->
while (rs.next()) {
result += Fortune(rs.getInt(1), rs.getString(2))
}
}
}
}
}
result.add(Fortune(0, "Additional fortune added at request time."))
result.sortBy { it.message }
call.respondHtml {
head { title { +"Fortunes" } }
body {
table {
tr {
th { +"id" }
th { +"message" }
}
for (fortune in result) {
tr {
td { +fortune.id.toString() }
td { +fortune.message }
}
}
}
}
}
}
get("/updates") {
val queries = call.queries()
val random = ThreadLocalRandom.current()
val result = ArrayList<World>(queries ?: 1)
withContext(databaseDispatcher) {
pool.connection.use { connection ->
connection.prepareStatement("SELECT id, randomNumber FROM World WHERE id = ?").use { statement ->
for (i in 1..(queries ?: 1)) {
statement.setInt(1, random.nextInt(dbRows) + 1)
statement.executeQuery().use { rs ->
while (rs.next()) {
result += World(rs.getInt(1), rs.getInt(2))
}
}
}
}
result.forEach { it.randomNumber = random.nextInt(dbRows) + 1 }
connection.prepareStatement("UPDATE World SET randomNumber = ? WHERE id = ?")
.use { updateStatement ->
for ((id, randomNumber) in result) {
updateStatement.setInt(1, randomNumber)
updateStatement.setInt(2, id)
updateStatement.executeUpdate()
}
}
}
}
call.respondText(
when (queries) {
null -> Json.encodeToString(worldSerializer, result.single())
else -> Json.encodeToString(worldListSerializer, result)
}, ContentType.Application.Json, HttpStatusCode.OK
)
}
}
}
fun HikariConfig.configurePostgres(poolSize: Int) {
jdbcUrl = "jdbc:postgresql://tfb-database/hello_world?useSSL=false"
driverClassName = org.postgresql.Driver::class.java.name
configureCommon(poolSize)
}
fun HikariConfig.configureCommon(poolSize: Int) {
username = "benchmarkdbuser"
password = "benchmarkdbpass"
addDataSourceProperty("cacheServerConfiguration", true)
addDataSourceProperty("cachePrepStmts", "true")
addDataSourceProperty("useUnbufferedInput", "false")
addDataSourceProperty("prepStmtCacheSize", "4096")
addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
connectionTimeout = 10000
maximumPoolSize = poolSize
minimumIdle = poolSize
}
fun HikariConfig.configureMySql(poolSize: Int) {
jdbcUrl = "jdbc:mysql://tfb-database:3306/hello_world?useSSL=false"
driverClassName = com.mysql.jdbc.Driver::class.java.name
configureCommon(poolSize)
}
fun ApplicationCall.queries() = try {
request.queryParameters["queries"]?.toInt()?.coerceIn(1, 500)
} catch (nfe: NumberFormatException) {
1
}
| bsd-3-clause | 60e84ee8fe94b8958ed3b36044feed5a | 33.859375 | 117 | 0.512924 | 5.303487 | false | true | false | false |
mizukami2005/StockQiita | app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/util/AnimatorUtils.kt | 1 | 747 | package com.mizukami2005.mizukamitakamasa.qiitaclient.util
import android.animation.ObjectAnimator
import android.view.View
/**
* Created by mizukamitakamasa on 2016/11/06.
*/
class AnimatorUtils {
val ALPHA = "alpha"
val ROTATION = "rotation"
val TRANSLATION_Y = "translationY"
fun translationY(view: View, value: Float) {
val animate = ObjectAnimator.ofFloat(view, TRANSLATION_Y, value)
}
fun alpha(view: View, beforeValue: Float, afterValue: Float) {
val animate = ObjectAnimator.ofFloat(view, ALPHA, beforeValue, afterValue)
}
fun rotation(view: View, value: Float) {
val animate = ObjectAnimator.ofFloat(view, ROTATION, value)
}
fun fabOpen(view: View, iconWhile: Float) {
}
fun fabClose() {
}
} | mit | 47aead67f266e42295d91d55e30b9d40 | 23.129032 | 78 | 0.716198 | 3.591346 | false | false | false | false |
gdgplzen/gugorg-android | app/src/main/java/cz/jacktech/gugorganizer/network/api_objects/GugEventOccurrence.kt | 1 | 2913 | package cz.jacktech.gugorganizer.network.api_objects
import com.google.gson.annotations.SerializedName
/**
* Created by toor on 29.7.15.
*/
public class GugEventOccurrence {
public var id: Int = 0
SerializedName("event_id")
public var eventId: Int = 0
SerializedName("occurence_name")
public var occurenceName: String? = null
SerializedName("event_tagline")
public var eventTagline: String? = null
SerializedName("is_published")
public var published: Boolean = false
SerializedName("date_from")
public var dateFrom: String? = null
SerializedName("date_to")
public var dateTo: String? = null
SerializedName("registration_deadline")
public var registrationDeadline: String? = null
SerializedName("registration_link")
public var registrationLink: String? = null
SerializedName("more_info_link")
public var moreInfoLink: String? = null
SerializedName("feedback_link")
public var feedbackLink: String? = null
public var hashtag: String? = null
SerializedName("g_plus_event_link")
public var gPlusEventLink: String? = null
SerializedName("fb_event_link")
public var fbEventLink: String? = null
SerializedName("srazy_event_link")
public var srazyEventLink: String? = null
SerializedName("meetup_event_link")
public var meetupEventLink: String? = null
SerializedName("lanyrd_event_link")
public var lanyrdEventLink: String? = null
SerializedName("support_mail")
public var supportMail: String? = null
SerializedName("twitter_link")
public var twitterLink: String? = null
SerializedName("seo_name")
public var seoName: String? = null
SerializedName("show_occurence_name")
public var showOccurenceName: Boolean = false
SerializedName("guests_count")
public var guestsCount: Int = 0
SerializedName("date_is_unknown")
public var dateUnknown: Boolean = false
SerializedName("event_description")
public var eventDescription: String? = null
SerializedName("logo_image")
public var logoImage: String? = null
SerializedName("description_image")
public var descImage: String? = null
SerializedName("google_directory_link")
public var googleDirectoryLink: String? = null
SerializedName("web_link")
public var webLink: String? = null
SerializedName("youtube_link")
public var youtubeLink: String? = null
SerializedName("newsletter_text")
public var newsletterText: String? = null
SerializedName("newsletter_button_label")
public var newsletterButtonLabel: String? = null
SerializedName("event_name")
public var name: String? = null
SerializedName("event_link")
public var relativeLink: String? = null
SerializedName("event_absolute_link")
public var link: String? = null
SerializedName("_embedded")
public var details: GugEventOccurrenceDetails? = null
}
| gpl-2.0 | b29d3317f5e6ef1c8e25926c35500d6c | 35.873418 | 57 | 0.713697 | 3.95788 | false | false | false | false |
joffrey-bion/hashcode-utils | src/test/kotlin/org/hildan/hashcode/utils/writer/HCWriterTest.kt | 1 | 1391 | package org.hildan.hashcode.utils.writer
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.readLines
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class HCWriterTest {
@TempDir
lateinit var tempDirPath: Path
@ParameterizedTest
@ValueSource(strings = ["testfile.out", "dir1/dir2/testfile.out"])
fun writeHCOutputFile(filename: String) {
val outputFilePath = tempDirPath.resolve(filename)
val expectedLines = listOf("abc42", "def42", "ghi42")
writeHCOutputFile(outputFilePath, expectedLines)
assertTrue(outputFilePath.exists())
assertEquals(expectedLines, outputFilePath.readLines())
}
@Test
fun `writeHCOutputFile fails on IOException`() {
val outputPath = tempDirPath.resolve("lockedFile.out")
val lockedFile = outputPath.toFile()
lockedFile.writeText("test content")
lockedFile.setReadable(false)
lockedFile.setWritable(false)
val expectedLines = listOf("abc42", "def42", "ghi42")
assertFailsWith<SolutionWritingException> { writeHCOutputFile(outputPath, expectedLines) }
lockedFile.delete()
}
}
| mit | 7ba42094161dc4e7f8ab926f66885ab0 | 30.613636 | 98 | 0.729691 | 4.189759 | false | true | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/bet/coinflipfriend/CoinFlipBetUtils.kt | 1 | 23764 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.bet.coinflipfriend
import dev.kord.common.DiscordTimestampStyle
import dev.kord.common.entity.ButtonStyle
import dev.kord.common.entity.Snowflake
import dev.kord.common.toMessageFormat
import kotlinx.datetime.Clock
import kotlinx.datetime.toJavaInstant
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromJsonElement
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.HighLevelEditableMessage
import net.perfectdreams.loritta.cinnamon.discord.interactions.InteractionContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.SlashContextHighLevelEditableMessage
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.mentionUser
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.disabledButton
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButtonWithDatabaseData
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji
import net.perfectdreams.loritta.cinnamon.discord.interactions.editMessage
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.BetCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.declarations.CoinFlipCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.*
import net.perfectdreams.loritta.cinnamon.discord.utils.SonhosUtils.appendUserHaventGotDailyTodayOrUpsellSonhosBundles
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.cinnamon.pudding.tables.CoinFlipBetMatchmakingResults
import net.perfectdreams.loritta.cinnamon.pudding.tables.Profiles
import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog
import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.CoinFlipBetSonhosTransactionsLog
import net.perfectdreams.loritta.common.utils.UserPremiumPlans
import org.jetbrains.exposed.sql.SqlExpressionBuilder
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.update
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
class CoinFlipBetUtils(val loritta: LorittaBot) {
suspend fun createBet(
context: InteractionContext,
howMuch: Long,
receiverId: Snowflake,
combo: Int
) {
val isLoritta = receiverId == loritta.config.loritta.discord.applicationId
val ttlDuration = 3.minutes
checkIfSelfAccountIsOldEnough(context)
checkIfOtherAccountIsOldEnough(context, receiverId)
// TODO: Reenable this
// checkIfSelfAccountGotDailyRecently(context)
if (UserUtils.handleIfUserIsBanned(loritta, context, receiverId))
return
// Only defer if it wasn't deferred yet
if (!context.interaKTionsContext.isDeferred)
context.deferChannelMessage()
val userProfile = loritta.pudding.users.getUserProfile(UserId(context.user.id))
if (userProfile == null || howMuch > userProfile.money) {
context.fail {
styled(
context.i18nContext.get(SonhosUtils.insufficientSonhos(userProfile, howMuch)),
Emotes.LoriSob
)
appendUserHaventGotDailyTodayOrUpsellSonhosBundles(
loritta,
context.i18nContext,
UserId(context.user.id),
"bet-coinflip-friend",
"mm-check"
)
}
}
val receiverProfile = loritta.pudding.users.getUserProfile(UserId(receiverId))
if (receiverProfile == null || howMuch > receiverProfile.money) {
// Receiver does not have enough sonhos
context.fail {
styled(
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.InsufficientFundsInvited(mentionUser(receiverId, notifyUser = false), howMuch, howMuch - (receiverProfile?.money ?: 0L))),
Emotes.LoriSob
)
}
}
val selfActiveDonations = loritta.pudding.payments.getActiveMoneyFromDonations(UserId(context.user.id))
val otherActiveDonations = loritta.pudding.payments.getActiveMoneyFromDonations(UserId(receiverId))
val selfPlan = UserPremiumPlans.getPlanFromValue(selfActiveDonations)
val otherPlan = UserPremiumPlans.getPlanFromValue(otherActiveDonations)
val hasNoTax: Boolean
val whoHasTheNoTaxReward: Snowflake?
val plan: UserPremiumPlans?
val tax: Long?
val taxPercentage: Double?
val quantityAfterTax: Long
val money: Long
if (selfPlan.totalCoinFlipReward == 1.0) {
whoHasTheNoTaxReward = context.user.id
hasNoTax = true
plan = selfPlan
taxPercentage = null
tax = null
money = howMuch
} else if (otherPlan.totalCoinFlipReward == 1.0) {
whoHasTheNoTaxReward = receiverId
hasNoTax = true
plan = otherPlan
taxPercentage = null
tax = null
money = howMuch
} else {
whoHasTheNoTaxReward = null
hasNoTax = false
plan = UserPremiumPlans.Essential
taxPercentage = (1.0.toBigDecimal() - selfPlan.totalCoinFlipReward.toBigDecimal()).toDouble() // Avoid rounding errors
tax = (howMuch * taxPercentage).toLong()
money = howMuch - tax
}
if (!hasNoTax && tax == 0L)
context.fail {
styled(
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.YouNeedToBetMore),
Emotes.Error
)
}
// We WANT to store on the database due to two things:
// 1. We want to control the interaction TTL
// 2. We want to block duplicate transactions by buttom spamming (with this, we can block this on transaction level)
val nowPlusTimeToLive = Clock.System.now() + ttlDuration
val (interactionDataId, data, encodedData) = context.loritta.encodeDataForComponentOnDatabase(
AcceptCoinFlipBetFriendData(
receiverId,
context.user.id,
howMuch,
money,
tax,
taxPercentage,
combo
),
ttl = ttlDuration
)
val message = context.sendMessage {
if (hasNoTax) {
styled(
context.i18nContext.get(
BetCommand.COINFLIP_FRIEND_I18N_PREFIX.StartBetNoTax(
friendMention = mentionUser(receiverId),
userMention = mentionUser(context.user),
betSonhosQuantity = money,
userWithNoTaxMention = mentionUser(whoHasTheNoTaxReward!!),
)
),
Emotes.LoriRich
)
} else {
styled(
context.i18nContext.get(
BetCommand.COINFLIP_FRIEND_I18N_PREFIX.StartBet(
friendMention = mentionUser(receiverId),
userMention = mentionUser(context.user),
betSonhosQuantity = howMuch,
taxSonhosQuantity = tax!!,
betSonhosQuantityAfterTax = money
)
),
Emotes.LoriRich
)
}
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.ConfirmTheTransaction(mentionUser(receiverId), nowPlusTimeToLive.toMessageFormat(
DiscordTimestampStyle.LongDateTime), nowPlusTimeToLive.toMessageFormat(DiscordTimestampStyle.RelativeTime))),
Emotes.LoriZap
)
actionRow {
interactiveButton(
ButtonStyle.Primary,
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.AcceptBet),
AcceptCoinFlipBetFriendButtonExecutor,
encodedData
) {
loriEmoji = Emotes.Handshake
}
/* interactiveButton(
ButtonStyle.Danger,
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.Cancel),
CancelSonhosTransferButtonExecutor,
context.loritta.encodeDataForComponentOrStoreInDatabase(
CancelSonhosTransferData(
context.user.id,
interactionDataId
)
)
) {
loriEmoji = Emotes.LoriHmpf
} */
}
}
if (isLoritta) {
// If it is Loritta, we will mimick that she is *actually* accepting the bet!
acceptBet(
context,
loritta.config.loritta.discord.applicationId,
SlashContextHighLevelEditableMessage(message),
data
)
}
}
suspend fun acceptBet(
context: InteractionContext,
acceptedUserId: Snowflake,
betRequestMessage: HighLevelEditableMessage,
decodedGenericInteractionData: StoredGenericInteractionData
) {
val result = loritta.pudding.transaction {
val dataFromDatabase = loritta.pudding.interactionsData.getInteractionData(decodedGenericInteractionData.interactionDataId) ?: return@transaction Result.DataIsNotPresent // Data is not present! Maybe it expired or it was already processed
val decoded = Json.decodeFromJsonElement<AcceptCoinFlipBetFriendData>(dataFromDatabase)
if (decoded.userId != acceptedUserId)
return@transaction Result.NotTheUser(decoded.userId)
val now = Clock.System.now()
val jtNow = now.toJavaInstant()
val receiverProfile = loritta.pudding.users.getOrCreateUserProfile(UserId(decoded.userId))
val giverProfile = loritta.pudding.users.getOrCreateUserProfile(UserId(decoded.sourceId))
if (decoded.quantity > giverProfile.money)
return@transaction Result.GiverDoesNotHaveSufficientFunds // get tf outta here
if (decoded.quantity > receiverProfile.money)
return@transaction Result.ReceiverDoesNotHaveSufficientFunds // get tf outta here²
val isTails = loritta.random.nextBoolean()
val winnerId: Snowflake
val loserId: Snowflake
if (isTails) {
winnerId = decoded.sourceId
loserId = decoded.userId
} else {
winnerId = decoded.userId
loserId = decoded.sourceId
}
// Update the sonhos of both users
Profiles.update({ Profiles.id eq winnerId.value.toLong() }) {
with(SqlExpressionBuilder) {
it[Profiles.money] = Profiles.money + decoded.quantityAfterTax
}
}
Profiles.update({ Profiles.id eq loserId.value.toLong() }) {
with(SqlExpressionBuilder) {
it[Profiles.money] = Profiles.money - decoded.quantityAfterTax
}
}
// Insert transactions about it
val mmResult = CoinFlipBetMatchmakingResults.insertAndGetId {
it[CoinFlipBetMatchmakingResults.timestamp] = jtNow
it[CoinFlipBetMatchmakingResults.winner] = winnerId.toLong()
it[CoinFlipBetMatchmakingResults.loser] = loserId.toLong()
it[CoinFlipBetMatchmakingResults.quantity] = decoded.quantity
it[CoinFlipBetMatchmakingResults.quantityAfterTax] = decoded.quantityAfterTax
it[CoinFlipBetMatchmakingResults.tax] = decoded.tax
it[CoinFlipBetMatchmakingResults.taxPercentage] = decoded.taxPercentage
}
val winnerTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = winnerId.toLong()
it[SonhosTransactionsLog.timestamp] = jtNow
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = winnerTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
val loserTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = loserId.toLong()
it[SonhosTransactionsLog.timestamp] = jtNow
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = loserTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
// Delete interaction ID
loritta.pudding.interactionsData.deleteInteractionData(decodedGenericInteractionData.interactionDataId)
// Get the profiles again
val updatedReceiverProfile = loritta.pudding.users.getOrCreateUserProfile(UserId(decoded.userId))
val updatedGiverProfile = loritta.pudding.users.getOrCreateUserProfile(UserId(decoded.sourceId))
val receiverRanking = if (updatedReceiverProfile.money != 0L) loritta.pudding.sonhos.getSonhosRankPositionBySonhos(updatedReceiverProfile.money) else null
val giverRanking = if (updatedGiverProfile.money != 0L) loritta.pudding.sonhos.getSonhosRankPositionBySonhos(updatedGiverProfile.money) else null
return@transaction Result.Success(
winnerId,
loserId,
isTails,
decoded.quantity,
decoded.quantityAfterTax,
decoded.tax,
decoded.taxPercentage,
updatedReceiverProfile.money,
receiverRanking,
updatedGiverProfile.money,
giverRanking,
decoded.combo
)
}
when (result) {
is Result.Success -> {
val emote = if (result.isTails) {
Emotes.CoinTails
} else {
Emotes.CoinHeads
}
// Let's go!!
betRequestMessage.editMessage {
actionRow {
disabledButton(
ButtonStyle.Primary,
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.BetAccepted)
) {
loriEmoji = emote
}
}
}
context.sendMessage {
if (result.combo != 0) {
styled(
"**Combo! X${result.combo}**"
)
}
if (result.isTails) {
styled(
"**${context.i18nContext.get(CoinFlipCommand.I18N_PREFIX.Tails)}**!",
emote
)
} else {
styled(
"**${context.i18nContext.get(CoinFlipCommand.I18N_PREFIX.Heads)}**!",
emote
)
}
styled(
context.i18nContext.get(
BetCommand.COINFLIP_FRIEND_I18N_PREFIX.Congratulations(
winnerMention = mentionUser(result.receiverId),
quantityEmoji = SonhosUtils.getSonhosEmojiOfQuantity(result.quantityAfterTax),
sonhos = result.quantityAfterTax,
loserMention = mentionUser(result.giverId)
)
),
Emotes.Handshake
)
if (result.giverRanking != null) {
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TransferredSonhosWithRanking(mentionUser(result.giverId), SonhosUtils.getSonhosEmojiOfQuantity(result.giverQuantity), result.giverQuantity, result.giverRanking)),
Emotes.LoriSunglasses
)
} else {
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TransferredSonhos(mentionUser(result.giverId), SonhosUtils.getSonhosEmojiOfQuantity(result.giverQuantity), result.giverQuantity)),
Emotes.LoriSunglasses
)
}
if (result.receiverRanking != null) {
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TransferredSonhosWithRanking(mentionUser(result.receiverId), SonhosUtils.getSonhosEmojiOfQuantity(result.receiverQuantity), result.receiverQuantity, result.receiverRanking)),
Emotes.LoriBonk
)
} else {
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TransferredSonhos(mentionUser(result.receiverId), SonhosUtils.getSonhosEmojiOfQuantity(result.receiverQuantity), result.receiverQuantity)),
Emotes.LoriBonk
)
}
actionRow {
interactiveButtonWithDatabaseData(
loritta,
ButtonStyle.Primary,
RematchCoinFlipBetFriendButtonExecutor,
RematchCoinFlipBetFriendData(
context.user.id,
if (context.user.id == result.receiverId) result.giverId else result.receiverId,
result.quantity,
result.combo
)
) {
label = "Revanche"
}
}
}
}
is Result.NotTheUser -> {
context.failEphemerally {
styled(
context.i18nContext.get(
I18nKeysData.Commands.YouArentTheUserSingleUser(
mentionUser(result.targetId, false)
)
),
Emotes.LoriRage
)
}
}
Result.DataIsNotPresent -> {
betRequestMessage.editMessage {
actionRow {
disabledButton(
ButtonStyle.Danger,
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.BetFailed(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.FailReasons.Expired))
) {
loriEmoji = Emotes.LoriSob
}
}
}
}
Result.GiverDoesNotHaveSufficientFunds, Result.ReceiverDoesNotHaveSufficientFunds -> {
betRequestMessage.editMessage {
actionRow {
disabledButton(
ButtonStyle.Danger,
context.i18nContext.get(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.BetFailed(BetCommand.COINFLIP_FRIEND_I18N_PREFIX.FailReasons.InsufficientSonhos))
) {
loriEmoji = Emotes.LoriSob
}
}
}
}
}
}
private suspend fun checkIfSelfAccountGotDailyRecently(context: InteractionContext) {
val now = Clock.System.now()
// Check if the user got daily in the last 14 days before allowing a transaction
val gotDailyRewardInTheLastXDays = context.loritta.pudding.sonhos.getUserLastDailyRewardReceived(
UserId(context.user.id),
now - 14.days
) != null
if (!gotDailyRewardInTheLastXDays)
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.SelfAccountNeedsToGetDaily(context.loritta.commandMentions.daily)),
Emotes.LoriSob
)
}
private fun checkIfSelfAccountIsOldEnough(context: InteractionContext) {
val now = Clock.System.now()
val timestamp = context.user.id.timestamp
val allowedAfterTimestamp = timestamp + (14.days)
if (allowedAfterTimestamp > now) // 14 dias
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.SelfAccountIsTooNew(allowedAfterTimestamp.toMessageFormat(
DiscordTimestampStyle.LongDateTime), allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.RelativeTime))),
Emotes.LoriSob
)
}
private fun checkIfOtherAccountIsOldEnough(context: InteractionContext, targetId: Snowflake) {
val now = Clock.System.now()
val timestamp = targetId.timestamp
val allowedAfterTimestamp = timestamp + (7.days)
if (timestamp + (7.days) > now) // 7 dias
context.failEphemerally {
styled(
context.i18nContext.get(
SonhosCommand.PAY_I18N_PREFIX.OtherAccountIsTooNew(
mentionUser(targetId),
allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.LongDateTime),
allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.RelativeTime)
)
),
Emotes.LoriSob
)
}
}
private sealed class Result {
class Success(
val receiverId: Snowflake,
val giverId: Snowflake,
val isTails: Boolean,
val quantity: Long,
val quantityAfterTax: Long,
val tax: Long?,
val taxPercentage: Double?,
val receiverQuantity: Long,
val receiverRanking: Long?,
val giverQuantity: Long,
val giverRanking: Long?,
val combo: Int
) : Result()
class NotTheUser(val targetId: Snowflake) : Result()
object DataIsNotPresent : Result()
object GiverDoesNotHaveSufficientFunds : Result()
object ReceiverDoesNotHaveSufficientFunds : Result()
}
} | agpl-3.0 | 898c6d6210180eab3e5a817255406aff | 43.501873 | 256 | 0.580609 | 5.399455 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/services/PowerConnectedWork.kt | 1 | 2741 | package com.androidvip.hebf.services
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.work.*
import com.androidvip.hebf.receivers.PowerConnectionReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
class PowerConnectedWork(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
unregisterReceiver(applicationContext)
return@withContext registerPowerConnectionReceiver(applicationContext)
}
companion object {
private const val WORK_TAG = "POWER_CONNECTED_WORK_REQUEST"
var receiver: PowerConnectionReceiver? = null
fun registerPowerConnectionReceiver(context: Context): Result {
return runCatching {
receiver = PowerConnectionReceiver()
IntentFilter(Intent.ACTION_POWER_CONNECTED).apply {
context.applicationContext.registerReceiver(receiver, this)
}
Result.success()
}.getOrDefault(Result.failure())
}
fun unregisterReceiver(context: Context) {
try {
if (receiver != null) {
context.applicationContext.unregisterReceiver(receiver)
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
receiver = null
}
}
fun scheduleJobPeriodic(context: Context?) {
if (context == null) return
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.setRequiresCharging(false)
.build()
val request = PeriodicWorkRequest.Builder(
PowerConnectedWork::class.java,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS,
PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,
TimeUnit.MILLISECONDS
).setConstraints(constraints).build()
val workManager = WorkManager.getInstance(context.applicationContext)
workManager.enqueueUniquePeriodicWork(
WORK_TAG,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancelJob(context: Context) {
runCatching {
WorkManager.getInstance(context.applicationContext).cancelAllWorkByTag(WORK_TAG)
unregisterReceiver(context)
}
}
}
} | apache-2.0 | 9c29a70c2719831a1a67ed455bf4a9df | 34.61039 | 104 | 0.610726 | 5.971678 | false | false | false | false |
gotev/recycler-adapter | app/demo/src/main/java/net/gotev/recycleradapterdemo/App.kt | 1 | 761 | package net.gotev.recycleradapterdemo
import android.app.Application
import net.gotev.recycleradapterdemo.network.NetworkFactory
import net.gotev.recycleradapterdemo.network.api.StarWarsAPI
import retrofit2.converter.gson.GsonConverterFactory
class App : Application() {
companion object {
lateinit var starWarsClient: StarWarsAPI
}
override fun onCreate() {
super.onCreate()
val network = NetworkFactory()
starWarsClient = network.newRetrofit(
service = StarWarsAPI::class.java,
httpClient = network.newClientBuilder().build(),
converterFactory = GsonConverterFactory.create(),
baseUrl = "https://gotev.github.io/swapi-android/"
)
}
}
| apache-2.0 | 5486d4696bf84005d8f8dcfc8fe9281b | 29.44 | 66 | 0.681997 | 4.816456 | false | false | false | false |
jiangkang/KTools | tools/src/main/java/com/jiangkang/tools/utils/DownloadUtils.kt | 1 | 2380 | package com.jiangkang.tools.utils
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import okhttp3.*
import okhttp3.internal.closeQuietly
import java.io.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Created by jiangkang on 2017/10/16.
*/
object DownloadUtils {
private val client: OkHttpClient = OkHttpClient.Builder().build()
private val downloadService: ExecutorService = Executors.newCachedThreadPool()
@JvmStatic
fun downloadBitmap(url: String, callback: DownloadBitmapCallback?) {
val request = Request.Builder().url(url).build()
downloadService.submit {
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
callback?.onFailed(e.message)
}
override fun onResponse(call: Call, response: Response) {
val bitmap = BitmapFactory.decodeStream(response.body?.byteStream())
callback?.onSuccess(bitmap)
}
})
}
}
@JvmStatic
fun downloadFile(url: String,outputFile:File,callback: DownloadCallback?){
val request = Request.Builder().url(url).build()
downloadService.submit {
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
callback?.onFailed(e.message)
}
override fun onResponse(call: Call, response: Response) {
if (!outputFile.exists()){
outputFile.createNewFile()
}
FileOutputStream(outputFile).apply {
write(response.body?.bytes())
flush()
closeQuietly()
}
callback?.onSuccess(outputFile)
}
})
}
}
interface DownloadCallback {
fun onSuccess(downloadedFile: File)
fun onFailed(msg: String?)
}
abstract class DownloadBitmapCallback: DownloadCallback{
abstract fun onSuccess(bitmap:Bitmap?)
override fun onSuccess(downloadedFile: File) {
// do nothing
}
}
}
| mit | e3a93d9b14403fa151a546e4fbfe5764 | 31.162162 | 88 | 0.586134 | 5.36036 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/controller/GameController.kt | 1 | 9860 | package cz.vhromada.catalog.web.controller
import cz.vhromada.catalog.entity.Game
import cz.vhromada.catalog.facade.GameFacade
import cz.vhromada.catalog.web.exception.IllegalRequestException
import cz.vhromada.catalog.web.fo.GameFO
import cz.vhromada.catalog.web.mapper.GameMapper
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.Errors
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import javax.validation.Valid
/**
* A class represents controller for games.
*
* @author Vladimir Hromada
*/
@Controller("gameController")
@RequestMapping("/games")
class GameController(
private val gameFacade: GameFacade,
private val gameMapper: GameMapper) : AbstractResultController() {
/**
* Process new data.
*
* @return view for redirect to page with list of games
*/
@GetMapping("/new")
fun processNew(): String {
processResults(gameFacade.newData())
return LIST_REDIRECT_URL
}
/**
* Shows page with list of games.
*
* @param model model
* @return view for page with list of games
*/
@GetMapping("", "/list")
fun showList(model: Model): String {
val gamesResult = gameFacade.getAll()
val mediaCountResult = gameFacade.getTotalMediaCount()
processResults(gamesResult, mediaCountResult)
model.addAttribute("games", gamesResult.data)
model.addAttribute("mediaCount", mediaCountResult.data)
model.addAttribute("title", "Games")
return "game/index"
}
/**
* Shows page with detail of game.
*
* @param model model
* @param id ID of editing game
* @return view for page with detail of game
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/{id}/detail")
fun showDetail(model: Model, @PathVariable("id") id: Int?): String {
val result = gameFacade.get(id!!)
processResults(result)
val game = result.data
if (game != null) {
model.addAttribute("game", game)
model.addAttribute("title", "Game detail")
return "game/detail"
} else {
throw IllegalRequestException(ILLEGAL_REQUEST_MESSAGE)
}
}
/**
* Shows page for adding game.
*
* @param model model
* @return view for page for adding game
*/
@GetMapping("/add")
fun showAdd(model: Model): String {
val game = GameFO(id = null,
name = null,
wikiEn = null,
wikiCz = null,
mediaCount = null,
crack = null,
serialKey = null,
patch = null,
trainer = null,
trainerData = null,
editor = null,
saves = null,
otherData = null,
note = null,
position = null)
return createFormView(model, game, "Add game", "add")
}
/**
* Process adding game.
*
* @param model model
* @param game FO for game
* @param errors errors
* @return view for redirect to page with list of games (no errors) or view for page for adding game (errors)
* @throws IllegalArgumentException if ID isn't null
*/
@PostMapping(value = ["/add"], params = ["create"])
fun processAdd(model: Model, @ModelAttribute("game") @Valid game: GameFO, errors: Errors): String {
require(game.id == null) { "ID must be null." }
if (errors.hasErrors()) {
return createFormView(model, game, "Add game", "add")
}
processResults(gameFacade.add(gameMapper.mapBack(game)))
return LIST_REDIRECT_URL
}
/**
* Cancel adding game.
*
* @return view for redirect to page with list of games
*/
@PostMapping(value = ["/add"], params = ["cancel"])
fun cancelAdd(): String {
return LIST_REDIRECT_URL
}
/**
* Shows page for editing game.
*
* @param model model
* @param id ID of editing game
* @return view for page for editing game
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/edit/{id}")
fun showEdit(model: Model, @PathVariable("id") id: Int): String {
val result = gameFacade.get(id)
processResults(result)
val game = result.data
return if (game != null) {
createFormView(model, gameMapper.map(game), "Edit game", "edit")
} else {
throw IllegalRequestException(ILLEGAL_REQUEST_MESSAGE)
}
}
/**
* Process editing game.
*
* @param model model
* @param game FO for game
* @param errors errors
* @return view for redirect to page with list of games (no errors) or view for page for editing game (errors)
* @throws IllegalArgumentException if ID is null
* @throws IllegalRequestException if game doesn't exist
*/
@PostMapping(value = ["/edit"], params = ["update"])
fun processEdit(model: Model, @ModelAttribute("game") @Valid game: GameFO, errors: Errors): String {
require(game.id != null) { "ID mustn't be null." }
if (errors.hasErrors()) {
return createFormView(model, game, "Edit game", "edit")
}
processResults(gameFacade.update(processGame(gameMapper.mapBack(game))))
return LIST_REDIRECT_URL
}
/**
* Cancel editing game.
*
* @return view for redirect to page with list of games
*/
@PostMapping(value = ["/edit"], params = ["cancel"])
fun processEdit(): String {
return LIST_REDIRECT_URL
}
/**
* Process duplicating game.
*
* @param id ID of duplicating game
* @return view for redirect to page with list of games
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/duplicate/{id}")
fun processDuplicate(@PathVariable("id") id: Int): String {
processResults(gameFacade.duplicate(getGame(id)))
return LIST_REDIRECT_URL
}
/**
* Process removing game.
*
* @param id ID of removing game
* @return view for redirect to page with list of games
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/remove/{id}")
fun processRemove(@PathVariable("id") id: Int): String {
processResults(gameFacade.remove(getGame(id)))
return LIST_REDIRECT_URL
}
/**
* Process moving game up.
*
* @param id ID of moving game
* @return view for redirect to page with list of games
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/moveUp/{id}")
fun processMoveUp(@PathVariable("id") id: Int): String {
processResults(gameFacade.moveUp(getGame(id)))
return LIST_REDIRECT_URL
}
/**
* Process moving game down.
*
* @param id ID of moving game
* @return view for redirect to page with list of games
* @throws IllegalRequestException if game doesn't exist
*/
@GetMapping("/moveDown/{id}")
fun processMoveDown(@PathVariable("id") id: Int): String {
processResults(gameFacade.moveDown(getGame(id)))
return LIST_REDIRECT_URL
}
/**
* Process updating positions.
*
* @return view for redirect to page with list of games
*/
@GetMapping("/update")
fun processUpdatePositions(): String {
processResults(gameFacade.updatePositions())
return LIST_REDIRECT_URL
}
/**
* Returns game with ID.
*
* @param id ID
* @return game with ID
* @throws IllegalRequestException if game doesn't exist
*/
private fun getGame(id: Int): Game {
val game = Game(id = id,
name = null,
wikiEn = null,
wikiCz = null,
mediaCount = null,
crack = null,
serialKey = null,
patch = null,
trainer = null,
trainerData = null,
editor = null,
saves = null,
otherData = null,
note = null,
position = null)
return processGame(game)
}
/**
* Returns processed game.
*
* @param game for processing
* @return processed game
* @throws IllegalRequestException if game doesn't exist
*/
private fun processGame(game: Game): Game {
val gameResult = gameFacade.get(game.id!!)
processResults(gameResult)
if (gameResult.data != null) {
return game
}
throw IllegalRequestException(ILLEGAL_REQUEST_MESSAGE)
}
/**
* Returns page's view with form.
*
* @param model model
* @param game FO for game
* @param title page's title
* @param action action
* @return page's view with form
*/
private fun createFormView(model: Model, game: GameFO, title: String, action: String): String {
model.addAttribute("game", game)
model.addAttribute("title", title)
model.addAttribute("action", action)
return "game/form"
}
companion object {
/**
* Redirect URL to list
*/
private const val LIST_REDIRECT_URL = "redirect:/games/list"
/**
* Message for illegal request
*/
private const val ILLEGAL_REQUEST_MESSAGE = "Game doesn't exist."
}
}
| mit | 14a09072350f29000ec3ba55f5846e19 | 28.171598 | 114 | 0.595538 | 4.489982 | false | false | false | false |
Livin21/KotlinSolitaire | src/FoundationPile.kt | 1 | 543 | /**
* Created by livin on 29/5/17.
*/
class FoundationPile(val suit: String){
val cards: MutableList<Card> = mutableListOf()
fun reset(){
cards.clear()
}
fun removeCard(card: Card){
cards.remove(card)
}
fun addCard(card: Card): Boolean{
var nextValue = 0
if (cards.size > 0){
nextValue = cards.last().value + 1
}
if (card.suit == suit && card.value == nextValue){
cards.add(card)
return true
}
return false
}
} | mit | acdaf55759c01d8e66b1a6733dd147d1 | 19.923077 | 58 | 0.519337 | 3.963504 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/block/heat/BlockRedstoneHeatPipe.kt | 2 | 2493 | @file:Suppress("DEPRECATION", "OverridingDeprecatedMember")
package block.heat
import com.cout970.magneticraft.block.PROPERTY_OPEN
import com.cout970.magneticraft.misc.block.get
import com.cout970.magneticraft.misc.tileentity.getTile
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.tileentity.heat.TileRedstoneHeatPipe
import com.cout970.magneticraft.util.DEFAULT_CONDUCTIVITY
import com.teamwizardry.librarianlib.common.base.block.BlockModContainer
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLivingBase
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by cout970 on 04/07/2016.
*/
object BlockRedstoneHeatPipe : BlockModContainer("redstone_heat_pipe", Material.ROCK) {
init {
tickRandomly = true
}
override fun createTileEntity(worldIn: World, meta: IBlockState): TileEntity = TileRedstoneHeatPipe()
override fun onBlockPlacedBy(worldIn: World?, pos: BlockPos, state: IBlockState?, placer: EntityLivingBase, stack: ItemStack?) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack)
worldIn?.setBlockState(pos, defaultState.withProperty(PROPERTY_OPEN, false))
}
override fun getMetaFromState(state: IBlockState): Int {
if (state[PROPERTY_OPEN]) return 1 else return 0
}
override fun getStateFromMeta(meta: Int): IBlockState = defaultState.
withProperty(PROPERTY_OPEN, (meta and 1) != 0)
override fun createBlockState(): BlockStateContainer {
return BlockStateContainer(this, PROPERTY_OPEN)
}
override fun neighborChanged(state: IBlockState, worldIn: World, pos: BlockPos, blockIn: Block) {
if (worldIn.isServer) {
val flag = worldIn.isBlockPowered(pos)
if (flag || blockIn.defaultState.canProvidePower()) {
if (state.get(PROPERTY_OPEN) != flag) {
worldIn.setBlockState(pos, defaultState.withProperty(PROPERTY_OPEN, flag))
val tile = worldIn.getTile<TileRedstoneHeatPipe>(pos)
tile?.heat?.conductivity = if (flag) 0.0 else DEFAULT_CONDUCTIVITY
}
}
}
super.neighborChanged(state, worldIn, pos, blockIn)
}
} | gpl-2.0 | 18050145cb12000a56836b7c044dd96f | 39.225806 | 132 | 0.726033 | 4.350785 | false | false | false | false |
koesie10/AdventOfCode-Solutions-Kotlin | 2015/src/main/kotlin/com/koenv/adventofcode/Day12.kt | 1 | 1227 | package com.koenv.adventofcode
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
object Day12 {
public fun getSum(input: String, skipRed: Boolean = false): Int {
return getSum(JSONTokener(input).nextValue(), skipRed)
}
fun getSum(input: Any, skipRed: Boolean = false): Int {
var sum = 0
when (input) {
is JSONObject -> {
sum += getSum(input, skipRed)
}
is JSONArray -> {
sum += getSum(input, skipRed)
}
is Int -> {
sum += input
}
}
return sum
}
fun getSum(input: JSONObject, skipRed: Boolean = false): Int {
var sum = 0
input.keys().forEach {
val value = input.get(it)
if (skipRed) {
if (value is String && value == "red") {
return@getSum 0
}
}
sum += getSum(value, skipRed)
}
return sum
}
fun getSum(input: JSONArray, skipRed: Boolean = false): Int {
var sum = 0
input.forEach {
sum += getSum(it, skipRed)
}
return sum
}
} | mit | f4f922fe8b10600b33c62f7f9f3d43ac | 24.061224 | 69 | 0.484108 | 4.245675 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/giphy/GiphyAuthInterceptor.kt | 1 | 1333 | package com.baulsupp.okurl.services.giphy
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.secrets.Secrets
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class GiphyAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition =
Oauth2ServiceDefinition(
"api.giphy.com", "Giphy API", "giphy",
"https://github.com/Giphy/GiphyAPI", null
)
override fun defaultCredentials(): Oauth2Token? = Oauth2Token("dc6zaTOxFJmzC")
override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response {
var request = chain.request()
val token = credentials.accessToken
val newUrl = request.url.newBuilder().addQueryParameter("api_key", token).build()
request = request.newBuilder().url(newUrl).build()
return chain.proceed(request)
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val apiKey = Secrets.prompt("Giphy API Key", "giphy.apiKey", "", false)
return Oauth2Token(apiKey)
}
}
| apache-2.0 | 7bbea3bd8544788828648c8a95f61389 | 30 | 96 | 0.76069 | 4.245223 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-recyclerview/src/main/java/reactivecircus/flowbinding/recyclerview/RecyclerViewFlingEventFlow.kt | 1 | 1962 | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.recyclerview
import androidx.annotation.CheckResult
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of fling events on the [RecyclerView] instance.
*
* @param handled function to be invoked with each value to determine the return value of
* the underlying [RecyclerView.OnFlingListener]. Note that the [Flow] will only emit when this function
* evaluates to true.
*
* Note: Created flow keeps a strong reference to the [RecyclerView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* recyclerView.flingEvents { it.velocityX != 0 }
* .onEach { event ->
* // handle fling event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun RecyclerView.flingEvents(handled: (FlingEvent) -> Boolean = { true }): Flow<FlingEvent> = callbackFlow {
checkMainThread()
val listener = object : RecyclerView.OnFlingListener() {
override fun onFling(velocityX: Int, velocityY: Int): Boolean {
val event = FlingEvent(
view = this@flingEvents,
velocityX = velocityX,
velocityY = velocityY
)
return if (handled(event)) {
trySend(event)
true
} else {
false
}
}
}
onFlingListener = listener
awaitClose { onFlingListener = null }
}.conflate()
public data class FlingEvent(
public val view: RecyclerView,
public val velocityX: Int,
public val velocityY: Int
)
| apache-2.0 | 6babe186a328e8d8ce87dad99549002a | 31.163934 | 115 | 0.682977 | 4.727711 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt | 1 | 1235 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.model.guessAndSetupRustProject
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.hasCargoProject
class RefreshCargoProjectAction : AnAction() {
init {
templatePresentation.text = "Refresh Cargo project"
templatePresentation.description = "Update Cargo project information and download new dependencies"
}
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null || project.toolchain == null || !project.hasCargoProject) {
e.presentation.isEnabled = false
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (project.toolchain == null || !project.hasCargoProject) {
guessAndSetupRustProject(project, explicitRequest = true)
} else {
project.cargoProjects.refreshAllProjects()
}
}
}
| mit | 6c576acf0c490349774bc8319f7766f2 | 33.305556 | 107 | 0.707692 | 4.625468 | false | false | false | false |
Zhuinden/simple-stack | samples/scoping-samples/simple-stack-example-scoping-kotlin/src/main/java/com/zhuinden/simplestackexamplescoping/utils/Utils.kt | 1 | 1206 | package com.zhuinden.simplestackexamplescoping.utils
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
/**
* Created by zhuinden on 2018. 03. 03..
*/
@Suppress("NOTHING_TO_INLINE")
inline fun View.onClick(noinline clickListener: (View) -> Unit) {
setOnClickListener(clickListener)
}
fun Unit.safe() {
}
fun Any.safe() {
}
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToParent: Boolean = false) =
LayoutInflater.from(context).inflate(layoutRes, this, attachToParent)
fun Context.showToast(text: String, duration: Int = Toast.LENGTH_LONG) {
Toast.makeText(this, text, duration).show()
}
fun Fragment.showToast(text: String, duration: Int = Toast.LENGTH_LONG) {
requireContext().showToast(text, duration)
}
inline fun <T : ViewBinding> AppCompatActivity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) =
lazy(LazyThreadSafetyMode.NONE) {
bindingInflater.invoke(layoutInflater)
} | apache-2.0 | b36290ded2caa9f635b69714271dbb3a | 27.738095 | 112 | 0.771144 | 4.033445 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/musicbrainz/artist/search/ArtistSearchArea.kt | 1 | 1062 | package uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.search
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("id", "type", "type-id", "name", "sort-name", "life-span")
class ArtistSearchArea {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: String? = null
@get:JsonProperty("type")
@set:JsonProperty("type")
@JsonProperty("type")
var type: String? = null
@get:JsonProperty("type-id")
@set:JsonProperty("type-id")
@JsonProperty("type-id")
var typeId: String? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("sort-name")
@set:JsonProperty("sort-name")
@JsonProperty("sort-name")
var sortName: String? = null
@get:JsonProperty("life-span")
@set:JsonProperty("life-span")
@JsonProperty("life-span")
var lifeSpan: ArtistSearchLifeSpan? = null
} | apache-2.0 | e87e18ed5bfcf27491f39f894c21c9f5 | 26.973684 | 77 | 0.676083 | 3.6875 | false | false | false | false |
toastkidjp/Yobidashi_kt | article/src/main/java/jp/toastkid/article_viewer/article/list/ArticleListFragmentViewModel.kt | 1 | 3579 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.list
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import jp.toastkid.article_viewer.article.ArticleRepository
import jp.toastkid.article_viewer.article.list.sort.Sort
import jp.toastkid.article_viewer.bookmark.repository.BookmarkRepository
import jp.toastkid.article_viewer.tokenizer.NgramTokenizer
import jp.toastkid.lib.lifecycle.Event
import jp.toastkid.lib.preference.PreferenceApplier
/**
* @author toastkidjp
*/
class ArticleListFragmentViewModel(
private val articleRepository: ArticleRepository,
private val bookmarkRepository: BookmarkRepository,
private val preferencesWrapper: PreferenceApplier
) : ViewModel() {
private val tokenizer = NgramTokenizer()
private val _progressVisibility = mutableStateOf(false)
val progressVisibility : State<Boolean> = _progressVisibility
fun showProgress() {
_progressVisibility.value = true
}
fun hideProgress() {
_progressVisibility.value = false
}
private val _progress = MutableLiveData<Event<String>>()
val progress : LiveData<Event<String>> = _progress
private val _messageId = MutableLiveData<Event<Int>>()
val messageId : LiveData<Event<Int>> = _messageId
private val _sort = MutableLiveData<Event<Sort>>()
val sort: LiveData<Event<Sort>> = _sort
fun sort(sort: Sort) {
setNextPager { sort.invoke(articleRepository) }
}
private val _dataSource = MutableLiveData<Pager<Int, SearchResult>>()
val dataSource: LiveData<Pager<Int, SearchResult>> = _dataSource
fun search(keyword: String?) {
setNextPager {
if (keyword.isNullOrBlank()) {
val pagingSource = Sort.findByName(preferencesWrapper.articleSort()).invoke(articleRepository)
searchResult.value = "All article"
pagingSource
} else {
val start = System.currentTimeMillis()
val pagingSource = articleRepository.search("${tokenizer(keyword, 2)}")
searchResult.value = "Search ended. [${System.currentTimeMillis() - start}ms]"
pagingSource
}
}
}
fun filter(keyword: String?) {
setNextPager {
if (keyword.isNullOrBlank())
Sort.findByName(preferencesWrapper.articleSort())
.invoke(articleRepository)
else
articleRepository.filter(keyword)
}
}
fun bookmark() {
val findByIds = articleRepository.findByIds(bookmarkRepository.allArticleIds())
setNextPager { findByIds }
}
private fun setNextPager(pagingSourceFactory: () -> PagingSource<Int, SearchResult>) {
_dataSource.postValue(
Pager(
PagingConfig(pageSize = 10, enablePlaceholders = true),
pagingSourceFactory = pagingSourceFactory
)
)
}
val searchInput = mutableStateOf("")
val searchResult = mutableStateOf("")
} | epl-1.0 | 66aafaea118f53dda0975a6b277ab4c8 | 32.457944 | 110 | 0.686505 | 5.040845 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/language/completion/MdCompletionContributor.kt | 1 | 3250 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language.completion
import com.intellij.codeInsight.completion.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.util.ProcessingContext
import com.vladsch.md.nav.MdLanguage
import com.vladsch.md.nav.psi.element.MdFile
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.plugin.util.TestUtils
class MdCompletionContributor : CompletionContributor() {
private val LOG = Logger.getInstance("com.vladsch.md.nav.language.completion")
override fun beforeCompletion(context: CompletionInitializationContext) {
context.dummyIdentifier = TestUtils.DUMMY_IDENTIFIER
}
override fun duringCompletion(context: CompletionInitializationContext) {
val file = context.file
val position = context.caret.caretModel.offset
val elementPos = file.findElementAt(position) ?: return
val element = findMarkdownElement(elementPos)
for (contributor in elementCompletions) {
if (contributor.duringCompletion(context, element, elementPos)) break
}
}
init {
extend(CompletionType.BASIC,
PlatformPatterns.psiElement(PsiElement::class.java).withLanguage(MdLanguage.INSTANCE),
object : CompletionProvider<CompletionParameters>() {
public override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, resultSet: CompletionResultSet) {
val containingFile = parameters.originalFile as? MdFile ?: return
val elementPos = parameters.position
val element = findMarkdownElement(elementPos)
for (elementCompletion in elementCompletions) {
if (elementCompletion.getWantElement(element, elementPos, parameters, context)) {
if (!elementCompletion.addCompletions(parameters, context, resultSet, element, containingFile)) {
resultSet.runRemainingContributors(parameters) {
// leave out extras on request
}
}
break
}
}
}
})
}
companion object {
@JvmStatic
fun findMarkdownElement(elementPos: PsiElement): PsiElement {
var element: PsiElement = elementPos
while (element is LeafPsiElement || element.node.elementType == MdTypes.TEXT_BLOCK) {
element = element.parent
}
return element
}
val EP_NAME: ExtensionPointName<MdElementCompletion> = ExtensionPointName("com.vladsch.idea.multimarkdown.element.completionProvider")
val elementCompletions: Array<MdElementCompletion>
get() = EP_NAME.extensions
}
}
| apache-2.0 | 9f1a772a344e1fbd44d7fadfcea6f55d | 43.520548 | 177 | 0.661846 | 5.336617 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyTypeParameter.kt | 1 | 4194 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.ide.presentation.tyToString
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.RsTypeParameter
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.types.BoundElement
class TyTypeParameter private constructor(
private val parameter: TypeParameter,
private val bounds: Collection<BoundElement<RsTraitItem>>
) : Ty {
override fun equals(other: Any?): Boolean = other is TyTypeParameter && other.parameter == parameter
override fun hashCode(): Int = parameter.hashCode()
fun getTraitBoundsTransitively(): Collection<BoundElement<RsTraitItem>> =
bounds.flatMap { it.flattenHierarchy }.map { it.substitute(mapOf(self() to this)) }
override fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult {
var result: UnifyResult = UnifyResult.exact
if (!bounds.isEmpty()) {
val traits = lookup.findImplsAndTraits(other)
for ((element, boundSubst) in bounds) {
val trait = traits.find { it.element.implementedTrait?.element == element }
if (trait != null) {
val subst = boundSubst.substituteInValues(mapOf(self() to this))
for ((k, v) in subst) {
trait.subst[k]?.let { result = result.merge(v.unifyWith(it, lookup)) }
}
} else {
result = result.merge(UnifyResult.fuzzy)
}
}
}
return result.merge(mapOf(this to other))
}
override fun substitute(subst: Substitution): Ty {
val ty = subst[this] ?: TyUnknown
if (ty !is TyUnknown) return ty
if (parameter is AssociatedType) {
val oldType = parameter.type
val newType = if (oldType is TyTypeParameter && oldType.parameter is Self) {
oldType.substitute(subst)
} else {
oldType
}
return associated(newType, parameter.trait, parameter.target)
}
return TyTypeParameter(parameter, bounds.map { it.substitute(subst) })
}
val name: String? get() = parameter.name
override fun toString(): String = tyToString(this)
private interface TypeParameter {
val name: String?
}
private object Self : TypeParameter {
override val name: String? get() = "Self"
}
private data class Named(val parameter: RsTypeParameter) : TypeParameter {
override val name: String? get() = parameter.name
}
private data class AssociatedType(val type: Ty, val trait: RsTraitItem, val target: RsTypeAlias) : TypeParameter {
override val name: String? get() = "<$type as ${trait.name}>::${target.name}"
}
companion object {
private val SELF = TyTypeParameter(Self, emptyList())
fun self(): TyTypeParameter = SELF
fun self(trait: RsTraitOrImpl): TyTypeParameter =
TyTypeParameter(Self, trait.implementedTrait?.let { listOf(it) } ?: emptyList())
fun named(parameter: RsTypeParameter): TyTypeParameter =
TyTypeParameter(Named(parameter), bounds(parameter))
fun associated(target: RsTypeAlias): TyTypeParameter =
associated(self(), target)
private fun associated(type: Ty, target: RsTypeAlias): TyTypeParameter {
val trait = target.parentOfType<RsTraitItem>()
?: error("Tried to construct an associated type from RsTypeAlias declared out of a trait")
return associated(type, trait, target)
}
private fun associated(type: Ty, trait: RsTraitItem, target: RsTypeAlias): TyTypeParameter {
return TyTypeParameter(
AssociatedType(type, trait, target),
emptyList())
}
}
}
private fun bounds(parameter: RsTypeParameter): List<BoundElement<RsTraitItem>> =
parameter.bounds.mapNotNull { it.bound.traitRef?.resolveToBoundTrait }
| mit | f92bf70e6b67937a47057072387af953 | 36.783784 | 118 | 0.636624 | 4.722973 | false | false | false | false |
rei-m/android_hyakuninisshu | feature/examresult/src/main/java/me/rei_m/hyakuninisshu/feature/examresult/ui/ExamResultViewModel.kt | 1 | 2237 | /*
* Copyright (c) 2020. Rei Matsushita.
*
* 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 me.rei_m.hyakuninisshu.feature.examresult.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import me.rei_m.hyakuninisshu.feature.corecomponent.ext.map
import me.rei_m.hyakuninisshu.feature.corecomponent.ui.AbstractViewModel
import me.rei_m.hyakuninisshu.state.core.Dispatcher
import me.rei_m.hyakuninisshu.state.exam.action.ExamActionCreator
import me.rei_m.hyakuninisshu.state.exam.store.ExamResultStore
import me.rei_m.hyakuninisshu.state.material.model.Material
import javax.inject.Inject
class ExamResultViewModel(
private val examId: Long,
dispatcher: Dispatcher,
actionCreator: ExamActionCreator,
private val store: ExamResultStore
) : AbstractViewModel(dispatcher) {
val result = store.result
val materialMap = store.materialList.map {
val temp = hashMapOf<Int, Material>()
it?.forEach { material -> temp[material.no] = material }
return@map temp
}
init {
dispatchAction {
actionCreator.fetchResult(examId)
}
}
override fun onCleared() {
store.dispose()
super.onCleared()
}
class Factory @Inject constructor(
private val dispatcher: Dispatcher,
private val actionCreator: ExamActionCreator,
private val store: ExamResultStore
) : ViewModelProvider.Factory {
var examId: Long = -1
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = ExamResultViewModel(
examId,
dispatcher,
actionCreator,
store
) as T
}
}
| apache-2.0 | 4ba1447bfbe65a597d7dfd4009209c53 | 30.507042 | 91 | 0.701833 | 4.343689 | false | false | false | false |
jjoller/foxinabox | src/jjoller/foxinabox/TexasHand.kt | 1 | 11003 | package jjoller.foxinabox
import java.util.ArrayList
import java.util.EnumSet
import java.util.HashSet
import java.util.LinkedList
import java.util.Optional
/**
* Implementation of a texas hold'em game.
*/
abstract class TexasHand {
public val dealer: Dealer
public val players: MutableList<Player>
protected val activePlayers: LinkedList<Player>
public val actions: MutableList<Int>
// amount each player paid
protected val paid: IntArray
// preflop, flop, turn or river
protected var phase: Phase
// amount which a player has to pay to stay active
protected var toPay: Int = 0
// toPay at the end of the previous phase
protected var toPayPreviousPhase: Int = 0
// Number of minimal required player actions which are required to complete
// the phase.
protected var minPlayerActions: Int = 0
// iterate over the active players
private var onTurnIterator: MutableListIterator<Player>
// player currently on turn
public var onTurn: Player? = null
private set
var flop: EnumSet<Card>?
var turn: Card?
var river: Card?
constructor(dealer: Dealer, players: MutableList<Player>) {
assert(players.size > 1) { "A poker game consists of at least 2 players" }
dealer.reset()
this.dealer = dealer
this.players = players
this.activePlayers = LinkedList<Player>()
activePlayers.addAll(players)
this.actions = ArrayList<Int>(this.players.size * 8)
flop = null
turn = null
river = null
paid = IntArray(players.size)
phase = Phase.PRE_FLOP
toPay = 0
toPayPreviousPhase = 0
minPlayerActions = this.players.size
// deal cards
players.forEach { p -> dealer.dealHoleCards(p) }
// play blinds
performPlayerAction(players[0], dealer.smallBlind())
performPlayerAction(players[1], dealer.bigBlind())
onTurnIterator = this.activePlayers.listIterator(if (activePlayers.size > 2) 2 else 0)
for (phase in PHASES) {
performPhase()
if (this.activePlayers.size < 2) {
return
} else {
actions.add(phase.action)
dealer.dealTableCards(this)
this.toPayPreviousPhase = this.toPay
}
this.phase = phase
}
performPhase()
}
public fun tableCards(): List<Card> {
val tableCards = ArrayList<Card>(5);
if (flop != null) {
tableCards.addAll(flop!!)
if (turn != null) {
tableCards.add(turn!!)
if (river != null)
tableCards.add(river!!)
}
}
return tableCards
}
private fun performPhase() {
// every player has to perform at least 1 action
minPlayerActions = this.activePlayers.size
moveToNextPlayer()
do {
val action = onTurn!!.model.action(this)
performPlayerAction(onTurn!!, action)
moveToNextPlayer()
} while (onTurn != null)
}
private fun performPlayerAction(player: Player, action: Int) {
minPlayerActions--
actions.add(action)
val seat = seat(player)
if (action == Action.FOLD) {
onTurnIterator.remove()
} else {
paid[seat] += action
if (paid[seat] >= player.stack) {
// is all-in
onTurnIterator.remove()
}
}
toPay = Math.max(toPay, paid[seat])
}
protected fun toPay(): Int {
return toPay
}
protected fun toPayPreviousPhase(): Int {
return toPayPreviousPhase
}
public fun outcome(player: Player): Double {
assert(this.isComplete) { "Hand must be complete" }
val paid = this.paid(player)
if (this.activePlayers.contains(player)) {
var isWinner = false
var winners = 0.0
if (this.activePlayers.size < 2) {
// player is the only one left
isWinner = true
winners = 1.0
} else {
// has not folded
var bestVal: FiveCardValue? = null
for (p in this.activePlayers) {
val cards = p.holdings().get()
// println(p.name+" holdings: " + cards)
this.addTableCards(cards)
val value = FiveCardValue(cards)
if (bestVal == null || value.isBetterThan(bestVal)) {
winners = 1.0
bestVal = value
isWinner = p === player
} else if (value.isEqual(bestVal)) {
winners++
}
}
}
if (isWinner) {
// println(player.holdings().toString() + " is winner and wins " + (this.pot() / winners - paid) + " " + winners)
return this.pot() / winners - paid.toDouble()
} else {
// println(player.holdings().toString() + " is loser and loses " + (-paid.toDouble()))
return -paid.toDouble()
}
} else {
// has folded
return -paid.toDouble()
}
}
fun payOutPot(): TexasHand {
assert(this.isComplete) { "Hand must be complete when paying out the pot" }
val winners: MutableCollection<Player>
var bestVal: FiveCardValue? = null
if (this.activePlayers.size > 1) {
winners = HashSet<Player>()
for (player in this.activePlayers) {
val cards = player.holdings().get()
this.addTableCards(cards)
val `val` = FiveCardValue(cards)
if (bestVal == null || `val`.isBetterThan(bestVal)) {
winners.clear()
winners.add(player)
bestVal = `val`
} else if (`val`.isEqual(bestVal)) {
winners.add(player)
}
}
} else {
winners = this.activePlayers
}
val pot = this.pot()
for (player in players) {
var newStack = player.stack - this.paid(player)
if (winners.contains(player))
newStack += pot / winners.size
player.stack = newStack
}
// move dealer button
val smallBlind = players.removeAt(0)
players.add(smallBlind)
return follower(dealer, players)
}
/**
* Helper method to add the table cards
* @param cards
*/
private fun addTableCards(cards: EnumSet<Card>) {
if (flop != null) {
cards.addAll(flop!!)
if (turn != null) {
cards.add(turn!!)
if (river != null)
cards.add(river!!)
}
}
}
protected abstract fun follower(dealer: Dealer, players: MutableList<Player>): TexasHand
/**
* All the player except 1 folded or showdown
* @return true if the hand is
*/
val isComplete: Boolean
get() = this.activePlayers.size < 2 || phase() === Phase.RIVER && onTurn == null
/**
* Return the player which is on turn. Return empty if there is no player on
* turn, which means there is either a dealer action or the hand is
* complete.
*/
private fun moveToNextPlayer() {
if (this.activePlayers.size > 1) {
if (!this.onTurnIterator.hasNext())
this.onTurnIterator = this.activePlayers.listIterator()
val player = this.onTurnIterator.next()
if (this.minPlayerActions > 0 || paid(player) < toPay())
// the player still has to pay something to stay in the
// game or he did not perform an action in this phase
onTurn = player
else
onTurn = null
} else {
onTurn = null
}
}
fun phase(): Phase {
return phase
}
fun seat(player: Player): Int {
assert(players.contains(player)) { "Player not on table" }
return players.indexOf(player)
}
fun paid(player: Player): Int {
return paid[seat(player)]
// return actions.stream().filter(a -> a.getParty() == player)
// .filter(a -> a.getAction() > 0)
// .collect(Collectors.summingInt(a -> a.getAction()));
}
fun pot(): Int {
return actions.filter { a -> a > 0 }.sum();
}
override fun toString(): String {
// limiter
val separator = TexasHand.SEPARATOR
// write blinds
var s = dealer.smallBlind().toString() + separator + dealer.bigBlind().toString() + separator
// write table cards
if (flop != null) {
val iter = flop!!.iterator()
while (iter.hasNext())
s += iter.next()
if (this.turn != null) {
s += this.turn!!
if (this.river != null)
s += this.river!!
}
}
// write players
for (p in this.players) {
var cards = EMPTY
val holeCards = p.holdings()
if (holeCards.isPresent) {
val iter = holeCards.get().iterator()
cards = iter.next().toString() + "" + iter.next()
}
s += separator + p.name.replace("_".toRegex(), _REPLACEMENT) + separator + p.stack + separator + cards
}
// write actions
for (a in this.actions)
s += separator + Action.toString(a)
return s
}
abstract fun callAmount(): Int
abstract fun raiseAmount(): Int
fun actionIdentifier(): String {
var s = ""
for (a in this.actions)
s += Action.toString(a) + "_"
return s
}
open class Player(val name: String, var model: PlayerModel, stack: Int) {
var stack: Int
protected var cards: Optional<EnumSet<Card>> = Optional.empty()
init {
assert(name.length > 0)
assert(stack > 1) { "Player must have some stack" }
this.stack = stack
cards = Optional.empty<EnumSet<Card>>()
}
public fun holdings(): Optional<EnumSet<Card>> {
if (this.cards.isPresent)
return Optional.of(this.cards.get().clone())
else
return this.cards
}
open fun setCards(cards: EnumSet<Card>) {
assert(cards.size == 2)
this.cards = Optional.of(cards)
}
}
companion object {
protected val PHASES = arrayOf(Phase.FLOP, Phase.TURN, Phase.RIVER)
protected val EMPTY = "-"
protected val SEPARATOR = "_"
protected val _REPLACEMENT = "\\.\\*\\."
}
}
| mit | 9021603fdd6f32e6a9cc19f8ff9ecd59 | 27.653646 | 128 | 0.526947 | 4.445657 | false | false | false | false |
kgtkr/mhxx-switch-cis | src/main/kotlin/Param.kt | 1 | 2180 | package com.github.kgtkr.mhxxSwitchCIS
import javax.swing.*
import java.awt.*
import java.awt.image.*
import javax.imageio.ImageIO
fun paramCmd(){
ParamFrame()
}
class ParamFrame:JFrame("パラメーター調整"){
var image:BufferedImage?=null
val imageLabel=JLabel()
val color=JColorChooser(ImageConfig.COLOR)
val thSlider=JSlider(0,30000,ImageConfig.THRESHOLD)
val thLabel=JLabel()
init{
this.size=Dimension(500,500)
this.defaultCloseOperation=JFrame.EXIT_ON_CLOSE
val menuBar=JMenuBar()
val fileMenu=JMenu("File")
val openMenuItem=JMenuItem("Open")
openMenuItem.addActionListener {
val filechooser = JFileChooser(".")
if(filechooser.showOpenDialog(this)==0){
this.image=ImageIO.read(filechooser.selectedFile)
this.updateImage()
}
}
fileMenu.add(openMenuItem)
menuBar.add(fileMenu)
this.jMenuBar=menuBar
val imagePanel =JPanel()
imagePanel.add(this.imageLabel)
this.color.selectionModel.addChangeListener {
this.updateImage()
}
this.thSlider.addChangeListener {
this.updateImage()
}
val colorPanel =JPanel()
colorPanel.add(this.color)
val toolPanel =JPanel()
toolPanel.add(this.thSlider)
toolPanel.add(this.thLabel)
this.contentPane.add(imagePanel, BorderLayout.CENTER)
this.contentPane.add(colorPanel, BorderLayout.SOUTH)
this.contentPane.add(toolPanel, BorderLayout.NORTH)
this.isVisible=true
}
fun updateImage(){
val image=this.image
if(image==null)return
this.thLabel.text=this.thSlider.value.toString()
val bitImage=image.toBitImage(this.color.color,this.thSlider.value)
val bufImage=BufferedImage(image.width,image.height,image.type)
for(x in 0..image.width-1){
for(y in 0..image.height-1){
bufImage.setRGB(x,y,if(bitImage[x][y])Color.BLACK.rgb else Color.WHITE.rgb)
}
}
this.imageLabel.icon=ImageIcon(bufImage)
}
} | gpl-3.0 | f70c402178181377c257ad99c3913b73 | 25.402439 | 91 | 0.632625 | 3.941712 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/util/CookieStore.kt | 1 | 1107 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.http.util
import io.javalin.http.Cookie
import io.javalin.plugin.json.JsonMapper
import java.util.*
@Suppress("UNCHECKED_CAST")
class CookieStore(val jsonMapper: JsonMapper, cookie: String?) {
companion object {
var COOKIE_NAME = "javalin-cookie-store"
}
private val cookieMap = deserialize(cookie)
fun serializeToCookie() = Cookie(COOKIE_NAME, serialize(cookieMap))
operator fun <T> get(key: String) = cookieMap[key] as T
operator fun set(key: String, value: Any) = cookieMap.put(key, value)
fun clear() = cookieMap.clear()
private fun deserialize(cookie: String?) = if (!cookie.isNullOrEmpty()) {
jsonMapper.fromJsonString(String(Base64.getDecoder().decode(cookie)), Map::class.java) as MutableMap<String, Any>
} else mutableMapOf()
private fun serialize(map: MutableMap<String, Any>) = Base64.getEncoder().encodeToString(jsonMapper.toJsonString(map).toByteArray())
}
| apache-2.0 | b64c6c3d421e25b957a01efa6a308488 | 30.6 | 136 | 0.716094 | 3.813793 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/inventory/container/layout/RootBrewingContainerLayout.kt | 1 | 3521 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.container.layout
import org.lanternpowered.api.item.inventory.container.layout.BrewingContainerLayout
import org.lanternpowered.api.item.inventory.container.layout.ContainerLayout
import org.lanternpowered.api.item.inventory.container.layout.ContainerSlot
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.inventory.container.ClientWindowTypes
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.vanilla.packet.type.play.OpenWindowPacket
class RootBrewingContainerLayout : LanternTopBottomContainerLayout<BrewingContainerLayout>(
title = TITLE, slotFlags = ALL_INVENTORY_FLAGS, propertyCount = 2
) {
companion object {
private val TITLE = translatableTextOf("container.brewing")
private val TOP_INVENTORY_FLAGS = intArrayOf(
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.ONE_ITEM, // Bottle slot 1
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.ONE_ITEM, // Bottle slot 2
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.ONE_ITEM, // Bottle slot 3
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION, // Potion ingredient slot
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION // Blaze powder slot
)
private val ALL_INVENTORY_FLAGS = TOP_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS
private const val BREW_PROGRESS_PROPERTY = 0
private const val FUEL_PROGRESS_PROPERTY = 1
}
override fun createOpenPackets(data: ContainerData): List<Packet> =
listOf(OpenWindowPacket(data.containerId, ClientWindowTypes.BREWING_STAND, this.title))
override val top: BrewingContainerLayout = SubBrewingContainerLayout(0, TOP_INVENTORY_FLAGS.size, this)
var brewProgress: Double = 0.0
set(value) {
field = value.coerceIn(0.0, 1.0)
// Update the client property
// 0.0 is full, 1.0 is empty, so it needs to be swapped
this.setProperty(BREW_PROGRESS_PROPERTY, ((1.0 - field) * 400.0).toInt())
}
var fuelProgress: Double = 0.0
set(value) {
field = value.coerceIn(0.0, 1.0)
// Update the client property
this.setProperty(FUEL_PROGRESS_PROPERTY, (field * 20.0).toInt())
}
}
private class SubBrewingContainerLayout(
offset: Int, size: Int, private val root: RootBrewingContainerLayout
) : SubContainerLayout(offset, size, root), BrewingContainerLayout {
override val bottles: ContainerLayout = SubContainerLayout(offset, this.size - 2, this.base)
override val fuel: ContainerSlot get() = this[this.size - 1]
override val ingredient: ContainerSlot get() = this[this.size - 2]
override var brewProgress: Double
get() = this.root.brewProgress
set(value) { this.root.brewProgress = value }
override var fuelProgress: Double
get() = this.root.fuelProgress
set(value) { this.root.fuelProgress = value }
}
| mit | f457b6b7502cf2efec067bb0f3ef7c8c | 43.56962 | 122 | 0.708037 | 4.118129 | false | false | false | false |
jamieadkins95/Roach | base/src/main/java/com/jamieadkins/gwent/base/FeatureNavigator.kt | 1 | 1130 | package com.jamieadkins.gwent.base
import android.app.Activity
import android.content.Intent
import android.net.Uri
class FeatureNavigator(private val activity: Activity) {
fun openIntent(intent: Intent) = activity.startActivity(intent)
fun openCardDetails(cardId: String) = openIntent(getIntentForClassName(CARD_DETAIL_ACTIVITY, Uri.parse(CARD_DETAILS.format(cardId))))
fun openDeckBuilder(deckId: String) = openIntent(getIntentForClassName(DECK_DETAIL_ACTIVITY, Uri.parse(DECK_DETAILS.format(deckId))))
fun getIntentForClassName(activityName: String, uri: Uri? = null): Intent {
return Intent().apply {
setClassName(activity.applicationContext.packageName, activityName)
data = uri
}
}
companion object {
private const val CARD_DETAIL_ACTIVITY = "com.jamieadkins.gwent.card.detail.CardDetailsActivity"
private const val DECK_DETAIL_ACTIVITY = "com.jamieadkins.gwent.deck.builder.DeckDetailsActivity"
private const val CARD_DETAILS = "roach://card?cardId=%s"
private const val DECK_DETAILS = "roach://deck?deckId=%s"
}
} | apache-2.0 | 2c63b655ca263742afa44f4fd96f8b2c | 36.7 | 137 | 0.728319 | 4.24812 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/selected/SelectedConnection.kt | 2 | 4996 | package com.lasthopesoftware.bluewater.client.connection.selected
import android.content.Context
import android.content.Intent
import androidx.annotation.IntDef
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.session.ConnectionSessionManager
import com.lasthopesoftware.bluewater.client.connection.session.ManageConnectionSessions
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.android.messages.SendMessages
import com.lasthopesoftware.bluewater.shared.promises.extensions.keepPromise
import com.namehillsoftware.handoff.promises.Promise
import org.slf4j.LoggerFactory
class SelectedConnection(
private val localBroadcastManager: SendMessages,
private val selectedLibraryIdentifierProvider: ProvideSelectedLibraryId,
private val libraryConnections: ManageConnectionSessions
) {
fun promiseTestedSessionConnection(): Promise<IConnectionProvider?> =
selectedLibraryIdentifierProvider.selectedLibraryId.eventually { selectedLibraryId ->
selectedLibraryId
?.let {
libraryConnections.promiseTestedLibraryConnection(selectedLibraryId)
.also {
it.progress.then { progress ->
if (progress != BuildingConnectionStatus.BuildingConnectionComplete) {
if (progress != null) doStateChange(progress)
it.updates(::doStateChange)
}
}
}
}
.keepPromise()
}
fun isSessionConnectionActive(): Promise<Boolean> =
selectedLibraryIdentifierProvider.selectedLibraryId.then { id ->
id?.let(libraryConnections::isConnectionActive) ?: false
}
fun promiseSessionConnection(): Promise<IConnectionProvider?> =
selectedLibraryIdentifierProvider.selectedLibraryId.eventually { selectedLibraryId ->
selectedLibraryId
?.let {
libraryConnections
.promiseLibraryConnection(selectedLibraryId)
.also {
it.progress.then { progress ->
if (progress != BuildingConnectionStatus.BuildingConnectionComplete) {
if (progress != null) doStateChange(progress)
it.updates(::doStateChange)
}
}
}
}
.keepPromise()
}
private fun doStateChange(status: BuildingConnectionStatus) {
val broadcastIntent = Intent(buildSessionBroadcast)
broadcastIntent.putExtra(
buildSessionBroadcastStatus,
BuildingSessionConnectionStatus.getSessionConnectionStatus(status)
)
localBroadcastManager.sendBroadcast(broadcastIntent)
if (status === BuildingConnectionStatus.BuildingConnectionComplete) logger.info("Session started.")
}
object BuildingSessionConnectionStatus {
const val GettingLibrary = 1
const val GettingLibraryFailed = 2
const val SendingWakeSignal = 3
const val BuildingConnection = 4
const val BuildingConnectionFailed = 5
const val BuildingSessionComplete = 6
@SessionConnectionStatus
fun getSessionConnectionStatus(connectionStatus: BuildingConnectionStatus): Int =
when (connectionStatus) {
BuildingConnectionStatus.GettingLibrary -> GettingLibrary
BuildingConnectionStatus.SendingWakeSignal -> SendingWakeSignal
BuildingConnectionStatus.GettingLibraryFailed -> GettingLibraryFailed
BuildingConnectionStatus.BuildingConnection -> BuildingConnection
BuildingConnectionStatus.BuildingConnectionFailed -> BuildingConnectionFailed
BuildingConnectionStatus.BuildingConnectionComplete -> BuildingSessionComplete
}
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
@IntDef(GettingLibrary, GettingLibraryFailed, SendingWakeSignal, BuildingConnection, BuildingConnectionFailed, BuildingSessionComplete)
internal annotation class SessionConnectionStatus
}
companion object {
@JvmField
val buildSessionBroadcast = MagicPropertyBuilder.buildMagicPropertyName(SelectedConnection::class.java, "buildSessionBroadcast")
@JvmField
val buildSessionBroadcastStatus = MagicPropertyBuilder.buildMagicPropertyName(SelectedConnection::class.java, "buildSessionBroadcastStatus")
private val logger = LoggerFactory.getLogger(SelectedConnection::class.java)
@JvmStatic
fun getInstance(context: Context): SelectedConnection =
SelectedConnection(
MessageBus(LocalBroadcastManager.getInstance(context)),
SelectedBrowserLibraryIdentifierProvider(context.getApplicationSettingsRepository()),
ConnectionSessionManager.get(context)
)
}
}
| lgpl-3.0 | c560c3996b3239a949decdd40193452c | 42.068966 | 144 | 0.816453 | 5.072081 | false | false | false | false |
colriot/anko | dsl/testData/functional/sdk21/InterfaceWorkaroundsTest.kt | 9 | 36502 | public final class InterfaceWorkarounds {
public static interface SettingsColumns {
public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.Settings.ACCOUNT_NAME;
public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.Settings.ACCOUNT_TYPE;
public static final java.lang.String ANY_UNSYNCED = android.provider.ContactsContract.Settings.ANY_UNSYNCED;
public static final java.lang.String DATA_SET = android.provider.ContactsContract.Settings.DATA_SET;
public static final java.lang.String SHOULD_SYNC = android.provider.ContactsContract.Settings.SHOULD_SYNC;
public static final java.lang.String UNGROUPED_COUNT = android.provider.ContactsContract.Settings.UNGROUPED_COUNT;
public static final java.lang.String UNGROUPED_VISIBLE = android.provider.ContactsContract.Settings.UNGROUPED_VISIBLE;
public static final java.lang.String UNGROUPED_WITH_PHONES = android.provider.ContactsContract.Settings.UNGROUPED_WITH_PHONES;
}
public static interface DeletedContactsColumns {
public static final java.lang.String CONTACT_DELETED_TIMESTAMP = android.provider.ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP;
public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.DeletedContacts.CONTACT_ID;
}
public static interface CalendarCacheColumns {
public static final java.lang.String KEY = android.provider.CalendarContract.CalendarCache.KEY;
public static final java.lang.String VALUE = android.provider.CalendarContract.CalendarCache.VALUE;
}
public static interface ContactOptionsColumns {
public static final java.lang.String CUSTOM_RINGTONE = android.provider.ContactsContract.Contacts.CUSTOM_RINGTONE;
public static final java.lang.String LAST_TIME_CONTACTED = android.provider.ContactsContract.Contacts.LAST_TIME_CONTACTED;
public static final java.lang.String PINNED = android.provider.ContactsContract.Contacts.PINNED;
public static final java.lang.String SEND_TO_VOICEMAIL = android.provider.ContactsContract.Contacts.SEND_TO_VOICEMAIL;
public static final java.lang.String STARRED = android.provider.ContactsContract.Contacts.STARRED;
public static final java.lang.String TIMES_CONTACTED = android.provider.ContactsContract.Contacts.TIMES_CONTACTED;
}
public static interface ExtendedPropertiesColumns {
public static final java.lang.String EVENT_ID = android.provider.CalendarContract.ExtendedProperties.EVENT_ID;
public static final java.lang.String NAME = android.provider.CalendarContract.ExtendedProperties.NAME;
public static final java.lang.String VALUE = android.provider.CalendarContract.ExtendedProperties.VALUE;
}
public static interface RawContactsColumns {
public static final java.lang.String ACCOUNT_TYPE_AND_DATA_SET = android.provider.ContactsContract.RawContacts.ACCOUNT_TYPE_AND_DATA_SET;
public static final java.lang.String AGGREGATION_MODE = android.provider.ContactsContract.RawContacts.AGGREGATION_MODE;
public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.RawContacts.CONTACT_ID;
public static final java.lang.String DATA_SET = android.provider.ContactsContract.RawContacts.DATA_SET;
public static final java.lang.String DELETED = android.provider.ContactsContract.RawContacts.DELETED;
public static final java.lang.String RAW_CONTACT_IS_READ_ONLY = android.provider.ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY;
public static final java.lang.String RAW_CONTACT_IS_USER_PROFILE = android.provider.ContactsContract.RawContacts.RAW_CONTACT_IS_USER_PROFILE;
}
public static interface ColorsColumns {
public static final java.lang.String COLOR = android.provider.CalendarContract.Colors.COLOR;
public static final java.lang.String COLOR_KEY = android.provider.CalendarContract.Colors.COLOR_KEY;
public static final java.lang.String COLOR_TYPE = android.provider.CalendarContract.Colors.COLOR_TYPE;
public static final int TYPE_CALENDAR = android.provider.CalendarContract.Colors.TYPE_CALENDAR;
public static final int TYPE_EVENT = android.provider.CalendarContract.Colors.TYPE_EVENT;
}
public static interface EventsColumns {
public static final int ACCESS_CONFIDENTIAL = android.provider.CalendarContract.Events.ACCESS_CONFIDENTIAL;
public static final int ACCESS_DEFAULT = android.provider.CalendarContract.Events.ACCESS_DEFAULT;
public static final java.lang.String ACCESS_LEVEL = android.provider.CalendarContract.Events.ACCESS_LEVEL;
public static final int ACCESS_PRIVATE = android.provider.CalendarContract.Events.ACCESS_PRIVATE;
public static final int ACCESS_PUBLIC = android.provider.CalendarContract.Events.ACCESS_PUBLIC;
public static final java.lang.String ALL_DAY = android.provider.CalendarContract.Events.ALL_DAY;
public static final java.lang.String AVAILABILITY = android.provider.CalendarContract.Events.AVAILABILITY;
public static final int AVAILABILITY_BUSY = android.provider.CalendarContract.Events.AVAILABILITY_BUSY;
public static final int AVAILABILITY_FREE = android.provider.CalendarContract.Events.AVAILABILITY_FREE;
public static final int AVAILABILITY_TENTATIVE = android.provider.CalendarContract.Events.AVAILABILITY_TENTATIVE;
public static final java.lang.String CALENDAR_ID = android.provider.CalendarContract.Events.CALENDAR_ID;
public static final java.lang.String CAN_INVITE_OTHERS = android.provider.CalendarContract.Events.CAN_INVITE_OTHERS;
public static final java.lang.String CUSTOM_APP_PACKAGE = android.provider.CalendarContract.Events.CUSTOM_APP_PACKAGE;
public static final java.lang.String CUSTOM_APP_URI = android.provider.CalendarContract.Events.CUSTOM_APP_URI;
public static final java.lang.String DESCRIPTION = android.provider.CalendarContract.Events.DESCRIPTION;
public static final java.lang.String DISPLAY_COLOR = android.provider.CalendarContract.Events.DISPLAY_COLOR;
public static final java.lang.String DTEND = android.provider.CalendarContract.Events.DTEND;
public static final java.lang.String DTSTART = android.provider.CalendarContract.Events.DTSTART;
public static final java.lang.String DURATION = android.provider.CalendarContract.Events.DURATION;
public static final java.lang.String EVENT_COLOR = android.provider.CalendarContract.Events.EVENT_COLOR;
public static final java.lang.String EVENT_COLOR_KEY = android.provider.CalendarContract.Events.EVENT_COLOR_KEY;
public static final java.lang.String EVENT_END_TIMEZONE = android.provider.CalendarContract.Events.EVENT_END_TIMEZONE;
public static final java.lang.String EVENT_LOCATION = android.provider.CalendarContract.Events.EVENT_LOCATION;
public static final java.lang.String EVENT_TIMEZONE = android.provider.CalendarContract.Events.EVENT_TIMEZONE;
public static final java.lang.String EXDATE = android.provider.CalendarContract.Events.EXDATE;
public static final java.lang.String EXRULE = android.provider.CalendarContract.Events.EXRULE;
public static final java.lang.String GUESTS_CAN_INVITE_OTHERS = android.provider.CalendarContract.Events.GUESTS_CAN_INVITE_OTHERS;
public static final java.lang.String GUESTS_CAN_MODIFY = android.provider.CalendarContract.Events.GUESTS_CAN_MODIFY;
public static final java.lang.String GUESTS_CAN_SEE_GUESTS = android.provider.CalendarContract.Events.GUESTS_CAN_SEE_GUESTS;
public static final java.lang.String HAS_ALARM = android.provider.CalendarContract.Events.HAS_ALARM;
public static final java.lang.String HAS_ATTENDEE_DATA = android.provider.CalendarContract.Events.HAS_ATTENDEE_DATA;
public static final java.lang.String HAS_EXTENDED_PROPERTIES = android.provider.CalendarContract.Events.HAS_EXTENDED_PROPERTIES;
public static final java.lang.String IS_ORGANIZER = android.provider.CalendarContract.Events.IS_ORGANIZER;
public static final java.lang.String LAST_DATE = android.provider.CalendarContract.Events.LAST_DATE;
public static final java.lang.String LAST_SYNCED = android.provider.CalendarContract.Events.LAST_SYNCED;
public static final java.lang.String ORGANIZER = android.provider.CalendarContract.Events.ORGANIZER;
public static final java.lang.String ORIGINAL_ALL_DAY = android.provider.CalendarContract.Events.ORIGINAL_ALL_DAY;
public static final java.lang.String ORIGINAL_ID = android.provider.CalendarContract.Events.ORIGINAL_ID;
public static final java.lang.String ORIGINAL_INSTANCE_TIME = android.provider.CalendarContract.Events.ORIGINAL_INSTANCE_TIME;
public static final java.lang.String ORIGINAL_SYNC_ID = android.provider.CalendarContract.Events.ORIGINAL_SYNC_ID;
public static final java.lang.String RDATE = android.provider.CalendarContract.Events.RDATE;
public static final java.lang.String RRULE = android.provider.CalendarContract.Events.RRULE;
public static final java.lang.String SELF_ATTENDEE_STATUS = android.provider.CalendarContract.Events.SELF_ATTENDEE_STATUS;
public static final java.lang.String STATUS = android.provider.CalendarContract.Events.STATUS;
public static final int STATUS_CANCELED = android.provider.CalendarContract.Events.STATUS_CANCELED;
public static final int STATUS_CONFIRMED = android.provider.CalendarContract.Events.STATUS_CONFIRMED;
public static final int STATUS_TENTATIVE = android.provider.CalendarContract.Events.STATUS_TENTATIVE;
public static final java.lang.String SYNC_DATA1 = android.provider.CalendarContract.Events.SYNC_DATA1;
public static final java.lang.String SYNC_DATA10 = android.provider.CalendarContract.Events.SYNC_DATA10;
public static final java.lang.String SYNC_DATA2 = android.provider.CalendarContract.Events.SYNC_DATA2;
public static final java.lang.String SYNC_DATA3 = android.provider.CalendarContract.Events.SYNC_DATA3;
public static final java.lang.String SYNC_DATA4 = android.provider.CalendarContract.Events.SYNC_DATA4;
public static final java.lang.String SYNC_DATA5 = android.provider.CalendarContract.Events.SYNC_DATA5;
public static final java.lang.String SYNC_DATA6 = android.provider.CalendarContract.Events.SYNC_DATA6;
public static final java.lang.String SYNC_DATA7 = android.provider.CalendarContract.Events.SYNC_DATA7;
public static final java.lang.String SYNC_DATA8 = android.provider.CalendarContract.Events.SYNC_DATA8;
public static final java.lang.String SYNC_DATA9 = android.provider.CalendarContract.Events.SYNC_DATA9;
public static final java.lang.String TITLE = android.provider.CalendarContract.Events.TITLE;
public static final java.lang.String UID_2445 = android.provider.CalendarContract.Events.UID_2445;
}
public static interface CalendarContract_SyncColumns {
public static final java.lang.String ACCOUNT_NAME = android.provider.CalendarContract.Events.ACCOUNT_NAME;
public static final java.lang.String ACCOUNT_TYPE = android.provider.CalendarContract.Events.ACCOUNT_TYPE;
public static final java.lang.String CAN_PARTIALLY_UPDATE = android.provider.CalendarContract.Events.CAN_PARTIALLY_UPDATE;
public static final java.lang.String DELETED = android.provider.CalendarContract.Events.DELETED;
public static final java.lang.String DIRTY = android.provider.CalendarContract.Events.DIRTY;
public static final java.lang.String MUTATORS = android.provider.CalendarContract.Events.MUTATORS;
public static final java.lang.String _SYNC_ID = android.provider.CalendarContract.Events._SYNC_ID;
}
public static interface AttendeesColumns {
public static final java.lang.String ATTENDEE_EMAIL = android.provider.CalendarContract.Attendees.ATTENDEE_EMAIL;
public static final java.lang.String ATTENDEE_IDENTITY = android.provider.CalendarContract.Attendees.ATTENDEE_IDENTITY;
public static final java.lang.String ATTENDEE_ID_NAMESPACE = android.provider.CalendarContract.Attendees.ATTENDEE_ID_NAMESPACE;
public static final java.lang.String ATTENDEE_NAME = android.provider.CalendarContract.Attendees.ATTENDEE_NAME;
public static final java.lang.String ATTENDEE_RELATIONSHIP = android.provider.CalendarContract.Attendees.ATTENDEE_RELATIONSHIP;
public static final java.lang.String ATTENDEE_STATUS = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS;
public static final int ATTENDEE_STATUS_ACCEPTED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED;
public static final int ATTENDEE_STATUS_DECLINED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED;
public static final int ATTENDEE_STATUS_INVITED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_INVITED;
public static final int ATTENDEE_STATUS_NONE = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE;
public static final int ATTENDEE_STATUS_TENTATIVE = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE;
public static final java.lang.String ATTENDEE_TYPE = android.provider.CalendarContract.Attendees.ATTENDEE_TYPE;
public static final java.lang.String EVENT_ID = android.provider.CalendarContract.Attendees.EVENT_ID;
public static final int RELATIONSHIP_ATTENDEE = android.provider.CalendarContract.Attendees.RELATIONSHIP_ATTENDEE;
public static final int RELATIONSHIP_NONE = android.provider.CalendarContract.Attendees.RELATIONSHIP_NONE;
public static final int RELATIONSHIP_ORGANIZER = android.provider.CalendarContract.Attendees.RELATIONSHIP_ORGANIZER;
public static final int RELATIONSHIP_PERFORMER = android.provider.CalendarContract.Attendees.RELATIONSHIP_PERFORMER;
public static final int RELATIONSHIP_SPEAKER = android.provider.CalendarContract.Attendees.RELATIONSHIP_SPEAKER;
public static final int TYPE_NONE = android.provider.CalendarContract.Attendees.TYPE_NONE;
public static final int TYPE_OPTIONAL = android.provider.CalendarContract.Attendees.TYPE_OPTIONAL;
public static final int TYPE_REQUIRED = android.provider.CalendarContract.Attendees.TYPE_REQUIRED;
public static final int TYPE_RESOURCE = android.provider.CalendarContract.Attendees.TYPE_RESOURCE;
}
public static interface EventDaysColumns {
public static final java.lang.String ENDDAY = android.provider.CalendarContract.EventDays.ENDDAY;
public static final java.lang.String STARTDAY = android.provider.CalendarContract.EventDays.STARTDAY;
}
public static interface StatusColumns {
public static final int AVAILABLE = android.provider.ContactsContract.Contacts.Entity.AVAILABLE;
public static final int AWAY = android.provider.ContactsContract.Contacts.Entity.AWAY;
public static final int CAPABILITY_HAS_CAMERA = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_CAMERA;
public static final int CAPABILITY_HAS_VIDEO = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_VIDEO;
public static final int CAPABILITY_HAS_VOICE = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_VOICE;
public static final java.lang.String CHAT_CAPABILITY = android.provider.ContactsContract.Contacts.Entity.CHAT_CAPABILITY;
public static final int DO_NOT_DISTURB = android.provider.ContactsContract.Contacts.Entity.DO_NOT_DISTURB;
public static final int IDLE = android.provider.ContactsContract.Contacts.Entity.IDLE;
public static final int INVISIBLE = android.provider.ContactsContract.Contacts.Entity.INVISIBLE;
public static final int OFFLINE = android.provider.ContactsContract.Contacts.Entity.OFFLINE;
public static final java.lang.String PRESENCE = android.provider.ContactsContract.Contacts.Entity.PRESENCE;
public static final java.lang.String PRESENCE_CUSTOM_STATUS = android.provider.ContactsContract.Contacts.Entity.PRESENCE_CUSTOM_STATUS;
public static final java.lang.String PRESENCE_STATUS = android.provider.ContactsContract.Contacts.Entity.PRESENCE_STATUS;
public static final java.lang.String STATUS = android.provider.ContactsContract.Contacts.Entity.STATUS;
public static final java.lang.String STATUS_ICON = android.provider.ContactsContract.Contacts.Entity.STATUS_ICON;
public static final java.lang.String STATUS_LABEL = android.provider.ContactsContract.Contacts.Entity.STATUS_LABEL;
public static final java.lang.String STATUS_RES_PACKAGE = android.provider.ContactsContract.Contacts.Entity.STATUS_RES_PACKAGE;
public static final java.lang.String STATUS_TIMESTAMP = android.provider.ContactsContract.Contacts.Entity.STATUS_TIMESTAMP;
}
public static interface ContactStatusColumns {
public static final java.lang.String CONTACT_CHAT_CAPABILITY = android.provider.ContactsContract.Contacts.CONTACT_CHAT_CAPABILITY;
public static final java.lang.String CONTACT_PRESENCE = android.provider.ContactsContract.Contacts.CONTACT_PRESENCE;
public static final java.lang.String CONTACT_STATUS = android.provider.ContactsContract.Contacts.CONTACT_STATUS;
public static final java.lang.String CONTACT_STATUS_ICON = android.provider.ContactsContract.Contacts.CONTACT_STATUS_ICON;
public static final java.lang.String CONTACT_STATUS_LABEL = android.provider.ContactsContract.Contacts.CONTACT_STATUS_LABEL;
public static final java.lang.String CONTACT_STATUS_RES_PACKAGE = android.provider.ContactsContract.Contacts.CONTACT_STATUS_RES_PACKAGE;
public static final java.lang.String CONTACT_STATUS_TIMESTAMP = android.provider.ContactsContract.Contacts.CONTACT_STATUS_TIMESTAMP;
}
public static interface CalendarColumns {
public static final java.lang.String ALLOWED_ATTENDEE_TYPES = android.provider.CalendarContract.Events.ALLOWED_ATTENDEE_TYPES;
public static final java.lang.String ALLOWED_AVAILABILITY = android.provider.CalendarContract.Events.ALLOWED_AVAILABILITY;
public static final java.lang.String ALLOWED_REMINDERS = android.provider.CalendarContract.Events.ALLOWED_REMINDERS;
public static final java.lang.String CALENDAR_ACCESS_LEVEL = android.provider.CalendarContract.Events.CALENDAR_ACCESS_LEVEL;
public static final java.lang.String CALENDAR_COLOR = android.provider.CalendarContract.Events.CALENDAR_COLOR;
public static final java.lang.String CALENDAR_COLOR_KEY = android.provider.CalendarContract.Events.CALENDAR_COLOR_KEY;
public static final java.lang.String CALENDAR_DISPLAY_NAME = android.provider.CalendarContract.Events.CALENDAR_DISPLAY_NAME;
public static final java.lang.String CALENDAR_TIME_ZONE = android.provider.CalendarContract.Events.CALENDAR_TIME_ZONE;
public static final int CAL_ACCESS_CONTRIBUTOR = android.provider.CalendarContract.Events.CAL_ACCESS_CONTRIBUTOR;
public static final int CAL_ACCESS_EDITOR = android.provider.CalendarContract.Events.CAL_ACCESS_EDITOR;
public static final int CAL_ACCESS_FREEBUSY = android.provider.CalendarContract.Events.CAL_ACCESS_FREEBUSY;
public static final int CAL_ACCESS_NONE = android.provider.CalendarContract.Events.CAL_ACCESS_NONE;
public static final int CAL_ACCESS_OVERRIDE = android.provider.CalendarContract.Events.CAL_ACCESS_OVERRIDE;
public static final int CAL_ACCESS_OWNER = android.provider.CalendarContract.Events.CAL_ACCESS_OWNER;
public static final int CAL_ACCESS_READ = android.provider.CalendarContract.Events.CAL_ACCESS_READ;
public static final int CAL_ACCESS_RESPOND = android.provider.CalendarContract.Events.CAL_ACCESS_RESPOND;
public static final int CAL_ACCESS_ROOT = android.provider.CalendarContract.Events.CAL_ACCESS_ROOT;
public static final java.lang.String CAN_MODIFY_TIME_ZONE = android.provider.CalendarContract.Events.CAN_MODIFY_TIME_ZONE;
public static final java.lang.String CAN_ORGANIZER_RESPOND = android.provider.CalendarContract.Events.CAN_ORGANIZER_RESPOND;
public static final java.lang.String IS_PRIMARY = android.provider.CalendarContract.Events.IS_PRIMARY;
public static final java.lang.String MAX_REMINDERS = android.provider.CalendarContract.Events.MAX_REMINDERS;
public static final java.lang.String OWNER_ACCOUNT = android.provider.CalendarContract.Events.OWNER_ACCOUNT;
public static final java.lang.String SYNC_EVENTS = android.provider.CalendarContract.Events.SYNC_EVENTS;
public static final java.lang.String VISIBLE = android.provider.CalendarContract.Events.VISIBLE;
}
public static interface DataUsageStatColumns {
public static final java.lang.String LAST_TIME_USED = android.provider.ContactsContract.Contacts.Entity.LAST_TIME_USED;
public static final java.lang.String TIMES_USED = android.provider.ContactsContract.Contacts.Entity.TIMES_USED;
}
public static interface PresenceColumns {
public static final java.lang.String CUSTOM_PROTOCOL = android.provider.ContactsContract.StatusUpdates.CUSTOM_PROTOCOL;
public static final java.lang.String DATA_ID = android.provider.ContactsContract.StatusUpdates.DATA_ID;
public static final java.lang.String IM_ACCOUNT = android.provider.ContactsContract.StatusUpdates.IM_ACCOUNT;
public static final java.lang.String IM_HANDLE = android.provider.ContactsContract.StatusUpdates.IM_HANDLE;
public static final java.lang.String PROTOCOL = android.provider.ContactsContract.StatusUpdates.PROTOCOL;
}
public static interface GroupsColumns {
public static final java.lang.String AUTO_ADD = android.provider.ContactsContract.Groups.AUTO_ADD;
public static final java.lang.String DATA_SET = android.provider.ContactsContract.Groups.DATA_SET;
public static final java.lang.String DELETED = android.provider.ContactsContract.Groups.DELETED;
public static final java.lang.String FAVORITES = android.provider.ContactsContract.Groups.FAVORITES;
public static final java.lang.String GROUP_IS_READ_ONLY = android.provider.ContactsContract.Groups.GROUP_IS_READ_ONLY;
public static final java.lang.String GROUP_VISIBLE = android.provider.ContactsContract.Groups.GROUP_VISIBLE;
public static final java.lang.String NOTES = android.provider.ContactsContract.Groups.NOTES;
public static final java.lang.String RES_PACKAGE = android.provider.ContactsContract.Groups.RES_PACKAGE;
public static final java.lang.String SHOULD_SYNC = android.provider.ContactsContract.Groups.SHOULD_SYNC;
public static final java.lang.String SUMMARY_COUNT = android.provider.ContactsContract.Groups.SUMMARY_COUNT;
public static final java.lang.String SUMMARY_WITH_PHONES = android.provider.ContactsContract.Groups.SUMMARY_WITH_PHONES;
public static final java.lang.String SYSTEM_ID = android.provider.ContactsContract.Groups.SYSTEM_ID;
public static final java.lang.String TITLE = android.provider.ContactsContract.Groups.TITLE;
public static final java.lang.String TITLE_RES = android.provider.ContactsContract.Groups.TITLE_RES;
}
public static interface ContactsColumns {
public static final java.lang.String CONTACT_LAST_UPDATED_TIMESTAMP = android.provider.ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP;
public static final java.lang.String DISPLAY_NAME = android.provider.ContactsContract.Contacts.DISPLAY_NAME;
public static final java.lang.String HAS_PHONE_NUMBER = android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER;
public static final java.lang.String IN_DEFAULT_DIRECTORY = android.provider.ContactsContract.Contacts.IN_DEFAULT_DIRECTORY;
public static final java.lang.String IN_VISIBLE_GROUP = android.provider.ContactsContract.Contacts.IN_VISIBLE_GROUP;
public static final java.lang.String IS_USER_PROFILE = android.provider.ContactsContract.Contacts.IS_USER_PROFILE;
public static final java.lang.String LOOKUP_KEY = android.provider.ContactsContract.Contacts.LOOKUP_KEY;
public static final java.lang.String NAME_RAW_CONTACT_ID = android.provider.ContactsContract.Contacts.NAME_RAW_CONTACT_ID;
public static final java.lang.String PHOTO_FILE_ID = android.provider.ContactsContract.Contacts.PHOTO_FILE_ID;
public static final java.lang.String PHOTO_ID = android.provider.ContactsContract.Contacts.PHOTO_ID;
public static final java.lang.String PHOTO_THUMBNAIL_URI = android.provider.ContactsContract.Contacts.PHOTO_THUMBNAIL_URI;
public static final java.lang.String PHOTO_URI = android.provider.ContactsContract.Contacts.PHOTO_URI;
}
public static interface PhoneLookupColumns {
public static final java.lang.String LABEL = android.provider.ContactsContract.PhoneLookup.LABEL;
public static final java.lang.String NORMALIZED_NUMBER = android.provider.ContactsContract.PhoneLookup.NORMALIZED_NUMBER;
public static final java.lang.String NUMBER = android.provider.ContactsContract.PhoneLookup.NUMBER;
public static final java.lang.String TYPE = android.provider.ContactsContract.PhoneLookup.TYPE;
}
public static interface CommonColumns {
public static final java.lang.String DATA = android.provider.ContactsContract.CommonDataKinds.StructuredPostal.DATA;
public static final java.lang.String LABEL = android.provider.ContactsContract.CommonDataKinds.StructuredPostal.LABEL;
public static final java.lang.String TYPE = android.provider.ContactsContract.CommonDataKinds.StructuredPostal.TYPE;
}
public static interface ContactsContract_SyncColumns {
public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.Groups.ACCOUNT_NAME;
public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.Groups.ACCOUNT_TYPE;
public static final java.lang.String DIRTY = android.provider.ContactsContract.Groups.DIRTY;
public static final java.lang.String SOURCE_ID = android.provider.ContactsContract.Groups.SOURCE_ID;
public static final java.lang.String VERSION = android.provider.ContactsContract.Groups.VERSION;
}
public static interface DataColumns {
public static final java.lang.String DATA1 = android.provider.ContactsContract.Contacts.Data.DATA1;
public static final java.lang.String DATA10 = android.provider.ContactsContract.Contacts.Data.DATA10;
public static final java.lang.String DATA11 = android.provider.ContactsContract.Contacts.Data.DATA11;
public static final java.lang.String DATA12 = android.provider.ContactsContract.Contacts.Data.DATA12;
public static final java.lang.String DATA13 = android.provider.ContactsContract.Contacts.Data.DATA13;
public static final java.lang.String DATA14 = android.provider.ContactsContract.Contacts.Data.DATA14;
public static final java.lang.String DATA15 = android.provider.ContactsContract.Contacts.Data.DATA15;
public static final java.lang.String DATA2 = android.provider.ContactsContract.Contacts.Data.DATA2;
public static final java.lang.String DATA3 = android.provider.ContactsContract.Contacts.Data.DATA3;
public static final java.lang.String DATA4 = android.provider.ContactsContract.Contacts.Data.DATA4;
public static final java.lang.String DATA5 = android.provider.ContactsContract.Contacts.Data.DATA5;
public static final java.lang.String DATA6 = android.provider.ContactsContract.Contacts.Data.DATA6;
public static final java.lang.String DATA7 = android.provider.ContactsContract.Contacts.Data.DATA7;
public static final java.lang.String DATA8 = android.provider.ContactsContract.Contacts.Data.DATA8;
public static final java.lang.String DATA9 = android.provider.ContactsContract.Contacts.Data.DATA9;
public static final java.lang.String DATA_VERSION = android.provider.ContactsContract.Contacts.Data.DATA_VERSION;
public static final java.lang.String IS_PRIMARY = android.provider.ContactsContract.Contacts.Data.IS_PRIMARY;
public static final java.lang.String IS_READ_ONLY = android.provider.ContactsContract.Contacts.Data.IS_READ_ONLY;
public static final java.lang.String IS_SUPER_PRIMARY = android.provider.ContactsContract.Contacts.Data.IS_SUPER_PRIMARY;
public static final java.lang.String MIMETYPE = android.provider.ContactsContract.Contacts.Data.MIMETYPE;
public static final java.lang.String RAW_CONTACT_ID = android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID;
public static final java.lang.String RES_PACKAGE = android.provider.ContactsContract.Contacts.Data.RES_PACKAGE;
public static final java.lang.String SYNC1 = android.provider.ContactsContract.Contacts.Data.SYNC1;
public static final java.lang.String SYNC2 = android.provider.ContactsContract.Contacts.Data.SYNC2;
public static final java.lang.String SYNC3 = android.provider.ContactsContract.Contacts.Data.SYNC3;
public static final java.lang.String SYNC4 = android.provider.ContactsContract.Contacts.Data.SYNC4;
}
public static interface ContactNameColumns {
public static final java.lang.String DISPLAY_NAME_ALTERNATIVE = android.provider.ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE;
public static final java.lang.String DISPLAY_NAME_PRIMARY = android.provider.ContactsContract.Contacts.DISPLAY_NAME_PRIMARY;
public static final java.lang.String DISPLAY_NAME_SOURCE = android.provider.ContactsContract.Contacts.DISPLAY_NAME_SOURCE;
public static final java.lang.String PHONETIC_NAME = android.provider.ContactsContract.Contacts.PHONETIC_NAME;
public static final java.lang.String PHONETIC_NAME_STYLE = android.provider.ContactsContract.Contacts.PHONETIC_NAME_STYLE;
public static final java.lang.String SORT_KEY_ALTERNATIVE = android.provider.ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
public static final java.lang.String SORT_KEY_PRIMARY = android.provider.ContactsContract.Contacts.SORT_KEY_PRIMARY;
}
public static interface CalendarAlertsColumns {
public static final java.lang.String ALARM_TIME = android.provider.CalendarContract.CalendarAlerts.ALARM_TIME;
public static final java.lang.String BEGIN = android.provider.CalendarContract.CalendarAlerts.BEGIN;
public static final java.lang.String CREATION_TIME = android.provider.CalendarContract.CalendarAlerts.CREATION_TIME;
public static final java.lang.String DEFAULT_SORT_ORDER = android.provider.CalendarContract.CalendarAlerts.DEFAULT_SORT_ORDER;
public static final java.lang.String END = android.provider.CalendarContract.CalendarAlerts.END;
public static final java.lang.String EVENT_ID = android.provider.CalendarContract.CalendarAlerts.EVENT_ID;
public static final java.lang.String MINUTES = android.provider.CalendarContract.CalendarAlerts.MINUTES;
public static final java.lang.String NOTIFY_TIME = android.provider.CalendarContract.CalendarAlerts.NOTIFY_TIME;
public static final java.lang.String RECEIVED_TIME = android.provider.CalendarContract.CalendarAlerts.RECEIVED_TIME;
public static final java.lang.String STATE = android.provider.CalendarContract.CalendarAlerts.STATE;
public static final int STATE_DISMISSED = android.provider.CalendarContract.CalendarAlerts.STATE_DISMISSED;
public static final int STATE_FIRED = android.provider.CalendarContract.CalendarAlerts.STATE_FIRED;
public static final int STATE_SCHEDULED = android.provider.CalendarContract.CalendarAlerts.STATE_SCHEDULED;
}
public static interface StreamItemsColumns {
public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.RawContacts.StreamItems.ACCOUNT_NAME;
public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.RawContacts.StreamItems.ACCOUNT_TYPE;
public static final java.lang.String COMMENTS = android.provider.ContactsContract.RawContacts.StreamItems.COMMENTS;
public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.RawContacts.StreamItems.CONTACT_ID;
public static final java.lang.String CONTACT_LOOKUP_KEY = android.provider.ContactsContract.RawContacts.StreamItems.CONTACT_LOOKUP_KEY;
public static final java.lang.String DATA_SET = android.provider.ContactsContract.RawContacts.StreamItems.DATA_SET;
public static final java.lang.String RAW_CONTACT_ID = android.provider.ContactsContract.RawContacts.StreamItems.RAW_CONTACT_ID;
public static final java.lang.String RAW_CONTACT_SOURCE_ID = android.provider.ContactsContract.RawContacts.StreamItems.RAW_CONTACT_SOURCE_ID;
public static final java.lang.String RES_ICON = android.provider.ContactsContract.RawContacts.StreamItems.RES_ICON;
public static final java.lang.String RES_LABEL = android.provider.ContactsContract.RawContacts.StreamItems.RES_LABEL;
public static final java.lang.String RES_PACKAGE = android.provider.ContactsContract.RawContacts.StreamItems.RES_PACKAGE;
public static final java.lang.String SYNC1 = android.provider.ContactsContract.RawContacts.StreamItems.SYNC1;
public static final java.lang.String SYNC2 = android.provider.ContactsContract.RawContacts.StreamItems.SYNC2;
public static final java.lang.String SYNC3 = android.provider.ContactsContract.RawContacts.StreamItems.SYNC3;
public static final java.lang.String SYNC4 = android.provider.ContactsContract.RawContacts.StreamItems.SYNC4;
public static final java.lang.String TEXT = android.provider.ContactsContract.RawContacts.StreamItems.TEXT;
public static final java.lang.String TIMESTAMP = android.provider.ContactsContract.RawContacts.StreamItems.TIMESTAMP;
}
public static interface RemindersColumns {
public static final java.lang.String EVENT_ID = android.provider.CalendarContract.Reminders.EVENT_ID;
public static final java.lang.String METHOD = android.provider.CalendarContract.Reminders.METHOD;
public static final int METHOD_ALARM = android.provider.CalendarContract.Reminders.METHOD_ALARM;
public static final int METHOD_ALERT = android.provider.CalendarContract.Reminders.METHOD_ALERT;
public static final int METHOD_DEFAULT = android.provider.CalendarContract.Reminders.METHOD_DEFAULT;
public static final int METHOD_EMAIL = android.provider.CalendarContract.Reminders.METHOD_EMAIL;
public static final int METHOD_SMS = android.provider.CalendarContract.Reminders.METHOD_SMS;
public static final java.lang.String MINUTES = android.provider.CalendarContract.Reminders.MINUTES;
public static final int MINUTES_DEFAULT = android.provider.CalendarContract.Reminders.MINUTES_DEFAULT;
}
public static interface StreamItemPhotosColumns {
public static final java.lang.String PHOTO_FILE_ID = android.provider.ContactsContract.StreamItemPhotos.PHOTO_FILE_ID;
public static final java.lang.String PHOTO_URI = android.provider.ContactsContract.StreamItemPhotos.PHOTO_URI;
public static final java.lang.String SORT_INDEX = android.provider.ContactsContract.StreamItemPhotos.SORT_INDEX;
public static final java.lang.String STREAM_ITEM_ID = android.provider.ContactsContract.StreamItemPhotos.STREAM_ITEM_ID;
public static final java.lang.String SYNC1 = android.provider.ContactsContract.StreamItemPhotos.SYNC1;
public static final java.lang.String SYNC2 = android.provider.ContactsContract.StreamItemPhotos.SYNC2;
public static final java.lang.String SYNC3 = android.provider.ContactsContract.StreamItemPhotos.SYNC3;
public static final java.lang.String SYNC4 = android.provider.ContactsContract.StreamItemPhotos.SYNC4;
}
} | apache-2.0 | 4d74e292bbeac98833b98078d9e87396 | 94.308094 | 152 | 0.784067 | 4.554779 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/androidTest/org/videolan/vlc/PreferenceMatcher.kt | 1 | 5993 | package org.videolan.vlc
import org.hamcrest.Matchers.`is`
import android.content.res.Resources
import androidx.preference.Preference
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
/** A collection of hamcrest matchers that match [Preference]s.
* These match with the [androidx.preference.Preference] class from androidX APIs.
**/
object PreferenceMatchers {
val isEnabled: Matcher<Preference>
get() = object : TypeSafeMatcher<Preference>() {
override fun describeTo(description: Description) {
description.appendText(" is an enabled preference")
}
public override fun matchesSafely(pref: Preference): Boolean {
return pref.isEnabled
}
}
fun withSummary(resourceId: Int): Matcher<Preference> {
return object : TypeSafeMatcher<Preference>() {
private var resourceName: String? = null
private var expectedText: String? = null
override fun describeTo(description: Description) {
description.appendText(" with summary string from resource id: ")
description.appendValue(resourceId)
if (null != resourceName) {
description.appendText("[")
description.appendText(resourceName)
description.appendText("]")
}
if (null != expectedText) {
description.appendText(" value: ")
description.appendText(expectedText)
}
}
public override fun matchesSafely(preference: Preference): Boolean {
if (null == expectedText) {
try {
expectedText = preference.context.resources.getString(resourceId)
resourceName = preference.context.resources.getResourceEntryName(resourceId)
} catch (ignored: Resources.NotFoundException) {
/* view could be from a context unaware of the resource id. */
}
}
return if (null != expectedText) {
expectedText == preference.summary.toString()
} else {
false
}
}
}
}
fun withSummaryText(summary: String): Matcher<Preference> {
return withSummaryText(`is`(summary))
}
fun withSummaryText(summaryMatcher: Matcher<String>): Matcher<Preference> {
return object : TypeSafeMatcher<Preference>() {
override fun describeTo(description: Description) {
description.appendText(" a preference with summary matching: ")
summaryMatcher.describeTo(description)
}
public override fun matchesSafely(pref: Preference): Boolean {
val summary = pref.summary.toString()
return summaryMatcher.matches(summary)
}
}
}
fun withTitle(resourceId: Int): Matcher<Preference> {
return object : TypeSafeMatcher<Preference>() {
private var resourceName: String? = null
private var expectedText: String? = null
override fun describeTo(description: Description) {
description.appendText(" with title string from resource id: ")
description.appendValue(resourceId)
if (null != resourceName) {
description.appendText("[")
description.appendText(resourceName)
description.appendText("]")
}
if (null != expectedText) {
description.appendText(" value: ")
description.appendText(expectedText)
}
}
public override fun matchesSafely(preference: Preference): Boolean {
if (null == expectedText) {
try {
expectedText = preference.context.resources.getString(resourceId)
resourceName = preference.context.resources.getResourceEntryName(resourceId)
} catch (ignored: Resources.NotFoundException) {
/* view could be from a context unaware of the resource id. */
}
}
return if (null != expectedText && preference.title != null) {
expectedText == preference.title.toString()
} else {
false
}
}
}
}
fun withTitleText(title: String): Matcher<Preference> {
return withTitleText(`is`(title))
}
fun withTitleText(titleMatcher: Matcher<String>): Matcher<Preference> {
return object : TypeSafeMatcher<Preference>() {
override fun describeTo(description: Description) {
description.appendText(" a preference with title matching: ")
titleMatcher.describeTo(description)
}
public override fun matchesSafely(pref: Preference): Boolean {
if (pref.title == null) {
return false
}
val title = pref.title.toString()
return titleMatcher.matches(title)
}
}
}
fun withKey(key: String): Matcher<Preference> {
return withKey(`is`(key))
}
fun withKey(keyMatcher: Matcher<String>): Matcher<Preference> {
return object : TypeSafeMatcher<Preference>() {
override fun describeTo(description: Description) {
description.appendText(" preference with key matching: ")
keyMatcher.describeTo(description)
}
public override fun matchesSafely(pref: Preference): Boolean {
return keyMatcher.matches(pref.key)
}
}
}
}
| gpl-2.0 | bd136830a89824152d7987021384ad88 | 36.93038 | 100 | 0.558652 | 5.933663 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/category/fragment/CategoryBrowseFragment.kt | 1 | 10309 | package io.casey.musikcube.remote.ui.category.fragment
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.websocket.model.ICategoryValue
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.ui.category.adapter.CategoryBrowseAdapter
import io.casey.musikcube.remote.ui.category.constant.Category
import io.casey.musikcube.remote.ui.category.constant.NavigationType
import io.casey.musikcube.remote.ui.navigation.Navigate
import io.casey.musikcube.remote.ui.shared.activity.IFabConsumer
import io.casey.musikcube.remote.ui.shared.activity.IFilterable
import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider
import io.casey.musikcube.remote.ui.shared.activity.ITransportObserver
import io.casey.musikcube.remote.ui.shared.constant.Shared
import io.casey.musikcube.remote.ui.shared.extension.addFilterAction
import io.casey.musikcube.remote.ui.shared.extension.getLayoutId
import io.casey.musikcube.remote.ui.shared.extension.getTitleOverride
import io.casey.musikcube.remote.ui.shared.extension.setupDefaultRecyclerView
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.shared.mixin.ItemContextMenuMixin
import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin
import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin
import io.casey.musikcube.remote.ui.shared.view.EmptyListView
import io.casey.musikcube.remote.util.Debouncer
import io.reactivex.rxkotlin.subscribeBy
class CategoryBrowseFragment: BaseFragment(), IFilterable, ITitleProvider, ITransportObserver, IFabConsumer {
private lateinit var adapter: CategoryBrowseAdapter
private var lastFilter: String? = null
private lateinit var rootView: View
private lateinit var emptyView: EmptyListView
private lateinit var data: MetadataProxyMixin
private lateinit var playback: PlaybackMixin
private val navigationType: NavigationType
get() = NavigationType.get(extras.getInt(
Category.Extra.NAVIGATION_TYPE, NavigationType.Albums.ordinal))
private val category
get() = extras.getString(Category.Extra.CATEGORY, "")
private val predicateType: String
get() = extras.getString(Category.Extra.PREDICATE_TYPE, "")
private val predicateId: Long
get() = extras.getLong(Category.Extra.PREDICATE_ID, -1L)
override val title: String
get() {
Category.NAME_TO_TITLE[category]?.let {
return getTitleOverride(getString(it))
}
return getTitleOverride(Category.toDisplayString(app, category))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component.inject(this)
data = mixin(MetadataProxyMixin())
playback = mixin(PlaybackMixin())
mixin(ItemContextMenuMixin(appCompatActivity, contextMenuListener, this))
adapter = CategoryBrowseAdapter(adapterListener, playback, navigationType, category, prefs)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(this.getLayoutId(), container, false).apply {
[email protected] = this
val recyclerView = findViewById<FastScrollRecyclerView>(R.id.recycler_view)
emptyView = findViewById(R.id.empty_list_view)
emptyView.capability = EmptyListView.Capability.OnlineOnly
emptyView.emptyMessage = getString(R.string.empty_no_items_format, categoryTypeString)
emptyView.alternateView = recyclerView
setupDefaultRecyclerView(recyclerView, adapter)
}
override fun onFabPress(fab: FloatingActionButton) {
mixin(ItemContextMenuMixin::class.java)?.createPlaylist()
}
override val fabVisible: Boolean
get() = (category == Metadata.Category.PLAYLISTS)
override val addFilterToToolbar: Boolean
get() = true
override fun setFilter(filter: String) {
this.lastFilter = filter
this.filterDebouncer.call()
}
fun createOptionsMenu(menu: Menu): Boolean {
when (Metadata.Category.PLAYLISTS == category) {
true -> menu.clear()
else -> addFilterAction(menu, this)
}
return true
}
override fun onTransportChanged() =
adapter.notifyDataSetChanged()
override fun onInitObservables() {
disposables.add(data.provider.observeState().subscribeBy(
onNext = { states ->
when (states.first) {
IMetadataProxy.State.Connected -> {
filterDebouncer.cancel()
requery()
}
IMetadataProxy.State.Disconnected -> {
emptyView.update(states.first, adapter.itemCount)
}
else -> {
}
}
},
onError = {
}))
}
private val categoryTypeString: String
get() {
Category.NAME_TO_EMPTY_TYPE[category]?.let {
return getString(it)
}
return Category.toDisplayString(app, category)
}
private val resolvedFilter: String
get() =
when (category) {
Metadata.Category.PLAYLISTS -> ""
else -> lastFilter ?: ""
}
private fun requery() {
@Suppress("UNUSED")
data.provider
.getCategoryValues(category, predicateType, predicateId, resolvedFilter)
.subscribeBy(
onNext = { values -> adapter.setModel(values) },
onError = { },
onComplete = { emptyView.update(data.provider.state, adapter.itemCount)})
}
private val filterDebouncer = object : Debouncer<String>(350) {
override fun onDebounced(last: String?) {
if (!paused) {
requery()
}
}
}
private val contextMenuListener = object: ItemContextMenuMixin.EventListener() {
override fun onPlaylistDeleted(id: Long, name: String) = requery()
override fun onPlaylistUpdated(id: Long, name: String) = requery()
override fun onPlaylistCreated(id: Long, name: String) =
if (navigationType == NavigationType.Select) navigateToSelect(id, name) else requery()
}
private val adapterListener = object: CategoryBrowseAdapter.EventListener {
override fun onItemClicked(value: ICategoryValue) {
when (navigationType) {
NavigationType.Albums -> navigateToAlbums(value)
NavigationType.Tracks -> navigateToTracks(value)
NavigationType.Select -> navigateToSelect(value.id, value.value)
}
}
override fun onActionClicked(view: View, value: ICategoryValue) {
mixin(ItemContextMenuMixin::class.java)?.showForCategory(value, view)
}
}
private fun navigateToAlbums(entry: ICategoryValue) =
Navigate.toAlbums(category, entry, appCompatActivity, this)
private fun navigateToTracks(entry: ICategoryValue) =
Navigate.toTracks(category, entry, appCompatActivity, this)
private fun navigateToSelect(id: Long, name: String) =
appCompatActivity.run {
setResult(Activity.RESULT_OK, Intent().apply {
putExtra(Category.Extra.CATEGORY, category)
putExtra(Category.Extra.ID, id)
putExtra(Category.Extra.NAME, name)
})
finish()
}
companion object {
const val TAG = "CategoryBrowseFragment"
fun create(intent: Intent?): CategoryBrowseFragment {
if (intent == null) {
throw IllegalArgumentException("invalid intent")
}
return create(intent.getBundleExtra(Category.Extra.FRAGMENT_ARGUMENTS) ?: Bundle())
}
fun create(arguments: Bundle): CategoryBrowseFragment =
CategoryBrowseFragment().apply {
this.arguments = arguments
}
fun create(context: Context,
targetType: String,
predicateType: String = "",
predicateId: Long = -1,
predicateValue: String = ""): CategoryBrowseFragment =
create(arguments(context, targetType, predicateType, predicateId, predicateValue))
fun arguments(context: Context,
targetType: String,
sourceType: String = "",
sourceId: Long = -1,
sourceValue: String = ""): Bundle =
Bundle().apply {
putString(Category.Extra.CATEGORY, targetType)
putString(Category.Extra.PREDICATE_TYPE, sourceType)
putLong(Category.Extra.PREDICATE_ID, sourceId)
if (sourceValue.isNotBlank() && Category.NAME_TO_RELATED_TITLE.containsKey(targetType)) {
when (val format = Category.NAME_TO_RELATED_TITLE[targetType]) {
null -> throw IllegalArgumentException("unknown category $targetType")
else -> putString(Shared.Extra.TITLE_OVERRIDE, context.getString(format, sourceValue))
}
}
}
fun arguments(category: String,
navigationType: NavigationType,
title: String = ""): Bundle =
Bundle().apply {
putString(Category.Extra.CATEGORY, category)
putInt(Category.Extra.NAVIGATION_TYPE, navigationType.ordinal)
putString(Category.Extra.TITLE, title)
}
}
} | bsd-3-clause | 0a7e23e3404810a2271de3d1e39160cc | 39.273438 | 116 | 0.6505 | 4.944365 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/MapShowingLocationActivity.kt | 1 | 6359 | //package com.didichuxing.doraemondemo
//
//import android.Manifest
//import android.annotation.SuppressLint
//import android.os.Bundle
//import android.util.Log
//import android.view.View
//import androidx.appcompat.app.AppCompatActivity
//import com.baidu.location.BDAbstractLocationListener
//import com.baidu.location.BDLocation
//import com.baidu.location.LocationClient
//import com.baidu.location.LocationClientOption
//import com.didichuxing.doraemonkit.kit.core.ViewSetupHelper
//import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
//import com.tencent.tencentmap.mapsdk.maps.SupportMapFragment
//import com.tencent.tencentmap.mapsdk.maps.TencentMap
//import com.tencent.tencentmap.mapsdk.maps.model.*
//import pub.devrel.easypermissions.EasyPermissions
//import pub.devrel.easypermissions.PermissionRequest
//
//
//class MapShowingLocationActivity : AppCompatActivity() {
// private lateinit var mRootView: View
// private var mTencentMap: TencentMap? = null
// private var mBaiduLocationClient: LocationClient? = null
// private var mCustomMarker: Marker? = null
// private var mLocationMarker: Marker? = null
// private var mAccuracyCircle: Circle? = null
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_map_showing_location)
// mRootView = findViewById<View>(R.id.map_showing_location)
// initMap()
// initButtons()
// EasyPermissions.requestPermissions(
// PermissionRequest.Builder(
// this, 200,
// Manifest.permission.ACCESS_FINE_LOCATION,
// Manifest.permission.ACCESS_COARSE_LOCATION,
// Manifest.permission.READ_EXTERNAL_STORAGE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE
// ).build()
// )
// }
//
// private fun initMap() {
// val manager = supportFragmentManager
// val fragment = manager.findFragmentById(R.id.fragment_map) as SupportMapFragment?
// if (fragment != null) {
// mTencentMap = fragment.map
// }
// }
//
//
// private fun initButtons() {
// ViewSetupHelper.setupButton(mRootView, R.id.map_test_btn_1, "添加") {
// setMarker(40.011313, 116.391907)
// }
// ViewSetupHelper.setupButton(mRootView, R.id.map_test_btn_2, "移除") {
// removeMarker()
// }
// ViewSetupHelper.setupButton(mRootView, R.id.map_test_btn_3, "归位") {
// if (mCustomMarker != null) mTencentMap?.animateCamera(CameraUpdateFactory.newLatLng(mCustomMarker?.position))
// }
// ViewSetupHelper.setupButton(mRootView, R.id.map_test_btn_4, "启动定位") {
// startLocation()
// }
// ViewSetupHelper.setupButton(mRootView, R.id.map_test_btn_5, "停止定位") {
// stopLocation()
// }
// }
//
// private var mbdLocationListener: BDAbstractLocationListener =
// object : BDAbstractLocationListener() {
// override fun onReceiveLocation(bdLocation: BDLocation) {
// Log.i(TAG, "百度定位===onReceiveLocation===lat==>" + bdLocation.latitude + " lng==>" + bdLocation.longitude)
// setLocationMarker(bdLocation.latitude, bdLocation.longitude, 100f.toDouble())
// }
// }
//
// @SuppressLint("MissingPermission")
// private fun startLocation() {
// //百度地图
// if (mBaiduLocationClient == null) {
// mBaiduLocationClient = LocationClient(this)
// //通过LocationClientOption设置LocationClient相关参数
// val option = LocationClientOption()
// // 打开gps
// option.isOpenGps = true
// // 设置坐标类型
// option.setCoorType("gcj02")
// option.setScanSpan(5000)
// mBaiduLocationClient!!.locOption = option
// mBaiduLocationClient!!.registerLocationListener(mbdLocationListener)
// }
// mBaiduLocationClient?.start()
// }
//
// private fun stopLocation() {
// if (mBaiduLocationClient == null) return
// mBaiduLocationClient?.stop()
// }
//
// private fun setMarker(lat: Double, lng: Double) {
// val position = LatLng(lat, lng)
// mCustomMarker?.remove()
// mCustomMarker = mTencentMap?.addMarker(MarkerOptions(position))
// mTencentMap?.animateCamera(CameraUpdateFactory.newLatLng(position))
// }
//
// private fun setLocationMarker(lat: Double, lng: Double) {
// val position = LatLng(lat, lng)
// if (mLocationMarker == null) {
// val markerOptions = MarkerOptions(position)
// .icon(BitmapDescriptorFactory.fromResource(R.mipmap.dk_location_marker))
// mLocationMarker = mTencentMap?.addMarker(markerOptions)
// } else {
// mLocationMarker?.position = position
// }
// mTencentMap?.animateCamera(CameraUpdateFactory.newLatLng(position))
// }
//
// private fun setLocationMarker(lat: Double, lng: Double, radius: Double) {
// val position = LatLng(lat, lng)
// if (mLocationMarker == null) {
// val markerOptions = MarkerOptions(position)
// .icon(BitmapDescriptorFactory.fromResource(R.mipmap.dk_location_marker))
// mLocationMarker = mTencentMap?.addMarker(markerOptions)
// mAccuracyCircle = mTencentMap?.addCircle(
// CircleOptions().center(position)
// .radius(radius)
// .fillColor(resources.getColor(R.color.colorCircleMarkerFill))
// .strokeColor(resources.getColor(R.color.colorCircleMarkerStroke))
// )
// } else {
// mLocationMarker?.position = position
// mAccuracyCircle?.center = position
// mAccuracyCircle?.radius = radius
// }
// mTencentMap?.animateCamera(CameraUpdateFactory.newLatLng(position))
// }
//
//
// private fun removeMarker() {
// mCustomMarker?.remove()
// mCustomMarker = null
// }
//
// override fun onDestroy() {
// super.onDestroy()
// stopLocation()
// }
//
// companion object {
// const val TAG = "MapShowingLocationActivity"
// }
//} | apache-2.0 | 4c32c059c09020dc03a1c1f2e0a9e02c | 38.772152 | 124 | 0.628521 | 3.878395 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/UniversalActivity.kt | 1 | 1948 | package com.didichuxing.doraemonkit.kit.core
import android.os.Bundle
import android.widget.Toast
import com.didichuxing.doraemonkit.constant.BundleKey
import com.didichuxing.doraemonkit.constant.FragmentIndex
import com.didichuxing.doraemonkit.kit.blockmonitor.BlockMonitorFragment
import com.didichuxing.doraemonkit.kit.colorpick.ColorPickerSettingFragment
/**
* Created by jint on 2018/10/26.
* app基础信息Activity
*/
open class UniversalActivity : BaseActivity() {
var mFragmentClass: Class<out BaseFragment>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle = intent.extras
if (bundle == null) {
finish()
return
}
val index = bundle.getInt(BundleKey.FRAGMENT_INDEX)
if (index == 0) {
finish()
return
}
when (index) {
FragmentIndex.FRAGMENT_COLOR_PICKER_SETTING -> mFragmentClass =
ColorPickerSettingFragment::class.java
FragmentIndex.FRAGMENT_BLOCK_MONITOR -> mFragmentClass =
BlockMonitorFragment::class.java
FragmentIndex.FRAGMENT_SYSTEM -> if (bundle[BundleKey.SYSTEM_FRAGMENT_CLASS] != null) {
mFragmentClass = bundle[BundleKey.SYSTEM_FRAGMENT_CLASS] as Class<out BaseFragment>
}
FragmentIndex.FRAGMENT_CUSTOM -> if (bundle[BundleKey.CUSTOM_FRAGMENT_CLASS] != null) {
mFragmentClass = bundle[BundleKey.CUSTOM_FRAGMENT_CLASS] as Class<out BaseFragment>
}
else -> {
}
}
if (mFragmentClass == null) {
finish()
Toast.makeText(
this,
String.format("fragment index %s not found", index),
Toast.LENGTH_SHORT
).show()
return
}
showContent(mFragmentClass!!, bundle)
}
} | apache-2.0 | 1ae548c0a9eb2d061ec3a957dc8f760c | 34.944444 | 99 | 0.622165 | 4.790123 | false | false | false | false |
pedroSG94/rtmp-streamer-java | rtsp/src/main/java/com/pedro/rtsp/rtsp/commands/SdpBody.kt | 1 | 2623 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtsp.rtsp.commands
import com.pedro.rtsp.utils.RtpConstants
/**
* Created by pedro on 21/02/17.
*/
object SdpBody {
/** supported sampleRates. */
private val AUDIO_SAMPLING_RATES = intArrayOf(
96000, // 0
88200, // 1
64000, // 2
48000, // 3
44100, // 4
32000, // 5
24000, // 6
22050, // 7
16000, // 8
12000, // 9
11025, // 10
8000, // 11
7350, // 12
-1, // 13
-1, // 14
-1)
fun createAacBody(trackAudio: Int, sampleRate: Int, isStereo: Boolean): String {
val sampleRateNum = AUDIO_SAMPLING_RATES.toList().indexOf(sampleRate)
val channel = if (isStereo) 2 else 1
val config = 2 and 0x1F shl 11 or (sampleRateNum and 0x0F shl 7) or (channel and 0x0F shl 3)
val payload = RtpConstants.payloadType + RtpConstants.trackAudio
return "m=audio 0 RTP/AVP ${payload}\r\n" +
"a=rtpmap:$payload MPEG4-GENERIC/$sampleRate/$channel\r\n" +
"a=fmtp:$payload profile-level-id=1; mode=AAC-hbr; config=${Integer.toHexString(config)}; sizelength=13; indexlength=3; indexdeltalength=3\r\n" +
"a=control:streamid=$trackAudio\r\n"
}
fun createH264Body(trackVideo: Int, sps: String, pps: String): String {
val payload = RtpConstants.payloadType + RtpConstants.trackVideo
return "m=video 0 RTP/AVP $payload\r\n" +
"a=rtpmap:$payload H264/${RtpConstants.clockVideoFrequency}\r\n" +
"a=fmtp:$payload packetization-mode=1; sprop-parameter-sets=$sps,$pps\r\n" +
"a=control:streamid=$trackVideo\r\n"
}
fun createH265Body(trackVideo: Int, sps: String, pps: String, vps: String): String {
val payload = RtpConstants.payloadType + RtpConstants.trackVideo
return "m=video 0 RTP/AVP ${payload}\r\n" +
"a=rtpmap:$payload H265/${RtpConstants.clockVideoFrequency}\r\n" +
"a=fmtp:$payload packetization-mode=1; sprop-sps=$sps; sprop-pps=$pps; sprop-vps=$vps\r\n" +
"a=control:streamid=$trackVideo\r\n"
}
} | apache-2.0 | a9a914695923ac8249a6fbd8f1b7932b | 35.957746 | 153 | 0.658025 | 3.175545 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypeCreation.kt | 1 | 2161 | package net.nemerosa.ontrack.graphql.schema
import graphql.Scalars
import graphql.schema.DataFetcher
import graphql.schema.GraphQLObjectType
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.model.structure.Signature
import org.springframework.stereotype.Component
@Component
class GQLTypeCreation : GQLType {
override fun getTypeName() = SIGNATURE
override fun createType(cache: GQLTypeCache): GraphQLObjectType =
GraphQLObjectType.newObject()
.name(SIGNATURE)
.field {
it.name("user")
.description("User name")
.type(Scalars.GraphQLString)
}
.field {
it.name("time")
.description("ISO timestamp")
.type(Scalars.GraphQLString)
}
.build()
companion object {
const val SIGNATURE = "Signature"
@JvmStatic
fun getCreationFromSignature(signature: Signature?): Creation {
var result = Creation()
if (signature != null) {
val user = signature.user
result = result.withUser(user.name)
result = result.withTime(Time.store(signature.time))
}
return result
}
@JvmStatic
inline fun <reified T> dataFetcher(noinline signatureGetter: (T) -> Signature?) =
DataFetcher { environment ->
val source: Any = environment.getSource()
if (source is T) {
signatureGetter(source)?.let { getCreationFromSignature(it) }
} else {
throw IllegalStateException("Fetcher source not an ${T::class.qualifiedName}")
}
}
}
data class Creation(
val user: String? = null,
val time: String? = null
) {
fun withUser(v: String) = Creation(v, time)
fun withTime(v: String) = Creation(user, v)
}
} | mit | ad8065a4c78cb31a45ae5105a97443ce | 33.31746 | 102 | 0.525683 | 5.526854 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | app/src/main/java/home/smart/fly/animations/ui/activity/ViewStubActivity.kt | 1 | 968 | package home.smart.fly.animations.ui.activity
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
import home.smart.fly.animations.R
import home.smart.fly.animations.utils.StatusBarUtil
import kotlinx.android.synthetic.main.activity_view_stub.*
const val tag = "viewstub"
class ViewStubActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_stub)
StatusBarUtil.setColor(this, resources.getColor(R.color.colorPrimary), 0)
Log.e(tag,"clickable=="+load.isClickable)
load.setOnClickListener {
var viewStub = stub.inflate()
Toast.makeText(this, "ViewStub.inflate() consume only once !",Toast.LENGTH_SHORT).show()
load.isEnabled = false
}
Log.e(tag, "now clickable==" + load.isClickable)
}
}
| apache-2.0 | f74b914f4badcb525c5d0a1a53995890 | 33.571429 | 100 | 0.716942 | 4.136752 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/server/command/GetIPropsCmd.kt | 1 | 2755 | /*
* 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.server.command
import org.tmatesoft.svn.core.SVNErrorCode
import org.tmatesoft.svn.core.SVNErrorMessage
import org.tmatesoft.svn.core.SVNException
import svnserver.parser.SvnServerWriter
import svnserver.repository.git.GitBranch
import svnserver.repository.git.GitFile
import svnserver.repository.git.GitRevision
import svnserver.server.SessionContext
import java.io.IOException
import java.util.*
/**
* Get file content.
*
* <pre>
* get-iprops
* params: ( path:string [ rev:number ] )
* response: ( inherited-props:iproplist )
* New in svn 1.8. If rev is not specified, the youngest revision is used.
</pre> *
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class GetIPropsCmd : BaseCmd<GetIPropsCmd.Params>() {
override val arguments: Class<out Params>
get() {
return Params::class.java
}
@Throws(IOException::class, SVNException::class)
override fun processCommand(context: SessionContext, args: Params) {
val writer: SvnServerWriter = context.writer
val fullPath: String = context.getRepositoryPath(args.path)
val branch: GitBranch = context.branch
val info: GitRevision = branch.getRevisionInfo(getRevisionOrLatest(args.rev, context))
val files = ArrayList<GitFile>()
var index = -1
while (true) {
index = fullPath.indexOf('/', index + 1)
if (index < 0) {
break
}
val subPath = fullPath.substring(0, index)
val fileInfo = info.getFile(subPath) ?: throw SVNException(SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, subPath))
files.add(fileInfo)
}
writer
.listBegin()
.word("success")
.listBegin()
.listBegin()
for (file: GitFile in files) {
writer
.listBegin()
.string(file.fullPath)
.writeMap(file.properties)
.listEnd()
}
writer
.listEnd()
.listEnd()
.listEnd()
}
@Throws(IOException::class, SVNException::class)
override fun permissionCheck(context: SessionContext, args: Params) {
context.checkRead(context.getRepositoryPath(args.path))
}
class Params constructor(val path: String, val rev: IntArray)
}
| gpl-2.0 | adfca6cf5d94ca338e4abeabb152fb8d | 33.4375 | 133 | 0.647187 | 4.180577 | false | false | false | false |
jitsi/jicofo | jicofo-selector/src/main/kotlin/org/jitsi/jicofo/bridge/Bridge.kt | 1 | 11467 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2015-Present 8x8, 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 org.jitsi.jicofo.bridge
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.LoggerImpl
import org.jitsi.utils.stats.RateTracker
import org.jitsi.xmpp.extensions.colibri.ColibriStatsExtension
import org.jxmpp.jid.Jid
import java.time.Clock
import java.time.Duration
import java.time.Instant
/**
* Represents a jitsi-videobridge instance, reachable at a certain JID, which
* can be used by jicofo for hosting conferences. Contains the state related
* to the jitsi-videobridge instance, such as numbers of channels and streams,
* the region in which the instance resides, etc.
*
* TODO fix comparator (should not be reflexive unless the objects are the same?)
* @author Pawel Domas
* @author Boris Grozev
*/
@SuppressFBWarnings("EQ_COMPARETO_USE_OBJECT_EQUALS")
class Bridge @JvmOverloads internal constructor(
/**
* The XMPP address of the bridge.
*/
val jid: Jid,
private val clock: Clock = Clock.systemUTC()
) : Comparable<Bridge> {
/**
* Keep track of the recently added endpoints.
*/
private val newEndpointsRate = RateTracker(
BridgeConfig.config.participantRampupInterval(),
Duration.ofMillis(100),
clock
)
/**
* The last report stress level
*/
var lastReportedStressLevel = 0.0
private set
/**
* Holds bridge version (if known - not all bridge version are capable of
* reporting it).
*/
private var version: String? = null
/**
* Whether the last received presence indicated the bridge is healthy.
*/
var isHealthy = true
private set
/**
* Holds bridge release ID, or null if not known.
*/
private var releaseId: String? = null
/**
* Stores the `operational` status of the bridge, which is
* `true` if the bridge has been successfully used by the focus to
* allocate channels. It is reset to `false` when the focus fails
* to allocate channels, but it gets another chance when all currently
* working bridges go down and might eventually get elevated back to
* `true`.
*/
@Volatile
var isOperational = true
get() =
// To filter out intermittent failures, do not return operational
// until past the reset threshold since the last failure.
if (failureInstant != null &&
Duration.between(failureInstant, clock.instant()).compareTo(failureResetThreshold) < 0
) {
false
} else field
set(isOperational) {
field = isOperational
if (!isOperational) {
// Remember when the bridge has last failed
failureInstant = clock.instant()
}
}
/**
* Start out with the configured value, update if the bridge reports a value.
*/
private var averageParticipantStress = BridgeConfig.config.averageParticipantStress()
/**
* Stores a boolean that indicates whether the bridge is in graceful shutdown mode.
*/
var isInGracefulShutdown = false /* we assume it is not shutting down */
/**
* Whether the bridge is in SHUTTING_DOWN mode.
*/
var isShuttingDown = false
private set
/**
* @return true if the bridge is currently in drain mode
*/
/**
* Stores a boolean that indicates whether the bridge is in drain mode.
*/
var isDraining = true /* Default to true to prevent unwanted selection before reading actual state */
private set
/**
* The time when this instance has failed.
*
* Use `null` to represent "never" because calculating the duration from [Instant.MIN] is slow.
*/
private var failureInstant: Instant? = null
/**
* @return the region of this [Bridge].
*/
var region: String? = null
private set
/**
* @return the relay ID advertised by the bridge, or `null` if
* none was advertised.
*/
var relayId: String? = null
private set
private val logger: Logger = LoggerImpl(Bridge::class.java.name)
init {
logger.addContext("jid", jid.toString())
}
private var lastPresenceReceived = Instant.MIN
val timeSinceLastPresence: Duration
get() = Duration.between(lastPresenceReceived, clock.instant())
/**
* Notifies this instance that a new [ColibriStatsExtension] was
* received for this instance.
* @param stats the [ColibriStatsExtension] instance which was
* received.
*/
fun setStats(stats: ColibriStatsExtension?) {
if (stats == null) {
return
}
lastPresenceReceived = clock.instant()
val stressLevel = stats.getDouble("stress_level")
if (stressLevel != null) {
lastReportedStressLevel = stressLevel
}
val averageParticipantStress = stats.getDouble("average_participant_stress")
if (averageParticipantStress != null) {
this.averageParticipantStress = averageParticipantStress
}
if (java.lang.Boolean.parseBoolean(
stats.getValueAsString(
ColibriStatsExtension.SHUTDOWN_IN_PROGRESS
)
)
) {
isInGracefulShutdown = true
}
if (java.lang.Boolean.parseBoolean(stats.getValueAsString("shutting_down"))) {
isShuttingDown = true
}
val drainStr = stats.getValueAsString(ColibriStatsExtension.DRAIN)
if (drainStr != null) {
isDraining = java.lang.Boolean.parseBoolean(drainStr)
}
val newVersion = stats.getValueAsString(ColibriStatsExtension.VERSION)
if (newVersion != null) {
version = newVersion
}
val newReleaseId = stats.getValueAsString(ColibriStatsExtension.RELEASE)
if (newReleaseId != null) {
releaseId = newReleaseId
}
val region = stats.getValueAsString(ColibriStatsExtension.REGION)
if (region != null) {
this.region = region
}
val relayId = stats.getValueAsString(ColibriStatsExtension.RELAY_ID)
if (relayId != null) {
this.relayId = relayId
}
val healthy = stats.getValueAsString("healthy")
if (healthy != null) {
isHealthy = java.lang.Boolean.parseBoolean(healthy)
} else if (BridgeConfig.config.usePresenceForHealth) {
logger.warn(
"Presence-based health checks are enabled, but presence did not include health status. Health " +
"checks for this bridge are effectively disabled."
)
}
}
/**
* Returns a negative number if this instance is more able to serve conferences than o. For details see
* [.compare].
*
* @param other the other bridge instance
*
* @return a negative number if this instance is more able to serve conferences than o
*/
override fun compareTo(other: Bridge): Int {
return compare(this, other)
}
/**
* Notifies this [Bridge] that it was used for a new endpoint.
*/
fun endpointAdded() {
newEndpointsRate.update(1)
}
/**
* Returns the net number of video channels recently allocated or removed
* from this bridge.
*/
private val recentlyAddedEndpointCount: Long
get() = newEndpointsRate.getAccumulatedCount()
/**
* The version of this bridge (with embedded release ID, if available).
*/
val fullVersion: String?
get() = if (version != null && releaseId != null) "$version-$releaseId" else version
/**
* {@inheritDoc}
*/
override fun toString(): String {
return String.format(
"Bridge[jid=%s, version=%s, relayId=%s, region=%s, stress=%.2f]",
jid.toString(),
fullVersion,
relayId,
region,
stress
)
}
/**
* Gets the "stress" of the bridge, represented as a double between 0 and 1 (though technically the value
* can exceed 1).
* @return this bridge's stress level
*/
val stress: Double
get() =
// While a stress of 1 indicates a bridge is fully loaded, we allow
// larger values to keep sorting correctly.
lastReportedStressLevel +
recentlyAddedEndpointCount.coerceAtLeast(0) * averageParticipantStress
/**
* @return true if the stress of the bridge is greater-than-or-equal to the threshold.
*/
val isOverloaded: Boolean
get() = stress >= BridgeConfig.config.stressThreshold()
val debugState: OrderedJsonObject
get() {
val o = OrderedJsonObject()
o["version"] = version.toString()
o["release"] = releaseId.toString()
o["stress"] = stress
o["operational"] = isOperational
o["region"] = region.toString()
o["drain"] = isDraining
o["graceful-shutdown"] = isInGracefulShutdown
o["shutting-down"] = isShuttingDown
o["overloaded"] = isOverloaded
o["relay-id"] = relayId.toString()
o["healthy"] = isHealthy
return o
}
companion object {
/**
* How long the "failed" state should be sticky for. Once a [Bridge] goes in a non-operational state (via
* [.setIsOperational]) it will be considered non-operational for at least this amount of time.
* See the tests for example behavior.
*/
private val failureResetThreshold = BridgeConfig.config.failureResetThreshold()
/**
* Returns a negative number if b1 is more able to serve conferences than b2. The computation is based on the
* following three comparisons
*
* operating bridges < non operating bridges
* not in graceful shutdown mode < bridges in graceful shutdown mode
* lower stress < higher stress
*
* @param b1 the 1st bridge instance
* @param b2 the 2nd bridge instance
*
* @return a negative number if b1 is more able to serve conferences than b2
*/
fun compare(b1: Bridge, b2: Bridge): Int {
val myPriority = getPriority(b1)
val otherPriority = getPriority(b2)
return if (myPriority != otherPriority) {
myPriority - otherPriority
} else b1.stress.compareTo(b2.stress)
}
private fun getPriority(b: Bridge): Int {
return if (b.isOperational) { if (b.isInGracefulShutdown) 2 else 1 } else 3
}
}
}
| apache-2.0 | fc0bb4a4eeba64e19a06fa25eadec58c | 32.825959 | 117 | 0.621697 | 4.610776 | false | false | false | false |
lare96/luna | plugins/world/player/skill/fletching/cutLog/Log.kt | 1 | 1116 | package world.player.skill.fletching.cutLog
import world.player.skill.fletching.stringBow.Bow
import world.player.skill.fletching.stringBow.Bow.*
/**
* An enum representing an item that can be cut into a [Bow].
*/
enum class Log(val id: Int, val bows: List<Bow>) {
NORMAL(id = 1511,
bows = listOf(ARROW_SHAFT, SHORTBOW, LONGBOW)),
OAK(id = 1521,
bows = listOf(OAK_SHORTBOW, OAK_LONGBOW)),
WILLOW(id = 1519,
bows = listOf(WILLOW_SHORTBOW, WILLOW_LONGBOW)),
MAPLE(id = 1517,
bows = listOf(MAPLE_SHORTBOW, MAPLE_LONGBOW)),
YEW(id = 1515,
bows = listOf(YEW_SHORTBOW, YEW_LONGBOW)),
MAGIC(id = 1513,
bows = listOf(MAGIC_SHORTBOW, MAGIC_LONGBOW));
companion object {
/**
* The knife identifier.
*/
const val KNIFE = 946
/**
* Mappings of [Log.id] to [Log] instances.
*/
val ID_TO_LOG = values().associateBy { it.id }
}
/**
* An array of unstrung identifiers made from this log.
*/
val unstrungIds = bows.map { it.unstrung }.toIntArray()
} | mit | 23d8c60b25cc9710a169c8d8c5282992 | 26.925 | 61 | 0.594086 | 3.272727 | false | false | false | false |
SirWellington/alchemy-generator | src/main/java/tech/sirwellington/alchemy/generator/NetworkGenerators.kt | 1 | 4059 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.generator
import org.slf4j.LoggerFactory
import tech.sirwellington.alchemy.annotations.access.NonInstantiable
import tech.sirwellington.alchemy.annotations.arguments.NonEmpty
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.PeopleGenerators.Companion.popularEmailDomains
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphanumericStrings
import java.net.MalformedURLException
import java.net.URL
import java.util.Arrays
/**
* @author SirWellington
*/
@NonInstantiable
class NetworkGenerators
@Throws(IllegalAccessException::class)
private constructor()
{
init
{
throw IllegalAccessException("cannot instantiate")
}
companion object
{
private val LOG = LoggerFactory.getLogger(NetworkGenerators::class.java)
private val FALLBACK_URL: URL
init
{
try
{
FALLBACK_URL = URL("http://google.com")
}
catch (ex: MalformedURLException)
{
throw RuntimeException("Could not generate URL", ex)
}
}
private val VALID_PROTOCOLS = Arrays.asList("http", "https", "ftp", "file", "ssh")
/**
* @return URLs beginning with `http://`
*/
@JvmStatic
fun httpUrls(): AlchemyGenerator<URL>
{
return urlsWithProtocol("http")
}
/**
*
* @return URLs beginning with `https://`
*/
@JvmStatic
fun httpsUrls(): AlchemyGenerator<URL>
{
return urlsWithProtocol("https")
}
/**
*
* @param protocol The protocol to use for the URLs created. Do not include the "://".
*
* @return URLs beginning with the `protocol`
*/
@JvmStatic
fun urlsWithProtocol(@NonEmpty protocol: String): AlchemyGenerator<URL>
{
checkNotEmpty(protocol, "missing protocol")
val cleanProtocol = protocol.replace("://", "")
try
{
URL(cleanProtocol + "://")
}
catch (ex: MalformedURLException)
{
throw IllegalArgumentException("Unknown protocol: " + protocol, ex)
}
return AlchemyGenerator {
val url = "$cleanProtocol://${alphanumericStrings().get()}.${popularEmailDomains().get()}"
try
{
URL(url)
}
catch (ex: MalformedURLException)
{
LOG.error("Failed to create url from scheme {}", cleanProtocol, ex)
FALLBACK_URL
}
}
}
/**
* @return Ports from 22 to [32767][Short.MAX_VALUE].
*/
@JvmStatic
fun ports(): AlchemyGenerator<Int>
{
return integers(22, Short.MAX_VALUE.toInt())
}
/**
* Generates IPV4 addresses in the form `xxx.xx.xxx.xx`.
* @return An IPV4 address
*/
@JvmStatic
fun ip4Addresses(): AlchemyGenerator<String>
{
val integers = integers(1, 1000)
return AlchemyGenerator { "${integers.get()}.${integers.get()}.${integers.get()}.${integers.get()}" }
}
}
}
| apache-2.0 | 8ad53bd3d32042dd9e0ddef19bb882a2 | 27.377622 | 113 | 0.580582 | 4.93674 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.