repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Firenox89/Shinobooru | app/src/main/java/com/github/firenox89/shinobooru/repo/LocalPostLoader.kt | 1 | 2935 | package com.github.firenox89.shinobooru.repo
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import android.view.WindowManager
import com.github.firenox89.shinobooru.repo.model.DownloadedPost
import com.github.firenox89.shinobooru.repo.model.Post
import com.github.firenox89.shinobooru.repo.model.Tag
import com.github.firenox89.shinobooru.utility.Constants
import com.github.firenox89.shinobooru.utility.UI.loadSubsampledImage
import com.github.kittinunf.result.Result
import kotlinx.coroutines.channels.Channel
import timber.log.Timber
/**
* Sub-classes the [PostLoader] to use the downloaded post images as a source for posts.
* Does not refresh the post list when new images are downloaded.
*/
class LocalPostLoader(private val appContext: Context, private val fileManager: FileManager) : PostLoader {
override val board: String
get() = Constants.FILE_LOADER_NAME
override val tags: String
get() = ""
private val changeChannel = Channel<Pair<Int, Int>>()
private val newestDownloadedPostComparator = Comparator<DownloadedPost> { post1, post2 ->
val date1 = post1.file.lastModified()
val date2 = post2.file.lastModified()
var result = 0
if (date1 < date2)
result = 1
if (date1 > date2)
result = -1
result
}
private var posts = fileManager.getAllDownloadedPosts().sortedWith(newestDownloadedPostComparator)
override suspend fun loadPreview(post: Post): Result<Bitmap, Exception> =
loadSubsampledImage((post as DownloadedPost).file, 250, 400)
override suspend fun loadSample(post: Post): Result<Bitmap, Exception> {
val wm = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = Point()
display.getSize(size)
//sample huge images=
return loadSubsampledImage((post as DownloadedPost).file, size.x, size.y)
}
override suspend fun getRangeChangeEventStream(): Channel<Pair<Int, Int>> =
changeChannel.apply{ offer(Pair(0, posts.size))}
/**
* Return a post from the postlist for the given number
*/
override fun getPostAt(index: Int): DownloadedPost {
return posts[index]
}
/** Does nothing */
override suspend fun requestNextPosts() {
//nothing to request in file mode
}
/**
* Returns the size of the postlist.
*/
override fun getCount(): Int {
return posts.size
}
/**
* Return the index for a post in the postlist.
*/
override fun getIndexOf(post: Post): Int {
return posts.indexOf(post)
}
override suspend fun onRefresh() {
Timber.d("onRefresh")
posts = fileManager.getAllDownloadedPosts(true).sortedWith(newestDownloadedPostComparator)
changeChannel.offer(Pair(0, posts.size))
}
} | mit | 3ab2d7f0f1a9ba69aadae9b0b09c2d55 | 33.541176 | 107 | 0.694378 | 4.297218 | false | false | false | false |
cleverchap/AutoAnylysis | src/com/cc/patten/PattenManager.kt | 1 | 1080 | package com.cc.patten
/**
* Created by clevercong on 2017/10/15.
* 用于正则表达式匹配的字符串,从这里获取。
*/
fun getLogTagPattenString() : String = "startElement|endElement"
// 当前调试先用这个也OK,但是下面的更严谨一些,且符合新版本Log文件名格式。
fun getFileNamePattenString() : String = "rillogcat-log.[0-9]{1}"
fun getFileNamePattenStringV2() : String = "rillogcat-log.[0-9]{8}-[0-9]{6}"
const val VERSION_INCLUDE_DATE = 2
const val VERSION_NOT_INCLUDE_DATE = 1
const val VERSION_UNKNOWN = 0
/**
* fileName: Log文件名
* return 2: version 2 含有日期(新版)
* return 1: version 1 不含有日期
* return 0: version unknown 暂时没有用
*/
fun getFileNameVersion(fileName: String) : Int {
val pattenV1 = getFileNamePattenString().toRegex()
val pattenV2 = getFileNamePattenStringV2().toRegex()
return when {
pattenV2.containsMatchIn(fileName) -> VERSION_INCLUDE_DATE
pattenV1.containsMatchIn(fileName) -> VERSION_NOT_INCLUDE_DATE
else -> VERSION_UNKNOWN
}
} | apache-2.0 | 7772b3ad951dc81f92d61db0e07777d0 | 29.096774 | 76 | 0.711373 | 3.045752 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/completion/FeatureManagerImpl.kt | 2 | 2240 | /*
* 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
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ApplicationComponent
import com.jetbrains.completion.feature.*
import com.jetbrains.completion.feature.impl.CompletionFactors
import com.jetbrains.completion.feature.impl.FeatureInterpreterImpl
import com.jetbrains.completion.feature.impl.FeatureManagerFactory
import com.jetbrains.completion.feature.impl.FeatureReader
/**
* @author Vitaliy.Bibaev
*/
class FeatureManagerImpl : FeatureManager, ApplicationComponent {
companion object {
fun getInstance(): FeatureManager = ApplicationManager.getApplication().getComponent(FeatureManager::class.java)
}
private lateinit var manager: FeatureManager
override val binaryFactors: List<BinaryFeature> get() = manager.binaryFactors
override val doubleFactors: List<DoubleFeature> get() = manager.doubleFactors
override val categoricalFactors: List<CategoricalFeature> get() = manager.categoricalFactors
override val ignoredFactors: Set<String> get() = manager.ignoredFactors
override val completionFactors: CompletionFactors get() = manager.completionFactors
override val featureOrder: Map<String, Int> get() = manager.featureOrder
override fun createTransformer(): Transformer {
return manager.createTransformer()
}
override fun isUserFeature(name: String): Boolean = false
override fun initComponent() {
manager = FeatureManagerFactory().createFeatureManager(FeatureReader, FeatureInterpreterImpl())
}
override fun allFeatures(): List<Feature> = manager.allFeatures()
} | apache-2.0 | 85ae3b6a0720ef6bf9aa6489fe18ef88 | 39.745455 | 120 | 0.775 | 4.696017 | false | false | false | false |
eyneill777/SpacePirates | core/src/rustyengine/GeneralSettings.kt | 1 | 1680 | package rustyengine;
import com.badlogic.gdx.Preferences;
object GeneralSettings {
private const val APPID = "rustyice"
var preferences: Preferences? = null
set(value) {
field = value
if(value != null) {
width = value.getInteger("${APPID}.width", width)
height = value.getInteger("${APPID}.height", height)
fullscreen = value.getBoolean("${APPID}.fullscreen", fullscreen)
soundVolume = value.getFloat("${APPID}.soundVolume", soundVolume)
musicVolume = value.getFloat("${APPID}.musicVolume", musicVolume)
vsync = value.getBoolean("${APPID}.vsync", vsync)
}
}
var width: Int = 800
set(value) {
field = value
preferences?.putInteger("${APPID}.width", value)
}
var height: Int = 640
set(value) {
field = value
preferences?.putInteger("${APPID}.width", value)
}
var soundVolume: Float = 1f
set(value) {
field = value
preferences?.putFloat("${APPID}.soundVolume", value)
}
var musicVolume: Float = 1f
set(value) {
field = value
preferences?.putFloat("${APPID}.musicVolume", value)
}
var vsync: Boolean = true
set(value) {
field = value
preferences?.putBoolean("${APPID}.vsync", value)
}
var fullscreen: Boolean = false
set(value) {
field = value
preferences?.putBoolean("${APPID}.fullscreen", value)
}
fun save(){
preferences?.flush()
}
}
| mit | 10f7bb8c4be446179bff261aec754d60 | 26.540984 | 81 | 0.530357 | 4.628099 | false | false | false | false |
ktorio/ktor | ktor-network/nix/src/io/ktor/network/selector/WorkerSelectorManager.kt | 1 | 1293 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.selector
import kotlinx.coroutines.*
import kotlinx.coroutines.CancellationException
import kotlin.coroutines.*
@OptIn(ExperimentalCoroutinesApi::class)
internal class WorkerSelectorManager : SelectorManager {
private val selectorContext = newSingleThreadContext("WorkerSelectorManager")
private val job = Job()
override val coroutineContext: CoroutineContext = selectorContext + job
private val selector = SelectorHelper()
init {
selector.start(this)
}
override fun notifyClosed(selectable: Selectable) {
selector.notifyClosed(selectable.descriptor)
}
override suspend fun select(
selectable: Selectable,
interest: SelectInterest
) {
return suspendCancellableCoroutine { continuation ->
val selectorState = EventInfo(selectable.descriptor, interest, continuation)
if (!selector.interest(selectorState)) {
continuation.resumeWithException(CancellationException("Selector closed."))
}
}
}
override fun close() {
selector.requestTermination()
selectorContext.close()
}
}
| apache-2.0 | 2aff9bbbd5cb3db8899941d29c97907f | 29.785714 | 118 | 0.70379 | 5.277551 | false | false | false | false |
Mini-Stren/MultiThemer | multithemer/src/main/java/com/ministren/multithemer/MultiThemeActivity.kt | 1 | 2259 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.ministren.multithemer
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
/**
* * Activity use {@link MultiThemer} to automatically
* apply app's active theme and restart itself after theme change
* <p>
*
* Created by Mini-Stren on 28.08.2017.
*/
open class MultiThemeActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var mThemeTag: String
override fun onCreate(savedInstanceState: Bundle?) {
MultiThemer.applyThemeTo(this)
mThemeTag = MultiThemer.getSavedThemeTag()
super.onCreate(savedInstanceState)
}
override fun onPause() {
super.onPause()
MultiThemer.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this)
}
override fun onResume() {
super.onResume()
MultiThemer.getSharedPreferences().registerOnSharedPreferenceChangeListener(this)
val tag = MultiThemer.getSavedThemeTag()
if (mThemeTag != tag) restartActivity()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == MultiThemer.PREFERENCE_KEY) restartActivity()
}
private fun restartActivity() {
if (BuildConfig.DEBUG) {
Log.d(MultiThemer.LOG_TAG, "restarting activity '$this'")
}
recreate()
}
}
| apache-2.0 | 29053daf7f17b87370463bcc135d4083 | 32.716418 | 105 | 0.723772 | 4.648148 | false | false | false | false |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/BaseApplication.kt | 1 | 2604 | package com.example.demoaerisproject
import android.app.Application
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import com.aerisweather.aeris.communication.AerisEngine
import com.aerisweather.aeris.logging.Logger
import com.aerisweather.aeris.maps.AerisMapsEngine
import com.example.demoaerisproject.data.preferenceStore.PrefStoreRepository
import com.example.demoaerisproject.service.NotificationJobService
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
@HiltAndroidApp
class BaseApplication : Application() {
@Inject
lateinit var prefStore: PrefStoreRepository
override fun onCreate() {
super.onCreate()
// setting up secret key and client id for oauth to aeris
AerisEngine.initWithKeys(
this.getString(R.string.aerisapi_client_id),
this.getString(R.string.aerisapi_client_secret),
this
)
enableNotificationService(baseContext)
/*
* can override default point parameters programmatically used on the
* map. dt:-1 -> sorts to closest time| -4hours -> 4 hours ago. Limit is
* a required parameter.Can also be done through the xml values in the
* aeris_default_values.xml
*/
AerisMapsEngine.getInstance(this).defaultPointParameters
.setLightningParameters("dt:-1", 500, null, null)
}
companion object {
private const val NOTIFICATION_JOB_ID = 2001
const val PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001
private const val ONE_MIN = 60 * 1000
private val TAG = BaseApplication::class.java.simpleName
fun enableNotificationService(context: Context) {
Logger.d(TAG, "enableNotificationService() - using JobScheduler")
val notificationComponent = ComponentName(
context,
NotificationJobService::class.java
)
val notificationBuilder = JobInfo.Builder(
NOTIFICATION_JOB_ID,
notificationComponent
) // schedule it to run any time between 15-20 minutes
.setMinimumLatency((ONE_MIN * 1).toLong())
.setOverrideDeadline((ONE_MIN * 2).toLong())
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
val notificationJobScheduler =
context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
notificationJobScheduler.schedule(notificationBuilder.build())
}
}
} | mit | 7817524668aead04afac5fe1e53a947f | 36.214286 | 79 | 0.685868 | 4.96 | false | false | false | false |
Thelonedevil/TLDMaths | TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/Prime.kt | 1 | 602 | package uk.tldcode.math.tldmaths
import sequence.buildSequence
import java.math.BigInteger
object Prime : BigIntegerSequence {
override fun invoke(): Sequence<BigInteger> = buildSequence {
yield(BigInteger("2"))
for (a in OddNaturals().filter { it.isProbablePrime(10) }.filter { firstFactor(it, Prime()) == null }) {
yield(a)
}
}
private fun firstFactor(num: BigInteger, search: Sequence<BigInteger>): BigInteger? {
return search
.takeWhile { i -> i * i <= num }
.find { num % it == BigInteger.ZERO }
}
} | apache-2.0 | fcc81f5438e8e2dd5af002d1b6c2dafc | 26.409091 | 112 | 0.607973 | 4.20979 | false | false | false | false |
dahlstrom-g/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryBridgeImpl.kt | 5 | 7985 | // 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.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.RootProvider.RootSetChangedListener
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.impl.libraries.LibraryImpl
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.TraceableDisposable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryRootTypeId
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
interface LibraryBridge : LibraryEx {
val libraryId: LibraryId
@ApiStatus.Internal
fun getModifiableModel(builder: MutableEntityStorage): LibraryEx.ModifiableModelEx
}
@ApiStatus.Internal
class LibraryBridgeImpl(
var libraryTable: LibraryTable,
val project: Project,
initialId: LibraryId,
initialEntityStorage: VersionedEntityStorage,
private var targetBuilder: MutableEntityStorage?
) : LibraryBridge, RootProvider, TraceableDisposable(true) {
override fun getModule(): Module? = (libraryTable as? ModuleLibraryTableBridge)?.module
var entityStorage: VersionedEntityStorage = initialEntityStorage
set(value) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
field = value
}
var entityId: LibraryId = initialId
private var disposed = false
internal fun cleanCachedValue() {
entityStorage.clearCachedValue(librarySnapshotCached)
}
private val dispatcher = EventDispatcher.create(RootSetChangedListener::class.java)
private val librarySnapshotCached = CachedValue { storage ->
LibraryStateSnapshot(
libraryEntity = storage.findLibraryEntity(this) ?: error("Cannot find entity for library with ID $entityId"),
storage = storage,
libraryTable = libraryTable,
parentDisposable = this
)
}
val librarySnapshot: LibraryStateSnapshot
get() {
checkDisposed()
return entityStorage.cachedValue(librarySnapshotCached)
}
override val libraryId: LibraryId
get() = entityId
override fun getTable(): LibraryTable? = if (libraryTable is ModuleLibraryTableBridge) null else libraryTable
override fun getRootProvider(): RootProvider = this
override fun getPresentableName(): String = LibraryImpl.getPresentableName(this)
override fun toString(): String {
return "Library '$name', roots: ${librarySnapshot.libraryEntity.roots}"
}
override fun getModifiableModel(): LibraryEx.ModifiableModelEx {
return getModifiableModel(MutableEntityStorage.from(librarySnapshot.storage))
}
override fun getModifiableModel(builder: MutableEntityStorage): LibraryEx.ModifiableModelEx {
return LibraryModifiableModelBridgeImpl(this, librarySnapshot, builder, targetBuilder, false)
}
override fun getSource(): Library? = null
override fun getExternalSource(): ProjectModelExternalSource? = librarySnapshot.externalSource
override fun getInvalidRootUrls(type: OrderRootType): List<String> = librarySnapshot.getInvalidRootUrls(type)
override fun getKind(): PersistentLibraryKind<*>? = librarySnapshot.kind
override fun getName(): String? = LibraryNameGenerator.getLegacyLibraryName(entityId)
override fun getUrls(rootType: OrderRootType): Array<String> = librarySnapshot.getUrls(rootType)
override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = librarySnapshot.getFiles(rootType)
override fun getProperties(): LibraryProperties<*>? = librarySnapshot.properties
override fun getExcludedRoots(): Array<VirtualFile> = librarySnapshot.excludedRoots
override fun getExcludedRootUrls(): Array<String> = librarySnapshot.excludedRootUrls
override fun isJarDirectory(url: String): Boolean = librarySnapshot.isJarDirectory(url)
override fun isJarDirectory(url: String, rootType: OrderRootType): Boolean = librarySnapshot.isJarDirectory(url, rootType)
override fun isValid(url: String, rootType: OrderRootType): Boolean = librarySnapshot.isValid(url, rootType)
override fun hasSameContent(library: Library): Boolean {
if (this === library) return true
if (library !is LibraryBridgeImpl) return false
if (name != library.name) return false
if (kind != library.kind) return false
if (properties != library.properties) return false
if (librarySnapshot.libraryEntity.roots != library.librarySnapshot.libraryEntity.roots) return false
if (!excludedRoots.contentEquals(library.excludedRoots)) return false
return true
}
override fun readExternal(element: Element?) = throw NotImplementedError()
override fun writeExternal(element: Element) = throw NotImplementedError()
override fun addRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.addListener(listener)
override fun addRootSetChangedListener(listener: RootSetChangedListener, parentDisposable: Disposable) {
dispatcher.addListener(listener, parentDisposable)
}
override fun removeRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.removeListener(listener)
override fun isDisposed(): Boolean = disposed
override fun dispose() {
checkDisposed()
disposed = true
kill(null)
}
private fun checkDisposed() {
if (isDisposed) {
val libraryEntity = try {
entityStorage.cachedValue(librarySnapshotCached).libraryEntity
}
catch (t: Throwable) {
null
}
val isDisposedGlobally = libraryEntity?.let {
WorkspaceModel.getInstance(project).entityStorage.current.libraryMap.getDataByEntity(it)?.isDisposed
}
val message = """
Library $entityId already disposed:
Library id: $libraryId
Entity: ${libraryEntity.run { "$name, $this" }}
Is disposed in project model: ${isDisposedGlobally != false}
Stack trace: $stackTrace
""".trimIndent()
try {
throwDisposalError(message)
}
catch (e: Exception) {
thisLogger().error(message, e)
throw e
}
}
}
internal fun fireRootSetChanged() {
dispatcher.multicaster.rootSetChanged(this)
}
fun clearTargetBuilder() {
targetBuilder = null
}
companion object {
private val libraryRootTypes = ConcurrentFactoryMap.createMap<String, LibraryRootTypeId> { LibraryRootTypeId(it) }
internal fun OrderRootType.toLibraryRootType(): LibraryRootTypeId = when (this) {
OrderRootType.CLASSES -> LibraryRootTypeId.COMPILED
OrderRootType.SOURCES -> LibraryRootTypeId.SOURCES
else -> libraryRootTypes[name()]!!
}
}
}
| apache-2.0 | 231e0c48869da628163a01cda2753c09 | 40.806283 | 140 | 0.782091 | 5.302125 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/stepInto/defaultAccessors.kt | 13 | 659 | // FILE: defaultAccessors.kt
package defaultAccessors
fun main(args: Array<String>) {
//Breakpoint!
A().testPublicPropertyInClass()
testPublicPropertyInLibrary()
}
class A: B() {
fun testPublicPropertyInClass() {
prop
prop = 2
}
}
open class B {
public var prop: Int = 1
}
fun testPublicPropertyInLibrary() {
val myClass = customLib.simpleLibFile.B()
myClass.prop
myClass.prop = 2
}
// STEP_INTO: 21
// SKIP_SYNTHETIC_METHODS: true
// SKIP_CONSTRUCTORS: true
// FILE: customLib/simpleLibFile.kt
package customLib.simpleLibFile
public fun foo() {
1 + 1
}
class B {
public var prop: Int = 1
}
| apache-2.0 | add4feba613afd34aa4165a14893b2dd | 15.475 | 45 | 0.660091 | 3.486772 | false | true | false | false |
TechzoneMC/SonarPet | api/src/test/kotlin/net/techcable/sonarpet/test/assertions.kt | 1 | 2567 | package net.techcable.sonarpet.test
import org.junit.AssumptionViolatedException
import org.junit.ComparisonFailure
import kotlin.AssertionError
import kotlin.reflect.KClass
fun assertThat(condition: Boolean) = assertThat(condition) { "Assertion failed!" }
inline fun assertThat(condition: Boolean, lazyMessage: () -> String) {
if (!condition) {
fail(lazyMessage())
}
}
fun assertMatches(pattern: Regex, value: String) {
assertMatches(pattern, value) { "'$value' doesn't match $pattern" }
}
inline fun assertMatches(pattern: Regex, value: String, lazyMessage: () -> String) {
assertNotNull(pattern.matchEntire(value), lazyMessage = lazyMessage)
}
fun assertEqual(expected: Any?, actual: Any?) {
assertEqual(expected, actual) { "Expected $expected, but got $actual" }
}
inline fun assertEqual(expected: Any?, actual: Any?, lazyMessage: (actual: Any?) -> String) {
if (expected != actual) {
// NOTE: Only invoke lazyMessage once to avoid code bloat
val message = lazyMessage(actual)
if (expected is String && actual is String) {
throw ComparisonFailure(message, expected, actual)
} else {
throw AssertionError(message)
}
}
}
inline fun <reified T> assertNotNull(value: T?): T {
return assertNotNull(value) {
"${T::class.java.typeName} was null!"
}
}
inline fun <T> assertNotNull(value: T?, lazyMessage: () -> String): T {
if (value == null) {
fail(lazyMessage())
} else {
return value
}
}
fun assumeThat(condition: Boolean) {
assumeThat(condition) { "Assumption violated!" }
}
inline fun assumeThat(condition: Boolean, lazyMessage: () -> String) {
if (!condition) throw AssumptionViolatedException(lazyMessage())
}
inline fun assumeNoErrors(vararg errorTypes: KClass<out Throwable>, block: () -> Unit) {
try {
block()
} catch (e: Throwable) {
val matchedType = errorTypes.find { it.java.isInstance(e) }
if (matchedType != null) {
assumptionViolated("${matchedType.java.simpleName}: ${e.message}")
} else {
// Continue to propagate unexpected exception
throw e
}
}
}
inline fun <reified T: Throwable> assumeNoError(block: () -> Unit) {
assumeNoErrors(T::class, block = block)
}
@Suppress("NOTHING_TO_INLINE")
inline fun fail(message: String): Nothing = throw AssertionError(message)
@Suppress("NOTHING_TO_INLINE")
inline fun assumptionViolated(message: String): Nothing = throw AssumptionViolatedException(message)
| gpl-3.0 | 981685767d711133fe92b600e41d59ef | 31.0875 | 100 | 0.667316 | 4.173984 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/actpost/FeaturedTagCache.kt | 1 | 2371 | package jp.juggler.subwaytooter.actpost
import android.os.SystemClock
import jp.juggler.subwaytooter.ActPost
import jp.juggler.subwaytooter.api.ApiTask
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.TootTag
import jp.juggler.subwaytooter.api.runApiTask
import jp.juggler.util.jsonObject
import jp.juggler.util.launchMain
import jp.juggler.util.toPostRequestBuilder
import jp.juggler.util.wrapWeakReference
class FeaturedTagCache(val list: List<TootTag>, val time: Long)
fun ActPost.updateFeaturedTags() {
val account = account
if (account == null || account.isPseudo) {
return
}
val cache = featuredTagCache[account.acct.ascii]
val now = SystemClock.elapsedRealtime()
if (cache != null && now - cache.time <= 300000L) return
// 同時に実行するタスクは1つまで
if (jobFeaturedTag?.get()?.isActive != true) {
jobFeaturedTag = launchMain {
runApiTask(
account,
progressStyle = ApiTask.PROGRESS_NONE,
) { client ->
if (account.isMisskey) {
client.request(
"/api/hashtags/trend",
jsonObject { }
.toPostRequestBuilder()
)?.also { result ->
val list = TootTag.parseList(
TootParser(this@runApiTask, account),
result.jsonArray
)
featuredTagCache[account.acct.ascii] =
FeaturedTagCache(list, SystemClock.elapsedRealtime())
}
} else {
client.request("/api/v1/featured_tags")?.also { result ->
val list = TootTag.parseList(
TootParser(this@runApiTask, account),
result.jsonArray
)
featuredTagCache[account.acct.ascii] =
FeaturedTagCache(list, SystemClock.elapsedRealtime())
}
}
}
if (isFinishing || isDestroyed) return@launchMain
updateFeaturedTags()
}.wrapWeakReference
}
}
| apache-2.0 | 5911310569975bf504b188eb3d80a712 | 36.409836 | 81 | 0.533504 | 4.974522 | false | false | false | false |
JetBrains/workshop-jb | src/i_introduction/_2_Named_Arguments/n02NamedArguments.kt | 2 | 834 | package i_introduction._2_Named_Arguments
import i_introduction._1_Java_To_Kotlin_Converter.task1
import util.TODO
import util.doc2
// default values for arguments
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
// named arguments
bar(1, b = false)
}
fun todoTask2(): Nothing = TODO(
"""
Task 2.
Print out the collection contents surrounded by curly braces using the library function 'joinToString'.
Specify only 'prefix' and 'postfix' arguments.
Don't forget to remove the 'todoTask2()' invocation which throws an exception.
""",
documentation = doc2(),
references = { collection: Collection<Int> -> task1(collection); collection.joinToString() })
fun task2(collection: Collection<Int>): String {
todoTask2()
return collection.joinToString()
} | mit | 17b11dbea22e3001dcfe7e99e532f319 | 27.793103 | 111 | 0.682254 | 4.068293 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/util/weixin/PKCS7Encoder.kt | 1 | 1839 | package top.zbeboy.isy.web.util.weixin
import java.nio.charset.Charset
import java.util.*
/**
* Created by zbeboy 2017-11-20 .
**/
class PKCS7Encoder {
companion object {
@JvmField
val CHARSET = Charset.forName("utf-8")
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
@JvmStatic
fun encode(count: Int): ByteArray {
// 计算需要填充的位数
val BLOCK_SIZE = 32
var amountToPad = BLOCK_SIZE - count % BLOCK_SIZE
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE
}
// 获得补位所用的字符
val padChr = chr(amountToPad)
var tmp = ""
for (index in 0 until amountToPad) {
tmp += padChr
}
return tmp.toByteArray(CHARSET)
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
@JvmStatic
fun decode(decrypted: ByteArray): ByteArray {
var pad = decrypted[decrypted.size - 1].toInt()
if (pad < 1 || pad > 32) {
pad = 0
}
return Arrays.copyOfRange(decrypted, 0, decrypted.size - pad)
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
@JvmStatic
private fun chr(a: Int): Char {
val target = (a and 0xFF).toByte()
return target.toChar()
}
}
} | mit | 7677f13bd7ad1ae9eaba93322e393b81 | 23.584615 | 73 | 0.477771 | 3.731308 | false | false | false | false |
paplorinc/intellij-community | plugins/settings-repository/src/git/commit.kt | 2 | 3216 | // 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.settingsRepository.git
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import org.eclipse.jgit.lib.IndexDiff
import org.eclipse.jgit.lib.ProgressMonitor
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.LOG
import org.jetbrains.settingsRepository.PROJECTS_DIR_NAME
fun commit(repository: Repository, indicator: ProgressIndicator?, commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()): Boolean {
indicator?.checkCanceled()
val diff = repository.computeIndexDiff()
val changed = diff.diff(indicator?.asProgressMonitor(), ProgressMonitor.UNKNOWN, ProgressMonitor.UNKNOWN, "Commit")
// don't worry about untracked/modified only in the FS files
if (!changed || (diff.added.isEmpty() && diff.changed.isEmpty() && diff.removed.isEmpty())) {
if (diff.modified.isEmpty() && diff.missing.isEmpty()) {
LOG.debug("Nothing to commit")
return false
}
var edits: MutableList<PathEdit>? = null
for (path in diff.modified) {
if (!path.startsWith(PROJECTS_DIR_NAME)) {
if (edits == null) {
edits = SmartList()
}
edits.add(AddFile(path))
}
}
for (path in diff.missing) {
if (edits == null) {
edits = SmartList()
}
edits.add(DeleteFile(path))
}
if (edits != null) {
repository.edit(edits)
}
}
LOG.debug { indexDiffToString(diff) }
indicator?.checkCanceled()
val builder = commitMessageFormatter.prependMessage()
// we use Github (edit via web UI) terms here
builder.appendCompactList("Update", diff.changed)
builder.appendCompactList("Create", diff.added)
builder.appendCompactList("Delete", diff.removed)
repository.commit(builder.toString())
return true
}
private fun indexDiffToString(diff: IndexDiff): String {
val builder = StringBuilder()
builder.append("To commit:")
builder.addList("Added", diff.added)
builder.addList("Changed", diff.changed)
builder.addList("Deleted", diff.removed)
builder.addList("Modified on disk relative to the index", diff.modified)
builder.addList("Untracked files", diff.untracked)
builder.addList("Untracked folders", diff.untrackedFolders)
builder.addList("Missing", diff.missing)
return builder.toString()
}
private fun StringBuilder.appendCompactList(name: String, list: Collection<String>) {
addList(name, list, true)
}
private fun StringBuilder.addList(name: String, list: Collection<String>, compact: Boolean = false) {
if (list.isEmpty()) {
return
}
if (compact) {
if (length != 0 && this[length - 1] != ' ') {
append('\t')
}
append(name)
}
else {
append('\t').append(name).append(':')
}
append(' ')
var isNotFirst = false
for (path in list) {
if (isNotFirst) {
append(',').append(' ')
}
else {
isNotFirst = true
}
append(if (compact) PathUtilRt.getFileName(path) else path)
}
}
| apache-2.0 | d209224b51b8cfc79a04812438bc3447 | 29.056075 | 155 | 0.695896 | 4.030075 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/ACTIONS_DOWNLOAD_LAYOUTS.kt | 2 | 2717 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object ACTIONS_DOWNLOAD_LAYOUTS : Response() {
override val url = "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts"
override val str = """{
"id" : "downloadLayouts",
"memberType" : "action",
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
}, {
"rel" : "up",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object\"",
"title" : "Prototyping"
}, {
"rel" : "urn:org.restfulobjects:rels/invoke;action=\"downloadLayouts\"",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts/invoke",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"",
"arguments" : {
"style" : {
"value" : null
}
}
}, {
"rel" : "describedby",
"href" : "http://localhost:8080/restful/domain-types/causewayApplib.LayoutServiceMenu/actions/downloadLayouts",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
} ],
"extensions" : {
"actionType" : "prototype",
"actionSemantics" : "safe"
},
"parameters" : {
"style" : {
"num" : 0,
"id" : "style",
"name" : "Style",
"description" : "",
"choices" : [ "Current", "Complete", "Normalized", "Minimal" ],
"default" : "Normalized"
}
}
}
"""
}
| apache-2.0 | c287671fd4aa4564d3011c4988ed6483 | 37.267606 | 120 | 0.669488 | 3.686567 | false | false | false | false |
google/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/AddAccessorsFactories.kt | 2 | 1466 | // 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.quickfix.fixes
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KotlinApplicatorBasedQuickFix
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactories
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddAccessorApplicator
import org.jetbrains.kotlin.psi.KtProperty
object AddAccessorsFactories {
val addAccessorsToUninitializedProperty =
diagnosticFixFactories(
KtFirDiagnostic.MustBeInitialized::class,
KtFirDiagnostic.MustBeInitializedOrBeAbstract::class
) { diagnostic ->
val property: KtProperty = diagnostic.psi
val addGetter = property.getter == null
val addSetter = property.isVar && property.setter == null
if (!addGetter && !addSetter) return@diagnosticFixFactories emptyList()
listOf(
KotlinApplicatorBasedQuickFix(
property,
KotlinApplicatorInput.Empty,
AddAccessorApplicator.applicator(addGetter, addSetter),
)
)
}
} | apache-2.0 | 8f60b1f14375ce158b132e365b99a04f | 47.9 | 158 | 0.717599 | 5.090278 | false | false | false | false |
google/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/AnnotationInlayProvider.kt | 5 | 10328 | // 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.codeInsight.hints
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.codeInsight.InferredAnnotationsManager
import com.intellij.codeInsight.MakeInferredAnnotationExplicit
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.MenuOnClickPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.codeInsight.hints.presentation.SequencePresentation
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator
import com.intellij.java.JavaBundle
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.BlockInlayPriority
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsActions
import com.intellij.psi.*
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
class AnnotationInlayProvider : InlayHintsProvider<AnnotationInlayProvider.Settings> {
override val group: InlayGroup
get() = InlayGroup.ANNOTATIONS_GROUP
override fun getCollectorFor(file: PsiFile,
editor: Editor,
settings: Settings,
sink: InlayHintsSink): InlayHintsCollector {
val project = file.project
val document = PsiDocumentManager.getInstance(project).getDocument(file)
return object : FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (file.project.service<DumbService>().isDumb) return false
if (file.project.isDefault) return false
val presentations = SmartList<InlayPresentation>()
if (element is PsiModifierListOwner) {
var annotations = emptySequence<PsiAnnotation>()
if (settings.showExternal) {
annotations += ExternalAnnotationsManager.getInstance(project).findExternalAnnotations(element).orEmpty()
}
if (settings.showInferred) {
annotations += InferredAnnotationsManager.getInstance(project).findInferredAnnotations(element)
}
val previewAnnotation = PREVIEW_ANNOTATION_KEY.get(element)
if (previewAnnotation != null) {
annotations += previewAnnotation
}
val shownAnnotations = mutableSetOf<String>()
annotations.forEach {
val nameReferenceElement = it.nameReferenceElement
if (nameReferenceElement != null && element.modifierList != null &&
(shownAnnotations.add(nameReferenceElement.qualifiedName) || JavaDocInfoGenerator.isRepeatableAnnotationType(it))) {
presentations.add(createPresentation(it, element))
}
}
val modifierList = element.modifierList
if (modifierList != null) {
val textRange = modifierList.textRange ?: return true
val offset = textRange.startOffset
if (presentations.isNotEmpty()) {
val presentation = SequencePresentation(presentations)
val prevSibling = element.prevSibling
when {
// element is first in line
prevSibling is PsiWhiteSpace && element !is PsiParameter && prevSibling.textContains('\n') && document != null -> {
val width = EditorUtil.getPlainSpaceWidth(editor)
val line = document.getLineNumber(offset)
val startOffset = document.getLineStartOffset(line)
val column = offset - startOffset
val shifted = factory.inset(presentation, left = column * width)
sink.addBlockElement(offset, true, true, BlockInlayPriority.ANNOTATIONS, shifted)
}
else -> {
sink.addInlineElement(offset, false, factory.inset(presentation, left = 1, right = 1), false)
}
}
}
}
}
return true
}
private fun createPresentation(
annotation: PsiAnnotation,
element: PsiModifierListOwner
): MenuOnClickPresentation {
val presentation = annotationPresentation(annotation)
return MenuOnClickPresentation(presentation, project) {
val makeExplicit = InsertAnnotationAction(project, file, element)
listOf(
makeExplicit,
ToggleSettingsAction(JavaBundle.message("settings.inlay.java.turn.off.external.annotations"), settings::showExternal, settings),
ToggleSettingsAction(JavaBundle.message("settings.inlay.java.turn.off.inferred.annotations"), settings::showInferred, settings)
)
}
}
private fun annotationPresentation(annotation: PsiAnnotation): InlayPresentation = with(factory) {
val nameReferenceElement = annotation.nameReferenceElement
val parameterList = annotation.parameterList
val presentations = mutableListOf(
smallText("@"),
psiSingleReference(smallText(nameReferenceElement?.referenceName ?: "")) { nameReferenceElement?.resolve() }
)
parametersPresentation(parameterList)?.let {
presentations.add(it)
}
roundWithBackground(SequencePresentation(presentations))
}
private fun parametersPresentation(parameterList: PsiAnnotationParameterList) = with(factory) {
val attributes = parameterList.attributes
when {
attributes.isEmpty() -> null
else -> insideParametersPresentation(attributes, collapsed = parameterList.textLength > 60)
}
}
private fun insideParametersPresentation(attributes: Array<PsiNameValuePair>, collapsed: Boolean) = with(factory) {
collapsible(
smallText("("),
smallText("..."),
{
join(
presentations = attributes.map { pairPresentation(it) },
separator = { smallText(", ") }
)
},
smallText(")"),
collapsed
)
}
private fun pairPresentation(attribute: PsiNameValuePair) = with(factory) {
when (val attrName = attribute.name) {
null -> attrValuePresentation(attribute)
else -> seq(
psiSingleReference(smallText(attrName), resolve = { attribute.reference?.resolve() }),
smallText(" = "),
attrValuePresentation(attribute)
)
}
}
private fun PresentationFactory.attrValuePresentation(attribute: PsiNameValuePair) =
smallText(attribute.value?.text ?: "")
}
}
override fun createSettings(): Settings = Settings()
override val name: String
get() = JavaBundle.message("settings.inlay.java.annotations")
override val key: SettingsKey<Settings>
get() = ourKey
override fun getCaseDescription(case: ImmediateConfigurable.Case): String? {
when (case.id) {
"inferred.annotations" -> return JavaBundle.message("inlay.annotation.hints.inferred.annotations")
"external.annotations" -> return JavaBundle.message("inlay.annotation.hints.external.annotations")
}
return null
}
override val previewText: String? = null
private val PREVIEW_ANNOTATION_KEY = Key.create<PsiAnnotation>("preview.annotation.key")
override fun preparePreview(editor: Editor, file: PsiFile, settings: Settings) {
val psiMethod = (file as PsiJavaFile).classes[0].methods[0]
val factory = PsiElementFactory.getInstance(file.project)
if (psiMethod.parameterList.isEmpty) {
PREVIEW_ANNOTATION_KEY.set(psiMethod, factory.createAnnotationFromText("@Deprecated", psiMethod))
}
else
PREVIEW_ANNOTATION_KEY.set(psiMethod.parameterList.getParameter(0), factory.createAnnotationFromText("@NotNull", psiMethod))
}
override fun createConfigurable(settings: Settings): ImmediateConfigurable {
return object : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): JComponent = panel {}
override val mainCheckboxText: String
get() = JavaBundle.message("settings.inlay.java.show.hints.for")
override val cases: List<ImmediateConfigurable.Case>
get() = listOf(
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.inferred.annotations"), "inferred.annotations", settings::showInferred),
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.external.annotations"), "external.annotations", settings::showExternal)
)
}
}
companion object {
val ourKey: SettingsKey<Settings> = SettingsKey("annotation.hints")
}
data class Settings(var showInferred: Boolean = false, var showExternal: Boolean = true)
class ToggleSettingsAction(@NlsActions.ActionText val text: String, val prop: KMutableProperty0<Boolean>, val settings: Settings) : AnAction() {
override fun update(e: AnActionEvent) {
val presentation = e.presentation
presentation.text = text
}
override fun actionPerformed(e: AnActionEvent) {
prop.set(!prop.get())
val storage = InlayHintsSettings.instance()
storage.storeSettings(ourKey, JavaLanguage.INSTANCE, settings)
InlayHintsPassFactory.forceHintsUpdateOnNextPass()
}
}
}
class InsertAnnotationAction(
private val project: Project,
private val file: PsiFile,
private val element: PsiModifierListOwner
) : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.text = JavaBundle.message("settings.inlay.java.insert.annotation")
}
override fun actionPerformed(e: AnActionEvent) {
val intention = MakeInferredAnnotationExplicit()
if (intention.isAvailable(file, element)) {
intention.makeAnnotationsExplicit(project, file, element)
}
}
}
| apache-2.0 | 75eccdcd0870a5ebd23f448215430a8d | 40.813765 | 149 | 0.690356 | 5.210898 | false | false | false | false |
denzelby/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/currency/CurrencyActualExchangeRateCommand.kt | 1 | 1878 | package com.github.bumblebee.command.currency
import com.github.bumblebee.command.SingleArgumentCommand
import com.github.bumblebee.command.currency.domain.SupportedCurrency
import com.github.bumblebee.command.currency.service.BYRExchangeRateRetrieveService
import com.github.bumblebee.service.RandomPhraseService
import com.github.bumblebee.util.logger
import com.github.telegram.api.BotApi
import com.github.telegram.domain.Update
import org.springframework.stereotype.Component
import java.text.MessageFormat
@Component
class CurrencyActualExchangeRateCommand(
private val botApi: BotApi,
private val randomPhrase: RandomPhraseService,
private val exchangeRateRetrieveService: BYRExchangeRateRetrieveService) : SingleArgumentCommand() {
override fun handleCommand(update: Update, chatId: Long, argument: String?) {
val currencyName = getCurrencyNameOrDefault(argument, SupportedCurrency.USD)
try {
val rate = exchangeRateRetrieveService.getCurrentExchangeRate(currencyName)
if (rate != null) {
val message = MessageFormat.format("BYR/{0}: {1}", currencyName, rate)
botApi.sendMessage(chatId, message)
} else {
botApi.sendMessage(chatId, "NBRB doesn't know.", update.message!!.messageId)
}
} catch (e: Exception) {
log.error("Currency retrieve failed for $currencyName", e)
botApi.sendMessage(chatId, randomPhrase.no(), update.message!!.messageId)
}
}
private fun getCurrencyNameOrDefault(argument: String?, defaultCurrency: SupportedCurrency): String {
return if (!argument.isNullOrEmpty()) argument.trim { it <= ' ' }.toUpperCase()
else defaultCurrency.name
}
companion object {
private val log = logger<CurrencyActualExchangeRateCommand>()
}
}
| mit | 5b374ad18ad6ddf1cfcce9212518bcec | 42.674419 | 108 | 0.71885 | 4.742424 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/widget/BottomSheetBehavior.kt | 1 | 31994 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.widget
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import androidx.annotation.IntDef
import androidx.annotation.VisibleForTesting
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior
import androidx.core.view.ViewCompat
import androidx.customview.view.AbsSavedState
import androidx.customview.widget.ViewDragHelper
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.shared.util.readBooleanUsingCompat
import com.google.samples.apps.iosched.shared.util.writeBooleanUsingCompat
import java.lang.ref.WeakReference
import kotlin.math.absoluteValue
/**
* Copy of material lib's BottomSheetBehavior that includes some bug fixes.
*/
// TODO remove when a fixed version in material lib is released.
class BottomSheetBehavior<V : View> : Behavior<V> {
companion object {
/** The bottom sheet is dragging. */
const val STATE_DRAGGING = 1
/** The bottom sheet is settling. */
const val STATE_SETTLING = 2
/** The bottom sheet is expanded. */
const val STATE_EXPANDED = 3
/** The bottom sheet is collapsed. */
const val STATE_COLLAPSED = 4
/** The bottom sheet is hidden. */
const val STATE_HIDDEN = 5
/** The bottom sheet is half-expanded (used when behavior_fitToContents is false). */
const val STATE_HALF_EXPANDED = 6
/**
* Peek at the 16:9 ratio keyline of its parent. This can be used as a parameter for
* [setPeekHeight(Int)]. [getPeekHeight()] will return this when the value is set.
*/
const val PEEK_HEIGHT_AUTO = -1
private const val HIDE_THRESHOLD = 0.5f
private const val HIDE_FRICTION = 0.1f
@IntDef(
value = [
STATE_DRAGGING,
STATE_SETTLING,
STATE_EXPANDED,
STATE_COLLAPSED,
STATE_HIDDEN,
STATE_HALF_EXPANDED
]
)
@Retention(AnnotationRetention.SOURCE)
annotation class State
/** Utility to get the [BottomSheetBehavior] from a [view]. */
@JvmStatic
fun from(view: View): BottomSheetBehavior<*> {
val lp = view.layoutParams as? CoordinatorLayout.LayoutParams
?: throw IllegalArgumentException("view is not a child of CoordinatorLayout")
return lp.behavior as? BottomSheetBehavior
?: throw IllegalArgumentException("view not associated with this behavior")
}
}
/** Callback for monitoring events about bottom sheets. */
interface BottomSheetCallback {
/**
* Called when the bottom sheet changes its state.
*
* @param bottomSheet The bottom sheet view.
* @param newState The new state. This will be one of link [STATE_DRAGGING],
* [STATE_SETTLING], [STATE_EXPANDED], [STATE_COLLAPSED], [STATE_HIDDEN], or
* [STATE_HALF_EXPANDED].
*/
fun onStateChanged(bottomSheet: View, newState: Int) {}
/**
* Called when the bottom sheet is being dragged.
*
* @param bottomSheet The bottom sheet view.
* @param slideOffset The new offset of this bottom sheet within [-1,1] range. Offset
* increases as this bottom sheet is moving upward. From 0 to 1 the sheet is between
* collapsed and expanded states and from -1 to 0 it is between hidden and collapsed states.
*/
fun onSlide(bottomSheet: View, slideOffset: Float) {}
}
/** The current state of the bottom sheet, backing property */
private var _state = STATE_COLLAPSED
/** The current state of the bottom sheet */
@State
var state
get() = _state
set(@State value) {
if (_state == value) {
return
}
if (viewRef == null) {
// Child is not laid out yet. Set our state and let onLayoutChild() handle it later.
if (value == STATE_COLLAPSED ||
value == STATE_EXPANDED ||
value == STATE_HALF_EXPANDED ||
(isHideable && value == STATE_HIDDEN)
) {
_state = value
}
return
}
viewRef?.get()?.apply {
// Start the animation; wait until a pending layout if there is one.
if (parent != null && parent.isLayoutRequested && isAttachedToWindow) {
post {
startSettlingAnimation(this, value)
}
} else {
startSettlingAnimation(this, value)
}
}
}
/** Whether to fit to contents. If false, the behavior will include [STATE_HALF_EXPANDED]. */
var isFitToContents = true
set(value) {
if (field != value) {
field = value
// If sheet is already laid out, recalculate the collapsed offset.
// Otherwise onLayoutChild will handle this later.
if (viewRef != null) {
collapsedOffset = calculateCollapsedOffset()
}
// Fix incorrect expanded settings.
setStateInternal(
if (field && state == STATE_HALF_EXPANDED) STATE_EXPANDED else state
)
}
}
/** Real peek height in pixels */
private var _peekHeight = 0
/** Peek height in pixels, or [PEEK_HEIGHT_AUTO] */
var peekHeight
get() = if (peekHeightAuto) PEEK_HEIGHT_AUTO else _peekHeight
set(value) {
var needLayout = false
if (value == PEEK_HEIGHT_AUTO) {
if (!peekHeightAuto) {
peekHeightAuto = true
needLayout = true
}
} else if (peekHeightAuto || _peekHeight != value) {
peekHeightAuto = false
_peekHeight = Math.max(0, value)
collapsedOffset = parentHeight - value
needLayout = true
}
if (needLayout && (state == STATE_COLLAPSED || state == STATE_HIDDEN)) {
viewRef?.get()?.requestLayout()
}
}
/** Whether the bottom sheet can be hidden. */
var isHideable = false
set(value) {
if (field != value) {
field = value
if (!value && state == STATE_HIDDEN) {
// Fix invalid state by moving to collapsed
state = STATE_COLLAPSED
}
}
}
/** Whether the bottom sheet can be dragged or not. */
var isDraggable = true
/** Whether the bottom sheet should skip collapsed state after being expanded once. */
var skipCollapsed = false
/** Whether animations should be disabled, to be used from UI tests. */
@VisibleForTesting
var isAnimationDisabled = false
/** Whether or not to use automatic peek height */
private var peekHeightAuto = false
/** Minimum peek height allowed */
private var peekHeightMin = 0
/** The last peek height calculated in onLayoutChild */
private var lastPeekHeight = 0
private var parentHeight = 0
/** Bottom sheet's top offset in [STATE_EXPANDED] state. */
private var fitToContentsOffset = 0
/** Bottom sheet's top offset in [STATE_HALF_EXPANDED] state. */
private var halfExpandedOffset = 0
/** Bottom sheet's top offset in [STATE_COLLAPSED] state. */
private var collapsedOffset = 0
/** Keeps reference to the bottom sheet outside of Behavior callbacks */
private var viewRef: WeakReference<View>? = null
/** Controls movement of the bottom sheet */
private lateinit var dragHelper: ViewDragHelper
// Touch event handling, etc
private var lastTouchX = 0
private var lastTouchY = 0
private var initialTouchY = 0
private var activePointerId = MotionEvent.INVALID_POINTER_ID
private var acceptTouches = true
private var minimumVelocity = 0
private var maximumVelocity = 0
private var velocityTracker: VelocityTracker? = null
private var nestedScrolled = false
private var nestedScrollingChildRef: WeakReference<View>? = null
private val callbacks: MutableSet<BottomSheetCallback> = mutableSetOf()
constructor() : super()
@SuppressLint("PrivateResource")
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
// Re-use BottomSheetBehavior's attrs
val a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout)
val value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight)
peekHeight = if (value != null && value.data == PEEK_HEIGHT_AUTO) {
value.data
} else {
a.getDimensionPixelSize(
R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO
)
}
isHideable = a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false)
isFitToContents =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true)
skipCollapsed =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false)
a.recycle()
val configuration = ViewConfiguration.get(context)
minimumVelocity = configuration.scaledMinimumFlingVelocity
maximumVelocity = configuration.scaledMaximumFlingVelocity
}
override fun onSaveInstanceState(parent: CoordinatorLayout, child: V): Parcelable {
return SavedState(
super.onSaveInstanceState(parent, child) ?: Bundle.EMPTY,
state,
peekHeight,
isFitToContents,
isHideable,
skipCollapsed,
isDraggable
)
}
override fun onRestoreInstanceState(parent: CoordinatorLayout, child: V, state: Parcelable) {
val ss = state as SavedState
super.onRestoreInstanceState(parent, child, ss.superState ?: Bundle.EMPTY)
isDraggable = ss.isDraggable
peekHeight = ss.peekHeight
isFitToContents = ss.isFitToContents
isHideable = ss.isHideable
skipCollapsed = ss.skipCollapsed
// Set state last. Intermediate states are restored as collapsed state.
_state = if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) {
STATE_COLLAPSED
} else {
ss.state
}
}
fun addBottomSheetCallback(callback: BottomSheetCallback) {
callbacks.add(callback)
}
fun removeBottomSheetCallback(callback: BottomSheetCallback) {
callbacks.remove(callback)
}
private fun setStateInternal(@State state: Int) {
if (_state != state) {
_state = state
viewRef?.get()?.let { view ->
callbacks.forEach { callback ->
callback.onStateChanged(view, state)
}
}
}
}
// -- Layout
override fun onLayoutChild(
parent: CoordinatorLayout,
child: V,
layoutDirection: Int
): Boolean {
if (parent.fitsSystemWindows && !child.fitsSystemWindows) {
child.fitsSystemWindows = true
}
val savedTop = child.top
// First let the parent lay it out
parent.onLayoutChild(child, layoutDirection)
parentHeight = parent.height
// Calculate peek and offsets
if (peekHeightAuto) {
if (peekHeightMin == 0) {
// init peekHeightMin
@SuppressLint("PrivateResource")
peekHeightMin = parent.resources.getDimensionPixelSize(
R.dimen.design_bottom_sheet_peek_height_min
)
}
lastPeekHeight = Math.max(peekHeightMin, parentHeight - parent.width * 9 / 16)
} else {
lastPeekHeight = _peekHeight
}
fitToContentsOffset = Math.max(0, parentHeight - child.height)
halfExpandedOffset = parentHeight / 2
collapsedOffset = calculateCollapsedOffset()
// Offset the bottom sheet
when (state) {
STATE_EXPANDED -> ViewCompat.offsetTopAndBottom(child, getExpandedOffset())
STATE_HALF_EXPANDED -> ViewCompat.offsetTopAndBottom(child, halfExpandedOffset)
STATE_HIDDEN -> ViewCompat.offsetTopAndBottom(child, parentHeight)
STATE_COLLAPSED -> ViewCompat.offsetTopAndBottom(child, collapsedOffset)
STATE_DRAGGING, STATE_SETTLING -> ViewCompat.offsetTopAndBottom(
child, savedTop - child.top
)
}
// Init these for later
viewRef = WeakReference(child)
if (!::dragHelper.isInitialized) {
dragHelper = ViewDragHelper.create(parent, dragCallback)
}
return true
}
private fun calculateCollapsedOffset(): Int {
return if (isFitToContents) {
Math.max(parentHeight - lastPeekHeight, fitToContentsOffset)
} else {
parentHeight - lastPeekHeight
}
}
private fun getExpandedOffset() = if (isFitToContents) fitToContentsOffset else 0
// -- Touch events and scrolling
override fun onInterceptTouchEvent(
parent: CoordinatorLayout,
child: V,
event: MotionEvent
): Boolean {
if (!isDraggable || !child.isShown) {
acceptTouches = false
return false
}
val action = event.actionMasked
lastTouchX = event.x.toInt()
lastTouchY = event.y.toInt()
// Record velocity
if (action == MotionEvent.ACTION_DOWN) {
resetVelocityTracker()
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain()
}
velocityTracker?.addMovement(event)
when (action) {
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
activePointerId = MotionEvent.INVALID_POINTER_ID
if (!acceptTouches) {
acceptTouches = true
return false
}
}
MotionEvent.ACTION_DOWN -> {
activePointerId = event.getPointerId(event.actionIndex)
initialTouchY = event.y.toInt()
clearNestedScroll()
if (!parent.isPointInChildBounds(child, lastTouchX, initialTouchY)) {
// Not touching the sheet
acceptTouches = false
}
}
}
return acceptTouches &&
// CoordinatorLayout can call us before the view is laid out. >_<
::dragHelper.isInitialized &&
dragHelper.shouldInterceptTouchEvent(event)
}
override fun onTouchEvent(
parent: CoordinatorLayout,
child: V,
event: MotionEvent
): Boolean {
if (!isDraggable || !child.isShown) {
return false
}
val action = event.actionMasked
if (action == MotionEvent.ACTION_DOWN && state == STATE_DRAGGING) {
return true
}
lastTouchX = event.x.toInt()
lastTouchY = event.y.toInt()
// Record velocity
if (action == MotionEvent.ACTION_DOWN) {
resetVelocityTracker()
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain()
}
velocityTracker?.addMovement(event)
// CoordinatorLayout can call us before the view is laid out. >_<
if (::dragHelper.isInitialized) {
dragHelper.processTouchEvent(event)
}
if (acceptTouches &&
action == MotionEvent.ACTION_MOVE &&
exceedsTouchSlop(initialTouchY, lastTouchY)
) {
// Manually capture the sheet since nothing beneath us is scrolling.
dragHelper.captureChildView(child, event.getPointerId(event.actionIndex))
}
return acceptTouches
}
private fun resetVelocityTracker() {
activePointerId = MotionEvent.INVALID_POINTER_ID
velocityTracker?.recycle()
velocityTracker = null
}
private fun exceedsTouchSlop(p1: Int, p2: Int) = Math.abs(p1 - p2) >= dragHelper.touchSlop
// Nested scrolling
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
directTargetChild: View,
target: View,
axes: Int,
type: Int
): Boolean {
nestedScrolled = false
if (isDraggable &&
viewRef?.get() == directTargetChild &&
(axes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0
) {
// Scrolling view is a descendent of the sheet and scrolling vertically.
// Let's follow along!
nestedScrollingChildRef = WeakReference(target)
return true
}
return false
}
override fun onNestedPreScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
dx: Int,
dy: Int,
consumed: IntArray,
type: Int
) {
if (type == ViewCompat.TYPE_NON_TOUCH) {
return // Ignore fling here
}
if (target != nestedScrollingChildRef?.get()) {
return
}
val currentTop = child.top
val newTop = currentTop - dy
if (dy > 0) { // Upward
if (newTop < getExpandedOffset()) {
consumed[1] = currentTop - getExpandedOffset()
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(STATE_EXPANDED)
} else {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(STATE_DRAGGING)
}
} else if (dy < 0) { // Downward
if (!target.canScrollVertically(-1)) {
if (newTop <= collapsedOffset || isHideable) {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(STATE_DRAGGING)
} else {
consumed[1] = currentTop - collapsedOffset
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(STATE_COLLAPSED)
}
}
}
dispatchOnSlide(child.top)
nestedScrolled = true
}
override fun onStopNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
type: Int
) {
if (child.top == getExpandedOffset()) {
setStateInternal(STATE_EXPANDED)
return
}
if (target != nestedScrollingChildRef?.get() || !nestedScrolled) {
return
}
settleBottomSheet(child, getYVelocity(), true)
clearNestedScroll()
}
override fun onNestedPreFling(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
velocityX: Float,
velocityY: Float
): Boolean {
return isDraggable &&
target == nestedScrollingChildRef?.get() &&
(
state != STATE_EXPANDED || super.onNestedPreFling(
coordinatorLayout, child, target, velocityX, velocityY
)
)
}
private fun clearNestedScroll() {
nestedScrolled = false
nestedScrollingChildRef = null
}
// Settling
private fun getYVelocity(): Float {
return velocityTracker?.run {
computeCurrentVelocity(1000, maximumVelocity.toFloat())
getYVelocity(activePointerId)
} ?: 0f
}
private fun settleBottomSheet(sheet: View, yVelocity: Float, isNestedScroll: Boolean) {
val top: Int
@State val targetState: Int
val flinging = yVelocity.absoluteValue > minimumVelocity
if (flinging && yVelocity < 0) { // Moving up
if (isFitToContents) {
top = fitToContentsOffset
targetState = STATE_EXPANDED
} else {
if (sheet.top > halfExpandedOffset) {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
} else {
top = 0
targetState = STATE_EXPANDED
}
}
} else if (isHideable && shouldHide(sheet, yVelocity)) {
top = parentHeight
targetState = STATE_HIDDEN
} else if (flinging && yVelocity > 0) { // Moving down
top = collapsedOffset
targetState = STATE_COLLAPSED
} else {
val currentTop = sheet.top
if (isFitToContents) {
if (Math.abs(currentTop - fitToContentsOffset)
< Math.abs(currentTop - collapsedOffset)
) {
top = fitToContentsOffset
targetState = STATE_EXPANDED
} else {
top = collapsedOffset
targetState = STATE_COLLAPSED
}
} else {
if (currentTop < halfExpandedOffset) {
if (currentTop < Math.abs(currentTop - collapsedOffset)) {
top = 0
targetState = STATE_EXPANDED
} else {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
}
} else {
if (Math.abs(currentTop - halfExpandedOffset)
< Math.abs(currentTop - collapsedOffset)
) {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
} else {
top = collapsedOffset
targetState = STATE_COLLAPSED
}
}
}
}
val startedSettling = if (isNestedScroll) {
dragHelper.smoothSlideViewTo(sheet, sheet.left, top)
} else {
dragHelper.settleCapturedViewAt(sheet.left, top)
}
if (startedSettling) {
setStateInternal(STATE_SETTLING)
ViewCompat.postOnAnimation(sheet, SettleRunnable(sheet, targetState))
} else {
setStateInternal(targetState)
}
}
private fun shouldHide(child: View, yVelocity: Float): Boolean {
if (skipCollapsed) {
return true
}
if (child.top < collapsedOffset) {
return false // it should not hide, but collapse.
}
val newTop = child.top + yVelocity * HIDE_FRICTION
return Math.abs(newTop - collapsedOffset) / _peekHeight.toFloat() > HIDE_THRESHOLD
}
private fun startSettlingAnimation(child: View, state: Int) {
var top: Int
var finalState = state
when {
state == STATE_COLLAPSED -> top = collapsedOffset
state == STATE_EXPANDED -> top = getExpandedOffset()
state == STATE_HALF_EXPANDED -> {
top = halfExpandedOffset
// Skip to expanded state if we would scroll past the height of the contents.
if (isFitToContents && top <= fitToContentsOffset) {
finalState = STATE_EXPANDED
top = fitToContentsOffset
}
}
state == STATE_HIDDEN && isHideable -> top = parentHeight
else -> throw IllegalArgumentException("Invalid state: " + state)
}
if (isAnimationDisabled) {
// Prevent animations
ViewCompat.offsetTopAndBottom(child, top - child.top)
}
if (dragHelper.smoothSlideViewTo(child, child.left, top)) {
setStateInternal(STATE_SETTLING)
ViewCompat.postOnAnimation(child, SettleRunnable(child, finalState))
} else {
setStateInternal(finalState)
}
}
private fun dispatchOnSlide(top: Int) {
viewRef?.get()?.let { sheet ->
val denom = if (top > collapsedOffset) {
parentHeight - collapsedOffset
} else {
collapsedOffset - getExpandedOffset()
}
callbacks.forEach { callback ->
callback.onSlide(sheet, (collapsedOffset - top).toFloat() / denom)
}
}
}
private inner class SettleRunnable(
private val view: View,
@State private val state: Int
) : Runnable {
override fun run() {
if (dragHelper.continueSettling(true)) {
view.postOnAnimation(this)
} else {
setStateInternal(state)
}
}
}
private val dragCallback: ViewDragHelper.Callback = object : ViewDragHelper.Callback() {
override fun tryCaptureView(child: View, pointerId: Int): Boolean {
when {
// Sanity check
state == STATE_DRAGGING -> return false
// recapture a settling sheet
dragHelper.viewDragState == ViewDragHelper.STATE_SETTLING -> return true
// let nested scroll handle this
nestedScrollingChildRef?.get() != null -> return false
}
val dy = lastTouchY - initialTouchY
if (dy == 0) {
// ViewDragHelper tries to capture in onTouch for the ACTION_DOWN event, but there's
// really no way to check for a scrolling child without a direction, so wait.
return false
}
if (state == STATE_COLLAPSED) {
if (isHideable) {
// Any drag should capture in order to expand or hide the sheet
return true
}
if (dy < 0) {
// Expand on upward movement, even if there's scrolling content underneath
return true
}
}
// Check for scrolling content underneath the touch point that can scroll in the
// appropriate direction.
val scrollingChild = findScrollingChildUnder(child, lastTouchX, lastTouchY, -dy)
return scrollingChild == null
}
private fun findScrollingChildUnder(view: View, x: Int, y: Int, direction: Int): View? {
if (view.visibility == View.VISIBLE && dragHelper.isViewUnder(view, x, y)) {
if (view.canScrollVertically(direction)) {
return view
}
if (view is ViewGroup) {
// TODO this doesn't account for elevation or child drawing order.
for (i in (view.childCount - 1) downTo 0) {
val child = view.getChildAt(i)
val found =
findScrollingChildUnder(child, x - child.left, y - child.top, direction)
if (found != null) {
return found
}
}
}
}
return null
}
override fun getViewVerticalDragRange(child: View): Int {
return if (isHideable) parentHeight else collapsedOffset
}
override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
val maxOffset = if (isHideable) parentHeight else collapsedOffset
return top.coerceIn(getExpandedOffset(), maxOffset)
}
override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int) = child.left
override fun onViewDragStateChanged(state: Int) {
if (state == ViewDragHelper.STATE_DRAGGING) {
setStateInternal(STATE_DRAGGING)
}
}
override fun onViewPositionChanged(child: View, left: Int, top: Int, dx: Int, dy: Int) {
dispatchOnSlide(top)
}
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
settleBottomSheet(releasedChild, yvel, false)
}
}
/** SavedState implementation */
internal class SavedState : AbsSavedState {
@State internal val state: Int
internal val peekHeight: Int
internal val isFitToContents: Boolean
internal val isHideable: Boolean
internal val skipCollapsed: Boolean
internal val isDraggable: Boolean
constructor(source: Parcel) : this(source, null)
constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) {
state = source.readInt()
peekHeight = source.readInt()
isFitToContents = source.readBooleanUsingCompat()
isHideable = source.readBooleanUsingCompat()
skipCollapsed = source.readBooleanUsingCompat()
isDraggable = source.readBooleanUsingCompat()
}
constructor(
superState: Parcelable,
@State state: Int,
peekHeight: Int,
isFitToContents: Boolean,
isHideable: Boolean,
skipCollapsed: Boolean,
isDraggable: Boolean
) : super(superState) {
this.state = state
this.peekHeight = peekHeight
this.isFitToContents = isFitToContents
this.isHideable = isHideable
this.skipCollapsed = skipCollapsed
this.isDraggable = isDraggable
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.apply {
writeInt(state)
writeInt(peekHeight)
writeBooleanUsingCompat(isFitToContents)
writeBooleanUsingCompat(isHideable)
writeBooleanUsingCompat(skipCollapsed)
writeBooleanUsingCompat(isDraggable)
}
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<SavedState> =
object : Parcelable.ClassLoaderCreator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source, null)
}
override fun createFromParcel(source: Parcel, loader: ClassLoader): SavedState {
return SavedState(source, loader)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| apache-2.0 | d5f8f5d509a4d67cb5245af0f47e8995 | 34.707589 | 100 | 0.57067 | 5.183733 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/internal/LockFreeTaskQueue.kt | 1 | 13602 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.jvm.*
private typealias Core<E> = LockFreeTaskQueueCore<E>
/**
* Lock-free Multiply-Producer xxx-Consumer Queue for task scheduling purposes.
*
* **Note 1: This queue is NOT linearizable. It provides only quiescent consistency for its operations.**
* However, this guarantee is strong enough for task-scheduling purposes.
* In particular, the following execution is permitted for this queue, but is not permitted for a linearizable queue:
*
* ```
* Thread 1: addLast(1) = true, removeFirstOrNull() = null
* Thread 2: addLast(2) = 2 // this operation is concurrent with both operations in the first thread
* ```
*
* **Note 2: When this queue is used with multiple consumers (`singleConsumer == false`) this it is NOT lock-free.**
* In particular, consumer spins until producer finishes its operation in the case of near-empty queue.
* It is a very short window that could manifest itself rarely and only under specific load conditions,
* but it still deprives this algorithm of its lock-freedom.
*/
internal open class LockFreeTaskQueue<E : Any>(
singleConsumer: Boolean // true when there is only a single consumer (slightly faster & lock-free)
) {
private val _cur = atomic(Core<E>(Core.INITIAL_CAPACITY, singleConsumer))
// Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false)
val isEmpty: Boolean get() = _cur.value.isEmpty
val size: Int get() = _cur.value.size
fun close() {
_cur.loop { cur ->
if (cur.close()) return // closed this copy
_cur.compareAndSet(cur, cur.next()) // move to next
}
}
fun addLast(element: E): Boolean {
_cur.loop { cur ->
when (cur.addLast(element)) {
Core.ADD_SUCCESS -> return true
Core.ADD_CLOSED -> return false
Core.ADD_FROZEN -> _cur.compareAndSet(cur, cur.next()) // move to next
}
}
}
@Suppress("UNCHECKED_CAST")
fun removeFirstOrNull(): E? {
_cur.loop { cur ->
val result = cur.removeFirstOrNull()
if (result !== Core.REMOVE_FROZEN) return result as E?
_cur.compareAndSet(cur, cur.next())
}
}
// Used for validation in tests only
fun <R> map(transform: (E) -> R): List<R> = _cur.value.map(transform)
// Used for validation in tests only
fun isClosed(): Boolean = _cur.value.isClosed()
}
/**
* Lock-free Multiply-Producer xxx-Consumer Queue core.
* @see LockFreeTaskQueue
*/
internal class LockFreeTaskQueueCore<E : Any>(
private val capacity: Int,
private val singleConsumer: Boolean // true when there is only a single consumer (slightly faster)
) {
private val mask = capacity - 1
private val _next = atomic<Core<E>?>(null)
private val _state = atomic(0L)
private val array = atomicArrayOfNulls<Any?>(capacity)
init {
check(mask <= MAX_CAPACITY_MASK)
check(capacity and mask == 0)
}
// Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false)
val isEmpty: Boolean get() = _state.value.withState { head, tail -> head == tail }
val size: Int get() = _state.value.withState { head, tail -> (tail - head) and MAX_CAPACITY_MASK }
fun close(): Boolean {
_state.update { state ->
if (state and CLOSED_MASK != 0L) return true // ok - already closed
if (state and FROZEN_MASK != 0L) return false // frozen -- try next
state or CLOSED_MASK // try set closed bit
}
return true
}
// ADD_CLOSED | ADD_FROZEN | ADD_SUCCESS
fun addLast(element: E): Int {
_state.loop { state ->
if (state and (FROZEN_MASK or CLOSED_MASK) != 0L) return state.addFailReason() // cannot add
state.withState { head, tail ->
val mask = this.mask // manually move instance field to local for performance
// If queue is Single-Consumer then there could be one element beyond head that we cannot overwrite,
// so we check for full queue with an extra margin of one element
if ((tail + 2) and mask == head and mask) return ADD_FROZEN // overfull, so do freeze & copy
// If queue is Multi-Consumer then the consumer could still have not cleared element
// despite the above check for one free slot.
if (!singleConsumer && array[tail and mask].value != null) {
// There are two options in this situation
// 1. Spin-wait until consumer clears the slot
// 2. Freeze & resize to avoid spinning
// We use heuristic here to avoid memory-overallocation
// Freeze & reallocate when queue is small or more than half of the queue is used
if (capacity < MIN_ADD_SPIN_CAPACITY || (tail - head) and MAX_CAPACITY_MASK > capacity shr 1) {
return ADD_FROZEN
}
// otherwise spin
return@loop
}
val newTail = (tail + 1) and MAX_CAPACITY_MASK
if (_state.compareAndSet(state, state.updateTail(newTail))) {
// successfully added
array[tail and mask].value = element
// could have been frozen & copied before this item was set -- correct it by filling placeholder
var cur = this
while(true) {
if (cur._state.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet
cur = cur.next().fillPlaceholder(tail, element) ?: break
}
return ADD_SUCCESS // added successfully
}
}
}
}
private fun fillPlaceholder(index: Int, element: E): Core<E>? {
val old = array[index and mask].value
/*
* addLast actions:
* 1) Commit tail slot
* 2) Write element to array slot
* 3) Check for array copy
*
* If copy happened between 2 and 3 then the consumer might have consumed our element,
* then another producer might have written its placeholder in our slot, so we should
* perform *unique* check that current placeholder is our to avoid overwriting another producer placeholder
*/
if (old is Placeholder && old.index == index) {
array[index and mask].value = element
// we've corrected missing element, should check if that propagated to further copies, just in case
return this
}
// it is Ok, no need for further action
return null
}
// REMOVE_FROZEN | null (EMPTY) | E (SUCCESS)
fun removeFirstOrNull(): Any? {
_state.loop { state ->
if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify
state.withState { head, tail ->
if ((tail and mask) == (head and mask)) return null // empty
val element = array[head and mask].value
if (element == null) {
// If queue is Single-Consumer, then element == null only when add has not finished yet
if (singleConsumer) return null // consider it not added yet
// retry (spin) until consumer adds it
return@loop
}
// element == Placeholder can only be when add has not finished yet
if (element is Placeholder) return null // consider it not added yet
// we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster
val newHead = (head + 1) and MAX_CAPACITY_MASK
if (_state.compareAndSet(state, state.updateHead(newHead))) {
// Array could have been copied by another thread and it is perfectly fine, since only elements
// between head and tail were copied and there are no extra steps we should take here
array[head and mask].value = null // now can safely put null (state was updated)
return element // successfully removed in fast-path
}
// Multi-Consumer queue must retry this loop on CAS failure (another consumer might have removed element)
if (!singleConsumer) return@loop
// Single-consumer queue goes to slow-path for remove in case of interference
var cur = this
while (true) {
@Suppress("UNUSED_VALUE")
cur = cur.removeSlowPath(head, newHead) ?: return element
}
}
}
}
private fun removeSlowPath(oldHead: Int, newHead: Int): Core<E>? {
_state.loop { state ->
state.withState { head, _ ->
assert { head == oldHead } // "This queue can have only one consumer"
if (state and FROZEN_MASK != 0L) {
// state was already frozen, so removed element was copied to next
return next() // continue to correct head in next
}
if (_state.compareAndSet(state, state.updateHead(newHead))) {
array[head and mask].value = null // now can safely put null (state was updated)
return null
}
}
}
}
fun next(): LockFreeTaskQueueCore<E> = allocateOrGetNextCopy(markFrozen())
private fun markFrozen(): Long =
_state.updateAndGet { state ->
if (state and FROZEN_MASK != 0L) return state // already marked
state or FROZEN_MASK
}
private fun allocateOrGetNextCopy(state: Long): Core<E> {
_next.loop { next ->
if (next != null) return next // already allocated & copied
_next.compareAndSet(null, allocateNextCopy(state))
}
}
private fun allocateNextCopy(state: Long): Core<E> {
val next = LockFreeTaskQueueCore<E>(capacity * 2, singleConsumer)
state.withState { head, tail ->
var index = head
while (index and mask != tail and mask) {
// replace nulls with placeholders on copy
val value = array[index and mask].value ?: Placeholder(index)
next.array[index and next.mask].value = value
index++
}
next._state.value = state wo FROZEN_MASK
}
return next
}
// Used for validation in tests only
fun <R> map(transform: (E) -> R): List<R> {
val res = ArrayList<R>(capacity)
_state.value.withState { head, tail ->
var index = head
while (index and mask != tail and mask) {
// replace nulls with placeholders on copy
val element = array[index and mask].value
@Suppress("UNCHECKED_CAST")
if (element != null && element !is Placeholder) res.add(transform(element as E))
index++
}
}
return res
}
// Used for validation in tests only
fun isClosed(): Boolean = _state.value and CLOSED_MASK != 0L
// Instance of this class is placed into array when we have to copy array, but addLast is in progress --
// it had already reserved a slot in the array (with null) and have not yet put its value there.
// Placeholder keeps the actual index (not masked) to distinguish placeholders on different wraparounds of array
// Internal because of inlining
internal class Placeholder(@JvmField val index: Int)
@Suppress("PrivatePropertyName", "MemberVisibilityCanBePrivate")
internal companion object {
const val INITIAL_CAPACITY = 8
const val CAPACITY_BITS = 30
const val MAX_CAPACITY_MASK = (1 shl CAPACITY_BITS) - 1
const val HEAD_SHIFT = 0
const val HEAD_MASK = MAX_CAPACITY_MASK.toLong() shl HEAD_SHIFT
const val TAIL_SHIFT = HEAD_SHIFT + CAPACITY_BITS
const val TAIL_MASK = MAX_CAPACITY_MASK.toLong() shl TAIL_SHIFT
const val FROZEN_SHIFT = TAIL_SHIFT + CAPACITY_BITS
const val FROZEN_MASK = 1L shl FROZEN_SHIFT
const val CLOSED_SHIFT = FROZEN_SHIFT + 1
const val CLOSED_MASK = 1L shl CLOSED_SHIFT
const val MIN_ADD_SPIN_CAPACITY = 1024
@JvmField val REMOVE_FROZEN = Symbol("REMOVE_FROZEN")
const val ADD_SUCCESS = 0
const val ADD_FROZEN = 1
const val ADD_CLOSED = 2
infix fun Long.wo(other: Long) = this and other.inv()
fun Long.updateHead(newHead: Int) = (this wo HEAD_MASK) or (newHead.toLong() shl HEAD_SHIFT)
fun Long.updateTail(newTail: Int) = (this wo TAIL_MASK) or (newTail.toLong() shl TAIL_SHIFT)
inline fun <T> Long.withState(block: (head: Int, tail: Int) -> T): T {
val head = ((this and HEAD_MASK) shr HEAD_SHIFT).toInt()
val tail = ((this and TAIL_MASK) shr TAIL_SHIFT).toInt()
return block(head, tail)
}
// FROZEN | CLOSED
fun Long.addFailReason(): Int = if (this and CLOSED_MASK != 0L) ADD_CLOSED else ADD_FROZEN
}
}
| apache-2.0 | 30dccf77621e1e64cb4a41f5c2caceb5 | 43.306189 | 134 | 0.590943 | 4.505465 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/component/GHHtmlErrorPanel.kt | 10 | 4771 | // 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 org.jetbrains.plugins.github.ui.component
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.HyperlinkAdapter
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.exceptions.GithubStatusCodeException
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.ui.util.getName
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.KeyStroke
import javax.swing.SwingConstants
import javax.swing.event.HyperlinkEvent
object GHHtmlErrorPanel {
private const val ERROR_ACTION_HREF = "ERROR_ACTION"
fun create(errorPrefix: String, error: Throwable,
errorAction: Action? = null,
horizontalAlignment: Int = SwingConstants.CENTER): JComponent {
val model = GHImmutableErrorPanelModel(errorPrefix, error, errorAction)
return create(model, horizontalAlignment)
}
fun create(model: GHErrorPanelModel, horizontalAlignment: Int = SwingConstants.CENTER): JComponent {
val pane = HtmlEditorPane().apply {
foreground = UIUtil.getErrorForeground()
isFocusable = true
removeHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
addHyperlinkListener(object : HyperlinkAdapter() {
override fun hyperlinkActivated(e: HyperlinkEvent) {
if (e.description == ERROR_ACTION_HREF) {
model.errorAction?.actionPerformed(ActionEvent(this@apply, ActionEvent.ACTION_PERFORMED, "perform"))
}
else {
BrowserUtil.browse(e.description)
}
}
})
registerKeyboardAction(ActionListener {
model.errorAction?.actionPerformed(it)
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
}
Controller(model, pane, horizontalAlignment)
return pane
}
private class Controller(private val model: GHErrorPanelModel,
private val pane: HtmlEditorPane,
horizontalAlignment: Int) {
private val alignmentText = when (horizontalAlignment) {
SwingConstants.LEFT -> "left"
SwingConstants.RIGHT -> "right"
else -> "center"
}
init {
model.addAndInvokeChangeEventListener(::update)
}
private fun update() {
val error = model.error
if (error != null) {
pane.isVisible = true
val errorTextBuilder = HtmlBuilder()
.appendP(model.errorPrefix)
.appendP(getLoadingErrorText(error))
val errorAction = model.errorAction
if (errorAction != null) {
errorTextBuilder.br()
.appendP(HtmlChunk.link(ERROR_ACTION_HREF, errorAction.getName()))
}
pane.setBody(errorTextBuilder.toString())
}
else {
pane.isVisible = false
pane.setBody("")
}
// JDK bug - need to force height recalculation (see JBR-2256)
pane.setSize(Int.MAX_VALUE / 2, Int.MAX_VALUE / 2)
}
private fun HtmlBuilder.appendP(chunk: HtmlChunk): HtmlBuilder = append(HtmlChunk.p().attr("align", alignmentText).child(chunk))
private fun HtmlBuilder.appendP(@Nls text: String): HtmlBuilder = appendP(HtmlChunk.text(text))
}
@Nls
private fun getLoadingErrorText(error: Throwable): String {
if (error is GithubStatusCodeException && error.error != null && error.error!!.message != null) {
val githubError = error.error!!
val message = githubError.message!!.removePrefix("[").removeSuffix("]")
val builder = HtmlBuilder().append(message)
if (message.startsWith("Could not resolve to a Repository", true)) {
@NlsSafe
val explanation = " Either repository doesn't exist or you don't have access. The most probable cause is that OAuth App access restrictions are enabled in organization."
builder.append(explanation)
}
val errors = githubError.errors?.map { e ->
HtmlChunk.text(e.message ?: GithubBundle.message("gql.error.in.field", e.code, e.resource, e.field.orEmpty()))
}
if (!errors.isNullOrEmpty()) builder.append(": ").append(HtmlChunk.br()).appendWithSeparators(HtmlChunk.br(), errors)
return builder.toString()
}
return error.message ?: GithubBundle.message("unknown.loading.error")
}
}
| apache-2.0 | 8fd26d27f6c809c3b41d8dc7c070f065 | 37.475806 | 177 | 0.698805 | 4.488241 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/GradleKotlinFrameworkSupportProviderUtils.kt | 5 | 2418 | // 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.gradleJava.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import java.io.File
import java.io.Writer
/**
* create parent directories and file
* @return null if file already exists
*/
internal fun getNewFileWriter(
module: Module,
relativeDir: String,
fileName: String
): Writer? {
val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null
if (contentEntryPath.isEmpty()) return null
val contentRootDir = File(contentEntryPath)
val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null
val dir = VfsUtil.createDirectoryIfMissing(modelContentRootDir, relativeDir) ?: return null
if (dir.findChild(fileName) != null) return null
val file = dir.createChildData(null, fileName)
return file.getOutputStream(null).writer()
}
internal fun addBrowserSupport(module: Module) {
getNewFileWriter(module, "src/main/resources", "index.html")?.use {
it.write(
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${module.name}</title>
<script src="${module.name}.js"></script>
</head>
<body>
</body>
</html>
""".trimIndent().trim()
)
}
getNewFileWriter(module, "src/main/kotlin", "main.kt")?.use {
it.write(
"""
import kotlinx.browser.document
fun main() {
document.write("Hello, world!")
}
""".trimIndent().trim()
)
}
}
internal fun browserConfiguration(): String {
return """
webpackTask {
cssSupport.enabled = true
}
runTask {
cssSupport.enabled = true
}
testTask {
useKarma {
useChromeHeadless()
webpackConfig.cssSupport.enabled = true
}
}
""".trimIndent()
} | apache-2.0 | e7c1ec6e58d36c760c3dfa381c83950a | 28.864198 | 158 | 0.578164 | 4.797619 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/advertiser/PluginFeatureCacheService.kt | 1 | 1329 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ide.plugins.advertiser
import com.intellij.openapi.components.*
import kotlinx.serialization.Serializable
import org.jetbrains.annotations.ApiStatus
@Service(Service.Level.APP)
@State(name = "PluginFeatureCacheService", storages = [Storage(StoragePathMacros.CACHE_FILE)], allowLoadInTests = true)
@ApiStatus.Internal
class PluginFeatureCacheService : SerializablePersistentStateComponent<PluginFeatureCacheService.MyState>(MyState()) {
companion object {
fun getInstance(): PluginFeatureCacheService = service()
}
override fun getStateModificationCount(): Long {
val state = state
return (state.extensions?.modificationCount ?: 0) + (state.dependencies?.modificationCount ?: 0)
}
@Serializable
data class MyState(
val extensions: PluginFeatureMap? = null,
val dependencies: PluginFeatureMap? = null
)
var extensions: PluginFeatureMap?
get() = state.extensions
set(value) {
loadState(MyState(value, state.dependencies))
}
var dependencies: PluginFeatureMap?
get() = state.dependencies
set(value) {
loadState(MyState(state.extensions, value))
}
} | apache-2.0 | 4576cbd62e5022b7636ff41a95dd896c | 32.25 | 120 | 0.754703 | 4.614583 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt | 1 | 9140 | package info.nightscout.androidaps.plugins.configBuilder
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginType
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface {
fun isLoopInvocationAllowed(): Constraint<Boolean> =
isLoopInvocationAllowed(Constraint(true))
fun isClosedLoopAllowed(): Constraint<Boolean> =
isClosedLoopAllowed(Constraint(true))
fun isAutosensModeEnabled(): Constraint<Boolean> =
isAutosensModeEnabled(Constraint(true))
fun isAMAModeEnabled(): Constraint<Boolean> =
isAMAModeEnabled(Constraint(true))
fun isSMBModeEnabled(): Constraint<Boolean> =
isSMBModeEnabled(Constraint(true))
fun isUAMEnabled(): Constraint<Boolean> =
isUAMEnabled(Constraint(true))
fun isAdvancedFilteringEnabled(): Constraint<Boolean> =
isAdvancedFilteringEnabled(Constraint(true))
fun isSuperBolusEnabled(): Constraint<Boolean> =
isSuperBolusEnabled(Constraint(true))
fun getMaxBasalAllowed(profile: Profile): Constraint<Double> =
applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile)
fun getMaxBasalPercentAllowed(profile: Profile): Constraint<Int> =
applyBasalPercentConstraints(Constraint(Constants.REALLYHIGHPERCENTBASALRATE), profile)
fun getMaxBolusAllowed(): Constraint<Double> =
applyBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS))
fun getMaxExtendedBolusAllowed(): Constraint<Double> =
applyExtendedBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS))
fun getMaxCarbsAllowed(): Constraint<Int> =
applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS))
fun getMaxIOBAllowed(): Constraint<Double> =
applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB))
fun isAutomationEnabled(): Constraint<Boolean> =
isAutomationEnabled(Constraint(true))
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isLoopInvocationAllowed(value)
}
return value
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isClosedLoopAllowed(value)
}
return value
}
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAutosensModeEnabled(value)
}
return value
}
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.isAMAModeEnabled(value)
}
return value
}
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isSMBModeEnabled(value)
}
return value
}
override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isUAMEnabled(value)
}
return value
}
override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAdvancedFilteringEnabled(value)
}
return value
}
override fun isSuperBolusEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isSuperBolusEnabled(value)
}
return value
}
override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.applyBasalConstraints(absoluteRate, profile)
}
return absoluteRate
}
override fun applyBasalPercentConstraints(percentRate: Constraint<Int>, profile: Profile): Constraint<Int> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyBasalPercentConstraints(percentRate, profile)
}
return percentRate
}
override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyBolusConstraints(insulin)
}
return insulin
}
override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyExtendedBolusConstraints(insulin)
}
return insulin
}
override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyCarbsConstraints(carbs)
}
return carbs
}
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyMaxIOBConstraints(maxIob)
}
return maxIob
}
override fun isAutomationEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAutomationEnabled(value)
}
return value
}
} | agpl-3.0 | 38663b331ab748578fea7179a5a581fc | 42.736842 | 116 | 0.717068 | 5.280185 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/PointMesh.kt | 1 | 1883 | package de.fabmax.kool.scene
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.GlslType
import de.fabmax.kool.pipeline.shadermodel.vertexStage
import de.fabmax.kool.pipeline.shading.UnlitMaterialConfig
import de.fabmax.kool.pipeline.shading.UnlitShader
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.PrimitiveType
import de.fabmax.kool.scene.geometry.VertexView
import de.fabmax.kool.util.Color
/**
* @author fabmax
*/
fun pointMesh(name: String? = null, block: PointMesh.() -> Unit): PointMesh {
return PointMesh(name = name).apply(block)
}
open class PointMesh(geometry: IndexedVertexList = IndexedVertexList(Attribute.POSITIONS, ATTRIB_POINT_SIZE, Attribute.COLORS), name: String? = null) :
Mesh(geometry, name) {
init {
geometry.primitiveType = PrimitiveType.POINTS
rayTest = MeshRayTest.nopTest()
val unlitCfg = UnlitMaterialConfig()
val unlitModel = UnlitShader.defaultUnlitModel(unlitCfg).apply {
vertexStage {
pointSize(attributeNode(ATTRIB_POINT_SIZE).output)
}
}
shader = UnlitShader(unlitCfg, unlitModel)
}
fun addPoint(block: VertexView.() -> Unit): Int {
val idx = geometry.addVertex(block)
geometry.addIndex(idx)
return idx
}
fun addPoint(position: Vec3f, pointSize: Float, color: Color): Int {
val idx = geometry.addVertex {
this.position.set(position)
this.color.set(color)
getFloatAttribute(ATTRIB_POINT_SIZE)?.f = pointSize
}
geometry.addIndex(idx)
return idx
}
fun clear() {
geometry.clear()
bounds.clear()
}
companion object {
val ATTRIB_POINT_SIZE = Attribute("aPointSize", GlslType.FLOAT)
}
}
| apache-2.0 | 429dd6df67dd962bbd2a9e11667ede26 | 29.868852 | 151 | 0.675518 | 3.898551 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitScoringButtonsView.kt | 1 | 3417 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityEvent
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.asDrawable
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class HabitScoringButtonsView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val positiveView: ViewGroup by bindView(R.id.positive_view)
private val negativeView: ViewGroup by bindView(R.id.negative_view)
private val positiveImageView: ImageView by bindView(R.id.positive_image_view)
private val negativeImageView: ImageView by bindView(R.id.negative_image_view)
private val positiveTextView: TextView by bindView(R.id.positive_text_view)
private val negativeTextView: TextView by bindView(R.id.negative_text_view)
var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300)
var isPositive = true
set(value) {
field = value
positiveImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlPlus(tintColor, value).asDrawable(resources))
if (value) {
positiveTextView.setTextColor(tintColor)
positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.on)
} else {
positiveTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_100))
positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.off)
}
}
var isNegative = true
set(value) {
field = value
negativeImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlMinus(tintColor, value).asDrawable(resources))
if (value) {
negativeTextView.setTextColor(tintColor)
negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.on)
} else {
negativeTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_100))
negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.off)
}
}
private fun toContentDescription(descriptionStringId: Int, statusStringId: Int): String {
return context.getString(descriptionStringId) + ", " + context.getString(statusStringId)
}
init {
View.inflate(context, R.layout.task_form_habit_scoring, this)
gravity = Gravity.CENTER
positiveView.setOnClickListener {
isPositive = !isPositive
sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION)
}
negativeView.setOnClickListener {
isNegative = !isNegative
sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
}
isPositive = true
isNegative = true
}
}
| gpl-3.0 | c43306cf5117f7859c5cf8b9243a2258 | 42.807692 | 132 | 0.719052 | 4.799157 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/RowLayout.kt | 1 | 4993 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2f
import kotlin.math.max
import kotlin.math.round
object RowLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.measure(uiNode, true)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.layout(uiNode, true)
}
}
object ReverseRowLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.measure(uiNode, false)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.layout(uiNode, false)
}
}
private object HorizontalLayout {
fun measure(uiNode: UiNode, isStartToEnd: Boolean) = uiNode.run {
val modWidth = modifier.width
val modHeight = modifier.height
var measuredWidth = 0f
var measuredHeight = 0f
var isDynamicWidth = true
var isDynamicHeight = true
if (modWidth is Dp) {
measuredWidth = modWidth.px
isDynamicWidth = false
}
if (modHeight is Dp) {
measuredHeight = modHeight.px
isDynamicHeight = false
}
if (isDynamicWidth || isDynamicHeight) {
// determine content size based on child sizes
var prevMargin = paddingTopPx
val indices = if (isStartToEnd) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
if (isDynamicWidth) {
measuredWidth += round(child.contentWidthPx) + round(max(prevMargin, child.marginStartPx))
prevMargin = child.marginEndPx
}
if (isDynamicHeight) {
val pTop = max(paddingTopPx, child.marginTopPx)
val pBottom = max(paddingBottomPx, child.marginBottomPx)
measuredHeight = max(measuredHeight, round(child.contentHeightPx + pTop + pBottom))
}
if (i == children.lastIndex && isDynamicWidth) {
measuredWidth += round(max(prevMargin, paddingEndPx))
}
}
if (modWidth is Grow) measuredWidth = modWidth.clampPx(measuredWidth, measuredWidth)
if (modHeight is Grow) measuredHeight = modHeight.clampPx(measuredHeight, measuredHeight)
}
setContentSize(measuredWidth, measuredHeight)
}
fun layout(uiNode: UiNode, isStartToEnd: Boolean) = uiNode.run {
val growSpace = determineAvailableGrowSpace(isStartToEnd)
var x = if (isStartToEnd) leftPx else rightPx
var prevMargin = if (isStartToEnd) paddingStartPx else paddingEndPx
for (i in children.indices) {
val child = children[i]
val growSpaceW = growSpace.x / growSpace.y
val growSpaceH = heightPx - max(paddingTopPx, child.marginTopPx) - max(paddingBottomPx, child.marginBottomPx)
val layoutW = round(child.computeWidthFromDimension(growSpaceW))
val layoutH = round(child.computeHeightFromDimension(growSpaceH))
val layoutY = round(uiNode.computeChildLocationY(child, layoutH))
val cw = child.modifier.width
if (cw is Grow) {
growSpace.x -= layoutW
growSpace.y -= cw.weight
}
val layoutX: Float
if (isStartToEnd) {
x += round(max(prevMargin, child.marginStartPx))
prevMargin = child.marginEndPx
layoutX = round(x)
x += layoutW
} else {
x -= round(max(prevMargin, child.marginEndPx))
prevMargin = child.marginStartPx
x -= layoutW
layoutX = round(x)
}
child.setBounds(layoutX, layoutY, layoutX + layoutW, layoutY + layoutH)
}
}
private fun UiNode.determineAvailableGrowSpace(isStartToEnd: Boolean): MutableVec2f {
var prevMargin = paddingStartPx
var remainingSpace = widthPx
var totalWeight = 0f
val indices = if (isStartToEnd) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
when (val childW = child.modifier.width) {
is Dp -> remainingSpace -= childW.px
is Grow -> totalWeight += childW.weight
FitContent -> remainingSpace -= child.contentWidthPx
}
remainingSpace -= max(prevMargin, child.marginStartPx)
prevMargin = child.marginEndPx
if (i == uiNode.children.lastIndex) {
remainingSpace -= max(prevMargin, uiNode.paddingEndPx)
}
}
if (totalWeight == 0f) totalWeight = 1f
return MutableVec2f(remainingSpace, totalWeight)
}
}
| apache-2.0 | 5f23e036e36fb656ee4b06d53dfa73f0 | 37.114504 | 121 | 0.602243 | 4.627433 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/views/ConfirmDialog.kt | 1 | 2313 | package com.kickstarter.ui.views
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import com.kickstarter.R
import com.kickstarter.databinding.GenericDialogAlertBinding
class ConfirmDialog @JvmOverloads constructor(
context: Context,
val title: String?,
val message: String,
private val buttonText: String? = null
) : AppCompatDialog(context) {
private lateinit var binding: GenericDialogAlertBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
binding = GenericDialogAlertBinding.inflate(layoutInflater)
setContentView(binding.root)
if (title != null) {
setTitleText(title)
} else {
binding.titleTextView.visibility = View.GONE
}
if (buttonText != null) {
setButtonText(buttonText)
} else {
setButtonText(context.getString(R.string.general_alert_buttons_ok))
}
setMessage(message)
binding.okButton.setOnClickListener {
okButtonClick()
}
}
private fun setButtonText(buttonText: String) {
binding.okButton.text = buttonText
}
/**
* Set the title on the TextView with id title_text_view.
* Note, default visibility is GONE since we may not always want a title.
*/
private fun setTitleText(title: String) {
binding.titleTextView.text = title
binding.titleTextView.visibility = TextView.VISIBLE
val params = binding.messageTextView.layoutParams as LinearLayout.LayoutParams
params.topMargin = context.resources.getDimension(R.dimen.grid_1).toInt()
binding.messageTextView.layoutParams = params
}
/**
* Set the message on the TextView with id message_text_view.
*/
private fun setMessage(message: String) {
binding.messageTextView.text = message
}
/**
* Dismiss the dialog on click ok_button".
*/
private fun okButtonClick() {
dismiss()
}
}
| apache-2.0 | 7a5f6a694a402163e6ecad2cac759a8f | 28.278481 | 86 | 0.685257 | 4.849057 | false | false | false | false |
mdaniel/intellij-community | plugins/ide-features-trainer/src/training/ui/LessonMessagePane.kt | 1 | 26269 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.FontPreferences
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.*
import training.FeaturesTrainerIcons
import training.dsl.TaskTextProperties
import training.learn.lesson.LessonManager
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.font.GlyphVector
import java.awt.geom.Point2D
import java.awt.geom.Rectangle2D
import java.awt.geom.RoundRectangle2D
import javax.swing.Icon
import javax.swing.JTextPane
import javax.swing.text.AttributeSet
import javax.swing.text.BadLocationException
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
import kotlin.math.roundToInt
internal class LessonMessagePane(private val panelMode: Boolean = true) : JTextPane(), Disposable {
//Style Attributes for LessonMessagePane(JTextPane)
private val INACTIVE = SimpleAttributeSet()
private val REGULAR = SimpleAttributeSet()
private val BOLD = SimpleAttributeSet()
private val SHORTCUT = SimpleAttributeSet()
private val SHORTCUT_SEPARATOR = SimpleAttributeSet()
private val ROBOTO = SimpleAttributeSet()
private val CODE = SimpleAttributeSet()
private val LINK = SimpleAttributeSet()
private var codeFontSize = UISettings.getInstance().plainFont.size
private val TASK_PARAGRAPH_STYLE = SimpleAttributeSet()
private val INTERNAL_PARAGRAPH_STYLE = SimpleAttributeSet()
private val BALLOON_STYLE = SimpleAttributeSet()
private val textColor: Color = if (panelMode) UISettings.getInstance().defaultTextColor else UISettings.getInstance().tooltipTextColor
private val codeForegroundColor: Color = if (panelMode) UISettings.getInstance().codeForegroundColor else UISettings.getInstance().tooltipTextColor
private val shortcutTextColor = if (panelMode) UISettings.getInstance().shortcutTextColor else UISettings.getInstance().tooltipShortcutTextColor
enum class MessageState { NORMAL, PASSED, INACTIVE, RESTORE, INFORMER }
data class MessageProperties(val state: MessageState = MessageState.NORMAL,
val visualIndex: Int? = null,
val useInternalParagraphStyle: Boolean = false,
val textProperties: TaskTextProperties? = null)
private data class LessonMessage(
val messageParts: List<MessagePart>,
var state: MessageState,
val visualIndex: Int?,
val useInternalParagraphStyle: Boolean,
val textProperties: TaskTextProperties?,
var start: Int = 0,
var end: Int = 0
)
private data class RangeData(var range: IntRange, val action: (Point, Int) -> Unit)
private val activeMessages = mutableListOf<LessonMessage>()
private val restoreMessages = mutableListOf<LessonMessage>()
private val inactiveMessages = mutableListOf<LessonMessage>()
private val fontFamily: String get() = StartupUiUtil.getLabelFont().fontName
private val ranges = mutableSetOf<RangeData>()
private var insertOffset: Int = 0
private var paragraphStyle = SimpleAttributeSet()
private fun allLessonMessages() = activeMessages + restoreMessages + inactiveMessages
var currentAnimation = 0
var totalAnimation = 0
//, fontFace, check_width + check_right_indent
init {
UIUtil.doNotScrollToCaret(this)
initStyleConstants()
isEditable = false
val listener = object : MouseAdapter() {
override fun mouseClicked(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me) ?: return
val middle = (rangeData.range.first + rangeData.range.last) / 2
val rectangle = modelToView2D(middle)
rangeData.action(Point(rectangle.x.roundToInt(), (rectangle.y.roundToInt() + rectangle.height.roundToInt() / 2)),
rectangle.height.roundToInt())
}
override fun mouseMoved(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me)
cursor = if (rangeData == null) {
Cursor.getDefaultCursor()
}
else {
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
}
}
addMouseListener(listener)
addMouseMotionListener(listener)
val connect = ApplicationManager.getApplication().messageBus.connect(this)
connect.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
redrawMessages()
}
override fun shortcutChanged(keymap: Keymap, actionId: String) {
redrawMessages()
}
})
}
override fun dispose() = Unit
private fun getRangeDataForMouse(me: MouseEvent): RangeData? {
val offset = viewToModel2D(Point2D.Double(me.x.toDouble(), me.y.toDouble()))
val result = ranges.find { offset in it.range } ?: return null
if (offset < 0 || offset >= document.length) return null
for (i in result.range) {
val rectangle = modelToView2D(i)
if (me.x >= rectangle.x && me.y >= rectangle.y && me.y <= rectangle.y + rectangle.height) {
return result
}
}
return null
}
override fun addNotify() {
super.addNotify()
initStyleConstants()
redrawMessages()
}
override fun updateUI() {
super.updateUI()
ApplicationManager.getApplication().invokeLater(Runnable {
initStyleConstants()
redrawMessages()
})
}
private fun initStyleConstants() {
val fontSize = UISettings.getInstance().plainFont.size
StyleConstants.setForeground(INACTIVE, UISettings.getInstance().inactiveColor)
StyleConstants.setFontFamily(REGULAR, fontFamily)
StyleConstants.setFontSize(REGULAR, fontSize)
StyleConstants.setFontFamily(BOLD, fontFamily)
StyleConstants.setFontSize(BOLD, fontSize)
StyleConstants.setBold(BOLD, true)
StyleConstants.setFontFamily(SHORTCUT, fontFamily)
StyleConstants.setFontSize(SHORTCUT, fontSize)
StyleConstants.setBold(SHORTCUT, true)
StyleConstants.setFontFamily(SHORTCUT_SEPARATOR, fontFamily)
StyleConstants.setFontSize(SHORTCUT_SEPARATOR, fontSize)
EditorColorsManager.getInstance().globalScheme.editorFontName
StyleConstants.setFontFamily(CODE, EditorColorsManager.getInstance().globalScheme.editorFontName)
StyleConstants.setFontSize(CODE, codeFontSize)
StyleConstants.setFontFamily(LINK, fontFamily)
StyleConstants.setUnderline(LINK, true)
StyleConstants.setFontSize(LINK, fontSize)
StyleConstants.setSpaceAbove(TASK_PARAGRAPH_STYLE, UISettings.getInstance().taskParagraphAbove.toFloat())
setCommonParagraphAttributes(TASK_PARAGRAPH_STYLE)
StyleConstants.setSpaceAbove(INTERNAL_PARAGRAPH_STYLE, UISettings.getInstance().taskInternalParagraphAbove.toFloat())
setCommonParagraphAttributes(INTERNAL_PARAGRAPH_STYLE)
StyleConstants.setLineSpacing(BALLOON_STYLE, 0.2f)
StyleConstants.setLeftIndent(BALLOON_STYLE, UISettings.getInstance().balloonIndent.toFloat())
StyleConstants.setForeground(REGULAR, textColor)
StyleConstants.setForeground(BOLD, textColor)
StyleConstants.setForeground(SHORTCUT, shortcutTextColor)
StyleConstants.setForeground(SHORTCUT_SEPARATOR, UISettings.getInstance().shortcutSeparatorColor)
StyleConstants.setForeground(LINK, UISettings.getInstance().lessonLinkColor)
StyleConstants.setForeground(CODE, codeForegroundColor)
}
private fun setCommonParagraphAttributes(attributeSet: SimpleAttributeSet) {
StyleConstants.setLeftIndent(attributeSet, UISettings.getInstance().checkIndent.toFloat())
StyleConstants.setRightIndent(attributeSet, 0f)
StyleConstants.setSpaceBelow(attributeSet, 0.0f)
StyleConstants.setLineSpacing(attributeSet, 0.2f)
}
fun messagesNumber(): Int = activeMessages.size
@Suppress("SameParameterValue")
private fun removeMessagesRange(startIdx: Int, endIdx: Int, list: MutableList<LessonMessage>) {
if (startIdx == endIdx) return
list.subList(startIdx, endIdx).clear()
}
fun clearRestoreMessages(): () -> Rectangle? {
removeMessagesRange(0, restoreMessages.size, restoreMessages)
redrawMessages()
val lastOrNull = activeMessages.lastOrNull()
return { lastOrNull?.let { getRectangleToScroll(it) } }
}
fun removeInactiveMessages(number: Int) {
removeMessagesRange(0, number, inactiveMessages)
redrawMessages()
}
fun resetMessagesNumber(number: Int): () -> Rectangle? {
val move = activeMessages.subList(number, activeMessages.size)
move.forEach {
it.state = MessageState.INACTIVE
}
inactiveMessages.addAll(0, move)
move.clear()
return clearRestoreMessages()
}
fun getCurrentMessageRectangle(): Rectangle? {
val lessonMessage = restoreMessages.lastOrNull() ?: activeMessages.lastOrNull() ?: return null
return getRectangleToScroll(lessonMessage)
}
private fun insertText(text: String, attributeSet: AttributeSet) {
document.insertString(insertOffset, text, attributeSet)
styledDocument.setParagraphAttributes(insertOffset, text.length - 1, paragraphStyle, true)
insertOffset += text.length
}
private fun insertIconWithFixedHeight(iconIdx: String, state: MessageState, getFixedHeight: (Icon) -> Int) {
val original = LearningUiManager.iconMap[iconIdx] ?: error("Not found icon with index: $iconIdx")
val icon = if (state == MessageState.INACTIVE) getInactiveIcon(original) else original
insertIcon(object : Icon {
override fun getIconWidth() = icon.iconWidth
override fun getIconHeight() = getFixedHeight(icon)
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
icon.paintIcon(c, g, x, y)
}
})
insertOffset++
}
fun addMessage(messageParts: List<MessagePart>, properties: MessageProperties = MessageProperties()): () -> Rectangle? {
val lessonMessage = LessonMessage(messageParts,
properties.state,
properties.visualIndex,
properties.useInternalParagraphStyle,
properties.textProperties,
)
when (properties.state) {
MessageState.INACTIVE -> inactiveMessages
MessageState.RESTORE -> restoreMessages
else -> activeMessages
}.add(lessonMessage)
redrawMessages()
return { getRectangleToScroll(lessonMessage) }
}
fun removeMessage(index: Int) {
activeMessages.removeAt(index)
}
private fun getRectangleToScroll(lessonMessage: LessonMessage): Rectangle? {
val startRect = modelToView2D(lessonMessage.start + 1)?.toRectangle() ?: return null
val endRect = modelToView2D(lessonMessage.end - 1)?.toRectangle() ?: return null
return Rectangle(startRect.x, startRect.y - activeTaskInset, endRect.x + endRect.width - startRect.x,
endRect.y + endRect.height - startRect.y + activeTaskInset * 2)
}
fun redrawMessages() {
initStyleConstants()
ranges.clear()
highlighter.removeAllHighlights()
text = ""
insertOffset = 0
var previous: LessonMessage? = null
for (lessonMessage in allLessonMessages()) {
if (previous?.messageParts?.firstOrNull()?.type != MessagePart.MessageType.ILLUSTRATION) {
val textProperties = previous?.textProperties
paragraphStyle = when {
textProperties != null -> {
val customStyle = SimpleAttributeSet()
setCommonParagraphAttributes(customStyle)
StyleConstants.setSpaceAbove(customStyle, textProperties.spaceAbove.toFloat())
StyleConstants.setSpaceBelow(customStyle, textProperties.spaceBelow.toFloat())
customStyle
}
previous?.useInternalParagraphStyle == true -> INTERNAL_PARAGRAPH_STYLE
panelMode -> TASK_PARAGRAPH_STYLE
else -> BALLOON_STYLE
}
}
val messageParts: List<MessagePart> = lessonMessage.messageParts
lessonMessage.start = insertOffset
if (insertOffset != 0)
insertText("\n", paragraphStyle)
for (part in messageParts) {
part.updateTextAndSplit()
val startOffset = insertOffset
part.startOffset = startOffset
when (part.type) {
MessagePart.MessageType.TEXT_REGULAR -> insertText(part.text, REGULAR)
MessagePart.MessageType.TEXT_BOLD -> insertText(part.text, BOLD)
MessagePart.MessageType.SHORTCUT -> {
val start = insertOffset
appendShortcut(part)?.let { ranges.add(it) }
val end = insertOffset
highlighter.addHighlight(start, end) { g, _, _, _, _ ->
val bg = if (panelMode) UISettings.getInstance().shortcutBackgroundColor else UISettings.getInstance().tooltipShortcutBackgroundColor
val needColor = if (lessonMessage.state == MessageState.INACTIVE) Color(bg.red, bg.green, bg.blue, 255 * 3 / 10) else bg
for (p in part.splitMe()) {
drawRectangleAroundText(p.startOffset, p.endOffset, g as Graphics2D, needColor, fill = true)
}
}
}
MessagePart.MessageType.CODE -> {
val start = insertOffset
insertText(part.text, CODE)
val end = insertOffset
highlighter.addHighlight(start, end) { g, _, _, _, _ ->
val needColor = UISettings.getInstance().codeBorderColor
drawRectangleAroundText(start, end, g, needColor, fill = !panelMode)
}
}
MessagePart.MessageType.CHECK -> insertText(part.text, ROBOTO)
MessagePart.MessageType.LINK -> appendLink(part)?.let { ranges.add(it) }
MessagePart.MessageType.ICON_IDX -> {
insertIconWithFixedHeight(part.text, lessonMessage.state) {
// substitute fake height to place icon little lower
getFontMetrics([email protected]).ascent
}
}
MessagePart.MessageType.PROPOSE_RESTORE -> insertText(part.text, BOLD)
MessagePart.MessageType.ILLUSTRATION -> {
insertIconWithFixedHeight(part.text, lessonMessage.state) { icon ->
// reduce the icon height by the line height, because otherwise there will be extra space below the icon
icon.iconHeight - getFontMetrics([email protected]).height
}
paragraphStyle = INTERNAL_PARAGRAPH_STYLE
}
MessagePart.MessageType.LINE_BREAK -> {
insertText("\n", REGULAR)
paragraphStyle = INTERNAL_PARAGRAPH_STYLE
}
}
part.endOffset = insertOffset
}
lessonMessage.end = insertOffset
if (lessonMessage.state == MessageState.INACTIVE) {
setInactiveStyle(lessonMessage)
}
previous = lessonMessage
}
}
fun passPreviousMessages() {
for (message in activeMessages) {
message.state = MessageState.PASSED
}
redrawMessages()
}
private fun setInactiveStyle(lessonMessage: LessonMessage) {
styledDocument.setCharacterAttributes(lessonMessage.start, lessonMessage.end, INACTIVE, false)
}
fun clear() {
text = ""
activeMessages.clear()
restoreMessages.clear()
inactiveMessages.clear()
ranges.clear()
}
/**
* Appends link inside JTextPane to Run another lesson
* @param messagePart - should have LINK type. message.runnable starts when the message has been clicked.
*/
@Throws(BadLocationException::class)
private fun appendLink(messagePart: MessagePart): RangeData? {
val clickRange = appendClickableRange(messagePart.text, LINK)
val runnable = messagePart.runnable ?: return null
return RangeData(clickRange) { _, _ -> runnable.run() }
}
private fun appendShortcut(messagePart: MessagePart): RangeData? {
val split = messagePart.split
val range = if (split != null) {
var start = 0
val startRange = insertOffset
for (part in split) {
appendClickableRange(messagePart.text.substring(start, part.first), SHORTCUT_SEPARATOR)
appendClickableRange(messagePart.text.substring(part.first, part.last + 1), SHORTCUT)
start = part.last + 1
}
appendClickableRange(messagePart.text.substring(start), SHORTCUT_SEPARATOR)
startRange .. insertOffset
} else {
appendClickableRange(messagePart.text, SHORTCUT)
}
val actionId = messagePart.link ?: return null
val clickRange = IntRange(range.first + 1, range.last - 1) // exclude around spaces
return RangeData(clickRange) { p, h -> showShortcutBalloon(p, h, actionId) }
}
private fun showShortcutBalloon(point: Point2D, height: Int, actionName: String?) {
if (actionName == null) return
showActionKeyPopup(this, point.toPoint(), height, actionName)
}
private fun appendClickableRange(clickable: String, attributeSet: SimpleAttributeSet): IntRange {
if (clickable.isEmpty()) return insertOffset .. insertOffset
val startLink = insertOffset
insertText(clickable, attributeSet)
val endLink = insertOffset
return startLink..endLink
}
override fun paintComponent(g: Graphics) {
adjustCodeFontSize(g)
try {
highlightActiveMessage(g)
}
catch (e: BadLocationException) {
LOG.warn(e)
}
super.paintComponent(g)
paintLessonCheckmarks(g)
drawTaskNumbers(g)
}
private fun adjustCodeFontSize(g: Graphics) {
val fontSize = StyleConstants.getFontSize(CODE)
val labelFont = UISettings.getInstance().plainFont
val (numberFont, _, _) = getNumbersFont(labelFont, g)
if (numberFont.size != fontSize) {
StyleConstants.setFontSize(CODE, numberFont.size)
codeFontSize = numberFont.size
redrawMessages()
}
}
private fun paintLessonCheckmarks(g: Graphics) {
val plainFont = UISettings.getInstance().plainFont
val fontMetrics = g.getFontMetrics(plainFont)
val height = if (g is Graphics2D) letterHeight(plainFont, g, "A") else fontMetrics.height
val baseLineOffset = fontMetrics.ascent + fontMetrics.leading
for (lessonMessage in allLessonMessages()) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val rectangle = modelToView2D(startOffset).toRectangle()
if (lessonMessage.messageParts.singleOrNull()?.type == MessagePart.MessageType.ILLUSTRATION) {
continue
}
val icon = if (lessonMessage.state == MessageState.PASSED) {
FeaturesTrainerIcons.Img.GreenCheckmark
}
else if (!LessonManager.instance.lessonIsRunning()) {
AllIcons.General.Information
}
else continue
val xShift = icon.iconWidth + UISettings.getInstance().numberTaskIndent
val y = rectangle.y + baseLineOffset - (height + icon.iconHeight + 1) / 2
icon.paintIcon(this, g, rectangle.x - xShift, y)
}
}
private data class FontSearchResult(val numberFont: Font, val numberHeight: Int, val textLetterHeight: Int)
private fun drawTaskNumbers(g: Graphics) {
val oldFont = g.font
val labelFont = UISettings.getInstance().plainFont
val (numberFont, numberHeight, textLetterHeight) = getNumbersFont(labelFont, g)
val textFontMetrics = g.getFontMetrics(labelFont)
val baseLineOffset = textFontMetrics.ascent + textFontMetrics.leading
g.font = numberFont
fun paintNumber(lessonMessage: LessonMessage, color: Color) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val s = lessonMessage.visualIndex?.toString()?.padStart(2, '0') ?: return
val width = textFontMetrics.stringWidth(s)
val modelToView2D = modelToView2D(startOffset)
val rectangle = modelToView2D.toRectangle()
val xOffset = rectangle.x - (width + UISettings.getInstance().numberTaskIndent)
val baseLineY = rectangle.y + baseLineOffset
val yOffset = baseLineY + (numberHeight - textLetterHeight)
val backupColor = g.color
g.color = color
GraphicsUtil.setupAAPainting(g)
g.drawString(s, xOffset, yOffset)
g.color = backupColor
}
for (lessonMessage in inactiveMessages) {
paintNumber(lessonMessage, UISettings.getInstance().futureTaskNumberColor)
}
if (activeMessages.lastOrNull()?.state != MessageState.PASSED || !panelMode) { // lesson can be opened as passed
val firstActiveMessage = firstActiveMessage()
if (firstActiveMessage != null) {
val color = if (panelMode) UISettings.getInstance().activeTaskNumberColor else UISettings.getInstance().tooltipTaskNumberColor
paintNumber(firstActiveMessage, color)
}
}
g.font = oldFont
}
private fun getNumbersFont(textFont: Font, g: Graphics): FontSearchResult {
val style = Font.PLAIN
val monoFontName = FontPreferences.DEFAULT_FONT_NAME
if (g is Graphics2D) {
val textHeight = letterHeight(textFont, g, "A")
var size = textFont.size
var numberHeight = 0
lateinit var numberFont: Font
fun calculateHeight(): Int {
numberFont = Font(monoFontName, style, size)
numberHeight = letterHeight(numberFont, g, "0")
return numberHeight
}
calculateHeight()
if (numberHeight > textHeight) {
size--
while (calculateHeight() >= textHeight) {
size--
}
size++
calculateHeight()
}
else if (numberHeight < textHeight) {
size++
while (calculateHeight() < textHeight) {
size++
}
}
return FontSearchResult(numberFont, numberHeight, textHeight)
}
return FontSearchResult(Font(monoFontName, style, textFont.size), 0, 0)
}
private fun letterHeight(font: Font, g: Graphics2D, str: String): Int {
val gv: GlyphVector = font.createGlyphVector(g.fontRenderContext, str)
return gv.getGlyphMetrics(0).bounds2D.height.roundToInt()
}
@Throws(BadLocationException::class)
private fun highlightActiveMessage(g: Graphics) {
val g2d = g as Graphics2D
val lastActiveMessage = activeMessages.lastOrNull()
val firstActiveMessage = firstActiveMessage()
if (panelMode && lastActiveMessage != null && lastActiveMessage.state == MessageState.NORMAL) {
val c = UISettings.getInstance().activeTaskBorder
val a = if (totalAnimation == 0) 255 else 255 * currentAnimation / totalAnimation
val needColor = Color(c.red, c.green, c.blue, a)
drawRectangleAroundMessage(firstActiveMessage, lastActiveMessage, g2d, needColor)
}
}
private fun getInactiveIcon(icon: Icon) = WatermarkIcon(icon, UISettings.getInstance().transparencyInactiveFactor.toFloat())
private fun firstActiveMessage(): LessonMessage? = activeMessages.indexOfLast { it.state == MessageState.PASSED }
.takeIf { it != -1 && it < activeMessages.size - 1 }
?.let { activeMessages[it + 1] } ?: activeMessages.firstOrNull()
private fun drawRectangleAroundText(startOffset: Int,
endOffset: Int,
g: Graphics,
needColor: Color,
fill: Boolean) {
val g2d = g as Graphics2D
val rectangleStart = modelToView2D(startOffset)
val rectangleEnd = modelToView2D(endOffset)
val color = g2d.color
val fontSize = UISettings.getInstance().fontSize
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val shift = if (SystemInfo.isMac) 1f else 2f
val r2d = RoundRectangle2D.Double(rectangleStart.x - 2 * indent, rectangleStart.y - indent + JBUIScale.scale(shift),
rectangleEnd.x - rectangleStart.x + 4 * indent, (fontSize + 2 * indent).toDouble(),
arc.toDouble(), arc.toDouble())
if (fill) g2d.fill(r2d) else g2d.draw(r2d)
g2d.color = color
}
private fun drawRectangleAroundMessage(lastPassedMessage: LessonMessage? = null,
lastActiveMessage: LessonMessage,
g2d: Graphics2D,
needColor: Color) {
val startOffset = lastPassedMessage?.let { if (it.start == 0) 0 else it.start + 1 } ?: 0
val endOffset = lastActiveMessage.end
val topLineY = modelToView2D(startOffset).y
val bottomLineY = modelToView2D(endOffset - 1).let { it.y + it.height }
val textHeight = bottomLineY - topLineY
val color = g2d.color
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val xOffset = JBUI.scale(2).toDouble()
val yOffset = topLineY - activeTaskInset
val width = this.bounds.width - 2*xOffset - JBUIScale.scale(2) // 1 + 1 line width
val height = textHeight + 2 * activeTaskInset - JBUIScale.scale(2) + (lastActiveMessage.textProperties?.spaceBelow ?: 0)
g2d.draw(RoundRectangle2D.Double(xOffset, yOffset, width, height, arc.toDouble(), arc.toDouble()))
g2d.color = color
}
override fun getMaximumSize(): Dimension {
return preferredSize
}
companion object {
private val LOG = Logger.getInstance(LessonMessagePane::class.java)
//arc & indent for shortcut back plate
private val arc by lazy { JBUI.scale(4) }
private val indent by lazy { JBUI.scale(2) }
private val activeTaskInset by lazy { JBUI.scale(12) }
private fun Point2D.toPoint(): Point {
return Point(x.roundToInt(), y.roundToInt())
}
private fun Rectangle2D.toRectangle(): Rectangle {
return Rectangle(x.roundToInt(), y.roundToInt(), width.roundToInt(), height.roundToInt())
}
}
}
| apache-2.0 | 88b3685cd22550c2fed4f750ce931efc | 38.621418 | 149 | 0.690548 | 4.527577 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/activity/BookmarkActivityViewModel.kt | 1 | 2567 | /*
* Copyright (c) 2017. 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.hbfavmaterial.viewmodel.activity
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.ObservableField
import android.view.View
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.application.HatenaService
class BookmarkActivityViewModel(private val hatenaService: HatenaService) : ViewModel() {
val entryTitle: ObservableField<String> = ObservableField()
val entryLink: ObservableField<String> = ObservableField()
private var showBookmarkEditEventSubject = PublishSubject.create<Unit>()
val showBookmarkEditEvent: Observable<Unit> = showBookmarkEditEventSubject
private var unauthorisedEventSubject = PublishSubject.create<Unit>()
val unauthorisedEvent: Observable<Unit> = unauthorisedEventSubject
private val disposable = CompositeDisposable()
init {
disposable.addAll(hatenaService.confirmAuthorisedEvent.subscribe {
if (it) {
showBookmarkEditEventSubject.onNext(Unit)
} else {
unauthorisedEventSubject.onNext(Unit)
}
})
}
override fun onCleared() {
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onClickFab(view: View) {
hatenaService.confirmAuthorised()
}
fun onAuthoriseHatena() {
hatenaService.confirmAuthorised()
}
class Factory(private val hatenaService: HatenaService) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(BookmarkActivityViewModel::class.java)) {
return BookmarkActivityViewModel(hatenaService) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 | a7c4fb744307a675c0316e754d926437 | 34.652778 | 112 | 0.721075 | 4.780261 | false | false | false | false |
kivensolo/UiUsingListView | app-Kotlin-Coroutines-Examples/src/main/java/com/kingz/coroutines/learn/errorhandling/exceptionhandler/ExceptionHandlerActivity.kt | 1 | 3150 | package com.kingz.coroutines.learn.errorhandling.exceptionhandler
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingz.base.response.Status
import com.kingz.coroutines.data.api.ApiHelperImpl
import com.kingz.coroutines.data.api.RetrofitBuilder
import com.kingz.coroutines.data.local.DatabaseBuilder
import com.kingz.coroutines.data.local.DatabaseHelperImpl
import com.kingz.coroutines.data.model.ApiUser
import com.kingz.coroutines.learn.base.ApiUserAdapter
import com.kingz.coroutines.utils.ViewModelFactory
import com.zeke.example.coroutines.R
import kotlinx.android.synthetic.main.activity_recycler_view.*
/**
* Learn how to handle error in Kotlin Coroutines using CoroutineExceptionHandler.
*/
class ExceptionHandlerActivity : AppCompatActivity() {
private lateinit var viewModel: ExceptionHandlerViewModel
private lateinit var adapter: ApiUserAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
setupUI()
setupViewModel()
setupObserver()
}
private fun setupUI() {
recyclerView.layoutManager = LinearLayoutManager(this)
adapter =
ApiUserAdapter(
arrayListOf()
)
recyclerView.addItemDecoration(
DividerItemDecoration(
recyclerView.context,
(recyclerView.layoutManager as LinearLayoutManager).orientation
)
)
recyclerView.adapter = adapter
}
private fun setupObserver() {
viewModel.getUsers().observe(this, Observer {
when (it.status) {
Status.SUCCESS -> {
progressBar.visibility = View.GONE
it.data?.let { users -> renderList(users) }
recyclerView.visibility = View.VISIBLE
}
Status.LOADING -> {
progressBar.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
}
Status.ERROR -> {
//Handle Error
progressBar.visibility = View.GONE
Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
}
}
})
}
private fun renderList(users: List<ApiUser>) {
adapter.addData(users)
adapter.notifyDataSetChanged()
}
private fun setupViewModel() {
viewModel = ViewModelProvider(
this,
ViewModelFactory.build {
ExceptionHandlerViewModel(
ApiHelperImpl(RetrofitBuilder.USER_SERVICE_API),
DatabaseHelperImpl(DatabaseBuilder.getInstance(applicationContext))
)
}
).get(ExceptionHandlerViewModel::class.java)
}
}
| gpl-2.0 | d71bf49beaeb17bd82239544ee5497bc | 33.615385 | 87 | 0.651746 | 5.403087 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt | 1 | 2062 | // 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.vfilefinder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import java.io.FileNotFoundException
import java.io.InputStream
class IDEVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFinder() {
override fun findMetadata(classId: ClassId): InputStream? {
val file = findVirtualFileWithHeader(classId.asSingleFqName(), KotlinMetadataFileIndex.KEY) ?: return null
return try {
file.inputStream
} catch (e: FileNotFoundException) {
null
}
}
override fun hasMetadataPackage(fqName: FqName): Boolean = KotlinMetadataFilePackageIndex.hasSomethingInPackage(fqName, scope)
override fun findBuiltInsData(packageFqName: FqName): InputStream? =
findVirtualFileWithHeader(packageFqName, KotlinBuiltInsMetadataIndex.KEY)?.inputStream
override fun findSourceOrBinaryVirtualFile(classId: ClassId) = findVirtualFileWithHeader(classId)
init {
if (scope != GlobalSearchScope.EMPTY_SCOPE && scope.project == null) {
LOG.warn("Scope with null project $scope")
}
}
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? =
findVirtualFileWithHeader(classId.asSingleFqName(), KotlinClassFileIndex.KEY)
private fun findVirtualFileWithHeader(fqName: FqName, key: ID<FqName, Void>): VirtualFile? =
FileBasedIndex.getInstance().getContainingFiles(key, fqName, scope).firstOrNull()
companion object {
private val LOG = Logger.getInstance(IDEVirtualFileFinder::class.java)
}
}
| apache-2.0 | 62848b15bcfb5417e827036524eb6e66 | 41.081633 | 158 | 0.758002 | 4.851765 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/security/sheets/NoPincodeBottomSheet.kt | 1 | 2649 | package com.maubis.scarlet.base.security.sheets
import android.app.Dialog
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.widget.Text
import com.facebook.yoga.YogaEdge
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface
import com.maubis.scarlet.base.support.sheets.LithoBottomSheet
import com.maubis.scarlet.base.support.sheets.getLithoBottomSheetTitle
import com.maubis.scarlet.base.support.specs.BottomSheetBar
import com.maubis.scarlet.base.support.ui.ThemeColorType
import com.maubis.scarlet.base.support.ui.ThemedActivity
const val STORE_KEY_NO_PIN_ASK = "KEY_NO_PIN_ASK"
var sNoPinSetupNoticeShown: Boolean
get() = sAppPreferences.get(STORE_KEY_NO_PIN_ASK, false)
set(value) = sAppPreferences.put(STORE_KEY_NO_PIN_ASK, value)
class NoPincodeBottomSheet : LithoBottomSheet() {
var onSuccess: () -> Unit = {}
override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component {
val activity = context as ThemedActivity
val component = Column.create(componentContext)
.widthPercent(100f)
.paddingDip(YogaEdge.VERTICAL, 8f)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.child(
getLithoBottomSheetTitle(componentContext)
.textRes(R.string.no_pincode_sheet_title)
.marginDip(YogaEdge.HORIZONTAL, 0f))
.child(
Text.create(componentContext)
.typeface(sAppTypeface.text())
.textSizeRes(R.dimen.font_size_large)
.textRes(R.string.no_pincode_sheet_details)
.marginDip(YogaEdge.BOTTOM, 16f)
.textColor(sAppTheme.get(ThemeColorType.TERTIARY_TEXT)))
.child(BottomSheetBar.create(componentContext)
.primaryActionRes(R.string.no_pincode_sheet_set_up)
.onPrimaryClick {
openCreateSheet(
activity = activity,
onCreateSuccess = {})
dismiss()
}
.secondaryActionRes(R.string.no_pincode_sheet_dont_ask)
.onSecondaryClick {
onSuccess()
dismiss()
}
.tertiaryActionRes(R.string.no_pincode_sheet_not_now)
.onTertiaryClick {
onSuccess()
dismiss()
}
.paddingDip(YogaEdge.VERTICAL, 8f))
return component.build()
}
}
| gpl-3.0 | c63f93368bfb63b37aed1c62e67a483f | 39.753846 | 92 | 0.682899 | 4.119751 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/AccountMembership.kt | 2 | 905 | package com.github.kerubistan.kerub.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import org.hibernate.search.annotations.Analyze
import org.hibernate.search.annotations.DocumentId
import org.hibernate.search.annotations.Field
import org.hibernate.search.annotations.Index
import org.hibernate.search.annotations.Indexed
import org.hibernate.search.annotations.Store
import java.util.UUID
@Indexed
@JsonTypeName("account-membership")
data class AccountMembership(
@Field(analyze = Analyze.NO)
override val user: String,
@Field(analyze = Analyze.NO)
override val groupId: UUID,
override val quota: Quota? = null,
@DocumentId
override val id: UUID = UUID.randomUUID()
) : GroupMembership {
val groupIdStr: String
@Field(store = Store.YES, index = Index.YES, analyze = Analyze.NO)
@JsonIgnore
get() = groupId.toString()
} | apache-2.0 | 1c3d2cfe8bfbf3f84e219966034f7977 | 31.357143 | 68 | 0.792265 | 3.770833 | false | false | false | false |
jwren/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessaryModifierInspection.kt | 3 | 1737 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.codeInspection.style
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.elementType
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrModifierFix
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrModifierListImpl
abstract class GrUnnecessaryModifierInspection(@GrModifier.GrModifierConstant val modifier: String) : LocalInspectionTool(), CleanupLocalInspectionTool {
private fun getFix(): GrModifierFix {
return GrRemoveModifierFix(modifier)
}
private val requiredElementType = GrModifierListImpl.NAME_TO_MODIFIER_ELEMENT_TYPE[modifier]!!
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.elementType === requiredElementType && isRedundant(element)) {
holder.registerProblem(
element,
GroovyBundle.message("unnecessary.modifier.description", modifier),
getFix()
)
}
}
}
/**
* [element] has element type that corresponds to [modifier]
*/
abstract fun isRedundant(element: PsiElement): Boolean
} | apache-2.0 | 190571eb7356a13801d97dfe82ac58bf | 43.564103 | 153 | 0.791019 | 4.948718 | false | false | false | false |
youdonghai/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrReferenceResolveRunner.kt | 1 | 7021 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTraitType
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
class GrReferenceResolveRunner(val place: GrReferenceExpression, val processor: PsiScopeProcessor) {
fun resolveReferenceExpression(): Boolean {
val processNonCode = PsiTreeUtil.skipParentsOfType(
place, GrReferenceExpression::class.java, GrAnnotationArrayInitializer::class.java
) !is GrAnnotationNameValuePair
val initialState = initialState(processNonCode)
val qualifier = place.qualifier
if (qualifier == null) {
if (!treeWalkUp(place, processor, initialState)) return false
if (!processNonCode) return true
if (place.context is GrMethodCall && !ClosureMissingMethodContributor.processMethodsFromClosures(place, processor)) return false
}
else {
if (place.dotTokenType === GroovyTokenTypes.mSPREAD_DOT) {
val qType = qualifier.type
val componentType = ClosureParameterEnhancer.findTypeForIteration(qType, place)
if (componentType != null) {
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier).put(SpreadState.SPREAD_STATE, SpreadState.create(qType, null))
return processQualifierType(componentType, state)
}
}
else {
if (ResolveUtil.isClassReference(place)) return false
if (!processJavaLangClass(qualifier, initialState)) return false
if (!processQualifier(qualifier, initialState)) return false
}
}
return true
}
private fun processJavaLangClass(qualifier: GrExpression, initialState: ResolveState): Boolean {
if (qualifier !is GrReferenceExpression) return true
//optimization: only 'class' or 'this' in static context can be an alias of java.lang.Class
if ("class" != qualifier.referenceName && !PsiUtil.isThisReference(qualifier) && qualifier.resolve() !is PsiClass) return true
val classType = ResolveUtil.unwrapClassType(qualifier.getType())
return classType?.let {
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier)
processQualifierType(classType, state)
} ?: true
}
private fun processQualifier(qualifier: GrExpression, initialState: ResolveState): Boolean {
val qualifierType = qualifier.type
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier)
if (qualifierType == null || PsiType.VOID == qualifierType) {
if (qualifier is GrReferenceExpression) {
val resolved = qualifier.resolve()
if (resolved is PsiClass) {
if (!ResolveUtil.processClassDeclarations((resolved as PsiClass?)!!, processor, state, null, place)) return false
}
else if (resolved != null && !resolved.processDeclarations(processor, state, null, place)) return false
if (resolved !is PsiPackage) {
val objectQualifier = TypesUtil.getJavaLangObject(place)
if (!processQualifierType(objectQualifier, state)) return false
}
}
}
else {
if (!processQualifierType(qualifierType, state)) return false
}
return true
}
private fun processQualifierType(qualifierType: PsiType, state: ResolveState): Boolean {
val type = (qualifierType as? PsiDisjunctionType)?.leastUpperBound ?: qualifierType
return doProcessQualifierType(type, state)
}
private fun doProcessQualifierType(qualifierType: PsiType, state: ResolveState): Boolean {
if (qualifierType is PsiIntersectionType) {
return qualifierType.conjuncts.find { !processQualifierType(it, state) } == null
}
if (qualifierType is PsiCapturedWildcardType) {
val wildcard = qualifierType.wildcard
if (wildcard.isExtends) {
return processQualifierType(wildcard.extendsBound, state)
}
}
// Process trait type conjuncts in reversed order because last applied trait matters.
if (qualifierType is GrTraitType) return qualifierType.conjuncts.findLast { !processQualifierType(it, state) } == null
if (qualifierType is PsiClassType) {
val qualifierResult = qualifierType.resolveGenerics()
qualifierResult.element?.let {
val resolveState = state.put(PsiSubstitutor.KEY, qualifierResult.substitutor)
if (!ResolveUtil.processClassDeclarations(it, processor, resolveState, null, place)) return false
}
}
else if (qualifierType is PsiArrayType) {
GroovyPsiManager.getInstance(place.project).getArrayClass(qualifierType.componentType)?.let {
if (!ResolveUtil.processClassDeclarations(it, processor, state, null, place)) return false
}
}
if (place.parent !is GrMethodCall && InheritanceUtil.isInheritor(qualifierType, CommonClassNames.JAVA_UTIL_COLLECTION)) {
ClosureParameterEnhancer.findTypeForIteration(qualifierType, place)?.let {
val spreadState = state.get(SpreadState.SPREAD_STATE)
val resolveState = state.put(SpreadState.SPREAD_STATE, SpreadState.create(qualifierType, spreadState))
if (!processQualifierType(it, resolveState)) return false
}
}
if (state.processNonCodeMembers()) {
if (!ResolveUtil.processCategoryMembers(place, processor, state)) return false
if (!ResolveUtil.processNonCodeMembers(qualifierType, processor, place, state)) return false
}
return true
}
}
| apache-2.0 | 38ef13ce8b445684de124ed617d7772a | 46.120805 | 139 | 0.74676 | 4.640449 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/misc/utilies/PausableTimer.kt | 1 | 2008 | package taiwan.no1.app.ssfm.misc.utilies
import android.os.CountDownTimer
/**
* Countdown timer with the pause function.
*
* @author jieyi
* @since 7/23/17
*/
class PausableTimer(private val millisInFuture: Long = -1,
private val countDownInterval: Long = 1000) {
var onTick: (millisUntilFinished: Long) -> Unit = {}
var onFinish: () -> Unit = {}
var isPause = false
var isStart = false
var curTime = 0L
lateinit private var timer: CountDownTimer
init {
val millisTime = if (-1L == millisInFuture) Long.MAX_VALUE else millisInFuture
init(millisTime, countDownInterval)
}
fun pause(): Long {
isPause = true
stop()
return curTime
}
fun resume() {
val time = if (isPause && 0 <= curTime) {
isPause = false
curTime
}
else {
millisInFuture
}
stop()
init(time, countDownInterval)
start()
}
fun start() {
if (!isStart && !isPause) {
if (0L == curTime) {
init(millisInFuture, countDownInterval)
}
timer.start()
isStart = true
}
else if (isPause) {
resume()
}
}
fun stop() {
timer.cancel()
isStart = false
}
private fun init(millisInFuture: Long, countDownInterval: Long) {
timer = object : CountDownTimer(millisInFuture, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
// OPTIMIZE(jieyi): 9/29/17
// val time = (Math.round(millisUntilFinished.toDouble() / 1000) - 1).toInt()
[email protected] = millisUntilFinished
[email protected](millisUntilFinished)
}
override fun onFinish() {
[email protected] = 0
[email protected]()
}
}
}
} | apache-2.0 | 8c9dae2e785bf28cd0a6890af5dabbde | 24.43038 | 93 | 0.539841 | 4.462222 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/maven/src/com/jetbrains/packagesearch/intellij/plugin/maven/MavenModuleTransformer.kt | 2 | 4452 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.maven
import com.intellij.openapi.application.readAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlText
import com.intellij.util.asSafely
import com.jetbrains.packagesearch.intellij.plugin.extensibility.BuildSystemType
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyDeclarationIndexes
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.dependencyDeclarationCallback
import com.jetbrains.packagesearch.intellij.plugin.maven.configuration.PackageSearchMavenConfiguration
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
internal class MavenModuleTransformer : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
nativeModules.parallelMap { nativeModule ->
readAction { runCatching { MavenProjectsManager.getInstance(project).findProject(nativeModule) } }.onFailure {
logDebug(contextName = "MavenModuleTransformer", it) { "Error finding Maven module ${nativeModule.name}" }
}.getOrNull()?.let {
createMavenProjectModule(project, nativeModule, it)
}
}.filterNotNull()
private fun createMavenProjectModule(
project: Project, nativeModule: Module, mavenProject: MavenProject
): ProjectModule {
val buildFile = mavenProject.file
return ProjectModule(
name = mavenProject.name ?: nativeModule.name,
nativeModule = nativeModule,
parent = null,
buildFile = buildFile,
projectDir = mavenProject.directoryFile.toNioPath().toFile(),
buildSystemType = BuildSystemType.MAVEN,
moduleType = MavenProjectModuleType,
availableScopes = PackageSearchMavenConfiguration.getInstance(project).getMavenScopes(),
dependencyDeclarationCallback = project.dependencyDeclarationCallback { dependency ->
val children: Array<PsiElement> = dependency.psiElement.asSafely<XmlTag>()
?.children
?: return@dependencyDeclarationCallback null
val xmlTag = children.filterIsInstance<XmlText>()
.find { it is Navigatable && it.canNavigate() }
?: return@dependencyDeclarationCallback null
DependencyDeclarationIndexes(
wholeDeclarationStartIndex = xmlTag.textOffset,
coordinatesStartIndex = xmlTag.textOffset,
versionStartIndex = children.filterIsInstance<XmlTag>()
.find { it.name == "version" }
?.children
?.filterIsInstance<XmlText>()
?.firstOrNull()
?.textOffset
)
}
)
}
}
val BuildSystemType.Companion.MAVEN
get() = BuildSystemType(
name = "MAVEN", language = "xml", dependencyAnalyzerKey = MavenUtil.SYSTEM_ID, statisticsKey = "maven"
)
| apache-2.0 | b536afdd55969498200da356ec9a636b | 49.590909 | 122 | 0.681941 | 5.530435 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt | 1 | 4667 | // 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.compiler.configuration
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.ReflectionUtil
import com.intellij.util.messages.Topic
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilterBase
import com.intellij.util.xmlb.XmlSerializer
import org.jdom.Element
import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.idea.syncPublisherWithDisposeCheck
import kotlin.reflect.KClass
abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) :
PersistentStateComponent<Element>, Cloneable {
// Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters
private object DefaultValuesFilter : SerializationFilterBase() {
private val defaultBeans = HashMap<Class<*>, Any>()
private fun createDefaultBean(beanClass: Class<Any>): Any {
return ReflectionUtil.newInstance<Any>(beanClass).apply {
if (this is K2JSCompilerArguments) {
sourceMapPrefix = ""
}
}
}
private fun getDefaultValue(accessor: Accessor, bean: Any): Any? {
if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) {
return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null
}
val beanClass = bean.javaClass
val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) }
return accessor.read(defaultBean)
}
override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean {
val defValue = getDefaultValue(accessor, bean)
return if (defValue is Element && beanValue is Element) {
!JDOMUtil.areElementsEqual(beanValue, defValue)
} else {
!Comparing.equal(beanValue, defValue)
}
}
}
@Suppress("LeakingThis", "UNCHECKED_CAST")
private var _settings: T = createSettings().frozen() as T
private set(value) {
field = value.frozen() as T
}
var settings: T
get() = _settings
set(value) {
validateNewSettings(value)
_settings = value
ApplicationManager.getApplication().invokeLater {
project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(value)
}
}
fun update(changer: T.() -> Unit) {
@Suppress("UNCHECKED_CAST")
settings = (settings.unfrozen() as T).apply { changer() }
}
protected fun validateInheritedFieldsUnchanged(settings: T) {
@Suppress("UNCHECKED_CAST")
val inheritedProperties = collectProperties<T>(settings::class as KClass<T>, true)
val defaultInstance = createSettings()
val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) }
if (invalidFields.isNotEmpty()) {
throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}")
}
}
protected open fun validateNewSettings(settings: T) {
}
protected abstract fun createSettings(): T
override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter)
override fun loadState(state: Element) {
_settings = ReflectionUtil.newInstance(_settings.javaClass).apply {
if (this is CommonCompilerArguments) {
freeArgs = mutableListOf()
internalArguments = mutableListOf()
}
XmlSerializer.deserializeInto(this, state)
}
ApplicationManager.getApplication().invokeLater {
project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(settings)
}
}
public override fun clone(): Any = super.clone()
}
interface KotlinCompilerSettingsListener {
fun <T> settingsChanged(newSettings: T)
companion object {
val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java)
}
} | apache-2.0 | beb66d3df73059dde573172d29e1ef74 | 38.897436 | 164 | 0.68438 | 5.067318 | false | false | false | false |
chcat/restler | restler-integration-tests/src/main/kotlin/org/restler/integration/Controller.kt | 1 | 1999 | package org.restler.integration
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.*
import org.springframework.web.context.request.async.DeferredResult
import java.io.PrintWriter
import java.io.StringWriter
import java.util.concurrent.Callable
import javax.servlet.http.HttpServletRequest
import kotlin.concurrent.thread
RestController
public open class Controller {
RequestMapping("get")
open fun publicGet() = "OK"
RequestMapping("secured/get")
open fun securedGet() = "Secure OK"
RequestMapping("forceLogout")
open fun logout(): String {
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false)
return "OK"
}
RequestMapping("getDeferred")
open fun deferredGet(): DeferredResult<String> {
var deferredResult = DeferredResult<String>();
thread {
Thread.sleep(1000)
deferredResult.setResult("Deferred OK");
}
return deferredResult;
}
RequestMapping("getCallable")
open fun callableGet(): Callable<String> {
return Callable (
fun call(): String {
Thread.sleep(1000)
return "Callable OK"
}
);
}
RequestMapping("getWithVariable/{title}")
open fun getWithVariable(@PathVariable(value = "title") title: String, @RequestParam(value = "name") name: String): String {
return name;
}
RequestMapping("throwException")
@throws(Throwable::class)
open fun throwException(@RequestParam exceptionClass: String) {
throw Class.forName(exceptionClass).asSubclass(javaClass<Throwable>()).newInstance()
}
@ExceptionHandler(Exception::class)
fun printStackTrace(req: HttpServletRequest, e: Exception): String {
val stringWriter = StringWriter()
e.printStackTrace(PrintWriter(stringWriter))
return stringWriter.toString()
}
}
| apache-2.0 | f06a8716e4d76d97eb22ae1815643bd0 | 28.835821 | 128 | 0.678839 | 4.887531 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/_custom/view/LolAbilityView.kt | 1 | 9292 | /*
* Copyright 2017 NIRVANA
*
* 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.zwq65.unity.ui._custom.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Point
import androidx.core.content.ContextCompat
import android.util.AttributeSet
import com.blankj.utilcode.util.SizeUtils
import com.zwq65.unity.R
import com.zwq65.unity.ui._base.BaseSubView
import kotlin.math.abs
import kotlin.math.sin
/**
* ================================================
* 仿掌上英雄联盟的对局能力分布图
*
*
* Created by NIRVANA on 2017/10/19
* Contact with <zwq651406441></zwq651406441>@gmail.com>
* ================================================
*/
class LolAbilityView @JvmOverloads constructor(mContext: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: BaseSubView(mContext, attrs, defStyleAttr) {
private var mPaint: Paint? = null
private var radiusPaint: Paint? = null
private var textPaint: Paint? = null
private var valuePaint: Paint? = null
private var pathHeptagon: Path? = null
private val sideNum = 7
/**
* 七边形的半径长度
*/
private var radius: Int = 0
/**
* 七边形的内角角度
*/
private var degree = (360 / sideNum + 0.5).toFloat()
/**
* 6个点文字的坐标数组
*/
private val mPoints = arrayOfNulls<Point>(7)
/**
* 6种能力的名称
*/
private val abilityName = arrayOf("击杀", "生存", "助攻", "物理", "魔法", "防御", "金钱")
/**
* 6种能力的分值
*/
private val abilityValue = floatArrayOf(50f, 70f, 87f, 18f, 46f, 35f, 34f)
public override fun setUp(context: Context, attrs: AttributeSet?) {
mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
radiusPaint = Paint(Paint.ANTI_ALIAS_FLAG)
textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
valuePaint = Paint(Paint.ANTI_ALIAS_FLAG)
radiusPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_3)
textPaint!!.color = ContextCompat.getColor(context, R.color.text_color_dark)
valuePaint!!.color = ContextCompat.getColor(context, R.color.value_color)
textPaint!!.textSize = 24f
radiusPaint!!.strokeWidth = 2f
radiusPaint!!.style = Paint.Style.STROKE
valuePaint!!.strokeWidth = 5f
valuePaint!!.style = Paint.Style.STROKE
mPaint!!.style = Paint.Style.FILL
mPaint!!.strokeCap = Paint.Cap.ROUND
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (pathHeptagon == null) {
pathHeptagon = getPathHeptagon()
}
drawText(canvas)
drawHeptagon(canvas)
drawHeptagonRadius(canvas)
drawAbilityPath(canvas)
}
/**
* 绘制能力值分布曲线path
*
* @param canvas 画布
*/
private fun drawAbilityPath(canvas: Canvas) {
val path = Path()
for (i in abilityValue.indices) {
val diff = getDiffrence(mPoints[i]!!, abilityValue[i])
when (i) {
0 -> path.moveTo(centerX + diff[0], centerY - diff[1])
1 -> path.lineTo(centerX + diff[0], centerY - diff[1])
2, 3 -> path.lineTo(centerX + diff[0], centerY + diff[1])
4, 5 -> path.lineTo(centerX - diff[0], centerY + diff[1])
6 -> path.lineTo(centerX - diff[0], centerY - diff[1])
else -> {
}
}
}
path.close()
canvas.drawPath(path, valuePaint!!)
}
private fun getDiffrence(distance: Point, value: Float): FloatArray {
val xx = abs(distance.x - centerX).toFloat()
val yy = abs(distance.y - centerY).toFloat()
return floatArrayOf(xx * (value / 100), yy * (value / 100))
}
/**
* 绘制七边形的7条半径
*
* @param canvas 画布
*/
private fun drawHeptagonRadius(canvas: Canvas) {
canvas.save()
canvas.rotate(0f, centerX.toFloat(), centerY.toFloat())
for (j in 0 until sideNum + 1) {
canvas.drawLine(centerX.toFloat(), centerY.toFloat(), centerX.toFloat(), (centerY - radius).toFloat(), radiusPaint!!)
//旋转7次,绘制七边形的7条半径
canvas.rotate(degree, centerX.toFloat(), centerY.toFloat())
}
canvas.restore()
}
/**
* 绘制七边形Heptagon
*
* @param canvas 画布
*/
private fun drawHeptagon(canvas: Canvas) {
canvas.save()
mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_4)
canvas.drawPath(pathHeptagon!!, mPaint!!)
//缩放canvas,绘制多个同心七边形
canvas.scale(0.75f, 0.75f, centerX.toFloat(), centerY.toFloat())
mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_3)
canvas.drawPath(pathHeptagon!!, mPaint!!)
canvas.restore()
canvas.save()
canvas.scale(0.5f, 0.5f, centerX.toFloat(), centerY.toFloat())
mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_2)
canvas.drawPath(pathHeptagon!!, mPaint!!)
canvas.restore()
canvas.save()
canvas.scale(0.25f, 0.25f, centerX.toFloat(), centerY.toFloat())
mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_1)
canvas.drawPath(pathHeptagon!!, mPaint!!)
canvas.restore()
}
/**
* 绘制六个能力text
*
* @param canvas 画布
*/
private fun drawText(canvas: Canvas) {
val interval = SizeUtils.dp2px(10f).toFloat()
for (i in mPoints.indices) {
when (i) {
0 -> canvas.drawText(abilityName[i], (mPoints[i]!!.x - 1.5 * interval).toFloat(), mPoints[i]!!.y - interval, textPaint!!)
1 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y.toFloat(), textPaint!!)
2 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y + interval, textPaint!!)
3 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y + 2 * interval, textPaint!!)
4 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y + 2 * interval, textPaint!!)
5 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y + interval, textPaint!!)
6 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y.toFloat(), textPaint!!)
else -> {
}
}
}
}
/**
* @return 七边形的边path
*/
private fun getPathHeptagon(): Path {
val path = Path()
path.moveTo(centerX.toFloat(), (centerY - radius).toFloat())
mPoints[0] = Point(centerX, centerY - radius)
//根据已知角度分别计算来绘制七边形的7条边
val l1 = (sin(Math.toRadians(degree.toDouble())) * radius).toInt()
val l2 = ((1 - sin(Math.toRadians((90 - degree).toDouble()))) * radius).toInt()
path.rLineTo(l1.toFloat(), l2.toFloat())
mPoints[1] = Point(centerX + l1, centerY - radius + l2)
val l3 = (sin(Math.toRadians(1.5 * degree)) * radius).toInt()
val l4 = (sin(Math.toRadians(90 - 1.5 * degree)) * radius).toInt()
path.lineTo((centerX + l3).toFloat(), (centerY + l4).toFloat())
mPoints[2] = Point(centerX + l3, centerY + l4)
val l5 = (sin(Math.toRadians(0.5 * degree)) * radius).toInt()
val l6 = (sin(Math.toRadians(90 - 0.5 * degree)) * radius).toInt()
path.lineTo((centerX + l5).toFloat(), (centerY + l6).toFloat())
mPoints[3] = Point(centerX + l5, centerY + l6)
//对称,所以另外半边将x坐标改为'-'即可
path.rLineTo((-2 * l5).toFloat(), 0f)
mPoints[4] = Point(centerX - l5, centerY + l6)
path.moveTo(centerX.toFloat(), (centerY - radius).toFloat())
path.rLineTo((-l1).toFloat(), l2.toFloat())
mPoints[6] = Point(centerX - l1, centerY - radius + l2)
path.lineTo((centerX - l3).toFloat(), (centerY + l4).toFloat())
mPoints[5] = Point(centerX - l3, centerY + l4)
path.lineTo((centerX - l5).toFloat(), (centerY + l6).toFloat())
return path
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
radius = height / 5
setMeasuredDimension(width, height)
}
}
| apache-2.0 | 89989fba759e94b8b3b87bed1eb42327 | 37.603448 | 137 | 0.595355 | 3.658497 | false | false | false | false |
google/dagger | java/dagger/hilt/android/plugin/main/src/main/kotlin/dagger/hilt/android/plugin/util/AggregatedPackagesTransform.kt | 1 | 3908 | /*
* Copyright (C) 2021 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.hilt.android.plugin.util
import dagger.hilt.android.plugin.root.AggregatedAnnotation
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
import org.gradle.api.artifacts.transform.CacheableTransform
import org.gradle.api.artifacts.transform.InputArtifact
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformOutputs
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.file.FileSystemLocation
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Classpath
/**
* A transform that outputs classes and jars containing only classes in key aggregating Hilt
* packages that are used to pass dependencies between compilation units.
*/
@CacheableTransform
abstract class AggregatedPackagesTransform : TransformAction<TransformParameters.None> {
// TODO(danysantiago): Make incremental by using InputChanges and try to use @CompileClasspath
@get:Classpath
@get:InputArtifact
abstract val inputArtifactProvider: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
val input = inputArtifactProvider.get().asFile
when {
input.isFile -> transformFile(outputs, input)
input.isDirectory -> input.walkInPlatformIndependentOrder().filter { it.isFile }.forEach {
transformFile(outputs, it)
}
else -> error("File/directory does not exist: ${input.absolutePath}")
}
}
private fun transformFile(outputs: TransformOutputs, file: File) {
if (file.isJarFile()) {
var atLeastOneEntry = false
// TODO(danysantiago): This is an in-memory buffer stream, consider using a temp file.
val tmpOutputStream = ByteArrayOutputStream()
ZipOutputStream(tmpOutputStream).use { outputStream ->
ZipInputStream(file.inputStream()).forEachZipEntry { inputStream, inputEntry ->
if (inputEntry.isClassFile()) {
val parentDirectory = inputEntry.name.substringBeforeLast('/')
val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage ->
parentDirectory.endsWith(aggregatedPackage)
}
if (match) {
outputStream.putNextEntry(ZipEntry(inputEntry.name))
inputStream.copyTo(outputStream)
outputStream.closeEntry()
atLeastOneEntry = true
}
}
}
}
if (atLeastOneEntry) {
outputs.file(JAR_NAME).outputStream().use { tmpOutputStream.writeTo(it) }
}
} else if (file.isClassFile()) {
// If transforming a file, check if the parent directory matches one of the known aggregated
// packages structure. File and Path APIs are used to avoid OS-specific issues when comparing
// paths.
val parentDirectory: File = file.parentFile
val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage ->
parentDirectory.endsWith(aggregatedPackage)
}
if (match) {
outputs.file(file)
}
}
}
companion object {
// The output file name containing classes in the aggregated packages.
val JAR_NAME = "hiltAggregated.jar"
}
}
| apache-2.0 | 75b6530a9f94ffaecb656388a097b9c5 | 38.877551 | 99 | 0.721597 | 4.64133 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/actions/SendBufferAction.kt | 1 | 1065 | package actions
import MayaBundle as Loc
import mayacomms.MayaCommandInterface
import resources.MayaNotifications
import settings.ProjectSettings
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
class SendBufferAction : BaseSendAction(
Loc.message("mayacharm.action.SendDocumentText"),
Loc.message("mayacharm.action.SendDocumentDescription"), null
) {
override fun actionPerformed(e: AnActionEvent) {
val sdk = ProjectSettings.getInstance(e.project!!).selectedSdk
if (sdk == null) {
Notifications.Bus.notify(MayaNotifications.NO_SDK_SELECTED)
return
}
val docManager = FileDocumentManager.getInstance()
val data = e.getData(LangDataKeys.VIRTUAL_FILE) ?: return
data.let { docManager.getDocument(it) }?.also { docManager.saveDocument(it) }
MayaCommandInterface(sdk.port).sendFileToMaya(data.path)
}
}
| mit | ffb1176564fddf568be264a4bb56c9b5 | 37.035714 | 85 | 0.753991 | 4.551282 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKTimedPurchaseTable.kt | 1 | 6292 | /*
* Copyright 2018 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.store.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import com.rpkit.store.bukkit.RPKStoresBukkit
import com.rpkit.store.bukkit.purchase.RPKTimedPurchase
import com.rpkit.store.bukkit.purchase.RPKTimedPurchaseImpl
import com.rpkit.store.bukkit.storeitem.RPKStoreItemProvider
import com.rpkit.store.bukkit.storeitem.RPKTimedStoreItem
import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_PURCHASE
import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_TIMED_PURCHASE
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL
import org.jooq.impl.SQLDataType
class RPKTimedPurchaseTable(database: Database, private val plugin: RPKStoresBukkit): Table<RPKTimedPurchase>(database, RPKTimedPurchase::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_timed_purchase.id.enabled")) {
database.cacheManager.createCache("rpkit-stores-bukkit.rpkit_timed_purchase.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKTimedPurchase::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_timed_purchase.id.size"))).build())
} else {
null
}
override fun create() {
database.create.createTableIfNotExists(RPKIT_TIMED_PURCHASE)
.column(RPKIT_TIMED_PURCHASE.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_TIMED_PURCHASE.PURCHASE_ID, SQLDataType.INTEGER)
.constraints(
DSL.constraint("pk_rpkit_timed_purchase").primaryKey(RPKIT_TIMED_PURCHASE.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.6.0")
}
}
override fun insert(entity: RPKTimedPurchase): Int {
val id = database.getTable(RPKPurchaseTable::class).insert(entity)
database.create
.insertInto(
RPKIT_TIMED_PURCHASE,
RPKIT_TIMED_PURCHASE.PURCHASE_ID
)
.values(
id
)
.execute()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKTimedPurchase) {
database.getTable(RPKPurchaseTable::class).update(entity)
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKTimedPurchase? {
val result = database.create
.select(
RPKIT_PURCHASE.STORE_ITEM_ID,
RPKIT_PURCHASE.PROFILE_ID,
RPKIT_PURCHASE.PURCHASE_DATE,
RPKIT_TIMED_PURCHASE.PURCHASE_ID
)
.from(RPKIT_TIMED_PURCHASE)
.where(RPKIT_PURCHASE.ID.eq(id))
.and(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(RPKIT_PURCHASE.ID))
.fetchOne() ?: return null
val storeItemProvider = plugin.core.serviceManager.getServiceProvider(RPKStoreItemProvider::class)
val storeItem = storeItemProvider.getStoreItem(result[RPKIT_PURCHASE.STORE_ITEM_ID]) as? RPKTimedStoreItem
if (storeItem == null) {
database.create
.deleteFrom(RPKIT_PURCHASE)
.where(RPKIT_PURCHASE.ID.eq(id))
.execute()
database.create
.deleteFrom(RPKIT_TIMED_PURCHASE)
.where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(id))
.execute()
cache?.remove(id)
return null
}
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = profileProvider.getProfile(result[RPKIT_PURCHASE.PROFILE_ID])
if (profile == null) {
database.create
.deleteFrom(RPKIT_PURCHASE)
.where(RPKIT_PURCHASE.ID.eq(id))
.execute()
database.create
.deleteFrom(RPKIT_TIMED_PURCHASE)
.where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(id))
.execute()
cache?.remove(id)
return null
}
val timedPurchase = RPKTimedPurchaseImpl(
id,
storeItem,
profile,
result[RPKIT_PURCHASE.PURCHASE_DATE].toLocalDateTime()
)
cache?.put(id, timedPurchase)
return timedPurchase
}
fun get(profile: RPKProfile): List<RPKTimedPurchase> {
val result = database.create
.select(RPKIT_TIMED_PURCHASE.PURCHASE_ID)
.from(
RPKIT_PURCHASE,
RPKIT_TIMED_PURCHASE
)
.where(RPKIT_PURCHASE.ID.eq(RPKIT_TIMED_PURCHASE.ID))
.and(RPKIT_PURCHASE.PROFILE_ID.eq(profile.id))
.fetch()
return result.mapNotNull { row -> get(row[RPKIT_TIMED_PURCHASE.PURCHASE_ID]) }
}
override fun delete(entity: RPKTimedPurchase) {
database.getTable(RPKPurchaseTable::class).delete(entity)
database.create
.deleteFrom(RPKIT_TIMED_PURCHASE)
.where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | apache-2.0 | c316b48752695276fd45941562927f11 | 39.863636 | 146 | 0.618404 | 4.53641 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/WebScrollSingleAction.kt | 1 | 7712 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action.item
import android.app.AlertDialog
import android.content.Context
import android.hardware.SensorManager
import android.os.Parcel
import android.os.Parcelable
import android.view.View
import android.view.ViewConfiguration
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
import android.widget.Toast
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.core.utility.extensions.density
import jp.hazuki.yuzubrowser.core.utility.utils.ArrayUtils
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity
import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo
import jp.hazuki.yuzubrowser.webview.CustomWebView
import java.io.IOException
class WebScrollSingleAction : SingleAction, Parcelable {
private var mType = TYPE_FLING
private var mX: Int = 0
private var mY: Int = 0
val iconResourceId: Int
get() = when {
mX > 0 -> when {
mY > 0 -> R.drawable.ic_arrow_down_right_white_24dp
mY < 0 -> R.drawable.ic_arrow_up_right_white_24px
else -> R.drawable.ic_arrow_forward_white_24dp
}
mX < 0 -> when {
mY > 0 -> R.drawable.ic_arrow_down_left_24dp
mY < 0 -> R.drawable.ic_arrow_up_left_white_24px
else -> R.drawable.ic_arrow_back_white_24dp
}
else -> when {
mY > 0 -> R.drawable.ic_arrow_downward_white_24dp
mY < 0 -> R.drawable.ic_arrow_upward_white_24dp
else -> -1
}
}
@Throws(IOException::class)
constructor(id: Int, reader: JsonReader?) : super(id) {
if (reader != null) {
if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return
reader.beginObject()
while (reader.hasNext()) {
if (reader.peek() != JsonReader.Token.NAME) return
when (reader.nextName()) {
FIELD_NAME_TYPE -> mType = reader.nextInt()
FIELD_NAME_X -> mX = reader.nextInt()
FIELD_NAME_Y -> mY = reader.nextInt()
else -> reader.skipValue()
}
}
reader.endObject()
}
}
@Throws(IOException::class)
override fun writeIdAndData(writer: JsonWriter) {
writer.value(id)
writer.beginObject()
writer.name(FIELD_NAME_TYPE)
writer.value(mType)
writer.name(FIELD_NAME_X)
writer.value(mX)
writer.name(FIELD_NAME_Y)
writer.value(mY)
writer.endObject()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
dest.writeInt(mType)
dest.writeInt(mX)
dest.writeInt(mY)
}
private constructor(source: Parcel) : super(source.readInt()) {
mType = source.readInt()
mX = source.readInt()
mY = source.readInt()
}
override fun showMainPreference(context: ActionActivity): StartActivityInfo? {
return showSubPreference(context)
}
override fun showSubPreference(context: ActionActivity): StartActivityInfo? {
val view = View.inflate(context, R.layout.action_web_scroll_setting, null)
val typeSpinner = view.findViewById<Spinner>(R.id.typeSpinner)
val editTextX = view.findViewById<EditText>(R.id.editTextX)
val editTextY = view.findViewById<EditText>(R.id.editTextY)
val res = context.resources
val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, res.getStringArray(R.array.action_web_scroll_type_list))
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
typeSpinner.adapter = adapter
val values = res.getIntArray(R.array.action_web_scroll_type_values)
var current = ArrayUtils.findIndexOfValue(mType, values)
if (current < 0)
current = TYPE_FLING
typeSpinner.setSelection(current)
editTextX.setText(mX.toString())
editTextY.setText(mY.toString())
AlertDialog.Builder(context)
.setTitle(R.string.action_settings)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
mType = values[typeSpinner.selectedItemPosition]
var x = 0
var y = 0
try {
x = Integer.parseInt(editTextX.text.toString())
} catch (e: NumberFormatException) {
e.printStackTrace()
}
try {
y = Integer.parseInt(editTextY.text.toString())
} catch (e: NumberFormatException) {
e.printStackTrace()
}
if (x == 0 && y == 0) {
Toast.makeText(context.applicationContext, R.string.action_web_scroll_x_y_zero, Toast.LENGTH_SHORT).show()
showSubPreference(context)
return@setPositiveButton
}
mX = x
mY = y
}
.setNegativeButton(android.R.string.cancel, null)
.show()
return null
}
fun scrollWebView(context: Context, web: CustomWebView) {
when (mType) {
TYPE_FAST -> web.scrollBy(mX, mY)
TYPE_FLING -> web.flingScroll(makeFlingValue(context, mX), makeFlingValue(context, mY))
else -> throw RuntimeException("Unknown type : " + mType)
}
}
private fun makeFlingValue(context: Context, d: Int): Int {
val decelerationLate = (Math.log(0.78) / Math.log(0.9)).toFloat()
val physicalCoef = SensorManager.GRAVITY_EARTH * 39.37f * context.density * 160.0f * 0.84f
val flingFliction = ViewConfiguration.getScrollFriction()
return (Integer.signum(d) * Math.round(Math.exp(Math.log((Math.abs(d) / (flingFliction * physicalCoef)).toDouble()) / decelerationLate * (decelerationLate - 1.0)) / 0.35f * (flingFliction * physicalCoef))).toInt()
}
companion object {
private const val FIELD_NAME_TYPE = "0"
private const val FIELD_NAME_X = "1"
private const val FIELD_NAME_Y = "2"
private const val TYPE_FAST = 0
private const val TYPE_FLING = 1
@JvmField
val CREATOR: Parcelable.Creator<WebScrollSingleAction> = object : Parcelable.Creator<WebScrollSingleAction> {
override fun createFromParcel(source: Parcel): WebScrollSingleAction {
return WebScrollSingleAction(source)
}
override fun newArray(size: Int): Array<WebScrollSingleAction?> {
return arrayOfNulls(size)
}
}
}
}
| apache-2.0 | c8ec4537c85f8d16bdbf0b58fcea3169 | 36.436893 | 221 | 0.606328 | 4.296379 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/cpu/assembler/Assembler.kt | 1 | 4781 | package com.soywiz.kpspemu.cpu.assembler
import com.soywiz.korge.util.*
import com.soywiz.korio.error.*
import com.soywiz.korio.stream.*
import com.soywiz.kpspemu.cpu.*
import kotlin.collections.set
@NativeThreadLocal
object Assembler : InstructionDecoder() {
val mnemonicGpr get() = CpuState.gprInfosByMnemonic
fun parseGpr(str: String): Int {
if (str.startsWith("r")) return str.substring(1).toInt()
return mnemonicGpr[str]?.index ?: invalidOp("Unknown GPR $str")
}
fun String.parseInt(context: Context): Int {
context.labels[this]?.let { return it }
val str = this.replace("_", "")
if (str.startsWith("0x")) return str.substring(2).toInt(16)
return str.toInt()
}
fun assembleSingleInt(str: String, pc: Int = 0, context: Context = Context()): Int =
assembleSingle(str, pc, context).value
data class ParsedInstruction(val str: String) {
val parts = str.split(Regex("\\s+"), limit = 2)
val nameRaw = parts.getOrElse(0) { "" }
val name = nameRaw.toLowerCase()
val args = parts.getOrElse(1) { "" }
val argsParsed = args.trim().split(',').map { it.trim() }
}
fun assembleSingle(str: String, pc: Int = 0, context: Context = Context()): InstructionData {
val pi = ParsedInstruction(str)
val instruction = Instructions.instructionsByName[pi.name] ?: invalidOp("Unknown instruction '${pi.name}'")
val out = InstructionData(instruction.vm.value, pc)
val replacements = instruction.replacements
val formatRegex = instruction.formatRegex
val match = formatRegex.matchEntire(pi.args)
?: invalidOp("${instruction.format} -> $formatRegex doesn't match ${pi.args}")
val results = replacements.zip(match.groupValues.drop(1))
//println(context.labels)
for ((pat, value) in results) {
when (pat) {
"%s" -> out.rs = parseGpr(value)
"%d" -> out.rd = parseGpr(value)
"%t" -> out.rt = parseGpr(value)
"%a" -> out.pos = value.parseInt(context)
"%i" -> out.s_imm16 = value.parseInt(context)
"%I" -> out.u_imm16 = value.parseInt(context)
"%O" -> out.s_imm16 = value.parseInt(context) - pc - 4
"%j" -> out.jump_address = value.parseInt(context)
else -> invalidOp("Unsupported $pat :: value=$value in instruction $str")
}
}
return out
}
fun assembleTo(sstr: String, out: SyncStream, pc: Int = out.position.toInt(), context: Context = Context()): Int {
val labelParts = sstr.split(":", limit = 2).reversed()
val str = labelParts[0].trim()
val label = labelParts.getOrNull(1)?.trim()
if (label != null) {
context.labels[label] = pc
//println("$label -> ${pc.hex}")
}
//println("${pc.hex}: $str")
val pi = ParsedInstruction(str)
val start = out.position
when (pi.name) {
"" -> {
// None
}
"nop" -> {
out.write32_le(assembleSingleInt("sll zero, zero, 0", pc + 0, context))
}
"li" -> {
val reg = pi.argsParsed[0]
val value = pi.argsParsed[1].parseInt(context)
if ((value ushr 16) != 0) {
out.write32_le(assembleSingleInt("lui $reg, ${value ushr 16}", pc + 0, context))
out.write32_le(assembleSingleInt("ori $reg, $reg, ${value and 0xFFFF}", pc + 4, context))
} else {
out.write32_le(assembleSingleInt("ori $reg, r0, ${value and 0xFFFF}", pc + 0, context))
}
}
else -> {
out.write32_le(assembleSingleInt(str, pc, context))
}
}
val end = out.position
val written = (end - start).toInt()
//println(" : $written (${pi.name})")
return written
}
class Context {
val labels = LinkedHashMap<String, Int>()
}
fun assembleTo(lines: List<String>, out: SyncStream, pc: Int = out.position.toInt(), context: Context = Context()) {
var cpc = pc
for (line in lines) {
if (line.isEmpty()) continue
cpc += assembleTo(line, out, cpc, context)
}
}
fun assemble(lines: List<String>, pc: Int = 0, context: Context = Context()): ByteArray {
return MemorySyncStreamToByteArray {
assembleTo(lines, this, pc, context)
}
}
fun assemble(vararg lines: String, pc: Int = 0, context: Context = Context()): ByteArray =
assemble(lines.toList(), pc = pc, context = context)
} | mit | 1fbb5a4c323e3ee660863ff8f8781b18 | 38.520661 | 120 | 0.554487 | 3.980849 | false | false | false | false |
encodeering/conflate | modules/conflate-jvm/src/test/kotlin/com/encodeering/conflate/experimental/jvm/co/CycleDispatcherTest.kt | 1 | 2353 | package com.encodeering.conflate.experimental.jvm.co
import com.encodeering.conflate.experimental.api.Action
import com.encodeering.conflate.experimental.api.Dispatcher
import com.encodeering.conflate.experimental.test.fixture.Act
import com.encodeering.conflate.experimental.test.mock
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.Mockito.verify
import kotlin.coroutines.experimental.EmptyCoroutineContext
/**
* @author Michael Clausen - [email protected]
*/
@RunWith (JUnitPlatform::class)
class CycleDispatcherTest : Spek ({
describe ("CycleDispatcher") {
fun success () = mock<Dispatcher.(Unit) -> Unit> ()
fun failure () = mock<Dispatcher.(Throwable) -> Unit> ()
fun callback () = mock<(Action) -> Unit> ()
fun dispatcher (block : suspend (Action) -> Unit) = CycleDispatcher (EmptyCoroutineContext) { block (it) }
describe ("dispatch") {
it ("should dispatch an action properly") {
val action = Act ("ridley")
val callback = callback ()
dispatcher { callback (it) }.dispatch (action)
verify (callback).invoke (action)
}
}
describe ("completable") {
describe ("success") {
it ("should match the final state and scope") {
val action = Act ("ridley")
val success = success ()
val dispatcher = dispatcher { }
dispatcher.dispatch (action).then (fail = {}, ok = success)
verify (success).invoke (dispatcher, Unit)
}
}
describe ("failure") {
it ("should match the final state and scope") {
val action = Act ("ridley")
val failure = failure ()
val exception = IllegalStateException ()
val dispatcher = dispatcher { throw exception }
dispatcher.dispatch (action).then (fail = failure)
verify (failure).invoke (dispatcher, exception)
}
}
}
}
}) | apache-2.0 | fd3704b99ab7a70b21ccd2d337a38269 | 27.707317 | 114 | 0.577986 | 4.97463 | false | false | false | false |
duftler/orca | orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/PipelineTrigger.kt | 2 | 1736 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipeline.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.netflix.spinnaker.kork.artifacts.model.Artifact
import com.netflix.spinnaker.kork.artifacts.model.ExpectedArtifact
data class PipelineTrigger
@JvmOverloads constructor(
override val type: String = "pipeline",
override val correlationId: String? = null,
override val user: String? = "[anonymous]",
override val parameters: Map<String, Any> = mutableMapOf(),
override val artifacts: List<Artifact> = mutableListOf(),
override val notifications: List<Map<String, Any>> = mutableListOf(),
override var isRebake: Boolean = false,
override var isDryRun: Boolean = false,
override var isStrategy: Boolean = false,
val parentExecution: Execution,
val parentPipelineStageId: String? = null
) : Trigger {
override var other: Map<String, Any> = mutableMapOf()
override var resolvedExpectedArtifacts: List<ExpectedArtifact> = mutableListOf()
@JsonIgnore
val parentStage: Stage? =
if (parentPipelineStageId != null) {
parentExecution.stageById(parentPipelineStageId)
} else {
null
}
}
| apache-2.0 | 06a9fa140bed2ef3ec24891df9bd9aa3 | 35.93617 | 82 | 0.749424 | 4.28642 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/UnsignCommand.kt | 2 | 1965 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.essentials.bukkit.command
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import org.bukkit.Material
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import org.bukkit.inventory.meta.BookMeta
class UnsignCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender.hasPermission("rpkit.essentials.command.unsign")) {
if (sender is Player) {
if (sender.inventory.itemInMainHand.type == Material.WRITTEN_BOOK) {
val meta = sender.inventory.itemInMainHand.itemMeta as BookMeta
sender.inventory.itemInMainHand.type = Material.WRITABLE_BOOK
sender.inventory.itemInMainHand.itemMeta = meta
sender.sendMessage(plugin.messages["unsign-valid"])
} else {
sender.sendMessage(plugin.messages["unsign-invalid-book"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-unsign"])
}
return true
}
}
| apache-2.0 | 5be6d3441b1b300748b172c70363a539 | 39.102041 | 114 | 0.681425 | 4.559165 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/generics/kotlin/test5/Test1.kt | 1 | 1936 | package com.zj.example.kotlin.shengshiyuan.helloworld.generics.kotlin.test5
/**
* Created by zhengjiong
* date: 2018/2/25 21:07
*/
interface Producer<out T> {
fun produce(): T
}
interface Consumer<in T> {
fun consume(item: T)
}
open class Fruit
open class Apple : Fruit()
class ApplePear : Apple()
class FruitProducer : Producer<Fruit> {
override fun produce(): Fruit {
return Fruit()
}
}
class AppleProducer : Producer<Apple> {
override fun produce(): Apple {
return Apple()
}
}
class ApplePearProducer : Producer<ApplePear> {
override fun produce(): ApplePear {
return ApplePear()
}
}
private fun producerTest() {
//对于"out"泛型来说, 我们可以将子类型对象赋给父类型引用
val producer1: Producer<Fruit> = FruitProducer() //success
val producer2: Producer<Fruit> = AppleProducer() //success
val producer3: Producer<Fruit> = ApplePearProducer() //success
//这里返回的是Fruit类型的变量
val fruit = producer2.produce()
//val producer4: Producer<ApplePear> = AppleProducer() //error
val producer5: Producer<ApplePear> = ApplePearProducer() //success
}
fun main(args: Array<String>) {
producerTest()
consumerTest()
}
private fun consumerTest() {
//对于"in"泛型来说, 我们可以将父类型对象赋给子类型引用
val consumer1: Consumer<ApplePear> = FruitConsumer()
val consumer2: Consumer<ApplePear> = AppleConsumer()
val consumer3: Consumer<ApplePear> = ApplePearConsumer()
consumer2.consume(ApplePear())//这里的输入参数类型是ApplePear类型的
}
class FruitConsumer : Consumer<Fruit> {
override fun consume(item: Fruit) {
}
}
class AppleConsumer : Consumer<Apple> {
override fun consume(item: Apple) {
}
}
class ApplePearConsumer : Consumer<ApplePear> {
override fun consume(item: ApplePear) {
}
} | mit | 3a28b5985c98accc46a5089cea4a0798 | 20.141176 | 75 | 0.67539 | 3.563492 | false | true | false | false |
Kotlin/anko | anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/LayoutPsiFile.kt | 2 | 28183 | /*
* Copyright 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.
*/
@file:Suppress("UNREACHABLE_CODE", "OverridingDeprecatedMember", "DEPRECATION")
package org.jetbrains.kotlin.android.dslpreview
import com.intellij.injected.editor.DocumentWindow
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.lang.ASTNode
import com.intellij.lang.FileASTNode
import com.intellij.lang.Language
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable.IconFlags
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.PsiDocumentManagerImpl
import com.intellij.psi.impl.PsiManagerEx
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.SearchScope
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.IncorrectOperationException
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.android.resourceManagers.ModuleResourceManagers
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.psi.KtFile
import java.beans.PropertyChangeListener
import javax.swing.Icon
/*
Reason for these stubs:
Android Preview checks that the xml file is placed inside "layout-*" directory.
TODO: Implement some kind of stable api in Android plugin for this
*/
class LayoutPsiFile(private val myPsiFile: XmlFile, val originalFile: KtFile, module: Module) : XmlFile {
private val myPsiDirectory: PsiDirectory = LayoutPsiDirectory(module)
private val myViewProvider: FileViewProvider = object : FileViewProvider by myPsiFile.viewProvider {
override fun getPsi(p0: Language): PsiFile = this@LayoutPsiFile
}
private val myVirtualFile: VirtualFile by lazy {
LayoutLightVirtualFile(myPsiFile.name, myPsiFile.text).also { virtualFile ->
(myPsiFile.manager as? PsiManagerEx)?.fileManager?.setViewProvider(virtualFile, myViewProvider)
}
}
override fun getParent() = myPsiDirectory
override fun getDocument() = myPsiFile.document
override fun getRootTag() = myPsiFile.rootTag
override fun getVirtualFile(): VirtualFile? = myVirtualFile
override fun getContainingDirectory() = myPsiDirectory
override fun getModificationStamp() = myPsiFile.modificationStamp
override fun getOriginalFile() = this
override fun getFileType() = myPsiFile.fileType
override fun getViewProvider() = myViewProvider
override fun getNode(): FileASTNode? = myPsiFile.node
override fun getPsiRoots(): Array<PsiFile> = myPsiFile.psiRoots
override fun subtreeChanged() = myPsiFile.subtreeChanged()
override fun isDirectory() = myPsiFile.isDirectory
override fun getName() = myPsiFile.name
override fun checkSetName(s: String) = myPsiFile.checkSetName(s)
override fun setName(s: String): PsiElement = myPsiFile.setName(s)
override fun getProject() = myPsiFile.project
override fun getLanguage() = myPsiFile.language
override fun getManager(): PsiManager? = myPsiFile.manager
override fun getChildren(): Array<PsiElement> = myPsiFile.children
override fun getFirstChild(): PsiElement? = myPsiFile.firstChild
override fun getLastChild(): PsiElement? = myPsiFile.lastChild
override fun getNextSibling(): PsiElement? = myPsiFile.nextSibling
override fun getPrevSibling(): PsiElement? = myPsiFile.prevSibling
override fun getContainingFile(): PsiFile? = myPsiFile.containingFile
override fun getTextRange(): TextRange? = myPsiFile.textRange
override fun getStartOffsetInParent() = myPsiFile.startOffsetInParent
override fun getTextLength() = myPsiFile.textLength
override fun findElementAt(i: Int) = myPsiFile.findElementAt(i)
override fun findReferenceAt(i: Int) = myPsiFile.findReferenceAt(i)
override fun getTextOffset() = myPsiFile.textOffset
override fun getText(): String? = myPsiFile.text
override fun textToCharArray() = myPsiFile.textToCharArray()
override fun getNavigationElement(): PsiElement? = myPsiFile.navigationElement
override fun getOriginalElement(): PsiElement? = myPsiFile.originalElement
override fun textMatches(charSequence: CharSequence) = myPsiFile.textMatches(charSequence)
override fun textMatches(psiElement: PsiElement) = myPsiFile.textMatches(psiElement)
override fun textContains(c: Char) = myPsiFile.textContains(c)
override fun accept(psiElementVisitor: PsiElementVisitor) = myPsiFile.accept(psiElementVisitor)
override fun acceptChildren(psiElementVisitor: PsiElementVisitor) = myPsiFile.acceptChildren(psiElementVisitor)
override fun copy(): PsiElement? = myPsiFile.copy()
override fun add(psiElement: PsiElement): PsiElement? = myPsiFile.add(psiElement)
override fun processChildren(psiFileSystemItemPsiElementProcessor: PsiElementProcessor<PsiFileSystemItem>?): Boolean {
return myPsiFile.processChildren(psiFileSystemItemPsiElementProcessor)
}
override fun addBefore(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? =
myPsiFile.addBefore(psiElement, psiElement2)
override fun addAfter(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? =
myPsiFile.addAfter(psiElement, psiElement2)
override fun checkAdd(psiElement: PsiElement) = myPsiFile.checkAdd(psiElement)
override fun addRange(psiElement: PsiElement, psiElement2: PsiElement): PsiElement? {
return myPsiFile.addRange(psiElement, psiElement2)
}
override fun addRangeBefore(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? {
return myPsiFile.addRangeBefore(psiElement, psiElement2, psiElement3)
}
override fun addRangeAfter(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? {
return myPsiFile.addRangeAfter(psiElement, psiElement2, psiElement3)
}
override fun delete() = myPsiFile.delete()
override fun checkDelete() = myPsiFile.checkDelete()
override fun deleteChildRange(psiElement: PsiElement, psiElement2: PsiElement)
= myPsiFile.deleteChildRange(psiElement, psiElement2)
override fun replace(psiElement: PsiElement): PsiElement? = myPsiFile.replace(psiElement)
override fun isValid() = myPsiFile.isValid
override fun isWritable() = myPsiFile.isWritable
override fun getReference() = myPsiFile.reference
override fun getReferences(): Array<PsiReference> = myPsiFile.references
override fun <T> getCopyableUserData(tKey: Key<T>) = myPsiFile.getCopyableUserData(tKey)
override fun <T> putCopyableUserData(tKey: Key<T>, t: T?) = myPsiFile.putCopyableUserData(tKey, t)
override fun processDeclarations(
psiScopeProcessor: PsiScopeProcessor,
resolveState: ResolveState,
psiElement: PsiElement?,
psiElement2: PsiElement
): Boolean {
return myPsiFile.processDeclarations(psiScopeProcessor, resolveState, psiElement, psiElement2)
}
override fun getContext() = myPsiFile.context
override fun isPhysical() = myPsiFile.isPhysical
override fun getResolveScope() = myPsiFile.resolveScope
override fun getUseScope() = myPsiFile.useScope
override fun toString() = myPsiFile.toString()
override fun isEquivalentTo(psiElement: PsiElement) = myPsiFile.isEquivalentTo(psiElement)
override fun <T> getUserData(tKey: Key<T>) = myPsiFile.getUserData(tKey)
override fun <T> putUserData(tKey: Key<T>, t: T?) = myPsiFile.putUserData(tKey, t)
override fun getIcon(i: Int): Icon = myPsiFile.getIcon(i)
override fun getPresentation() = myPsiFile.presentation
override fun navigate(b: Boolean) = myPsiFile.navigate(b)
override fun canNavigate() = myPsiFile.canNavigate()
override fun canNavigateToSource() = myPsiFile.canNavigateToSource()
override fun getFileResolveScope() = myPsiFile.fileResolveScope
override fun ignoreReferencedElementAccessibility() = myPsiFile.ignoreReferencedElementAccessibility()
override fun processElements(psiElementProcessor: PsiElementProcessor<PsiElement>, psiElement: PsiElement): Boolean {
return myPsiFile.processElements(psiElementProcessor, psiElement)
}
private class LayoutPsiDirectory(val module: Module) : PsiDirectory {
private val parentDir by lazy {
val facet = AndroidFacet.getInstance(module) ?: return@lazy null
val dir = ModuleResourceManagers.getInstance(facet).localResourceManager.resourceDirs
.firstOrNull() ?: return@lazy null
PsiManager.getInstance(module.project).findDirectory(dir)
}
override fun getName(): String {
return "layout"
}
override fun getVirtualFile(): VirtualFile {
return null!!
}
@Throws(IncorrectOperationException::class)
override fun setName(s: String): PsiElement {
return null!!
}
override fun getParentDirectory(): PsiDirectory? = parentDir
override fun getParent() = parentDir
override fun getSubdirectories(): Array<PsiDirectory?> {
return arrayOfNulls(0)
}
override fun getFiles(): Array<PsiFile?> {
return arrayOfNulls(0)
}
override fun findSubdirectory(s: String): PsiDirectory? {
return null
}
override fun findFile(@NonNls s: String): PsiFile? {
return null
}
@Throws(IncorrectOperationException::class)
override fun createSubdirectory(s: String): PsiDirectory {
return null!!
}
@Throws(IncorrectOperationException::class)
override fun checkCreateSubdirectory(s: String) {
}
@Throws(IncorrectOperationException::class)
override fun createFile(@NonNls s: String): PsiFile {
return null!!
}
@Throws(IncorrectOperationException::class)
override fun copyFileFrom(s: String, psiFile: PsiFile): PsiFile {
return null!!
}
@Throws(IncorrectOperationException::class)
override fun checkCreateFile(s: String) {
}
override fun isDirectory(): Boolean {
return true
}
override fun processChildren(psiFileSystemItemPsiElementProcessor: PsiElementProcessor<PsiFileSystemItem>): Boolean {
return false
}
override fun getPresentation(): ItemPresentation? {
return null
}
override fun navigate(b: Boolean) {
}
override fun canNavigate(): Boolean {
return false
}
override fun canNavigateToSource(): Boolean {
return false
}
@Throws(IncorrectOperationException::class)
override fun checkSetName(s: String) {
}
@Throws(PsiInvalidElementAccessException::class)
override fun getProject(): Project {
return null!!
}
override fun getLanguage(): Language {
return null!!
}
override fun getManager(): PsiManager? {
return null
}
override fun getChildren(): Array<PsiElement?> {
return arrayOfNulls(0)
}
override fun getFirstChild(): PsiElement? {
return null
}
override fun getLastChild(): PsiElement? {
return null
}
override fun getNextSibling(): PsiElement? {
return null
}
override fun getPrevSibling(): PsiElement? {
return null
}
@Throws(PsiInvalidElementAccessException::class)
override fun getContainingFile(): PsiFile? {
return null
}
override fun getTextRange(): TextRange? {
return null
}
override fun getStartOffsetInParent(): Int {
return 0
}
override fun getTextLength(): Int {
return 0
}
override fun findElementAt(i: Int): PsiElement? {
return null
}
override fun findReferenceAt(i: Int): PsiReference? {
return null
}
override fun getTextOffset(): Int {
return 0
}
override fun getText(): String? {
return null
}
override fun textToCharArray(): CharArray {
return CharArray(0)
}
override fun getNavigationElement(): PsiElement? {
return null
}
override fun getOriginalElement(): PsiElement? {
return null
}
override fun textMatches(@NonNls charSequence: CharSequence): Boolean {
return false
}
override fun textMatches(psiElement: PsiElement): Boolean {
return false
}
override fun textContains(c: Char): Boolean {
return false
}
override fun accept(psiElementVisitor: PsiElementVisitor) {
}
override fun acceptChildren(psiElementVisitor: PsiElementVisitor) {
}
override fun copy(): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun add(psiElement: PsiElement): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun addBefore(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun addAfter(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun checkAdd(psiElement: PsiElement) {
}
@Throws(IncorrectOperationException::class)
override fun addRange(psiElement: PsiElement, psiElement2: PsiElement): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun addRangeBefore(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun addRangeAfter(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? {
return null
}
@Throws(IncorrectOperationException::class)
override fun delete() {
}
@Throws(IncorrectOperationException::class)
override fun checkDelete() {
}
@Throws(IncorrectOperationException::class)
override fun deleteChildRange(psiElement: PsiElement, psiElement2: PsiElement) {
}
@Throws(IncorrectOperationException::class)
override fun replace(psiElement: PsiElement): PsiElement? {
return null
}
override fun isValid(): Boolean {
return false
}
override fun isWritable(): Boolean {
return false
}
override fun getReference(): PsiReference? {
return null
}
override fun getReferences(): Array<PsiReference?> {
return arrayOfNulls(0)
}
override fun <T> getCopyableUserData(tKey: Key<T>): T? {
return null
}
override fun <T> putCopyableUserData(tKey: Key<T>, t: T?) {
}
override fun processDeclarations(
psiScopeProcessor: PsiScopeProcessor,
resolveState: ResolveState,
psiElement: PsiElement?,
psiElement2: PsiElement
): Boolean {
return false
}
override fun getContext(): PsiElement? {
return null
}
override fun isPhysical(): Boolean {
return false
}
override fun getResolveScope(): GlobalSearchScope {
return null!!
}
override fun getUseScope(): SearchScope {
return null!!
}
override fun getNode(): ASTNode? {
return null
}
override fun isEquivalentTo(psiElement: PsiElement): Boolean {
return false
}
override fun getIcon(@IconFlags i: Int): Icon? {
return null
}
override fun <T> getUserData(tKey: Key<T>): T? {
return null
}
override fun <T> putUserData(tKey: Key<T>, t: T?) {
}
}
inner class LayoutLightVirtualFile(name: String, text: String) : LightVirtualFile(name, text), VirtualFileWindow {
/*
* This hack is needed to force PsiDocumentManager return our LayoutPsiFile for LayoutLightVirtualFile
*/
override fun getDocumentWindow(): DocumentWindow {
val documentManager = PsiDocumentManager.getInstance(project)
val documentWindowStub = object : UserDataHolderBase(), DocumentWindow {
override fun hostToInjectedUnescaped(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isOneLine(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun removeDocumentListener(p0: DocumentListener) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun deleteString(p0: Int, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTextLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getHostRanges(): Array<Segment> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getText(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getText(p0: TextRange): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLineStartOffset(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createRangeMarker(p0: Int, p1: Int): RangeMarker {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createRangeMarker(p0: Int, p1: Int, p2: Boolean): RangeMarker {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createRangeMarker(p0: TextRange): RangeMarker {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun insertString(p0: Int, p1: CharSequence) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setText(p0: CharSequence) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun startGuardedBlockChecking() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getHostRange(p0: Int): TextRange? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getChars(): CharArray {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLineCount(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun stopGuardedBlockChecking() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun areRangesEqual(p0: DocumentWindow): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isValid(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun removeGuardedBlock(p0: RangeMarker) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLineSeparatorLength(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun injectedToHostLine(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addPropertyChangeListener(p0: PropertyChangeListener) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createGuardedBlock(p0: Int, p1: Int): RangeMarker {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun replaceString(p0: Int, p1: Int, p2: CharSequence) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getModificationStamp(): Long {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setReadOnly(p0: Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun intersectWithEditable(p0: TextRange): TextRange? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun fireReadOnlyModificationAttempt() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLineNumber(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCyclicBufferSize(p0: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hostToInjected(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getImmutableCharSequence(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getOffsetGuard(p0: Int): RangeMarker? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isWritable(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLineEndOffset(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCharsSequence(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDelegate(): Document {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun containsRange(p0: Int, p1: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addDocumentListener(p0: DocumentListener) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addDocumentListener(p0: DocumentListener, p1: Disposable) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun removePropertyChangeListener(p0: PropertyChangeListener) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getRangeGuard(p0: Int, p1: Int): RangeMarker? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun injectedToHost(p0: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun injectedToHost(p0: TextRange): TextRange {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
(documentManager as PsiDocumentManagerImpl).associatePsi(documentWindowStub, this@LayoutPsiFile)
return documentWindowStub
}
override fun getDelegate(): VirtualFile = [email protected]
override fun getParent() = object : LightVirtualFile("layout") {
override fun isDirectory() = true
}
}
} | apache-2.0 | 80e139e212dee50209584e76e1e8b545 | 38.418182 | 125 | 0.639322 | 5.450203 | false | false | false | false |
android/user-interface-samples | WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/RootViewDeferringInsetsCallback.kt | 1 | 6016 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.samples.insetsanimation
import android.view.View
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
/**
* A class which extends/implements both [WindowInsetsAnimationCompat.Callback] and
* [View.OnApplyWindowInsetsListener], which should be set on the root view in your layout.
*
* This class enables the root view is selectively defer handling any insets which match
* [deferredInsetTypes], to enable better looking [WindowInsetsAnimationCompat]s.
*
* An example is the following: when a [WindowInsetsAnimationCompat] is started, the system will dispatch
* a [WindowInsetsCompat] instance which contains the end state of the animation. For the scenario of
* the IME being animated in, that means that the insets contains the IME height. If the view's
* [View.OnApplyWindowInsetsListener] simply always applied the combination of
* [WindowInsetsCompat.Type.ime] and [WindowInsetsCompat.Type.systemBars] using padding, the viewport of any
* child views would then be smaller. This results in us animating a smaller (padded-in) view into
* a larger viewport. Visually, this results in the views looking clipped.
*
* This class allows us to implement a different strategy for the above scenario, by selectively
* deferring the [WindowInsetsCompat.Type.ime] insets until the [WindowInsetsAnimationCompat] is ended.
* For the above example, you would create a [RootViewDeferringInsetsCallback] like so:
*
* ```
* val callback = RootViewDeferringInsetsCallback(
* persistentInsetTypes = WindowInsetsCompat.Type.systemBars(),
* deferredInsetTypes = WindowInsetsCompat.Type.ime()
* )
* ```
*
* This class is not limited to just IME animations, and can work with any [WindowInsetsCompat.Type]s.
*
* @param persistentInsetTypes the bitmask of any inset types which should always be handled
* through padding the attached view
* @param deferredInsetTypes the bitmask of insets types which should be deferred until after
* any related [WindowInsetsAnimationCompat]s have ended
*/
class RootViewDeferringInsetsCallback(
val persistentInsetTypes: Int,
val deferredInsetTypes: Int
) : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE),
OnApplyWindowInsetsListener {
init {
require(persistentInsetTypes and deferredInsetTypes == 0) {
"persistentInsetTypes and deferredInsetTypes can not contain any of " +
" same WindowInsetsCompat.Type values"
}
}
private var view: View? = null
private var lastWindowInsets: WindowInsetsCompat? = null
private var deferredInsets = false
override fun onApplyWindowInsets(
v: View,
windowInsets: WindowInsetsCompat
): WindowInsetsCompat {
// Store the view and insets for us in onEnd() below
view = v
lastWindowInsets = windowInsets
val types = when {
// When the deferred flag is enabled, we only use the systemBars() insets
deferredInsets -> persistentInsetTypes
// Otherwise we handle the combination of the the systemBars() and ime() insets
else -> persistentInsetTypes or deferredInsetTypes
}
// Finally we apply the resolved insets by setting them as padding
val typeInsets = windowInsets.getInsets(types)
v.setPadding(typeInsets.left, typeInsets.top, typeInsets.right, typeInsets.bottom)
// We return the new WindowInsetsCompat.CONSUMED to stop the insets being dispatched any
// further into the view hierarchy. This replaces the deprecated
// WindowInsetsCompat.consumeSystemWindowInsets() and related functions.
return WindowInsetsCompat.CONSUMED
}
override fun onPrepare(animation: WindowInsetsAnimationCompat) {
if (animation.typeMask and deferredInsetTypes != 0) {
// We defer the WindowInsetsCompat.Type.ime() insets if the IME is currently not visible.
// This results in only the WindowInsetsCompat.Type.systemBars() being applied, allowing
// the scrolling view to remain at it's larger size.
deferredInsets = true
}
}
override fun onProgress(
insets: WindowInsetsCompat,
runningAnims: List<WindowInsetsAnimationCompat>
): WindowInsetsCompat {
// This is a no-op. We don't actually want to handle any WindowInsetsAnimations
return insets
}
override fun onEnd(animation: WindowInsetsAnimationCompat) {
if (deferredInsets && (animation.typeMask and deferredInsetTypes) != 0) {
// If we deferred the IME insets and an IME animation has finished, we need to reset
// the flag
deferredInsets = false
// And finally dispatch the deferred insets to the view now.
// Ideally we would just call view.requestApplyInsets() and let the normal dispatch
// cycle happen, but this happens too late resulting in a visual flicker.
// Instead we manually dispatch the most recent WindowInsets to the view.
if (lastWindowInsets != null && view != null) {
ViewCompat.dispatchApplyWindowInsets(view!!, lastWindowInsets!!)
}
}
}
}
| apache-2.0 | bade1dceadce1b5a3aee39755280481a | 44.575758 | 108 | 0.719581 | 4.955519 | false | false | false | false |
owntracks/android | project/app/src/main/java/org/owntracks/android/support/DeviceMetricsProvider.kt | 1 | 3504 | package org.owntracks.android.support
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.BatteryManager
import dagger.hilt.android.qualifiers.ApplicationContext
import org.owntracks.android.model.BatteryStatus
import org.owntracks.android.model.messages.MessageLocation
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DeviceMetricsProvider @Inject internal constructor(@ApplicationContext private val context: Context) {
val batteryLevel: Int
get() {
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = context.registerReceiver(null, intentFilter)
return batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) ?: 0
}
val batteryStatus: BatteryStatus
get() {
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = context.registerReceiver(null, intentFilter)
return when (batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, 0)) {
BatteryManager.BATTERY_STATUS_FULL -> BatteryStatus.FULL
BatteryManager.BATTERY_STATUS_CHARGING -> BatteryStatus.CHARGING
BatteryManager.BATTERY_STATUS_DISCHARGING -> BatteryStatus.UNPLUGGED
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> BatteryStatus.UNKNOWN
else -> BatteryStatus.UNKNOWN
}
}
val connectionType: String?
get() {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
cm.run {
try {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
if (!hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
return MessageLocation.CONN_TYPE_OFFLINE
}
if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return MessageLocation.CONN_TYPE_MOBILE
}
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return MessageLocation.CONN_TYPE_WIFI
}
}
// Android bug: https://issuetracker.google.com/issues/175055271
// ConnectivityManager::getNetworkCapabilities apparently throws a SecurityException
} catch (e: SecurityException) {
Timber.e(e, "Exception fetching networkcapabilities")
}
}
return null
} else @Suppress("DEPRECATION") {
val activeNetworkInfo = cm.activeNetworkInfo ?: return null
if (!activeNetworkInfo.isConnected) {
return MessageLocation.CONN_TYPE_OFFLINE
}
return when (activeNetworkInfo.type) {
ConnectivityManager.TYPE_WIFI -> MessageLocation.CONN_TYPE_WIFI
ConnectivityManager.TYPE_MOBILE -> MessageLocation.CONN_TYPE_MOBILE
else -> null
}
}
}
}
| epl-1.0 | 7983a35fa46f33d7588f6dd645483098 | 46.351351 | 108 | 0.605308 | 5.84975 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/BackgroundVariations.kt | 1 | 839 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import net.perfectdreams.exposedpowerutils.sql.jsonb
import org.jetbrains.exposed.dao.id.LongIdTable
object BackgroundVariations : LongIdTable() {
val background = reference("background", Backgrounds)
val profileDesignGroup = optReference("profile_design_group", ProfileDesignGroups)
val file = text("file")
val preferredMediaType = text("preferred_media_type")
val crop = jsonb("crop").nullable()
init {
// Combined index, we can only have a crop for a specific background + design group, not multiple
// This however does NOT WORK with upsert because profileDesignGroup can be null, and that breaks things
// So manual checks must be made instead of relying on upsert!
uniqueIndex(background, profileDesignGroup)
}
} | agpl-3.0 | c755f3464dd240af815c6769a2015eb0 | 43.210526 | 112 | 0.741359 | 4.486631 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/activities/EventDetailsActivity.kt | 1 | 6291 | package be.digitalia.fosdem.activities
import android.content.Intent
import android.nfc.NdefRecord
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.fragment.app.add
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import be.digitalia.fosdem.R
import be.digitalia.fosdem.fragments.EventDetailsFragment
import be.digitalia.fosdem.model.Event
import be.digitalia.fosdem.utils.CreateNfcAppDataCallback
import be.digitalia.fosdem.utils.assistedViewModels
import be.digitalia.fosdem.utils.extractNfcAppData
import be.digitalia.fosdem.utils.hasNfcAppData
import be.digitalia.fosdem.utils.isLightTheme
import be.digitalia.fosdem.utils.setNfcAppDataPushMessageCallbackIfAvailable
import be.digitalia.fosdem.utils.setTaskColorPrimary
import be.digitalia.fosdem.utils.statusBarColorCompat
import be.digitalia.fosdem.utils.tintBackground
import be.digitalia.fosdem.utils.toEventIdString
import be.digitalia.fosdem.utils.toNfcAppData
import be.digitalia.fosdem.viewmodels.BookmarkStatusViewModel
import be.digitalia.fosdem.viewmodels.EventViewModel
import be.digitalia.fosdem.widgets.setupBookmarkStatus
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* Displays a single event passed either as a complete Parcelable object in extras or as an id in data.
*
* @author Christophe Beyls
*/
@AndroidEntryPoint
class EventDetailsActivity : AppCompatActivity(R.layout.single_event), CreateNfcAppDataCallback {
private val bookmarkStatusViewModel: BookmarkStatusViewModel by viewModels()
@Inject
lateinit var viewModelFactory: EventViewModel.Factory
private val viewModel: EventViewModel by assistedViewModels {
// Load the event from the DB using its id
val intent = intent
val eventIdString = if (intent.hasNfcAppData()) {
// NFC intent
intent.extractNfcAppData().toEventIdString()
} else {
// Normal in-app intent
intent.dataString!!
}
viewModelFactory.create(eventIdString.toLong())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(findViewById(R.id.bottom_appbar))
findViewById<ImageButton>(R.id.fab).setupBookmarkStatus(bookmarkStatusViewModel, this)
val intentEvent: Event? = intent.getParcelableExtra(EXTRA_EVENT)
if (intentEvent != null) {
// The event has been passed as parameter, it can be displayed immediately
initEvent(intentEvent)
if (savedInstanceState == null) {
supportFragmentManager.commit {
add<EventDetailsFragment>(R.id.content,
args = EventDetailsFragment.createArguments(intentEvent))
}
}
} else {
lifecycleScope.launchWhenStarted {
val event = viewModel.event.await()
if (event == null) {
// Event not found, quit
Toast.makeText(this@EventDetailsActivity, getString(R.string.event_not_found_error), Toast.LENGTH_LONG).show()
finish()
} else {
initEvent(event)
val fm = supportFragmentManager
if (fm.findFragmentById(R.id.content) == null) {
fm.commit(allowStateLoss = true) {
add<EventDetailsFragment>(R.id.content,
args = EventDetailsFragment.createArguments(event))
}
}
}
}
}
}
/**
* Initialize event-related configuration after the event has been loaded.
*/
private fun initEvent(event: Event) {
// Enable up navigation only after getting the event details
val toolbar = findViewById<Toolbar>(R.id.toolbar).apply {
setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material)
setNavigationContentDescription(androidx.appcompat.R.string.abc_action_bar_up_description)
setNavigationOnClickListener { onSupportNavigateUp() }
title = event.track.name
}
val trackType = event.track.type
if (isLightTheme) {
window.statusBarColorCompat = ContextCompat.getColor(this, trackType.statusBarColorResId)
val trackAppBarColor = ContextCompat.getColorStateList(this, trackType.appBarColorResId)!!
setTaskColorPrimary(trackAppBarColor.defaultColor)
findViewById<View>(R.id.appbar).tintBackground(trackAppBarColor)
} else {
val trackTextColor = ContextCompat.getColorStateList(this, trackType.textColorResId)!!
toolbar.setTitleTextColor(trackTextColor)
}
bookmarkStatusViewModel.event = event
// Enable Android Beam
setNfcAppDataPushMessageCallbackIfAvailable(this)
}
override fun getSupportParentActivityIntent(): Intent? {
val event = bookmarkStatusViewModel.event ?: return null
// Navigate up to the track associated with this event
return Intent(this, TrackScheduleActivity::class.java)
.putExtra(TrackScheduleActivity.EXTRA_DAY, event.day)
.putExtra(TrackScheduleActivity.EXTRA_TRACK, event.track)
.putExtra(TrackScheduleActivity.EXTRA_FROM_EVENT_ID, event.id)
}
override fun supportNavigateUpTo(upIntent: Intent) {
// Replicate the compatibility implementation of NavUtils.navigateUpTo()
// to ensure the parent Activity is always launched
// even if not present on the back stack.
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(upIntent)
finish()
}
// CreateNfcAppDataCallback
override fun createNfcAppData(): NdefRecord? {
return bookmarkStatusViewModel.event?.toNfcAppData(this)
}
companion object {
const val EXTRA_EVENT = "event"
}
} | apache-2.0 | ee68de2f046ae79f7107036acb38223b | 39.593548 | 130 | 0.687331 | 5.004773 | false | false | false | false |
esafirm/android-image-picker | imagepicker/src/main/java/com/esafirm/imagepicker/view/SnackBarView.kt | 1 | 1488 | package com.esafirm.imagepicker.view
import android.content.Context
import android.util.AttributeSet
import android.view.animation.Interpolator
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import com.esafirm.imagepicker.R
class SnackBarView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : RelativeLayout(context, attrs, defStyle) {
private val txtCaption get() = findViewById<TextView>(R.id.ef_snackbar_txt_bottom_caption)
private val btnAction get() = findViewById<TextView>(R.id.ef_snackbar_btn_action)
init {
inflate(context, R.layout.ef_imagepicker_snackbar, this)
if (!isInEditMode) {
val height = context.resources.getDimensionPixelSize(R.dimen.ef_height_snackbar)
translationY = height.toFloat()
alpha = 0f
}
}
fun show(@StringRes textResId: Int, onClickListener: OnClickListener) {
txtCaption.text = context.getString(textResId)
btnAction.setOnClickListener(onClickListener)
animate().translationY(0f)
.setDuration(ANIM_DURATION.toLong())
.setInterpolator(INTERPOLATOR)
.alpha(1f)
}
companion object {
private const val ANIM_DURATION = 200
private val INTERPOLATOR: Interpolator = FastOutLinearInInterpolator()
}
} | mit | 7da0c8ee4ad0eb2ab30598fc20e6600f | 33.627907 | 94 | 0.714382 | 4.578462 | false | false | false | false |
SteffenKonrad/Term_Project_Simulation | src/main/kotlin/traffic_simulation/Network.kt | 1 | 1076 | package traffic_simulation
class Network(var capacity: Int) {
// function to tally the cars on the road
fun neededCapacity(cars: List<Car>): Int {
var requiredcapacity: Int = 0
for (car in cars) {
if (car.driving)
requiredcapacity = requiredcapacity + 1
}
return requiredcapacity
}
// function compares the capacity and the demand
fun enoughCapacity(requirement: Int): Boolean {
if (capacity <= requirement) {
return true
}
return false
}
// function asks whether the capacity is exhausted and whether or not a delay occurs
fun testScenario(carList: List<Car>): List<Car> {
val requirement: Int = neededCapacity(carList)
val compare: Boolean = enoughCapacity(requirement)
if (compare) {
for (car in carList) {
if (car.driving) {
val delayed = true
car.gettingDelayed = delayed
}
}
}
return carList
}
}
| apache-2.0 | 59accdf0104659e7a47baae3e10cf6ec | 26.589744 | 88 | 0.561338 | 4.803571 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/GithubRepositorieslinks.kt | 1 | 914 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.Link
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param self
* @param propertyClass
*/
data class GithubRepositorieslinks(
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("self") val self: Link? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
| mit | db3d0640ea39ec737ceb1e7c82fe74ab | 26.69697 | 74 | 0.780088 | 4.117117 | false | false | false | false |
yongce/DevTools | app/src/main/java/me/ycdev/android/devtools/CommonIntentService.kt | 1 | 637 | package me.ycdev.android.devtools
import android.app.IntentService
import android.content.Intent
import me.ycdev.android.devtools.security.unmarshall.UnmarshallScannerActivity
class CommonIntentService : IntentService("CommonIntentService") {
override fun onHandleIntent(intent: Intent?) {
val action = intent?.action
if (ACTION_UNMARSHALL_SCANNER == action) {
UnmarshallScannerActivity.scanUnmarshallIssue(this)
}
}
companion object {
private const val ACTION_PREFIX = "class.action."
const val ACTION_UNMARSHALL_SCANNER = ACTION_PREFIX + "UNMARSHALL_SCANNER"
}
}
| apache-2.0 | cb85e1b643409c318ba2e8418827ec94 | 30.85 | 82 | 0.723705 | 4.275168 | false | false | false | false |
cypressious/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/models/Weekday.kt | 1 | 1635 | package de.maxvogler.learningspaces.models
import de.maxvogler.learningspaces.helpers.toWeekday
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
public enum class Weekday(val weekday: Int) {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);
public fun toInt(): Int
= weekday
public fun equals(i: Int): Boolean
= weekday == i
public val next: Weekday
// values() indices start by zero, so [this.weekday] returns the successor!
get() = values().get(this.weekday % 7)
public fun rangeTo(other: Weekday): Progression<Weekday> {
val start = this
return object : Progression<Weekday> {
override val start: Weekday = start
override val end: Weekday = other
override val increment: Number = 1
override fun iterator(): Iterator<Weekday> {
val iterator = if (end >= start) {
IntProgressionIterator(start.toInt(), end.toInt(), 1)
} else {
IntProgressionIterator(start.toInt(), end.toInt() + 7, 1)
}
return object : Iterator<Weekday> {
override fun next(): Weekday
= (((iterator.next() - 1 ) % 7) + 1).toWeekday()
override fun hasNext(): Boolean
= iterator.hasNext()
}
}
}
}
companion object {
public fun today(): Weekday =
LocalDate.now().toWeekday()
}
}
| gpl-2.0 | 368e5cc0761e70c859036922fdb64f30 | 26.25 | 87 | 0.533333 | 4.725434 | false | false | false | false |
ejeinc/Meganekko | library/src/main/java/org/meganekkovr/audio_engine/SoundImpl.kt | 1 | 2845 | package org.meganekkovr.audio_engine
import android.animation.ValueAnimator
import android.os.Handler
import android.os.Looper
import com.google.vr.sdk.audio.GvrAudioEngine
import java.util.*
internal class SoundImpl(private val audioEngine: GvrAudioEngine, private val id: Int) : SoundObject, SoundField, StereoSound {
private val timedEvents = TreeMap<Float, () -> Unit>()
private var volume = 1f
private var currentTime: Float = 0.toFloat()
private var willBeInPlaying: Boolean = false
private var onEndCallback: (() -> Unit)? = null
override val isPlaying: Boolean
get() = audioEngine.isSoundPlaying(id)
override val isEnded: Boolean
get() = willBeInPlaying && !isPlaying
override fun play(loopingEnabled: Boolean) {
this.willBeInPlaying = true
audioEngine.playSound(id, loopingEnabled)
}
override fun pause() {
this.willBeInPlaying = false
audioEngine.pauseSound(id)
}
override fun resume() {
this.willBeInPlaying = true
audioEngine.resumeSound(id)
}
override fun stop() {
// I don't set willBeInPlaying to false here for onEndCallback.
audioEngine.stopSound(id)
}
override fun setPosition(x: Float, y: Float, z: Float) {
audioEngine.setSoundObjectPosition(id, x, y, z)
}
override fun setDistanceRolloffModel(rolloffModel: Int, minDistance: Float, maxDistance: Float) {
audioEngine.setSoundObjectDistanceRolloffModel(id, rolloffModel, minDistance, maxDistance)
}
override fun setVolume(volume: Float) {
this.volume = volume
audioEngine.setSoundVolume(id, volume)
}
override fun fadeVolume(volume: Float, time: Float) {
val animator = ValueAnimator.ofFloat(this.volume, volume)
.setDuration((time * 1000).toLong())
animator.addUpdateListener { animation ->
val value = animation.animatedValue as Float
[email protected](value)
}
Handler(Looper.getMainLooper()).post { animator.start() }
}
override fun setRotation(x: Float, y: Float, z: Float, w: Float) {
audioEngine.setSoundfieldRotation(id, x, y, z, w)
}
override fun onEnd(callback: () -> Unit) {
this.onEndCallback = callback
}
fun notifyOnEnd() {
onEndCallback?.invoke()
onEndCallback = null
}
override fun addTimedEvent(time: Float, event: () -> Unit) {
timedEvents[time] = event
}
fun deltaSeconds(deltaSeconds: Float) {
currentTime += deltaSeconds
// Emit timed events
if (!timedEvents.isEmpty()) {
val firstKey = timedEvents.firstKey()
if (firstKey < currentTime) {
timedEvents.remove(firstKey)?.invoke()
}
}
}
}
| apache-2.0 | 94ff1e1f55cd13f06bc28ec407bcbbce | 28.635417 | 127 | 0.645694 | 4.271772 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/guide/components/Text.kt | 2 | 5192 | package com.cout970.magneticraft.guide.components
import com.cout970.magneticraft.MOD_ID
import com.cout970.magneticraft.gui.client.guide.FONT_HEIGHT
import com.cout970.magneticraft.gui.client.guide.GuiGuideBook
import com.cout970.magneticraft.guide.BookPage
import com.cout970.magneticraft.guide.IPageComponent
import com.cout970.magneticraft.guide.JsonIgnore
import com.cout970.magneticraft.guide.LinkInfo
import com.cout970.magneticraft.util.i18n
import com.cout970.magneticraft.util.vector.Vec2d
import com.cout970.magneticraft.util.vector.contains
import net.minecraft.client.resources.I18n
class Text(
position: Vec2d,
override val size: Vec2d,
val text: String
) : PageComponent(position) {
override val id: String = "text"
@JsonIgnore
var words: List<Pair<String, LinkInfo?>>? = parseText(text)
override fun toGuiComponent(parent: BookPage.Gui): IPageComponent = TextComponentGui(parent)
private inner class TextComponentGui(parent: BookPage.Gui) : Gui(parent) {
lateinit var boxes: List<TextBox>
override fun initGui() {
super.initGui()
placeBoxes()
}
fun placeBoxes() {
var x = 0
var y = 0
val boxList = mutableListOf<TextBox>()
val space = parent.gui.getCharWidth(' ')
if(words == null){
words = parseText(text)
}
for ((word, link) in words!!) {
val width = parent.gui.getStringWidth(word)
if (width > size.x) {
// throw IllegalStateException(
// "Word $word is larger than text box. Increase text box width or change the word."
// )
}
if (x + width > size.x) {
x = 0
y += FONT_HEIGHT + 1
if (y > size.y) {
// throw IllegalStateException("Text is larger than the text box.")
}
} else {
if (boxList.isNotEmpty() && boxList.last().link == link) {
boxList.last().nextLink = true
}
}
if (x + space > size.x) {
boxList += TextBox(this, Vec2d(x, y), word, false, link)
} else {
boxList += TextBox(this, Vec2d(x, y), word, true, link)
x += space
}
x += width
}
boxes = boxList
}
override fun draw(mouse: Vec2d, time: Double) {
boxes.forEach { it.draw(mouse) }
}
override fun postDraw(mouse: Vec2d, time: Double) {
boxes.forEach { it.postDraw(mouse) }
}
override fun onLeftClick(mouse: Vec2d): Boolean {
val box = boxes.firstOrNull { it.isInside(mouse) && it.link != null }
box ?: return false
box.link ?: return false
parent.gui.mc.displayGuiScreen(GuiGuideBook(box.link.getEntryTarget()))
return true
}
}
private class TextBox(
val parent: Gui,
val position: Vec2d,
val text: String,
val space: Boolean,
val link: LinkInfo? = null
) {
val page = parent.parent
val size = Vec2d(page.gui.getStringWidth(text), FONT_HEIGHT)
var nextLink = false
val drawPos: Vec2d
get() = parent.drawPos + position
fun isInside(pos: Vec2d) = pos in drawPos toPoint (drawPos + size)
fun draw(mouse: Vec2d) {
val prefix = if (link == null) {
"§r"
} else {
if (isInside(mouse)) {
"§9§n"
} else {
"§r§n"
}
}
val spaceFormat = if (space) {
if (nextLink) " " else "§r "
} else {
""
}
page.gui.drawString(
pos = drawPos,
text = prefix + text + spaceFormat
)
}
fun postDraw(mouse: Vec2d) {
if (link != null && isInside(mouse)) {
page.gui.drawHoveringText(listOf(I18n.format("$MOD_ID.guide.link.text", link.entry.i18n(), link.page + 1)), mouse)
}
}
}
}
fun parseText(text: String): List<Pair<String, LinkInfo?>> {
if (!text.contains('[')) {
return text.split(' ').filter(String::isNotBlank).map { it to null }
}
//before first link
val prefix = parseText(text.substringBefore('['))
val remText = text.substringAfter('[')
//link text [<this part>](...)
val linkWords = parseText(remText.substringBefore(']'))
val remainder = remText.substringAfter("](")
//link target [...](<this part>)
val link = remainder.substringBefore(')').split(':').run {
LinkInfo(get(0).trim(), get(1).trim().toInt())
}
//recurse for rest of the text
return prefix + linkWords.map { it.first to link } + parseText(remainder.substringAfter(')'))
} | gpl-2.0 | d876897977f2eb31cc1ef5b97371a661 | 29.875 | 130 | 0.524682 | 4.247338 | false | false | false | false |
GyrosWorkshop/WukongAndroid | wukong/src/main/java/com/senorsen/wukong/utils/ResourceHelper.kt | 1 | 1795 | package com.senorsen.wukong.utils
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.content.pm.PackageManager
/**
* Generic reusable methods to handle resources.
*/
object ResourceHelper {
/**
* Get a color value from a theme attribute.
* @param context used for getting the color.
* *
* @param attribute theme attribute.
* *
* @param defaultColor default to use.
* *
* @return color value
*/
fun getThemeColor(context: Context, attribute: Int, defaultColor: Int): Int {
var themeColor = 0
val packageName = context.packageName
try {
val packageContext = context.createPackageContext(packageName, 0)
val applicationInfo = context.packageManager.getApplicationInfo(packageName, 0)
packageContext.setTheme(applicationInfo.theme)
val theme = packageContext.theme
val ta = theme.obtainStyledAttributes(intArrayOf(attribute))
themeColor = ta.getColor(0, defaultColor)
ta.recycle()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return themeColor
}
}
| agpl-3.0 | a677cc0b9736b2952b04520f9f9d33cb | 32.867925 | 91 | 0.677994 | 4.674479 | false | false | false | false |
xfournet/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/GroovyElementActionsFactory.kt | 1 | 1161 | // 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.annotator.intentions.elements
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.JvmElementActionsFactory
import com.intellij.openapi.util.text.StringUtil
class GroovyElementActionsFactory : JvmElementActionsFactory() {
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val javaClass = targetClass.toGroovyClassOrNull() ?: return emptyList()
val constantRequested = request.constant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers)
val result = ArrayList<IntentionAction>()
if (constantRequested || StringUtil.isCapitalized(request.fieldName)) {
result += CreateFieldAction(javaClass, request, true)
}
if (!constantRequested) {
result += CreateFieldAction(javaClass, request, false)
}
return result
}
}
| apache-2.0 | f84a24d040a5c2c5e37d93265e64b198 | 45.44 | 140 | 0.786391 | 4.644 | false | false | false | false |
jainaman224/Algo_Ds_Notes | Tree_Inorder_Traversal/Inorder_Traversal.kt | 1 | 1190 | //Code for printing inorder traversal in kotlin
class Node
{
//Structure of Binary tree node
int num;
Node left, right;
public node(int num)
{
key = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
BinaryTree()
{
root = null;
}
//function to print inorder traversal
fun printInorder(Node: node):void
{
if (node == null)
return;
printInorder(node.left);
//printing val of node
println(node.num);
printInorder(node.right);
}
fun printInorder():void
{
printInorder(root);
}
}
//Main function
fun main()
{
BinaryTree tree = new BinaryTree();
var read = Scanner(System.`in`)
println("Enter the size of Array:")
val arrSize = read.nextLine().toInt()
var arr = IntArray(arrSize)
println("Enter data of binary tree")
for(i in 0 until arrSize)
{
arr[i] = read.nextLine().toInt()
tree.root = new Node(arr[i]);
}
println("Inorder traversal of binary tree is");
tree.printInorder();//function call
}
/*
Input: 10 8 3 30 5 19 4 5 1
Output:5 3 1 2 8 10 19 30 4
*/
| gpl-3.0 | 43ef7f0a10abbff259d80c19b46b3079 | 18.193548 | 50 | 0.570588 | 3.695652 | false | false | false | false |
JavaEden/OrchidCore | OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/functions/AnchorFunction.kt | 1 | 2347 | package com.eden.orchid.impl.themes.functions
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.compilers.TemplateFunction
import com.eden.orchid.api.indexing.IndexService
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import javax.inject.Inject
@Description(value = "Generate an HTML link to a page.", name = "Anchor")
class AnchorFunction @Inject
constructor(val context: OrchidContext) : TemplateFunction("anchor", true) {
@Option
@Description("The title to display in an anchor tag for the given item if found. Otherwise, the title is " + "returned directly.")
lateinit var title: String
@Option
@Description("The Id of an item to link to.")
lateinit var itemId: String
@Option
@Description("The type of collection the item is expected to come from.")
lateinit var collectionType: String
@Option
@Description("The specific Id of the given collection type where the item is expected to come from.")
lateinit var collectionId: String
@Option
@Description("Custom classes to add to the resulting anchor tag. If no matching item is found, these classes are " + "not used.")
lateinit var customClasses: String
override fun parameters(): Array<String?> {
return arrayOf(
"title",
*IndexService.locateParams,
"customClasses"
)
}
override fun apply(): String? {
if (EdenUtils.isEmpty(itemId) && !EdenUtils.isEmpty(title)) {
itemId = title
}
val page = context.findPage(collectionType, collectionId, itemId)
if (page != null) {
val link = page.link
return if (!EdenUtils.isEmpty(title) && !EdenUtils.isEmpty(customClasses)) {
Clog.format("<a href=\"#{$1}\" class=\"#{$3}\">#{$2}</a>", link, title, customClasses)
} else if (!EdenUtils.isEmpty(title)) {
Clog.format("<a href=\"#{$1}\">#{$2}</a>", link, title)
} else {
Clog.format("<a href=\"#{$1}\">#{$1}</a>", link)
}
}
return if (!EdenUtils.isEmpty(title)) {
title
} else {
""
}
}
}
| mit | 1d584eddda8c5845282645c620c7b5e5 | 33.014493 | 134 | 0.628462 | 4.330258 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/adapters/MultiSelectAdapter.kt | 1 | 3621 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.adapters
import android.support.v7.widget.RecyclerView
import android.util.SparseBooleanArray
import net.fred.taskgame.utils.recycler.ItemActionAdapter
import net.fred.taskgame.utils.recycler.ItemActionListener
import net.fred.taskgame.utils.recycler.ItemActionViewHolder
abstract class MultiSelectAdapter<VH>(private val mListener: ItemActionListener, private val mRecyclerView: RecyclerView) : RecyclerView.Adapter<VH>(), ItemActionAdapter where VH : RecyclerView.ViewHolder, VH : ItemActionViewHolder {
private val mSelectedItems = SparseBooleanArray()
fun isItemSelected(position: Int): Boolean {
return mSelectedItems.get(position)
}
fun selectAll() {
for (i in 0..itemCount - 1) {
if (!isItemSelected(i)) {
updateView(mRecyclerView, i, false)
mSelectedItems.put(i, true)
}
}
}
fun clearSelections() {
for (i in 0..itemCount - 1) {
updateView(mRecyclerView, i, true)
}
mSelectedItems.clear()
}
val selectedItemCount: Int
get() = mSelectedItems.size()
val selectedItems: IntArray
get() {
val itemsPos = IntArray(mSelectedItems.size())
for (i in 0..mSelectedItems.size() - 1) {
itemsPos[i] = mSelectedItems.keyAt(i)
}
return itemsPos
}
override fun onBindViewHolder(holder: VH, position: Int) {
if (isItemSelected(position)) {
holder.onItemSelected()
} else {
holder.onItemClear()
}
}
protected fun toggleSelection(select: Boolean, position: Int) {
updateView(mRecyclerView, position, !select)
if (!select) {
mSelectedItems.delete(position)
} else {
mSelectedItems.put(position, true)
}
}
private fun updateView(recyclerView: RecyclerView, position: Int, isCurrentlySelected: Boolean) {
val child = mRecyclerView.layoutManager.findViewByPosition(position)
if (child != null) {
val viewHolder = recyclerView.getChildViewHolder(child) as ItemActionViewHolder
// Let the view holder know that this item is being moved or dragged
if (isCurrentlySelected) {
viewHolder.onItemClear()
} else {
viewHolder.onItemSelected()
}
}
}
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
return mListener.onItemMove(fromPosition, toPosition)
}
override fun onItemMoveFinished() {
mListener.onItemMoveFinished()
}
override fun onItemSwiped(position: Int) {
mListener.onItemSwiped(position)
}
override fun onItemSelected(position: Int) {
toggleSelection(true, position)
mListener.onItemSelected(position)
}
}
| gpl-3.0 | 124fc505a16c889bdaf9de9bff4e2669 | 32.220183 | 233 | 0.654791 | 4.74574 | false | false | false | false |
SimpleTimeTracking/StandaloneClient | src/main/kotlin/org/stt/gui/jfx/MainWindowController.kt | 1 | 3836 | package org.stt.gui.jfx
import javafx.application.Platform
import javafx.fxml.FXML
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.control.Tab
import javafx.scene.image.Image
import javafx.scene.input.KeyCode
import javafx.stage.Stage
import net.engio.mbassy.bus.MBassador
import net.engio.mbassy.listener.Handler
import org.controlsfx.control.Notifications
import org.stt.event.NotifyUser
import org.stt.event.ShuttingDown
import org.stt.gui.UIMain
import java.io.IOException
import java.io.UncheckedIOException
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
import java.util.logging.Logger
import javax.inject.Inject
class MainWindowController @Inject
internal constructor(private val localization: ResourceBundle,
private val activitiesController: ActivitiesController,
private val reportController: ReportController,
private val eventBus: MBassador<Any>,
private val settingsController: SettingsController,
private val infoController: InfoController) {
private val rootNode: Parent
@FXML
private lateinit var activitiesTab: Tab
@FXML
private lateinit var reportTab: Tab
@FXML
private lateinit var settingsTab: Tab
@FXML
private lateinit var infoTab: Tab
init {
val loader = FXMLLoader(javaClass.getResource(
"/org/stt/gui/jfx/MainWindow.fxml"), localization)
loader.setController(this)
try {
rootNode = loader.load()
} catch (e: IOException) {
throw UncheckedIOException(e)
}
rootNode.stylesheets.add("org/stt/gui/jfx/STT.css")
eventBus.subscribe(this)
}
@Handler
fun onUserNotifactionRequest(event: NotifyUser) {
Notifications.create().text(event.message).show()
}
@FXML
fun initialize() {
activitiesTab.content = activitiesController.node
CompletableFuture.supplyAsync { reportController.panel }
.thenAcceptAsync({ reportTab.content = it }, { Platform.runLater(it) })
.handle { _, t ->
if (t != null) LOG.log(Level.SEVERE, "Error while building report controller", t)
t!!.message
}
CompletableFuture.supplyAsync { settingsController.panel }
.thenAcceptAsync({ settingsTab.content = it }, { Platform.runLater(it) })
.handle { _, t ->
if (t != null) LOG.log(Level.SEVERE, "Error while building settings controller", t)
t!!.message
}
CompletableFuture.supplyAsync { infoController.getPanel() }
.thenAcceptAsync({ infoTab.content = it }, { Platform.runLater(it) })
.handle { _, t ->
if (t != null) LOG.log(Level.SEVERE, "Error while building info controller", t)
t!!.message
}
}
fun show(stage: Stage) {
val scene = Scene(rootNode)
stage.setOnCloseRequest { Platform.runLater { this.shutdown() } }
scene.setOnKeyPressed { event ->
if (KeyCode.ESCAPE == event.code) {
event.consume()
shutdown()
}
}
val applicationIcon = Image("/Logo.png", 32.0, 32.0, true, true)
stage.icons.add(applicationIcon)
stage.title = localization.getString("window.title")
stage.scene = scene
stage.sizeToScene()
stage.show()
}
private fun shutdown() {
eventBus.publish(ShuttingDown())
}
companion object {
private val LOG = Logger.getLogger(UIMain::class.java
.name)
}
}
| gpl-3.0 | 22e0680c3fd1634d9d53e5f31873aad3 | 31.508475 | 103 | 0.623566 | 4.566667 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/data/database/DbFavoritePlayer.kt | 1 | 806 | package com.garpr.android.data.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.garpr.android.data.models.AbsPlayer
import com.garpr.android.data.models.FavoritePlayer
import com.garpr.android.data.models.Region
@Entity(tableName = "favoritePlayers")
class DbFavoritePlayer(
@PrimaryKey val id: String,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "region") val region: Region
) {
constructor(player: AbsPlayer, region: Region) : this(player.id, player.name, region)
fun toFavoritePlayer(): FavoritePlayer {
return FavoritePlayer(
id = id,
name = name,
region = region
)
}
override fun toString(): String = name
}
| unlicense | 05c1330c7def36e329356cac7e9cb0ae | 26.793103 | 89 | 0.677419 | 4.176166 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/test/kotlin/glimpse/shaders/ProgramBuilderSpec.kt | 1 | 3104 | package glimpse.shaders
import com.nhaarman.mockito_kotlin.*
import glimpse.gles.GLES
import glimpse.test.GlimpseSpec
class ProgramBuilderSpec : GlimpseSpec() {
init {
"Program builder" should {
"create both shaders" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).createShader(ShaderType.VERTEX)
verify(glesMock).createShader(ShaderType.FRAGMENT)
}
"compile both shaders" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).compileShader(ShaderHandle(1), "vertex shader code")
verify(glesMock).compileShader(ShaderHandle(2), "fragment shader code")
}
"cause exception if compilation fails" {
glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn false
on { getShaderLog(ShaderHandle(2)) } doReturn "Error"
}
shouldThrow<ShaderCompileException> {
buildShaderProgram()
}
}
"create a program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).createProgram()
}
"attach both shaders to program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(1))
verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(2))
}
"link a program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).linkProgram(ProgramHandle(3))
}
"return a program with correct data" {
val glesMock = glesMock()
val program = buildShaderProgram()
program.gles shouldBe glesMock
program.handle shouldBe ProgramHandle(3)
program.shaders should haveSize(2)
program.shaders.map { it.gles }.filter { it != glesMock } should beEmpty()
program.shaders.map { it.type } should containInAnyOrder(*ShaderType.values())
program.shaders.map { it.handle } should containInAnyOrder(ShaderHandle(1), ShaderHandle(2))
}
"cause exception if linking fails" {
glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true
on { createProgram() } doReturn ProgramHandle(3)
on { getProgramLinkStatus(ProgramHandle(3)) } doReturn false
on { getProgramLog(ProgramHandle(3)) } doReturn "Error"
}
shouldThrow<ProgramLinkException> {
buildShaderProgram()
}
}
}
}
private fun glesMock(): GLES = glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true
on { createProgram() } doReturn ProgramHandle(3)
on { getProgramLinkStatus(ProgramHandle(3)) } doReturn true
}
private fun buildShaderProgram(): Program = shaderProgram {
vertexShader {
"vertex shader code"
}
fragmentShader {
"fragment shader code"
}
}
}
| apache-2.0 | 799e9ffe3ef98f94a2c5756c9b14ed24 | 32.021277 | 96 | 0.707474 | 3.730769 | false | false | false | false |
ankidroid/Anki-Android | lint-rules/src/main/java/com/ichi2/anki/lint/rules/DirectGregorianInstantiation.kt | 1 | 4042 | /****************************************************************************************
* Copyright (c) 2020 lukstbit <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
@file:Suppress("UnstableApiUsage")
package com.ichi2.anki.lint.rules
import com.android.tools.lint.detector.api.*
import com.google.common.annotations.VisibleForTesting
import com.ichi2.anki.lint.utils.Constants
import com.ichi2.anki.lint.utils.LintUtils
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
import java.util.GregorianCalendar
/**
* This custom Lint rules will raise an error if a developer creates [GregorianCalendar] instances directly
* instead of using the collection's getTime() method.
*/
class DirectGregorianInstantiation : Detector(), SourceCodeScanner {
companion object {
@VisibleForTesting
const val ID = "DirectGregorianInstantiation"
@VisibleForTesting
const val DESCRIPTION = "Use the collection's getTime() method instead of directly creating GregorianCalendar instances"
private const val EXPLANATION = "Creating GregorianCalendar instances directly is not allowed, as it " +
"prevents control of time during testing. Use the collection's getTime() method instead"
private val implementation = Implementation(DirectGregorianInstantiation::class.java, Scope.JAVA_FILE_SCOPE)
val ISSUE: Issue = Issue.create(
ID,
DESCRIPTION,
EXPLANATION,
Constants.ANKI_TIME_CATEGORY,
Constants.ANKI_TIME_PRIORITY,
Constants.ANKI_TIME_SEVERITY,
implementation
)
}
override fun getApplicableMethodNames() = mutableListOf("from")
override fun getApplicableConstructorTypes() = mutableListOf("java.util.GregorianCalendar")
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
super.visitMethodCall(context, node, method)
val evaluator = context.evaluator
val foundClasses = context.uastFile!!.classes
if (!LintUtils.isAnAllowedClass(foundClasses, "Time") && evaluator.isMemberInClass(method, "java.util.GregorianCalendar")) {
context.report(
ISSUE,
context.getCallLocation(node, includeReceiver = true, includeArguments = true),
DESCRIPTION
)
}
}
override fun visitConstructor(context: JavaContext, node: UCallExpression, constructor: PsiMethod) {
super.visitConstructor(context, node, constructor)
val foundClasses = context.uastFile!!.classes
if (!LintUtils.isAnAllowedClass(foundClasses, "Time")) {
context.report(
ISSUE,
node,
context.getLocation(node),
DESCRIPTION
)
}
}
}
| gpl-3.0 | 674a4fcf01e8bda8f1c3f92561e6263e | 47.698795 | 132 | 0.588323 | 5.432796 | false | false | false | false |
tipsy/javalin | javalin-openapi/src/main/java/io/javalin/plugin/openapi/annotations/AnnotationApi.kt | 1 | 6133 | package io.javalin.plugin.openapi.annotations
import io.javalin.core.PathParser
import io.javalin.core.util.JavalinLogger
import kotlin.reflect.KClass
/**
* Provide metadata for the generation of the open api documentation to the annotated Handler.
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
annotation class OpenApi(
/** Ignore the endpoint in the open api documentation */
val ignore: Boolean = false,
val summary: String = NULL_STRING,
val description: String = NULL_STRING,
val operationId: String = NULL_STRING,
val deprecated: Boolean = false,
val tags: Array<String> = [],
val cookies: Array<OpenApiParam> = [],
val headers: Array<OpenApiParam> = [],
val pathParams: Array<OpenApiParam> = [],
val queryParams: Array<OpenApiParam> = [],
val formParams: Array<OpenApiFormParam> = [],
val requestBody: OpenApiRequestBody = OpenApiRequestBody([]),
val composedRequestBody: OpenApiComposedRequestBody = OpenApiComposedRequestBody([]),
val fileUploads: Array<OpenApiFileUpload> = [],
val responses: Array<OpenApiResponse> = [],
val security: Array<OpenApiSecurity> = [],
/** The path of the endpoint. This will if the annotation * couldn't be found via reflection. */
val path: String = NULL_STRING,
/** The method of the endpoint. This will if the annotation * couldn't be found via reflection. */
val method: HttpMethod = HttpMethod.GET
)
@Target()
annotation class OpenApiResponse(
val status: String,
val content: Array<OpenApiContent> = [],
val description: String = NULL_STRING
)
@Target()
annotation class OpenApiParam(
val name: String,
val type: KClass<*> = String::class,
val description: String = NULL_STRING,
val deprecated: Boolean = false,
val required: Boolean = false,
val allowEmptyValue: Boolean = false,
val isRepeatable: Boolean = false
)
@Target()
annotation class OpenApiFormParam(
val name: String,
val type: KClass<*> = String::class,
val required: Boolean = false
)
@Target()
annotation class OpenApiRequestBody(
val content: Array<OpenApiContent>,
val required: Boolean = false,
val description: String = NULL_STRING
)
@Target()
annotation class OpenApiComposedRequestBody(
val anyOf: Array<OpenApiContent> = [],
val oneOf: Array<OpenApiContent> = [],
val required: Boolean = false,
val description: String = NULL_STRING,
val contentType: String = ContentType.AUTODETECT
)
@Target()
annotation class OpenApiFileUpload(
val name: String,
val isArray: Boolean = false,
val description: String = NULL_STRING,
val required: Boolean = false
)
@Target()
annotation class OpenApiContent(
val from: KClass<*> = NULL_CLASS::class,
/** Whenever the schema should be wrapped in an array */
val isArray: Boolean = false,
val type: String = ContentType.AUTODETECT
)
@Target()
annotation class OpenApiSecurity(
val name: String,
val scopes: Array<String> = []
)
/** Null string because annotations do not support null values */
const val NULL_STRING = "-- This string represents a null value and shouldn't be used --"
/** Null class because annotations do not support null values */
class NULL_CLASS
object ContentType {
const val JSON = "application/json"
const val HTML = "text/html"
const val FORM_DATA_URL_ENCODED = "application/x-www-form-urlencoded"
const val FORM_DATA_MULTIPART = "multipart/form-data"
const val AUTODETECT = "AUTODETECT - Will be replaced later"
}
enum class ComposedType {
NULL,
ANY_OF,
ONE_OF;
}
enum class HttpMethod {
POST,
GET,
PUT,
PATCH,
DELETE,
HEAD,
OPTIONS,
TRACE;
}
data class PathInfo(val path: String, val method: HttpMethod)
val OpenApi.pathInfo get() = PathInfo(path, method)
/** Checks if there are any potential bugs in the configuration */
fun OpenApi.warnUserAboutPotentialBugs(parentClass: Class<*>) {
warnUserIfPathParameterIsMissingInPath(parentClass)
}
fun OpenApi.warnUserIfPathParameterIsMissingInPath(parentClass: Class<*>) {
if (pathParams.isEmpty() || path == NULL_STRING) {
// Nothing to check
return
}
val detectedPathParams = PathParser(path, ignoreTrailingSlashes = true).pathParamNames.toSet()
val pathParamsPlaceholderNotInPath = pathParams.map { it.name }.filter { it !in detectedPathParams }
if (pathParamsPlaceholderNotInPath.isNotEmpty()) {
JavalinLogger.warn(
formatMissingPathParamsPlaceholderWarningMessage(parentClass, pathParamsPlaceholderNotInPath)
)
}
}
fun OpenApi.formatMissingPathParamsPlaceholderWarningMessage(parentClass: Class<*>, pathParamsPlaceholders: List<String>): String {
val methodAsString = method.name
val multipleParams = pathParamsPlaceholders.size > 1
val secondSentence = if (multipleParams) {
"The path params ${pathParamsPlaceholders.toFormattedString()} are documented, but couldn't be found in $methodAsString \"$path\"."
} else {
"The path param ${pathParamsPlaceholders.toFormattedString()} is documented, but couldn't be found in $methodAsString \"$path\"."
}
return "The `path` of one of the @OpenApi annotations on ${parentClass.canonicalName} is incorrect. " +
secondSentence + " " +
"You need to use Javalin's path parameter syntax inside the path and only use the parameter name for the name field." + " " +
"Do you mean $methodAsString \"$path/${pathParamsPlaceholders.joinToString("/") { "{$it}" }}\"?"
}
fun List<String>.toFormattedString(): String {
if (size == 1) {
return "\"${this[0]}\""
}
var result = ""
this.forEachIndexed { index, s ->
when {
index == lastIndex -> result += " and "
index > 0 -> result += ", "
}
result += "\"$s\""
}
return result
}
| apache-2.0 | cdf6fc5e9a15ee6e36157099768d4644 | 32.883978 | 139 | 0.664927 | 4.428159 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/patterns/WCP9.kt | 1 | 2204 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.patterns
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.configurableModel.activity
import nl.adaptivity.process.processModel.configurableModel.endNode
import nl.adaptivity.process.processModel.configurableModel.join
import nl.adaptivity.process.processModel.configurableModel.startNode
import org.junit.jupiter.api.DisplayName
@DisplayName("WCP9: Structured Discriminator")
class WCP9 : TraceTest(Companion) {
companion object : ConfigBase() {
override val modelData: ModelData = run {
val model = object : TestConfigurableModel("WCP9") {
val start1 by startNode
val start2 by startNode
val ac1 by activity(start1)
val ac2 by activity(start2)
val join by join(ac1, ac2) { min = 1; max = 1 }
val ac3 by activity(join)
val end by endNode(ac3)
}
val validTraces = with(model) {
trace {
((start1 .. ac1) or (start2 .. ac2)) .. join .. ac3 ..end
}
}
val invalidTraces = with(model) {
trace {
val starts = (start1.opt % start2.opt).filter { it.elems.isNotEmpty() }
ac1 or ac2 or (starts..(ac3 or end or join)) or
(starts..ac1 % ac2)
}
}
ModelData(model, validTraces, invalidTraces)
}
}
}
| lgpl-3.0 | f2c6fcfe43c9659f935b43bbd0d61f73 | 39.814815 | 112 | 0.631579 | 4.38171 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/geometry/ElementGeometryCreator.kt | 1 | 10030 | package de.westnordost.streetcomplete.data.osm.geometry
import de.westnordost.streetcomplete.data.osm.mapdata.MapData
import de.westnordost.streetcomplete.data.osm.mapdata.*
import de.westnordost.streetcomplete.ktx.isArea
import de.westnordost.streetcomplete.util.centerPointOfPolygon
import de.westnordost.streetcomplete.util.centerPointOfPolyline
import de.westnordost.streetcomplete.util.isRingDefinedClockwise
import javax.inject.Inject
import kotlin.collections.ArrayList
/** Creates an ElementGeometry from an element and a collection of positions. */
class ElementGeometryCreator @Inject constructor() {
/** Create an ElementGeometry from any element, using the given MapData to find the positions
* of the nodes.
*
* @param element the element to create the geometry for
* @param mapData the MapData that contains the elements with the necessary
* @param allowIncomplete whether incomplete relations should return an incomplete
* ElementGeometry (otherwise: null)
*
* @return an ElementGeometry or null if any necessary element to create the geometry is not
* in the given MapData */
fun create(element: Element, mapData: MapData, allowIncomplete: Boolean = false): ElementGeometry? {
when(element) {
is Node -> {
return create(element)
}
is Way -> {
val positions = mapData.getNodePositions(element) ?: return null
return create(element, positions)
}
is Relation -> {
val positionsByWayId = mapData.getWaysNodePositions(element, allowIncomplete) ?: return null
return create(element, positionsByWayId)
}
else -> return null
}
}
/** Create an ElementPointGeometry for a node. */
fun create(node: Node) = ElementPointGeometry(node.position)
/**
* Create an ElementGeometry for a way
*
* @param way the way to create the geometry for
* @param wayGeometry the geometry of the way: A list of positions of its nodes.
*
* @return an ElementPolygonsGeometry if the way is an area or an ElementPolylinesGeometry
* if the way is a linear feature */
fun create(way: Way, wayGeometry: List<LatLon>): ElementGeometry? {
val polyline = ArrayList(wayGeometry)
polyline.eliminateDuplicates()
if (wayGeometry.size < 2) return null
return if (way.isArea()) {
/* ElementGeometry considers polygons that are defined clockwise holes, so ensure that
it is defined CCW here. */
if (polyline.isRingDefinedClockwise()) polyline.reverse()
ElementPolygonsGeometry(arrayListOf(polyline), polyline.centerPointOfPolygon())
} else {
ElementPolylinesGeometry(arrayListOf(polyline), polyline.centerPointOfPolyline())
}
}
/**
* Create an ElementGeometry for a relation
*
* @param relation the relation to create the geometry for
* @param wayGeometries the geometries of the ways that are members of the relation. It is a
* map of way ids to a list of positions.
*
* @return an ElementPolygonsGeometry if the relation describes an area or an
* ElementPolylinesGeometry if it describes is a linear feature */
fun create(relation: Relation, wayGeometries: Map<Long, List<LatLon>>): ElementGeometry? {
return if (relation.isArea()) {
createMultipolygonGeometry(relation, wayGeometries)
} else {
createPolylinesGeometry(relation, wayGeometries)
}
}
private fun createMultipolygonGeometry(
relation: Relation,
wayGeometries: Map<Long, List<LatLon>>
): ElementPolygonsGeometry? {
val outer = createNormalizedRingGeometry(relation, "outer", false, wayGeometries)
val inner = createNormalizedRingGeometry(relation, "inner", true, wayGeometries)
if (outer.isEmpty()) return null
val rings = ArrayList<ArrayList<LatLon>>()
rings.addAll(outer)
rings.addAll(inner)
/* only use first ring that is not a hole if there are multiple
this is the same behavior as Leaflet or Tangram */
return ElementPolygonsGeometry(rings, outer.first().centerPointOfPolygon())
}
private fun createPolylinesGeometry(
relation: Relation,
wayGeometries: Map<Long, List<LatLon>>
): ElementPolylinesGeometry? {
val waysNodePositions = getRelationMemberWaysNodePositions(relation, wayGeometries)
val joined = waysNodePositions.joined()
val polylines = joined.ways
polylines.addAll(joined.rings)
if (polylines.isEmpty()) return null
/* if there are more than one polylines, these polylines are not connected to each other,
so there is no way to find a reasonable "center point". In most cases however, there
is only one polyline, so let's just take the first one...
This is the same behavior as Leaflet or Tangram */
return ElementPolylinesGeometry(polylines, polylines.first().centerPointOfPolyline())
}
private fun createNormalizedRingGeometry(
relation: Relation,
role: String,
clockwise: Boolean,
wayGeometries: Map<Long, List<LatLon>>
): ArrayList<ArrayList<LatLon>> {
val waysNodePositions = getRelationMemberWaysNodePositions(relation, role, wayGeometries)
val ringGeometry = waysNodePositions.joined().rings
ringGeometry.setOrientation(clockwise)
return ringGeometry
}
private fun getRelationMemberWaysNodePositions(
relation: Relation, wayGeometries: Map<Long, List<LatLon>>
): List<List<LatLon>> {
return relation.members
.filter { it.type == ElementType.WAY }
.mapNotNull { getValidNodePositions(wayGeometries[it.ref]) }
}
private fun getRelationMemberWaysNodePositions(
relation: Relation, withRole: String, wayGeometries: Map<Long, List<LatLon>>
): List<List<LatLon>> {
return relation.members
.filter { it.type == ElementType.WAY && it.role == withRole }
.mapNotNull { getValidNodePositions(wayGeometries[it.ref]) }
}
private fun getValidNodePositions(wayGeometry: List<LatLon>?): List<LatLon>? {
if (wayGeometry == null) return null
val nodePositions = ArrayList(wayGeometry)
nodePositions.eliminateDuplicates()
return if (nodePositions.size >= 2) nodePositions else null
}
}
/** Ensures that all given rings are defined in clockwise/counter-clockwise direction */
private fun List<MutableList<LatLon>>.setOrientation(clockwise: Boolean) {
for (ring in this) {
if (ring.isRingDefinedClockwise() != clockwise) {
ring.reverse()
}
}
}
private fun List<LatLon>.isRing() = first() == last()
private class ConnectedWays(val rings: ArrayList<ArrayList<LatLon>>, val ways: ArrayList<ArrayList<LatLon>>)
/** Returns a list of polylines joined together at their endpoints into rings and ways */
private fun List<List<LatLon>>.joined(): ConnectedWays {
val nodeWayMap = NodeWayMap(this)
val rings: ArrayList<ArrayList<LatLon>> = ArrayList()
val ways: ArrayList<ArrayList<LatLon>> = ArrayList()
var currentWay: ArrayList<LatLon> = ArrayList()
while (nodeWayMap.hasNextNode()) {
val node: LatLon = if (currentWay.isEmpty()) nodeWayMap.getNextNode() else currentWay.last()
val waysAtNode = nodeWayMap.getWaysAtNode(node)
if (waysAtNode == null) {
ways.add(currentWay)
currentWay = ArrayList()
} else {
val way = waysAtNode.first()
currentWay.join(way)
nodeWayMap.removeWay(way)
// finish ring and start new one
if (currentWay.isRing()) {
rings.add(currentWay)
currentWay = ArrayList()
}
}
}
if (currentWay.isNotEmpty()) {
ways.add(currentWay)
}
return ConnectedWays(rings, ways)
}
/** Join the given adjacent polyline into this polyline */
private fun MutableList<LatLon>.join(way: List<LatLon>) {
if (isEmpty()) {
addAll(way)
} else {
when {
last() == way.last() -> addAll(way.asReversed().subList(1, way.size))
last() == way.first() -> addAll(way.subList(1, way.size))
first() == way.last() -> addAll(0, way.subList(0, way.size - 1))
first() == way.first() -> addAll(0, way.asReversed().subList(0, way.size - 1))
else -> throw IllegalArgumentException("The ways are not adjacent")
}
}
}
private fun MutableList<LatLon>.eliminateDuplicates() {
val it = iterator()
var prev: LatLon? = null
while (it.hasNext()) {
val line = it.next()
if (prev == null || line.latitude != prev.latitude || line.longitude != prev.longitude) {
prev = line
} else {
it.remove()
}
}
}
private fun MapData.getNodePositions(way: Way): List<LatLon>? {
return way.nodeIds.map { nodeId ->
val node = getNode(nodeId) ?: return null
node.position
}
}
private fun MapData.getWaysNodePositions(relation: Relation, allowIncomplete: Boolean = false): Map<Long, List<LatLon>>? {
val wayMembers = relation.members.filter { it.type == ElementType.WAY }
val result = mutableMapOf<Long, List<LatLon>>()
for (wayMember in wayMembers) {
val way = getWay(wayMember.ref)
if (way != null) {
val wayPositions = getNodePositions(way)
if (wayPositions != null) {
result[way.id] = wayPositions
} else {
if (!allowIncomplete) return null
}
} else {
if (!allowIncomplete) return null
}
}
return result
}
| gpl-3.0 | 6758b2f8dc5d01072983302aed609f06 | 37.429119 | 122 | 0.644865 | 4.493728 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/auth/LoginFragment.kt | 1 | 9184 | package org.fossasia.openevent.general.auth
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.navArgs
import kotlinx.android.synthetic.main.fragment_login.email
import kotlinx.android.synthetic.main.fragment_login.loginButton
import kotlinx.android.synthetic.main.fragment_login.password
import kotlinx.android.synthetic.main.fragment_login.view.*
import kotlinx.android.synthetic.main.fragment_login.view.email
import kotlinx.android.synthetic.main.fragment_login.view.skipTextView
import kotlinx.android.synthetic.main.fragment_login.view.toolbar
import org.fossasia.openevent.general.BuildConfig
import org.fossasia.openevent.general.PLAY_STORE_BUILD_FLAVOR
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.event.EVENT_DETAIL_FRAGMENT
import org.fossasia.openevent.general.favorite.FAVORITE_FRAGMENT
import org.fossasia.openevent.general.notification.NOTIFICATION_FRAGMENT
import org.fossasia.openevent.general.order.ORDERS_FRAGMENT
import org.fossasia.openevent.general.search.ORDER_COMPLETED_FRAGMENT
import org.fossasia.openevent.general.search.SEARCH_RESULTS_FRAGMENT
import org.fossasia.openevent.general.speakercall.SPEAKERS_CALL_FRAGMENT
import org.fossasia.openevent.general.ticket.TICKETS_FRAGMENT
import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard
import org.fossasia.openevent.general.utils.Utils.progressDialog
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.Utils.show
import org.fossasia.openevent.general.utils.Utils.showNoInternetDialog
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.fossasia.openevent.general.utils.extensions.setSharedElementEnterTransition
import org.jetbrains.anko.design.longSnackbar
import org.jetbrains.anko.design.snackbar
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class LoginFragment : Fragment() {
private val loginViewModel by viewModel<LoginViewModel>()
private val smartAuthViewModel by sharedViewModel<SmartAuthViewModel>()
private lateinit var rootView: View
private val safeArgs: LoginFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
rootView = inflater.inflate(R.layout.fragment_login, container, false)
val progressDialog = progressDialog(context)
setToolbar(activity, show = false)
rootView.toolbar.setNavigationOnClickListener {
activity?.onBackPressed()
}
rootView.settings.setOnClickListener {
findNavController(rootView).navigate(LoginFragmentDirections.actionLoginToSetting())
}
if (loginViewModel.isLoggedIn())
popBackStack()
rootView.loginButton.setOnClickListener {
loginViewModel.login(email.text.toString(), password.text.toString())
hideSoftKeyboard(context, rootView)
}
rootView.skipTextView.isVisible = safeArgs.showSkipButton
rootView.skipTextView.setOnClickListener {
findNavController(rootView).navigate(
LoginFragmentDirections.actionLoginToEventsPop()
)
}
if (safeArgs.email.isNotEmpty()) {
setSharedElementEnterTransition()
rootView.email.text = SpannableStringBuilder(safeArgs.email)
rootView.email.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
if (s.toString() != safeArgs.email) {
findNavController(rootView).navigate(LoginFragmentDirections
.actionLoginToAuthPop(redirectedFrom = safeArgs.redirectedFrom, email = s.toString()))
rootView.email.removeTextChangedListener(this)
}
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { /*Do Nothing*/ }
override fun onTextChanged(email: CharSequence, start: Int, before: Int, count: Int) { /*Do Nothing*/ }
})
} else if (BuildConfig.FLAVOR == PLAY_STORE_BUILD_FLAVOR) {
smartAuthViewModel.requestCredentials(SmartAuthUtil.getCredentialsClient(requireActivity()))
smartAuthViewModel.id
.nonNull()
.observe(viewLifecycleOwner, Observer {
email.text = SpannableStringBuilder(it)
})
smartAuthViewModel.password
.nonNull()
.observe(viewLifecycleOwner, Observer {
password.text = SpannableStringBuilder(it)
})
smartAuthViewModel.apiExceptionCodePair.nonNull().observe(viewLifecycleOwner, Observer {
SmartAuthUtil.handleResolvableApiException(
it.first, requireActivity(), it.second)
})
smartAuthViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer {
progressDialog.show(it)
})
}
loginViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer {
progressDialog.show(it)
})
loginViewModel.showNoInternetDialog
.nonNull()
.observe(viewLifecycleOwner, Observer {
showNoInternetDialog(context)
})
loginViewModel.error
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.loginCoordinatorLayout.longSnackbar(it)
})
loginViewModel.loggedIn
.nonNull()
.observe(viewLifecycleOwner, Observer {
loginViewModel.fetchProfile()
})
rootView.password.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(password: CharSequence, start: Int, before: Int, count: Int) {
loginButton.isEnabled = password.isNotEmpty()
}
})
loginViewModel.requestTokenSuccess
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (it.status) {
rootView.mailSentTextView.text = it.message
rootView.sentEmailLayout.isVisible = true
rootView.tick.isVisible = true
rootView.loginLayout.isVisible = false
rootView.toolbar.isVisible = true
} else {
rootView.toolbar.isVisible = false
}
})
rootView.tick.setOnClickListener {
rootView.sentEmailLayout.isVisible = false
rootView.tick.isVisible = false
rootView.toolbar.isVisible = true
rootView.loginLayout.isVisible = true
}
rootView.forgotPassword.setOnClickListener {
hideSoftKeyboard(context, rootView)
loginViewModel.sendResetPasswordEmail(email.text.toString())
}
loginViewModel.user
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (BuildConfig.FLAVOR == PLAY_STORE_BUILD_FLAVOR) {
smartAuthViewModel.saveCredential(
email.text.toString(), password.text.toString(),
SmartAuthUtil.getCredentialsClient(requireActivity()))
}
popBackStack()
})
return rootView
}
private fun popBackStack() {
val destinationId =
when (safeArgs.redirectedFrom) {
PROFILE_FRAGMENT -> R.id.profileFragment
EVENT_DETAIL_FRAGMENT -> R.id.eventDetailsFragment
ORDERS_FRAGMENT -> R.id.orderUnderUserFragment
TICKETS_FRAGMENT -> R.id.ticketsFragment
NOTIFICATION_FRAGMENT -> R.id.notificationFragment
SPEAKERS_CALL_FRAGMENT -> R.id.speakersCallFragment
FAVORITE_FRAGMENT -> R.id.favoriteFragment
SEARCH_RESULTS_FRAGMENT -> R.id.searchResultsFragment
ORDER_COMPLETED_FRAGMENT -> R.id.orderCompletedFragment
else -> R.id.eventsFragment
}
if (destinationId == R.id.eventsFragment) {
findNavController(rootView).navigate(LoginFragmentDirections.actionLoginToEventsPop())
} else {
findNavController(rootView).popBackStack(destinationId, false)
}
rootView.snackbar(R.string.welcome_back)
}
}
| apache-2.0 | 2a6ac327c128598d21869d43da2fc890 | 40.556561 | 119 | 0.663436 | 5.311741 | false | false | false | false |
fossasia/open-event-android | app/src/test/java/org/fossasia/openevent/general/event/EventUtilsTest.kt | 1 | 6546 | package org.fossasia.openevent.general.event
import java.time.ZoneId
import java.util.TimeZone
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.threeten.bp.ZonedDateTime
class EventUtilsTest {
private var timeZone: TimeZone? = null
@Before
fun setUp() {
// Set fixed local time zone for tests
timeZone = TimeZone.getDefault()
TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata")))
}
@After
fun tearDown() {
TimeZone.setDefault(timeZone)
}
private fun getEvent(
id: Long = 34,
name: String = "Eva Event",
identifier: String = "abcdefgh",
startsAt: String = "2008-09-15T15:53:00+05:00",
endsAt: String = "2008-09-19T19:25:00+05:00",
timeZone: String = "Asia/Kolkata",
description: String? = null,
locationName: String? = "Test Location",
link: String? = null
) =
Event(id, name, identifier, startsAt, endsAt, timeZone,
locationName = locationName, description = description, externalEventUrl = link)
private fun getEventDateTime(dateTime: String, timeZone: String): ZonedDateTime =
EventUtils.getEventDateTime(dateTime, timeZone)
@Test
fun `should get timezone name`() {
val event = getEvent()
val localizedDateTime = getEventDateTime(event.startsAt, event.timezone)
assertEquals("""
IST
""".trimIndent(), EventUtils.getFormattedTimeZone(localizedDateTime))
}
@Test
fun `should get formatted time`() {
val event = getEvent()
val localizedDateTime = getEventDateTime(event.startsAt, event.timezone)
assertEquals("""
04:23 PM
""".trimIndent(), EventUtils.getFormattedTime(localizedDateTime))
}
@Test
fun `should get formatted date and time without year`() {
val event = getEvent()
val localizedDateTime = getEventDateTime(event.startsAt, event.timezone)
assertEquals("""
Monday, Sep 15
""".trimIndent(), EventUtils.getFormattedDateWithoutYear(localizedDateTime))
}
@Test
fun `should get formatted date short`() {
val event = getEvent()
val localizedDateTime = getEventDateTime(event.startsAt, event.timezone)
assertEquals("""
Mon, Sep 15
""".trimIndent(), EventUtils.getFormattedDateShort(localizedDateTime))
}
@Test
fun `should get formatted date`() {
val event = getEvent()
val localizedDateTime = getEventDateTime(event.startsAt, event.timezone)
assertEquals("""
Monday, September 15, 2008
""".trimIndent(), EventUtils.getFormattedDate(localizedDateTime))
}
@Test
fun `should get formatted date range when start and end date are not same`() {
val event = getEvent()
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Mon, Sep 15, 04:23 PM
""".trimIndent(), EventUtils.getFormattedEventDateTimeRange(startsAt, endsAt))
}
@Test
fun `should get formatted date range when start and end date are same`() {
val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00")
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Monday, Sep 15
""".trimIndent(), EventUtils.getFormattedEventDateTimeRange(startsAt, endsAt))
}
@Test
fun `should get formatted date range when start and end date are not same in event details`() {
val event = getEvent()
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
- Fri, Sep 19, 07:55 PM IST
""".trimIndent(), EventUtils.getFormattedEventDateTimeRangeSecond(startsAt, endsAt))
}
@Test
fun `should get formatted date range when start and end date are same in event details`() {
val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00")
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
04:23 PM - 04:23 PM IST
""".trimIndent(), EventUtils.getFormattedEventDateTimeRangeSecond(startsAt, endsAt))
}
@Test
fun `should get formatted date range when start and end date are not same in details`() {
val event = getEvent()
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Monday, September 15, 2008 at 04:23 PM - Friday, September 19, 2008 at 07:55 PM (IST)
""".trimIndent(), EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt))
}
@Test
fun `should get formatted date range when start and end date are same in details`() {
val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00")
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Monday, September 15, 2008 from 04:23 PM to 04:23 PM (IST)
""".trimIndent(), EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt))
}
@Test
fun `should get formatted date range bulleted when start and end date are not same in details`() {
val event = getEvent()
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Mon, Sep 15 - Fri, Sep 19 • 04:23 PM IST
""".trimIndent(), EventUtils.getFormattedDateTimeRangeBulleted(startsAt, endsAt))
}
@Test
fun `should get formatted date range bulleted when start and end date are same in details`() {
val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00")
val startsAt = getEventDateTime(event.startsAt, event.timezone)
val endsAt = getEventDateTime(event.endsAt, event.timezone)
assertEquals("""
Mon, Sep 15 • 04:23 PM IST
""".trimIndent(), EventUtils.getFormattedDateTimeRangeBulleted(startsAt, endsAt))
}
}
| apache-2.0 | e67c8f6e9b62e2b9d527943dbf54dc89 | 37.940476 | 102 | 0.651024 | 4.514838 | false | true | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/fragment/CrashReporterFragment.kt | 1 | 1567 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_crash_reporter.*
import org.mozilla.focus.R
import org.mozilla.focus.telemetry.TelemetryWrapper
class CrashReporterFragment : Fragment() {
var onCloseTabPressed: ((sendCrashReport: Boolean) -> Unit)? = null
private var wantsSubmitCrashReport = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_crash_reporter, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
TelemetryWrapper.crashReporterOpened()
closeTabButton.setOnClickListener {
wantsSubmitCrashReport = sendCrashCheckbox.isChecked
TelemetryWrapper.crashReporterClosed(wantsSubmitCrashReport)
onCloseTabPressed?.invoke(wantsSubmitCrashReport)
}
}
fun onBackPressed() {
TelemetryWrapper.crashReporterClosed(false)
}
companion object {
val FRAGMENT_TAG = "crash-reporter"
fun create() = CrashReporterFragment()
}
}
| mpl-2.0 | f3be0af32282e5fd4edb017cc84a1f0e | 31.645833 | 83 | 0.726867 | 4.66369 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/main/kotlin/com/google/api/kotlin/util/FieldNamer.kt | 1 | 6757 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.util
import com.google.api.kotlin.config.PropertyPath
import com.google.api.kotlin.config.ProtobufTypeMapper
import com.squareup.kotlinpoet.CodeBlock
import mu.KotlinLogging
private val log = KotlinLogging.logger {}
/**
* Utilities for creating field names, getters, setters, and accessors.
*/
internal object FieldNamer {
/*
* Create setter code based on type of field (map vs. repeated, vs. single object) using
* the DSL builder for the type.
*/
fun getDslSetterCode(
typeMap: ProtobufTypeMapper,
fieldInfo: ProtoFieldInfo,
value: CodeBlock
): CodeBlock = when {
fieldInfo.field.isMap(typeMap) -> {
val name = getDslSetterMapName(fieldInfo.field.name)
CodeBlock.of(
"this.$name = %L",
value
)
}
fieldInfo.field.isRepeated() -> {
if (fieldInfo.index >= 0) {
log.warn { "Indexed setter operations currently ignore the specified index! (${fieldInfo.message.name}.${fieldInfo.field.name})" }
CodeBlock.of(
"this.${getDslSetterRepeatedNameAtIndex(fieldInfo.field.name)}(%L)",
value
)
} else {
val name = getDslSetterRepeatedName(fieldInfo.field.name)
CodeBlock.of(
"this.$name = %L",
value
)
}
}
else -> { // normal fields
val name = getFieldName(fieldInfo.field.name)
CodeBlock.of("this.$name = %L", value)
}
}
fun getDslSetterCode(
typeMap: ProtobufTypeMapper,
fieldInfo: ProtoFieldInfo,
value: String
) = getDslSetterCode(typeMap, fieldInfo, CodeBlock.of("%L", value))
/**
* Get the accessor field name for a Java proto message type.
*/
fun getJavaAccessorName(typeMap: ProtobufTypeMapper, fieldInfo: ProtoFieldInfo): String {
if (fieldInfo.field.isMap(typeMap)) {
return getJavaBuilderAccessorMapName(fieldInfo.field.name)
} else if (fieldInfo.field.isRepeated()) {
return if (fieldInfo.index >= 0) {
"${getJavaBuilderAccessorRepeatedName(fieldInfo.field.name)}[${fieldInfo.index}]"
} else {
getJavaBuilderAccessorRepeatedName(fieldInfo.field.name)
}
}
return getJavaBuilderAccessorName(fieldInfo.field.name)
}
fun getNestedFieldName(p: PropertyPath): String =
p.segments.map { it.asVarName() }.joinToString(".")
fun getFieldName(protoFieldName: String): String =
protoFieldName.asVarName()
private fun getDslSetterMapName(protoFieldName: String): String =
protoFieldName.asVarName().escapeIfReserved()
private fun getDslSetterRepeatedName(protoFieldName: String): String =
protoFieldName.asVarName().escapeIfReserved()
private fun getDslSetterRepeatedNameAtIndex(protoFieldName: String): String =
protoFieldName.asVarName().escapeIfReserved()
fun getJavaBuilderSetterMapName(protoFieldName: String): String =
"putAll${protoFieldName.asVarName(false)}".escapeIfReserved()
fun getJavaBuilderSetterRepeatedName(protoFieldName: String): String =
"addAll${protoFieldName.asVarName(false)}".escapeIfReserved()
fun getJavaBuilderRawSetterName(protoFieldName: String): String =
"set${protoFieldName.asVarName(false)}".escapeIfReserved()
fun getJavaBuilderSyntheticSetterName(protoFieldName: String): String =
protoFieldName.asVarName().escapeIfReserved()
fun getJavaBuilderAccessorMapName(protoFieldName: String): String =
"${protoFieldName.asVarName()}Map".escapeIfReserved()
fun getJavaBuilderAccessorRepeatedName(protoFieldName: String): String =
"${protoFieldName.asVarName()}List".escapeIfReserved()
fun getJavaBuilderAccessorName(protoFieldName: String): String =
protoFieldName.asVarName().escapeIfReserved()
private fun String.asVarName(isLower: Boolean = true): String =
this.underscoresToCamelCase(!isLower)
private val LEADING_UNDERSCORES = Regex("^(_)+")
// this is taken from the protobuf utility of the same name
// snapshot: https://github.com/protocolbuffers/protobuf/blob/61301f01552dd84d744a05c88af95833c600a1a7/src/google/protobuf/compiler/cpp/cpp_helpers.cc
private fun String.underscoresToCamelCase(capitalize: Boolean): String {
var cap = capitalize
val result = StringBuffer()
// addition to the protobuf rule to handle synthetic names
var str = this.replace(LEADING_UNDERSCORES, "")
for (char in str) {
if (char.isLetter() && char.isLowerCase()) {
result.append(if (cap) char.toUpperCase() else char)
cap = false
} else if (char.isLetter() && char.isUpperCase()) {
result.append(char)
cap = false
} else if (char.isDigit()) {
result.append(char)
cap = true
} else {
cap = true
}
}
str = result.toString()
// addition to the protobuf rule to handle synthetic names
if (!capitalize) {
if (str.matches(Regex("[a-z0-9][A-Z0-9]+"))) {
str = str.toLowerCase()
}
}
return str
}
// TODO: can remove this when Kotlin poet releases %M support
private fun String.escapeIfReserved() = if (KEYWORDS.contains(this)) "`$this`" else this
private val KEYWORDS = setOf(
"package",
"as",
"typealias",
"class",
"this",
"super",
"val",
"var",
"fun",
"for",
"null",
"true",
"false",
"is",
"in",
"throw",
"return",
"break",
"continue",
"object",
"if",
"try",
"else",
"while",
"do",
"when",
"interface",
"typeof"
)
}
| apache-2.0 | 66f76679bc6fa903ea69fff7ae6fa549 | 33.126263 | 154 | 0.613142 | 4.510681 | false | false | false | false |
ageery/kwicket | kwicket-wicket-webjars/src/main/kotlin/org/kwicket/agilecoders/wicket/webjars/Applications.kt | 1 | 2592 | package org.kwicket.agilecoders.wicket.webjars
import de.agilecoders.wicket.webjars.WicketWebjars
import de.agilecoders.wicket.webjars.collectors.AssetPathCollector
import de.agilecoders.wicket.webjars.settings.ResourceStreamProvider
import de.agilecoders.wicket.webjars.settings.WebjarsSettings
import org.apache.wicket.protocol.http.WebApplication
import org.apache.wicket.util.time.Duration
import java.util.regex.Pattern
/**
* Extension method for enabling webjars in a [WebApplication].
*
* @receiver the [WebApplication] to add the webjars functionality to
* @param A type of [WebApplication] the webjar functionality is being added to
* @param resourceStreamProvider [ResourceStreamProvider] to use to load resources
* @param assetPathCollectors [AssetPathCollector instances to use to find resources
* @param webjarsPackage webjars package path (e.g. "META-INF.resources.webjars")
* @param webjarsPath the path where all webjars are stored (e.g. "META-INF/resources/webjars")
* @param resourcePattern the pattern to filter accepted webjars resources
* @param recentVersionPlaceHolder placeholder for recent version (e.g. current)
* @param readFromCacheTimeout timeout which is used when reading from cache (Future.get(timeout))
* @param useCdnResources whether the resources for the webjars should be loaded from a CDN network
* @param cdnUrl base URL of the webjars CDN
* @return the [WebApplication] the webjar functionality was added to
*/
fun <A : WebApplication> A.enableWebjars(
resourceStreamProvider: ResourceStreamProvider? = null,
assetPathCollectors: Array<AssetPathCollector>? = null,
webjarsPackage: String? = null,
webjarsPath: String? = null,
resourcePattern: Pattern? = null,
recentVersionPlaceHolder: String? = null,
readFromCacheTimeout: Duration? = null,
useCdnResources: Boolean? = null,
cdnUrl: String? = null
): A {
val settings = WebjarsSettings()
resourceStreamProvider?.let { settings.resourceStreamProvider(it) }
assetPathCollectors?.let { settings.assetPathCollectors(*it) }
webjarsPackage?.let { settings.webjarsPackage(it) }
webjarsPath?.let { settings.webjarsPath(it) }
resourcePattern?.let { settings.resourcePattern(it) }
webjarsPath?.let { settings.webjarsPath(it) }
recentVersionPlaceHolder?.let { settings.recentVersionPlaceHolder(it) }
readFromCacheTimeout?.let { settings.readFromCacheTimeout(it) }
useCdnResources?.let { settings.useCdnResources(it) }
cdnUrl?.let { settings.cdnUrl(it) }
WicketWebjars.install(this, settings)
return this
} | apache-2.0 | 24418b31740461fc24823ad5ae936017 | 47.924528 | 99 | 0.774306 | 4.05 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/dialog/AppLoginDialogFragment.kt | 1 | 2633 | package me.ykrank.s1next.view.dialog
import android.os.Bundle
import com.github.ykrank.androidtools.widget.RxBus
import io.reactivex.Single
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.data.api.app.AppService
import me.ykrank.s1next.data.api.app.model.AppDataWrapper
import me.ykrank.s1next.data.api.app.model.AppLoginResult
import me.ykrank.s1next.view.event.AppLoginEvent
import javax.inject.Inject
/**
* A [ProgressDialogFragment] posts a request to login to server.
*/
class AppLoginDialogFragment : ProgressDialogFragment<AppDataWrapper<AppLoginResult>>() {
@Inject
internal lateinit var mAppService: AppService
@Inject
internal lateinit var mRxBus: RxBus
override fun onCreate(savedInstanceState: Bundle?) {
App.appComponent.inject(this)
super.onCreate(savedInstanceState)
}
override fun getSourceObservable(): Single<AppDataWrapper<AppLoginResult>> {
val username = arguments?.getString(ARG_USERNAME)
val password = arguments?.getString(ARG_PASSWORD)
val questionId = arguments?.getInt(ARG_QUESTION_ID)
val answer = arguments?.getString(ARG_ANSWER)
return mAppService.login(username, password, questionId, answer)
}
override fun onNext(data: AppDataWrapper<AppLoginResult>) {
if (data.success) {
if (mUserValidator.validateAppLoginInfo(data.data)) {
showShortTextAndFinishCurrentActivity(data.message)
mRxBus.post(AppLoginEvent())
} else {
showToastText(getString(R.string.app_login_info_error))
}
} else {
showToastText(data.message)
}
}
override fun getProgressMessage(): CharSequence? {
return getText(R.string.dialog_progress_message_login)
}
companion object {
val TAG: String = AppLoginDialogFragment::class.java.name
private const val ARG_USERNAME = "username"
private const val ARG_PASSWORD = "password"
private const val ARG_QUESTION_ID = "question_id"
private const val ARG_ANSWER = "answer"
fun newInstance(username: String, password: String, questionId: Int, answer: String): AppLoginDialogFragment {
val fragment = AppLoginDialogFragment()
val bundle = Bundle()
bundle.putString(ARG_USERNAME, username)
bundle.putString(ARG_PASSWORD, password)
bundle.putInt(ARG_QUESTION_ID, questionId)
bundle.putString(ARG_ANSWER, answer)
fragment.arguments = bundle
return fragment
}
}
}
| apache-2.0 | 7738f160714788693ba96fa237ceef64 | 34.106667 | 118 | 0.682491 | 4.352066 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/adapter/TitleAdapter.kt | 2 | 2899 | package org.worshipsongs.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import java.util.*
/**
* Author : Madasamy
* Version : 3.x.x
*/
class TitleAdapter<T>(context: AppCompatActivity, @LayoutRes resource: Int) : ArrayAdapter<T>(context, resource)
{
private var titleAdapterListener: TitleAdapterListener<T>? = null
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View
{
var view = convertView
if (view == null)
{
val layoutInflater = LayoutInflater.from(context)
view = layoutInflater.inflate(R.layout.title_row, null)
}
setViews(view!!, position)
return view
}
private fun setViews(view: View, position: Int)
{
val maps = HashMap<String, Any>()
maps[CommonConstants.TITLE_KEY] = getTitlesView(view)
maps[CommonConstants.SUBTITLE_KEY] = getSubtitleTextView(view)
maps[CommonConstants.COUNT_KEY] = getCountView(view)
maps[CommonConstants.PLAY_IMAGE_KEy] = getPlayImageView(view)
maps[CommonConstants.OPTIONS_IMAGE_KEY] = getOptionsImageView(view)
maps[CommonConstants.POSITION_KEY] = position
maps[CommonConstants.SONG_BOOK_NAME_KEY] = getSongBookNameTextView(view)
titleAdapterListener!!.setViews(maps, getItem(position))
}
private fun getTitlesView(view: View): TextView
{
return view.findViewById<View>(R.id.title_text_view) as TextView
}
private fun getCountView(view: View): TextView
{
return view.findViewById<View>(R.id.count_text_view) as TextView
}
private fun getSubtitleTextView(view: View): TextView
{
return view.findViewById<View>(R.id.subtitle_text_view) as TextView
}
private fun getPlayImageView(rowView: View): ImageView
{
return rowView.findViewById<View>(R.id.video_image_view) as ImageView
}
private fun getOptionsImageView(rowView: View): ImageView
{
return rowView.findViewById<View>(R.id.option_image_view) as ImageView
}
private fun getSongBookNameTextView(view: View): TextView
{
return view.findViewById<View>(R.id.songBookName_text_view) as TextView
}
fun addObjects(objects: List<T>)
{
clear()
addAll(objects)
notifyDataSetChanged()
}
fun setTitleAdapterListener(titleAdapterListener: TitleAdapterListener<T>)
{
this.titleAdapterListener = titleAdapterListener
}
interface TitleAdapterListener<T>
{
open fun setViews(objects: Map<String, Any>, t: T?)
}
}
| gpl-3.0 | 64c03e7d6d347b66786d1984bce2cced | 28.886598 | 112 | 0.693343 | 4.275811 | false | false | false | false |
PaulWoitaschek/Voice | settings/src/main/kotlin/voice/settings/views/TimeSettingDialog.kt | 1 | 1879 | package voice.settings.views
import androidx.annotation.PluralsRes
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import voice.settings.R
import kotlin.math.roundToInt
@Composable // ktlint-disable twitter-compose:modifier-missing-check
fun TimeSettingDialog(
title: String,
currentSeconds: Int,
@PluralsRes textPluralRes: Int,
minSeconds: Int,
maxSeconds: Int,
onSecondsConfirmed: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val sliderValue = remember { mutableStateOf(currentSeconds.toFloat()) }
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(text = title)
},
text = {
Column {
Text(
LocalContext.current.resources.getQuantityString(
textPluralRes,
sliderValue.value.roundToInt(),
sliderValue.value.roundToInt(),
),
)
Slider(
valueRange = minSeconds.toFloat()..maxSeconds.toFloat(),
value = sliderValue.value,
onValueChange = {
sliderValue.value = it
},
)
}
},
confirmButton = {
TextButton(
onClick = {
onSecondsConfirmed(sliderValue.value.roundToInt())
onDismiss()
},
) {
Text(stringResource(R.string.dialog_confirm))
}
},
dismissButton = {
TextButton(
onClick = {
onDismiss()
},
) {
Text(stringResource(R.string.dialog_cancel))
}
},
)
}
| gpl-3.0 | ac842babb3f7b4ee55b511164ee27f9b | 25.464789 | 73 | 0.653007 | 4.527711 | false | false | false | false |
borisf/classyshark-bytecode-viewer | src/IncrementalSearch.kt | 1 | 2879 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.awt.Color
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.util.regex.Matcher
import java.util.regex.Pattern
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.text.BadLocationException
import javax.swing.text.DefaultHighlighter
import javax.swing.text.Document
import javax.swing.text.JTextComponent
class IncrementalSearch(private var content: JTextComponent) : DocumentListener, ActionListener {
private var matcher: Matcher? = null
override fun insertUpdate(evt: DocumentEvent) {
runNewSearch(evt.document)
}
override fun removeUpdate(evt: DocumentEvent) {
runNewSearch(evt.document)
}
override fun changedUpdate(evt: DocumentEvent) {
runNewSearch(evt.document)
}
override fun actionPerformed(evt: ActionEvent) {
continueSearch()
}
private fun runNewSearch(query_doc: Document) {
try {
val query = query_doc.getText(0, query_doc.length)
val pattern = Pattern.compile(query)
val content_doc = content.document
val body = content_doc.getText(0, content_doc.length)
matcher = pattern.matcher(body)
continueSearch()
} catch (ex: Exception) {
ex.printStackTrace()
}
}
private fun continueSearch() {
if (matcher != null) {
content.highlighter.removeAllHighlights()
while (matcher!!.find()) {
val group = matcher!!.group()
if (group.length > 1) {
content.caret.dot = matcher!!.start()
content.caret.moveDot(matcher!!.end())
val highlightPainter = DefaultHighlighter.DefaultHighlightPainter(HIGHLIGHTER_COLOR)
try {
content.highlighter.addHighlight(matcher!!.start(),
matcher!!.end(),
highlightPainter)
} catch (e: BadLocationException) {
e.printStackTrace()
}
}
}
}
}
companion object {
private val HIGHLIGHTER_COLOR = Color(71, 86, 89)
}
}
| apache-2.0 | dcd72c14cbd0c225c8bde20baa65f7e2 | 31.348315 | 104 | 0.625912 | 4.735197 | false | false | false | false |
FHannes/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt | 3 | 13689 | /*
* 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.codeInsight.hints
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.HintInfo.MethodInfo
import com.intellij.codeInsight.hints.settings.Diff
import com.intellij.codeInsight.hints.settings.ParameterNameHintsConfigurable
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.injected.editor.EditorWindow
import com.intellij.lang.Language
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
class ShowSettingsWithAddedPattern : AnAction() {
init {
templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description")
templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_")
}
override fun update(e: AnActionEvent) {
val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) ?: return
val text = when (info) {
is HintInfo.OptionInfo -> "Show Hints Settings..."
is HintInfo.MethodInfo -> CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName())
}
e.presentation.setText(text, false)
}
override fun actionPerformed(e: AnActionEvent) {
val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val language = file.language.baseLanguage ?: file.language
InlayParameterHintsExtension.forLanguage(language) ?: return
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) ?: return
val newPreselectedPattern = when (info) {
is HintInfo.OptionInfo -> null
is HintInfo.MethodInfo -> info.toPattern()
}
val dialog = ParameterNameHintsConfigurable(language, newPreselectedPattern)
dialog.show()
}
}
class BlacklistCurrentMethodIntention : IntentionAction, HighPriorityAction {
companion object {
private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method")
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
override fun getText(): String = presentableText
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
val language = file.language
val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false
return hintsProvider.isBlackListSupported
&& hasEditorParameterHintAtOffset(editor, file)
&& isMethodHintAtOffset(editor, file)
}
private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean {
val offset = editor.caretModel.offset
return getHintInfoFromProvider(offset, file, editor) is MethodInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return
ParameterNameHintsSettings.getInstance().addIgnorePattern(file.language, info.toPattern())
refreshAllOpenEditors()
showHint(project, file, info)
}
private fun showHint(project: Project, file: PsiFile, info: MethodInfo) {
val methodName = info.getMethodName()
val language = file.language
val listener = NotificationListener { notification, event ->
when (event.description) {
"settings" -> showSettings(language)
"undo" -> undo(language, info)
}
notification.expire()
}
val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist",
"<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>",
NotificationType.INFORMATION, listener)
notification.notify(project)
}
private fun showSettings(language: Language) {
val dialog = ParameterNameHintsConfigurable(language, null)
dialog.show()
}
private fun undo(language: Language, info: MethodInfo) {
val settings = ParameterNameHintsSettings.getInstance()
val diff = settings.getBlackListDiff(language)
val updated = diff.added.toMutableSet().apply {
remove(info.toPattern())
}
settings.setBlackListDiff(language, Diff(updated, diff.removed))
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
class DisableCustomHintsOption: IntentionAction, HighPriorityAction {
companion object {
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
private var lastOptionName = ""
override fun getText(): String = getIntentionText()
private fun getIntentionText(): String {
if (lastOptionName.startsWith("show", ignoreCase = true)) {
return "Do not ${lastOptionName.toLowerCase()}"
}
return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName)
}
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
InlayParameterHintsExtension.forLanguage(file.language) ?: return false
if (!hasEditorParameterHintAtOffset(editor, file)) return false
val option = getOptionHintAtOffset(editor, file) ?: return false
lastOptionName = option.optionName
return true
}
private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? {
val offset = editor.caretModel.offset
return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val option = getOptionHintAtOffset(editor, file) ?: return
option.disable()
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
class EnableCustomHintsOption: IntentionAction, HighPriorityAction {
companion object {
private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name")
}
private var lastOptionName = ""
override fun getText(): String {
if (lastOptionName.startsWith("show", ignoreCase = true)) {
return lastOptionName.capitalizeFirstLetter()
}
return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName)
}
override fun getFamilyName(): String = presentableFamilyName
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return false
if (editor !is EditorImpl) return false
InlayParameterHintsExtension.forLanguage(file.language) ?: return false
val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false
lastOptionName = option.optionName
return true
}
private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? {
val offset = editor.caretModel.offset
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val target = PsiTreeUtil.findFirstParent(element, { provider.hasDisabledOptionHintInfo(it) }) ?: return null
return provider.getHintInfo(target) as? HintInfo.OptionInfo
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return
option.enable()
refreshAllOpenEditors()
}
override fun startInWriteAction() = false
}
private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean {
val info = getHintInfo(element)
return info is HintInfo.OptionInfo && !info.isOptionEnabled()
}
class ToggleInlineHintsAction : AnAction() {
companion object {
private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize()
private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize()
}
override fun update(e: AnActionEvent) {
if (!InlayParameterHintsExtension.hasAnyExtensions()) {
e.presentation.isEnabledAndVisible = false
return
}
val isHintsShownNow = EditorSettingsExternalizable.getInstance().isShowParameterNameHints
e.presentation.text = if (isHintsShownNow) disableText else enableText
e.presentation.isEnabledAndVisible = true
if (isInMainEditorPopup(e)) {
val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val caretOffset = editor.caretModel.offset
e.presentation.isEnabledAndVisible = !isHintsShownNow && isPossibleHintNearOffset(file, caretOffset)
}
}
private fun isInMainEditorPopup(e: AnActionEvent): Boolean {
if (e.place != ActionPlaces.EDITOR_POPUP) return false
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return false
val offset = editor.caretModel.offset
return !editor.inlayModel.hasInlineElementAt(offset)
}
override fun actionPerformed(e: AnActionEvent) {
val settings = EditorSettingsExternalizable.getInstance()
val before = settings.isShowParameterNameHints
settings.isShowParameterNameHints = !before
refreshAllOpenEditors()
}
}
private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean {
if (editor is EditorWindow) return false
val offset = editor.caretModel.offset
val element = file.findElementAt(offset)
val startOffset = element?.textRange?.startOffset ?: offset
val endOffset = element?.textRange?.endOffset ?: offset
return editor.inlayModel
.getInlineElementsInRange(startOffset, endOffset)
.find { ParameterHintsPresentationManager.getInstance().isParameterHint(it) } != null
}
private fun refreshAllOpenEditors() {
ParameterHintsPassFactory.forceHintsUpdateOnNextPass();
ProjectManager.getInstance().openProjects.forEach {
val psiManager = PsiManager.getInstance(it)
val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(it)
val fileEditorManager = FileEditorManager.getInstance(it)
fileEditorManager.selectedFiles.forEach {
psiManager.findFile(it)?.let { daemonCodeAnalyzer.restart(it) }
}
}
}
private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? {
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) }
val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null
return provider.getHintInfo(method)
}
fun PsiElement.isOwnsInlayInEditor(editor: Editor): Boolean {
if (textRange == null) return false
val start = if (textRange.isEmpty) textRange.startOffset else textRange.startOffset + 1
return !editor.inlayModel.getInlineElementsInRange(start, textRange.endOffset).isEmpty()
}
fun isPossibleHintNearOffset(file: PsiFile, offset: Int): Boolean {
val hintProvider = InlayParameterHintsExtension.forLanguage(file.language) ?: return false
var element = file.findElementAt(offset)
for (i in 0..3) {
if (element == null) return false
val hints = hintProvider.getParameterHints(element)
if (hints.isNotEmpty()) return true
element = element.parent
}
return false
}
fun MethodInfo.toPattern() = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')'
private fun String.capitalize() = StringUtil.capitalizeWords(this, true)
private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this) | apache-2.0 | 261f5486a7e9ce8236ea591c009b39dd | 35.90027 | 127 | 0.753817 | 4.890675 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/video/VideoPlayerActivity.kt | 1 | 114200 | /*****************************************************************************
* VideoPlayerActivity.java
*
* Copyright © 2011-2017 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui.video
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.app.KeyguardManager
import android.app.PictureInPictureParams
import android.bluetooth.BluetoothA2dp
import android.bluetooth.BluetoothHeadset
import android.content.*
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.media.AudioManager
import android.net.Uri
import android.os.*
import android.support.v4.media.session.PlaybackStateCompat
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.DisplayMetrics
import android.util.Log
import android.util.Rational
import android.view.*
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup.LayoutParams
import android.view.animation.*
import android.widget.*
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.annotation.StringRes
import androidx.annotation.WorkerThread
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.ViewStubCompat
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.Guideline
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.videolan.libvlc.MediaPlayer
import org.videolan.libvlc.RendererItem
import org.videolan.libvlc.interfaces.IMedia
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.libvlc.util.DisplayManager
import org.videolan.libvlc.util.VLCVideoLayout
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.Tools
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.resources.*
import org.videolan.tools.*
import org.videolan.vlc.*
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.databinding.PlayerHudBinding
import org.videolan.vlc.databinding.PlayerHudRightBinding
import org.videolan.vlc.gui.audio.EqualizerFragment
import org.videolan.vlc.gui.audio.PlaylistAdapter
import org.videolan.vlc.gui.browser.EXTRA_MRL
import org.videolan.vlc.gui.browser.FilePickerActivity
import org.videolan.vlc.gui.dialogs.RenderersDialog
import org.videolan.vlc.gui.helpers.*
import org.videolan.vlc.gui.helpers.hf.StoragePermissionsDelegate
import org.videolan.vlc.interfaces.IPlaybackSettingsController
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.repository.ExternalSubRepository
import org.videolan.vlc.repository.SlaveRepository
import org.videolan.vlc.util.FileUtils
import org.videolan.vlc.util.Permissions
import org.videolan.vlc.util.Util
import org.videolan.vlc.viewmodels.PlaylistModel
import java.lang.Runnable
import kotlin.math.roundToInt
@Suppress("DEPRECATION")
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
open class VideoPlayerActivity : AppCompatActivity(), PlaybackService.Callback, PlaylistAdapter.IPlayer, OnClickListener, OnLongClickListener, StoragePermissionsDelegate.CustomActionController, TextWatcher {
private lateinit var startedScope : CoroutineScope
private var wasPlaying = true
var service: PlaybackService? = null
private lateinit var medialibrary: Medialibrary
private var videoLayout: VLCVideoLayout? = null
lateinit var displayManager: DisplayManager
private var rootView: View? = null
private var videoUri: Uri? = null
private var askResume = true
private lateinit var closeButton: View
private lateinit var playlistContainer: View
private lateinit var playlist: RecyclerView
private lateinit var playlistSearchText: TextInputLayout
private lateinit var playlistAdapter: PlaylistAdapter
private var playlistModel: PlaylistModel? = null
private lateinit var abRepeatAddMarker: Button
private lateinit var settings: SharedPreferences
/** Overlay */
private var overlayBackground: View? = null
private var isDragging: Boolean = false
internal var isShowing: Boolean = false
private set
private var isShowingDialog: Boolean = false
var info: TextView? = null
var overlayInfo: View? = null
var verticalBar: View? = null
private lateinit var verticalBarProgress: View
private lateinit var verticalBarBoostProgress: View
internal var isLoading: Boolean = false
private set
private var isPlaying = false
private var loadingImageView: ImageView? = null
private var navMenu: ImageView? = null
private var rendererBtn: ImageView? = null
protected var enableCloneMode: Boolean = false
private var screenOrientation: Int = 0
private var screenOrientationLock: Int = 0
private var currentScreenOrientation: Int = 0
private var currentAudioTrack = -2
private var currentSpuTrack = -2
internal var isLocked = false
private set
/* -1 is a valid track (Disable) */
private var lastAudioTrack = -2
private var lastSpuTrack = -2
private var overlayTimeout = 0
private var lockBackButton = false
private var wasPaused = false
private var savedTime: Long = -1
/**
* For uninterrupted switching between audio and video mode
*/
private var switchingView: Boolean = false
private var switchToPopup: Boolean = false
//Volume
internal lateinit var audiomanager: AudioManager
private set
internal var audioMax: Int = 0
private set
internal var isAudioBoostEnabled: Boolean = false
private set
private var isMute = false
private var volSave: Int = 0
internal var volume: Float = 0.toFloat()
internal var originalVol: Float = 0.toFloat()
private var warningToast: Toast? = null
internal var fov: Float = 0.toFloat()
lateinit var touchDelegate: VideoTouchDelegate
private val statsDelegate: VideoStatsDelegate by lazy(LazyThreadSafetyMode.NONE) { VideoStatsDelegate(this, { showOverlayTimeout(OVERLAY_INFINITE) }, { showOverlay(true) }) }
val delayDelegate: VideoDelayDelegate by lazy(LazyThreadSafetyMode.NONE) { VideoDelayDelegate(this@VideoPlayerActivity) }
private var isTv: Boolean = false
// Tracks & Subtitles
private var audioTracksList: Array<MediaPlayer.TrackDescription>? = null
private var videoTracksList: Array<MediaPlayer.TrackDescription>? = null
private var subtitleTracksList: Array<MediaPlayer.TrackDescription>? = null
/**
* Flag to indicate whether the media should be paused once loaded
* (e.g. lock screen, or to restore the pause state)
*/
private var playbackStarted = false
// Tips
private var overlayTips: View? = null
// Navigation handling (DVD, Blu-Ray...)
private var menuIdx = -1
private var isNavMenu = false
/* for getTime and seek */
private var forcedTime: Long = -1
private var lastTime: Long = -1
private var alertDialog: AlertDialog? = null
protected var isBenchmark = false
private val addedExternalSubs = ArrayList<org.videolan.vlc.mediadb.models.ExternalSub>()
private var downloadedSubtitleLiveData: LiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>? = null
private var previousMediaPath: String? = null
private val isInteractive: Boolean
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
get() {
val pm = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
return if (AndroidUtil.isLolliPopOrLater) pm.isInteractive else pm.isScreenOn
}
private val playlistObserver = Observer<List<MediaWrapper>> { mediaWrappers -> if (mediaWrappers != null) playlistAdapter.update(mediaWrappers) }
private var addNextTrack = false
private lateinit var playToPause: AnimatedVectorDrawableCompat
private lateinit var pauseToPlay: AnimatedVectorDrawableCompat
internal val isPlaybackSettingActive: Boolean
get() = delayDelegate.playbackSetting != IPlaybackSettingsController.DelayState.OFF
/**
* Handle resize of the surface and the overlay
*/
val handler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
service?.run {
when (msg.what) {
FADE_OUT -> hideOverlay(false)
FADE_OUT_INFO -> fadeOutInfo()
START_PLAYBACK -> startPlayback()
AUDIO_SERVICE_CONNECTION_FAILED -> exit(RESULT_CONNECTION_FAILED)
RESET_BACK_LOCK -> lockBackButton = true
CHECK_VIDEO_TRACKS -> if (videoTracksCount < 1 && audioTracksCount > 0) {
Log.i(TAG, "No video track, open in audio mode")
switchToAudioMode(true)
} else {
}
LOADING_ANIMATION -> startLoading()
HIDE_INFO -> hideOverlay(true)
SHOW_INFO -> showOverlay()
HIDE_SEEK -> touchDelegate.hideSeekOverlay()
HIDE_SETTINGS -> delayDelegate.endPlaybackSetting()
else -> {}
}
}
}
}
private val switchAudioRunnable = Runnable {
if (displayManager.isPrimary && service?.hasMedia() == true && service?.videoTracksCount == 0) {
Log.i(TAG, "Video track lost, switching to audio")
switchingView = true
exit(RESULT_VIDEO_TRACK_LOST)
}
}
/**
* handle changes of the seekbar (slicer)
*/
private val seekListener = object : OnSeekBarChangeListener {
override fun onStartTrackingTouch(seekBar: SeekBar) {
isDragging = true
showOverlayTimeout(OVERLAY_INFINITE)
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
isDragging = false
showOverlay(true)
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (!isFinishing && fromUser && service?.isSeekable == true) {
seek(progress.toLong())
showInfo(Tools.millisToString(progress.toLong()), 1000)
}
if (fromUser) {
showOverlay(true)
}
}
}
internal val isOnPrimaryDisplay: Boolean
get() = displayManager.isPrimary
val currentScaleType: MediaPlayer.ScaleType
get() = service?.mediaplayer?.videoScale ?: MediaPlayer.ScaleType.SURFACE_BEST_FIT
private val isOptionsListShowing: Boolean
get() = optionsDelegate?.isShowing() == true
/* XXX: After a seek, playbackService.getTime can return the position before or after
* the seek position. Therefore we return forcedTime in order to avoid the seekBar
* to move between seek position and the actual position.
* We have to wait for a valid position (that is after the seek position).
* to re-init lastTime and forcedTime to -1 and return the actual position.
*/
val time: Long
get() {
var time = service?.time ?: 0L
if (forcedTime != -1L && lastTime != -1L) {
if (lastTime > forcedTime) {
if (time in (forcedTime + 1)..lastTime || time > lastTime) {
forcedTime = -1
lastTime = forcedTime
}
} else {
if (time > forcedTime) {
forcedTime = -1
lastTime = forcedTime
}
}
} else if (time == 0L) service?.currentMediaWrapper?.time?.let { time = it }
return if (forcedTime == -1L) time else forcedTime
}
private lateinit var hudBinding: PlayerHudBinding
private lateinit var hudRightBinding: PlayerHudRightBinding
private var seekButtons: Boolean = false
private var hasPlaylist: Boolean = false
private var enableSubs = true
private val downloadedSubtitleObserver = Observer<List<org.videolan.vlc.mediadb.models.ExternalSub>> { externalSubs ->
for (externalSub in externalSubs) {
if (!addedExternalSubs.contains(externalSub)) {
service?.addSubtitleTrack(externalSub.subtitlePath, currentSpuTrack == -2)
addedExternalSubs.add(externalSub)
}
}
}
private val screenRotation: Int
get() {
val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
return wm.defaultDisplay?.rotation ?: Surface.ROTATION_0
}
private var optionsDelegate: PlayerOptionsDelegate? = null
val isPlaylistVisible: Boolean
get() = playlistContainer.visibility == View.VISIBLE
private val btReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null) return
service?.let { service ->
when (intent.action) {
BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED, BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> {
val savedDelay = settings.getLong(KEY_BLUETOOTH_DELAY, 0L)
val currentDelay = service.audioDelay
if (savedDelay != 0L) {
val connected = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1) == BluetoothA2dp.STATE_CONNECTED
if (connected && currentDelay == 0L)
toggleBtDelay(true)
else if (!connected && savedDelay == currentDelay)
toggleBtDelay(false)
}
}
}
}
}
}
private val serviceReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == PLAY_FROM_SERVICE) onNewIntent(intent)
else if (intent.action == EXIT_PLAYER) exitOK()
}
}
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase?.getContextWithLocale(AppContextProvider.locale))
}
override fun getApplicationContext(): Context {
return super.getApplicationContext().getContextWithLocale(AppContextProvider.locale)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Util.checkCpuCompatibility(this)
settings = Settings.getInstance(this)
/* Services and miscellaneous */
audiomanager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioMax = audiomanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
isAudioBoostEnabled = settings.getBoolean("audio_boost", true)
enableCloneMode = clone ?: settings.getBoolean("enable_clone_mode", false)
displayManager = DisplayManager(this, PlaybackService.renderer, false, enableCloneMode, isBenchmark)
setContentView(if (displayManager.isPrimary) R.layout.player else R.layout.player_remote_control)
rootView = findViewById(R.id.player_root)
playlist = findViewById(R.id.video_playlist)
playlistSearchText = findViewById(R.id.playlist_search_text)
playlistContainer = findViewById(R.id.video_playlist_container)
closeButton = findViewById(R.id.close_button)
playlistSearchText.editText?.addTextChangedListener(this)
screenOrientation = Integer.valueOf(
settings.getString(SCREEN_ORIENTATION, "99" /*SCREEN ORIENTATION SENSOR*/)!!)
videoLayout = findViewById(R.id.video_layout)
/* Loading view */
loadingImageView = findViewById(R.id.player_overlay_loading)
dimStatusBar(true)
handler.sendEmptyMessageDelayed(LOADING_ANIMATION, LOADING_ANIMATION_DELAY.toLong())
switchingView = false
askResume = settings.getString(KEY_VIDEO_CONFIRM_RESUME, "0") == "2"
sDisplayRemainingTime = settings.getBoolean(KEY_REMAINING_TIME_DISPLAY, false)
// Clear the resume time, since it is only used for resumes in external
// videos.
settings.putSingle(VIDEO_RESUME_TIME, -1L)
// Paused flag - per session too, like the subs list.
this.volumeControlStream = AudioManager.STREAM_MUSIC
// 100 is the value for screen_orientation_start_lock
try {
requestedOrientation = getScreenOrientation(screenOrientation)
} catch (ignored: IllegalStateException) {
Log.w(TAG, "onCreate: failed to set orientation")
}
// Extra initialization when no secondary display is detected
isTv = Settings.showTvUi
if (displayManager.isPrimary) {
// Orientation
// Tips
if (!BuildConfig.DEBUG && !isTv && !settings.getBoolean(PREF_TIPS_SHOWN, false)
&& !isBenchmark) {
(findViewById<View>(R.id.player_overlay_tips) as ViewStubCompat).inflate()
overlayTips = findViewById(R.id.overlay_tips_layout)
}
}
medialibrary = Medialibrary.getInstance()
val touch = if (!isTv) {
val audioTouch = (!AndroidUtil.isLolliPopOrLater || !audiomanager.isVolumeFixed) && settings.getBoolean(ENABLE_VOLUME_GESTURE, true)
val brightnessTouch = !AndroidDevices.isChromeBook && settings.getBoolean(ENABLE_BRIGHTNESS_GESTURE, true)
((if (audioTouch) TOUCH_FLAG_AUDIO_VOLUME else 0)
+ (if (brightnessTouch) TOUCH_FLAG_BRIGHTNESS else 0)
+ if (settings.getBoolean(ENABLE_DOUBLE_TAP_SEEK, true)) TOUCH_FLAG_SEEK else 0)
} else 0
currentScreenOrientation = resources.configuration.orientation
val dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
val yRange = Math.min(dm.widthPixels, dm.heightPixels)
val xRange = Math.max(dm.widthPixels, dm.heightPixels)
val sc = ScreenConfig(dm, xRange, yRange, currentScreenOrientation)
touchDelegate = VideoTouchDelegate(this, touch, sc, isTv)
UiTools.setRotationAnimation(this)
if (savedInstanceState != null) {
savedTime = savedInstanceState.getLong(KEY_TIME)
val list = savedInstanceState.getBoolean(KEY_LIST, false)
if (list) {
intent.removeExtra(PLAY_EXTRA_ITEM_LOCATION)
} else {
videoUri = savedInstanceState.getParcelable<Parcelable>(KEY_URI) as Uri?
}
}
playToPause = AnimatedVectorDrawableCompat.create(this, R.drawable.anim_play_pause)!!
pauseToPlay = AnimatedVectorDrawableCompat.create(this, R.drawable.anim_pause_play)!!
}
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s == null) return
val length = s.length
if (length > 0) {
playlistModel?.filter(s)
} else {
playlistModel?.filter(null)
}
}
private fun hideSearchField(): Boolean {
if (playlistSearchText.visibility != View.VISIBLE) return false
playlistSearchText.editText?.apply {
removeTextChangedListener(this@VideoPlayerActivity)
setText("")
addTextChangedListener(this@VideoPlayerActivity)
}
UiTools.setKeyboardVisibility(playlistSearchText, false)
return true
}
override fun onResume() {
overridePendingTransition(0, 0)
super.onResume()
isShowingDialog = false
/*
* Set listeners here to avoid NPE when activity is closing
*/
setListeners(true)
if (isLocked && screenOrientation == 99) requestedOrientation = screenOrientationLock
}
private fun setListeners(enabled: Boolean) {
navMenu?.setOnClickListener(if (enabled) this else null)
if (::hudBinding.isInitialized) {
hudBinding.playerOverlaySeekbar.setOnSeekBarChangeListener(if (enabled) seekListener else null)
hudBinding.orientationToggle.setOnClickListener(if (enabled) this else null)
hudBinding.orientationToggle.setOnLongClickListener(if (enabled) this else null)
abRepeatAddMarker.setOnClickListener(this)
}
if (::hudRightBinding.isInitialized) {
hudRightBinding.abRepeatReset.setOnClickListener(this)
hudRightBinding.abRepeatStop.setOnClickListener(this)
}
UiTools.setViewOnClickListener(rendererBtn, if (enabled) this else null)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
if (playbackStarted) service?.run {
if (::hudBinding.isInitialized) {
hudRightBinding.playerOverlayTitle.text = currentMediaWrapper?.title ?: return@run
}
var uri: Uri? = if (intent.hasExtra(PLAY_EXTRA_ITEM_LOCATION)) {
intent.extras?.getParcelable<Parcelable>(PLAY_EXTRA_ITEM_LOCATION) as Uri?
} else intent.data
if (uri == null || uri == videoUri) return
if (TextUtils.equals("file", uri.scheme) && uri.path?.startsWith("/sdcard") == true) {
val convertedUri = FileUtils.convertLocalUri(uri)
if (convertedUri == videoUri) return
else uri = convertedUri
}
videoUri = uri
if (isPlaylistVisible) {
playlistAdapter.currentIndex = currentMediaPosition
playlistContainer.setGone()
}
if (settings.getBoolean("video_transition_show", true)) showTitle()
initUI()
lastTime = -1
forcedTime = lastTime
enableSubs()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onPause() {
val finishing = isFinishing
if (finishing)
overridePendingTransition(0, 0)
else
hideOverlay(true)
super.onPause()
setListeners(false)
/* Stop the earliest possible to avoid vout error */
if (!isInPictureInPictureMode
&& (finishing || (AndroidUtil.isNougatOrLater && !AndroidUtil.isOOrLater //Video on background on Nougat Android TVs
&& AndroidDevices.isAndroidTv && !requestVisibleBehind(true))))
stopPlayback()
}
@TargetApi(Build.VERSION_CODES.O)
override fun onUserLeaveHint() {
if (!isInPictureInPictureMode && displayManager.isPrimary && !isShowingDialog &&
"2" == settings.getString(KEY_VIDEO_APP_SWITCH, "0") && isInteractive && service?.hasRenderer() == false)
switchToPopup()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (videoUri != null && "content" != videoUri?.scheme) {
outState.putLong(KEY_TIME, savedTime)
if (playlistModel == null) outState.putParcelable(KEY_URI, videoUri)
}
videoUri = null
outState.putBoolean(KEY_LIST, hasPlaylist)
}
@TargetApi(Build.VERSION_CODES.O)
fun switchToPopup() {
if (isBenchmark) return
optionsDelegate?.hide()
//look for dialogs and close them
supportFragmentManager.fragments.forEach { (it as? DialogFragment)?.dismiss() }
val mw = service?.currentMediaWrapper
if (mw == null || !AndroidDevices.pipAllowed || !isStarted()) return
val forceLegacy = Settings.getInstance(this).getBoolean(POPUP_FORCE_LEGACY, false)
if (AndroidDevices.hasPiP && !forceLegacy) {
if (AndroidUtil.isOOrLater)
try {
val track = service?.playlistManager?.player?.mediaplayer?.currentVideoTrack
?: return
val ar = Rational(track.width.coerceAtMost((track.height * 2.39f).toInt()), track.height)
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(ar).build())
} catch (e: IllegalArgumentException) { // Fallback with default parameters
enterPictureInPictureMode()
}
else enterPictureInPictureMode()
} else {
if (Permissions.canDrawOverlays(this)) {
switchingView = true
switchToPopup = true
if (service?.isPlaying != true) mw.addFlags(MediaWrapper.MEDIA_PAUSED)
cleanUI()
exitOK()
} else Permissions.checkDrawOverlaysPermission(this)
}
}
override fun onVisibleBehindCanceled() {
super.onVisibleBehindCanceled()
stopPlayback()
exitOK()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
currentScreenOrientation = newConfig.orientation
if (touchDelegate != null) {
val dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
val sc = ScreenConfig(dm,
Math.max(dm.widthPixels, dm.heightPixels),
Math.min(dm.widthPixels, dm.heightPixels),
currentScreenOrientation)
touchDelegate.screenConfig = sc
}
resetHudLayout()
showControls(isShowing)
statsDelegate.onConfigurationChanged()
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun resetHudLayout() {
if (!::hudBinding.isInitialized) return
if (!isTv && !AndroidDevices.isChromeBook) {
hudBinding.orientationToggle.setVisible()
hudBinding.lockOverlayButton.setVisible()
}
}
override fun onStart() {
medialibrary.pauseBackgroundOperations()
super.onStart()
startedScope = MainScope()
PlaybackService.start(this)
PlaybackService.serviceFlow.onEach { onServiceChanged(it) }.launchIn(startedScope)
restoreBrightness()
val filter = IntentFilter(PLAY_FROM_SERVICE)
filter.addAction(EXIT_PLAYER)
LocalBroadcastManager.getInstance(this).registerReceiver(
serviceReceiver, filter)
val btFilter = IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)
btFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
registerReceiver(btReceiver, btFilter)
overlayInfo.setInvisible()
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
override fun onStop() {
super.onStop()
startedScope.cancel()
LocalBroadcastManager.getInstance(this).unregisterReceiver(serviceReceiver)
unregisterReceiver(btReceiver)
alertDialog?.dismiss()
if (displayManager.isPrimary && !isFinishing && service?.isPlaying == true
&& "1" == settings.getString(KEY_VIDEO_APP_SWITCH, "0")) {
switchToAudioMode(false)
}
cleanUI()
stopPlayback()
if (savedTime != -1L) settings.putSingle(VIDEO_RESUME_TIME, savedTime)
saveBrightness()
service?.removeCallback(this)
service = null
// Clear Intent to restore playlist on activity restart
intent = Intent()
handler.removeCallbacksAndMessages(null)
removeDownloadedSubtitlesObserver()
previousMediaPath = null
addedExternalSubs.clear()
medialibrary.resumeBackgroundOperations()
service?.playlistManager?.videoStatsOn?.postValue(false)
}
private fun saveBrightness() {
// Save brightness if user wants to
if (settings.getBoolean(SAVE_BRIGHTNESS, false)) {
val brightness = window.attributes.screenBrightness
if (brightness != -1f) settings.putSingle(BRIGHTNESS_VALUE, brightness)
}
}
private fun restoreBrightness() {
if (settings.getBoolean(SAVE_BRIGHTNESS, false)) {
val brightness = settings.getFloat(BRIGHTNESS_VALUE, -1f)
if (brightness != -1f) setWindowBrightness(brightness)
}
}
override fun onDestroy() {
super.onDestroy()
playlistModel?.run {
dataset.removeObserver(playlistObserver)
onCleared()
}
// Dismiss the presentation when the activity is not visible.
displayManager.release()
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun startPlayback() {
/* start playback only when audio service and both surfaces are ready */
if (playbackStarted) return
service?.run {
playbackStarted = true
val vlcVout = vout
if (vlcVout != null && vlcVout.areViewsAttached()) {
if (isPlayingPopup) {
stop(video = true)
} else
vlcVout.detachViews()
}
val mediaPlayer = mediaplayer
if (!displayManager.isOnRenderer) videoLayout?.let {
mediaPlayer.attachViews(it, displayManager, true, false)
val size = if (isBenchmark) MediaPlayer.ScaleType.SURFACE_FILL else MediaPlayer.ScaleType.values()[settings.getInt(VIDEO_RATIO, MediaPlayer.ScaleType.SURFACE_BEST_FIT.ordinal)]
mediaPlayer.videoScale = size
}
initUI()
loadMedia()
}
}
private fun initPlaylistUi() {
if (service?.hasPlaylist() == true) {
if (!::playlistAdapter.isInitialized) {
playlistAdapter = PlaylistAdapter(this)
val layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
playlist.layoutManager = layoutManager
}
if (playlistModel == null) {
playlistModel = ViewModelProviders.of(this).get(PlaylistModel::class.java).apply {
playlistAdapter.setModel(this)
dataset.observe(this@VideoPlayerActivity, playlistObserver)
}
}
hudRightBinding.playlistToggle.setVisible()
if (::hudBinding.isInitialized) {
hudBinding.playlistPrevious.setVisible()
hudBinding.playlistNext.setVisible()
}
hudRightBinding.playlistToggle.setOnClickListener(this@VideoPlayerActivity)
closeButton.setOnClickListener { togglePlaylist() }
val callback = SwipeDragItemTouchHelperCallback(playlistAdapter, true)
val touchHelper = ItemTouchHelper(callback)
touchHelper.attachToRecyclerView(playlist)
}
}
private fun initUI() {
/* Listen for changes to media routes. */
if (!isBenchmark) displayManager.setMediaRouterCallback()
rootView?.run { keepScreenOn = true }
}
private fun setPlaybackParameters() {
service?.run {
if (audioDelay != 0L && audioDelay != audioDelay) setAudioDelay(audioDelay)
else if (audiomanager.isBluetoothA2dpOn || audiomanager.isBluetoothScoOn) toggleBtDelay(true)
if (spuDelay != 0L && spuDelay != spuDelay) setSpuDelay(spuDelay)
}
}
private fun stopPlayback() {
if (!playbackStarted) return
if (!displayManager.isPrimary && !isFinishing || service == null) {
playbackStarted = false
return
}
service?.run {
val tv = Settings.showTvUi
val interactive = isInteractive
wasPaused = !isPlaying || (!tv && !interactive)
if (wasPaused) settings.putSingle(VIDEO_PAUSED, true)
if (!isFinishing) {
currentAudioTrack = audioTrack
currentSpuTrack = spuTrack
if (tv) finish() // Leave player on TV, restauration can be difficult
}
if (isMute) mute(false)
playbackStarted = false
handler.removeCallbacksAndMessages(null)
if (hasMedia() && switchingView) {
if (BuildConfig.DEBUG) Log.d(TAG, "mLocation = \"$videoUri\"")
if (switchToPopup)
switchToPopup(currentMediaPosition)
else {
currentMediaWrapper?.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
showWithoutParse(currentMediaPosition)
}
return
}
if (isSeekable) {
savedTime = time
val length = length
//remove saved position if in the last 5 seconds
if (length - savedTime < 5000)
savedTime = 0
else
savedTime -= 2000 // go back 2 seconds, to compensate loading time
}
stop(video = true)
}
}
private fun cleanUI() {
rootView?.run { keepScreenOn = false }
/* Stop listening for changes to media routes. */
if (!isBenchmark) displayManager.removeMediaRouterCallback()
if (!displayManager.isSecondary) service?.mediaplayer?.detachViews()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (data == null) return
if (data.hasExtra(EXTRA_MRL)) {
service?.addSubtitleTrack(Uri.parse(data.getStringExtra(EXTRA_MRL)), false)
service?.currentMediaWrapper?.let {
SlaveRepository.getInstance(this).saveSlave(it.location, IMedia.Slave.Type.Subtitle, 2, data.getStringExtra(EXTRA_MRL))
}
addNextTrack = true
} else if (BuildConfig.DEBUG) Log.d(TAG, "Subtitle selection dialog was cancelled")
}
open fun exit(resultCode: Int) {
if (isFinishing) return
val resultIntent = Intent(ACTION_RESULT)
videoUri?.let { uri ->
service?.run {
if (AndroidUtil.isNougatOrLater)
resultIntent.putExtra(EXTRA_URI, uri.toString())
else
resultIntent.data = videoUri
resultIntent.putExtra(EXTRA_POSITION, time)
resultIntent.putExtra(EXTRA_DURATION, length)
}
setResult(resultCode, resultIntent)
finish()
}
}
private fun exitOK() {
exit(Activity.RESULT_OK)
}
override fun onTrackballEvent(event: MotionEvent): Boolean {
if (isLoading) return false
showOverlay()
return true
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
return !isLoading && ::touchDelegate.isInitialized && touchDelegate.dispatchGenericMotionEvent(event)
}
override fun onBackPressed() {
if (optionsDelegate?.isShowing() == true) {
optionsDelegate?.hide()
} else if (lockBackButton) {
lockBackButton = false
handler.sendEmptyMessageDelayed(RESET_BACK_LOCK, 2000)
Toast.makeText(applicationContext, getString(R.string.back_quit_lock), Toast.LENGTH_SHORT).show()
} else if (isPlaylistVisible) {
togglePlaylist()
} else if (isPlaybackSettingActive) {
delayDelegate.endPlaybackSetting()
} else if (isTv && isShowing && !isLocked) {
hideOverlay(true)
} else {
exitOK()
super.onBackPressed()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (service == null || keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_BUTTON_B)
return super.onKeyDown(keyCode, event)
if (isOptionsListShowing) return false
if (isPlaybackSettingActive && keyCode != KeyEvent.KEYCODE_J && keyCode != KeyEvent.KEYCODE_K
&& keyCode != KeyEvent.KEYCODE_G && keyCode != KeyEvent.KEYCODE_H) return false
if (isLoading) {
when (keyCode) {
KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_MEDIA_STOP -> {
exitOK()
return true
}
}
return false
}
if (isShowing || fov == 0f && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && !playlistContainer.isVisible())
showOverlayTimeout(OVERLAY_TIMEOUT)
when (keyCode) {
KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> {
touchDelegate.seekDelta(10000)
return true
}
KeyEvent.KEYCODE_MEDIA_REWIND -> {
touchDelegate.seekDelta(-10000)
return true
}
KeyEvent.KEYCODE_BUTTON_R1 -> {
touchDelegate.seekDelta(60000)
return true
}
KeyEvent.KEYCODE_BUTTON_L1 -> {
touchDelegate.seekDelta(-60000)
return true
}
KeyEvent.KEYCODE_BUTTON_A -> {
if (::hudBinding.isInitialized && hudBinding.progressOverlay.isVisible())
return false
when {
isNavMenu -> return navigateDvdMenu(keyCode)
keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
//prevent conflict with remote control
-> return super.onKeyDown(keyCode, event)
else -> doPlayPause()
}
return true
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_SPACE -> {
when {
isNavMenu -> return navigateDvdMenu(keyCode)
keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> return super.onKeyDown(keyCode, event)
else -> doPlayPause()
}
return true
}
KeyEvent.KEYCODE_O, KeyEvent.KEYCODE_BUTTON_Y, KeyEvent.KEYCODE_MENU -> {
showAdvancedOptions()
return true
}
KeyEvent.KEYCODE_V, KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK, KeyEvent.KEYCODE_BUTTON_X -> {
onAudioSubClick(if (::hudBinding.isInitialized) hudBinding.playerOverlayTracks else null)
return true
}
KeyEvent.KEYCODE_A -> {
resizeVideo()
return true
}
KeyEvent.KEYCODE_M, KeyEvent.KEYCODE_VOLUME_MUTE -> {
updateMute()
return true
}
KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_MEDIA_STOP -> {
exitOK()
return true
}
KeyEvent.KEYCODE_E -> {
if (event.isCtrlPressed) {
val newFragment = EqualizerFragment()
newFragment.onDismissListener = DialogInterface.OnDismissListener { dimStatusBar(true) }
newFragment.show(supportFragmentManager, "equalizer")
}
return true
}
KeyEvent.KEYCODE_DPAD_LEFT -> {
if (isNavMenu)
return navigateDvdMenu(keyCode)
else if (!isShowing && !playlistContainer.isVisible()) {
if (event.isAltPressed && event.isCtrlPressed) {
touchDelegate.seekDelta(-300000)
} else if (event.isCtrlPressed) {
touchDelegate.seekDelta(-60000)
} else if (fov == 0f)
touchDelegate.seekDelta(-10000)
else
service?.updateViewpoint(-5f, 0f, 0f, 0f, false)
return true
}
}
KeyEvent.KEYCODE_DPAD_RIGHT -> {
if (isNavMenu)
return navigateDvdMenu(keyCode)
else if (!isShowing && !playlistContainer.isVisible()) {
if (event.isAltPressed && event.isCtrlPressed) {
touchDelegate.seekDelta(300000)
} else if (event.isCtrlPressed) {
touchDelegate.seekDelta(60000)
} else if (fov == 0f)
touchDelegate.seekDelta(10000)
else
service?.updateViewpoint(5f, 0f, 0f, 0f, false)
return true
}
}
KeyEvent.KEYCODE_DPAD_UP -> {
if (isNavMenu)
return navigateDvdMenu(keyCode)
else if (event.isCtrlPressed) {
volumeUp()
return true
} else if (!isShowing && !playlistContainer.isVisible()) {
if (fov == 0f)
showAdvancedOptions()
else
service?.updateViewpoint(0f, -5f, 0f, 0f, false)
return true
}
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
if (isNavMenu)
return navigateDvdMenu(keyCode)
else if (event.isCtrlPressed) {
volumeDown()
return true
} else if (!isShowing && fov != 0f) {
service?.updateViewpoint(0f, 5f, 0f, 0f, false)
return true
}
}
KeyEvent.KEYCODE_DPAD_CENTER -> {
if (isNavMenu)
return navigateDvdMenu(keyCode)
else if (!isShowing) {
doPlayPause()
return true
}
}
KeyEvent.KEYCODE_ENTER -> return if (isNavMenu)
navigateDvdMenu(keyCode)
else
super.onKeyDown(keyCode, event)
KeyEvent.KEYCODE_J -> {
delayDelegate.delayAudioOrSpu(delta = -50000L, delayState = IPlaybackSettingsController.DelayState.AUDIO)
handler.removeMessages(HIDE_SETTINGS)
handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L)
return true
}
KeyEvent.KEYCODE_K -> {
delayDelegate.delayAudioOrSpu(delta = 50000L, delayState = IPlaybackSettingsController.DelayState.AUDIO)
handler.removeMessages(HIDE_SETTINGS)
handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L)
return true
}
KeyEvent.KEYCODE_G -> {
delayDelegate.delayAudioOrSpu(delta = -50000L, delayState = IPlaybackSettingsController.DelayState.SUBS)
handler.removeMessages(HIDE_SETTINGS)
handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L)
return true
}
KeyEvent.KEYCODE_T -> {
showOverlay()
}
KeyEvent.KEYCODE_H -> {
if (event.isCtrlPressed) {
showOverlay()
} else {
delayDelegate.delayAudioOrSpu(delta = 50000L, delayState = IPlaybackSettingsController.DelayState.SUBS)
handler.removeMessages(HIDE_SETTINGS)
handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L)
}
return true
}
KeyEvent.KEYCODE_Z -> {
resizeVideo()
return true
}
KeyEvent.KEYCODE_N -> {
next()
return true
}
KeyEvent.KEYCODE_P -> {
previous()
return true
}
KeyEvent.KEYCODE_VOLUME_DOWN -> {
volumeDown()
return true
}
KeyEvent.KEYCODE_VOLUME_UP -> {
volumeUp()
return true
}
KeyEvent.KEYCODE_CAPTIONS -> {
selectSubtitles()
return true
}
KeyEvent.KEYCODE_PLUS -> {
service?.run { setRate(rate * 1.2f, true) }
return true
}
KeyEvent.KEYCODE_EQUALS -> {
if (event.isShiftPressed) {
service?.run { setRate(rate * 1.2f, true) }
return true
} else service?.run { setRate(1f, true) }
return false
}
KeyEvent.KEYCODE_MINUS -> {
service?.run { setRate(rate / 1.2f, true) }
return true
}
KeyEvent.KEYCODE_C -> {
resizeVideo()
return true
}
}
return super.onKeyDown(keyCode, event)
}
private fun volumeUp() {
if (isMute) {
updateMute()
} else service?.let { service ->
var volume = if (audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) < audioMax)
audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) + 1
else
Math.round(service.volume.toFloat() * audioMax / 100 + 1)
volume = Math.min(Math.max(volume, 0), audioMax * if (isAudioBoostEnabled) 2 else 1)
setAudioVolume(volume)
}
}
private fun volumeDown() {
service?.let { service ->
var vol = if (service.volume > 100)
Math.round(service.volume.toFloat() * audioMax / 100 - 1)
else
audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) - 1
vol = Math.min(Math.max(vol, 0), audioMax * if (isAudioBoostEnabled) 2 else 1)
originalVol = vol.toFloat()
setAudioVolume(vol)
}
}
internal fun navigateDvdMenu(keyCode: Int): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> {
service?.navigate(MediaPlayer.Navigate.Up)
return true
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
service?.navigate(MediaPlayer.Navigate.Down)
return true
}
KeyEvent.KEYCODE_DPAD_LEFT -> {
service?.navigate(MediaPlayer.Navigate.Left)
return true
}
KeyEvent.KEYCODE_DPAD_RIGHT -> {
service?.navigate(MediaPlayer.Navigate.Right)
return true
}
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_A -> {
service?.navigate(MediaPlayer.Navigate.Activate)
return true
}
else -> return false
}
}
fun focusPlayPause() {
if (::hudBinding.isInitialized) hudBinding.playerOverlayPlay.requestFocus()
}
/**
* Lock screen rotation
*/
private fun lockScreen() {
if (screenOrientation != 100) {
screenOrientationLock = requestedOrientation
requestedOrientation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
ActivityInfo.SCREEN_ORIENTATION_LOCKED
else
getScreenOrientation(100)
}
showInfo(R.string.locked, 1000)
if (::hudBinding.isInitialized) {
hudBinding.lockOverlayButton.setImageResource(R.drawable.ic_locked_player)
hudBinding.playerOverlayTime.isEnabled = false
hudBinding.playerOverlaySeekbar.isEnabled = false
hudBinding.playerOverlayLength.isEnabled = false
hudBinding.playlistNext.isEnabled = false
hudBinding.playlistPrevious.isEnabled = false
}
hideOverlay(true)
lockBackButton = true
isLocked = true
}
/**
* Remove screen lock
*/
private fun unlockScreen() {
if (screenOrientation != 100)
requestedOrientation = screenOrientationLock
showInfo(R.string.unlocked, 1000)
if (::hudBinding.isInitialized) {
hudBinding.lockOverlayButton.setImageResource(R.drawable.ic_lock_player)
hudBinding.playerOverlayTime.isEnabled = true
hudBinding.playerOverlaySeekbar.isEnabled = service?.isSeekable != false
hudBinding.playerOverlayLength.isEnabled = true
hudBinding.playlistNext.isEnabled = true
hudBinding.playlistPrevious.isEnabled = true
}
isShowing = false
isLocked = false
showOverlay()
lockBackButton = false
}
/**
* Show text in the info view and vertical progress bar for "duration" milliseconds
* @param text
* @param duration
* @param barNewValue new volume/brightness value (range: 0 - 15)
*/
private fun showInfoWithVerticalBar(text: String, duration: Int, barNewValue: Int, max: Int) {
showInfo(text, duration)
if (!::verticalBarProgress.isInitialized) return
var layoutParams: LinearLayout.LayoutParams
if (barNewValue <= 100) {
layoutParams = verticalBarProgress.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = barNewValue * 100 / max.toFloat()
verticalBarProgress.layoutParams = layoutParams
layoutParams = verticalBarBoostProgress.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 0f
verticalBarBoostProgress.layoutParams = layoutParams
} else {
layoutParams = verticalBarProgress.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 100 * 100 / max.toFloat()
verticalBarProgress.layoutParams = layoutParams
layoutParams = verticalBarBoostProgress.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = (barNewValue - 100) * 100 / max.toFloat()
verticalBarBoostProgress.layoutParams = layoutParams
}
verticalBar.setVisible()
}
/**
* Show text in the info view for "duration" milliseconds
* @param text
* @param duration
*/
internal fun showInfo(text: String, duration: Int) {
if (isInPictureInPictureMode) return
initInfoOverlay()
verticalBar.setGone()
overlayInfo.setVisible()
info.setVisible()
info?.text = text
handler.removeMessages(FADE_OUT_INFO)
handler.sendEmptyMessageDelayed(FADE_OUT_INFO, duration.toLong())
}
fun initInfoOverlay() {
val vsc = findViewById<ViewStubCompat>(R.id.player_info_stub)
if (vsc != null) {
vsc.setVisible()
// the info textView is not on the overlay
info = findViewById(R.id.player_overlay_textinfo)
overlayInfo = findViewById(R.id.player_overlay_info)
verticalBar = findViewById(R.id.verticalbar)
verticalBarProgress = findViewById(R.id.verticalbar_progress)
verticalBarBoostProgress = findViewById(R.id.verticalbar_boost_progress)
}
}
internal fun showInfo(textid: Int, duration: Int) {
showInfo(getString(textid), duration)
}
/**
* hide the info view with "delay" milliseconds delay
* @param delay
*/
private fun hideInfo(delay: Int = 0) {
handler.sendEmptyMessageDelayed(FADE_OUT_INFO, delay.toLong())
}
private fun fadeOutInfo() {
if (overlayInfo?.visibility == View.VISIBLE) {
overlayInfo?.startAnimation(AnimationUtils.loadAnimation(
this@VideoPlayerActivity, android.R.anim.fade_out))
overlayInfo.setInvisible()
}
}
/* PlaybackService.Callback */
override fun update() {
if (service == null || !::playlistAdapter.isInitialized) return
playlistModel?.update()
}
override fun onMediaEvent(event: IMedia.Event) {
when (event.type) {
IMedia.Event.ParsedChanged -> updateNavStatus()
IMedia.Event.MetaChanged -> {
}
}
}
override fun onMediaPlayerEvent(event: MediaPlayer.Event) {
service?.let { service ->
when (event.type) {
MediaPlayer.Event.Playing -> onPlaying()
MediaPlayer.Event.Paused -> updateOverlayPausePlay()
MediaPlayer.Event.Opening -> forcedTime = -1
MediaPlayer.Event.Vout -> {
updateNavStatus()
if (event.voutCount > 0)
service.mediaplayer.updateVideoSurfaces()
if (menuIdx == -1)
handleVout(event.voutCount)
}
MediaPlayer.Event.ESAdded -> {
if (menuIdx == -1) {
val mw = service.currentMediaWrapper ?: return
if (event.esChangedType == IMedia.Track.Type.Audio) {
setESTrackLists()
lifecycleScope.launch(Dispatchers.IO) {
val media = medialibrary.findMedia(mw)
val audioTrack = media.getMetaLong(MediaWrapper.META_AUDIOTRACK).toInt()
if (audioTrack != 0 || currentAudioTrack != -2)
service.setAudioTrack(if (media.id == 0L) currentAudioTrack else audioTrack)
}
} else if (event.esChangedType == IMedia.Track.Type.Text) {
setESTrackLists()
lifecycleScope.launch(Dispatchers.IO) {
val media = medialibrary.findMedia(mw)
val spuTrack = media.getMetaLong(MediaWrapper.META_SUBTITLE_TRACK).toInt()
if (addNextTrack) {
val tracks = service.spuTracks
if (!(tracks as Array<MediaPlayer.TrackDescription>).isNullOrEmpty()) service.setSpuTrack(tracks[tracks.size - 1].id)
addNextTrack = false
} else if (spuTrack != 0 || currentSpuTrack != -2) {
service.setSpuTrack(if (media.id == 0L) currentSpuTrack else spuTrack)
}
}
}
}
if (menuIdx == -1 && event.esChangedType == IMedia.Track.Type.Video) {
handler.removeMessages(CHECK_VIDEO_TRACKS)
handler.sendEmptyMessageDelayed(CHECK_VIDEO_TRACKS, 1000)
}
invalidateESTracks(event.esChangedType)
}
MediaPlayer.Event.ESDeleted -> {
if (menuIdx == -1 && event.esChangedType == IMedia.Track.Type.Video) {
handler.removeMessages(CHECK_VIDEO_TRACKS)
handler.sendEmptyMessageDelayed(CHECK_VIDEO_TRACKS, 1000)
}
invalidateESTracks(event.esChangedType)
}
MediaPlayer.Event.ESSelected -> if (event.esChangedType == IMedia.Track.Type.Video) {
val vt = service.currentVideoTrack
if (vt != null)
fov = if (vt.projection == IMedia.VideoTrack.Projection.Rectangular) 0f else DEFAULT_FOV
}
MediaPlayer.Event.SeekableChanged -> updateSeekable(event.seekable)
MediaPlayer.Event.PausableChanged -> updatePausable(event.pausable)
MediaPlayer.Event.Buffering -> {
if (isPlaying) {
if (event.buffering == 100f)
stopLoading()
else if (!handler.hasMessages(LOADING_ANIMATION) && !isLoading
&& (touchDelegate == null || !touchDelegate.isSeeking()) && !isDragging)
handler.sendEmptyMessageDelayed(LOADING_ANIMATION, LOADING_ANIMATION_DELAY.toLong())
}
}
}
}
}
private fun onPlaying() {
val mw = service?.currentMediaWrapper ?: return
isPlaying = true
hasPlaylist = service?.hasPlaylist() == true
setPlaybackParameters()
stopLoading()
updateOverlayPausePlay()
updateNavStatus()
if (!mw.hasFlag(MediaWrapper.MEDIA_PAUSED))
handler.sendEmptyMessageDelayed(FADE_OUT, OVERLAY_TIMEOUT.toLong())
else {
mw.removeFlags(MediaWrapper.MEDIA_PAUSED)
wasPaused = false
}
setESTracks()
if (::hudBinding.isInitialized && hudRightBinding.playerOverlayTitle.length() == 0)
hudRightBinding.playerOverlayTitle.text = mw.title
// Get possible subtitles
observeDownloadedSubtitles()
optionsDelegate?.setup()
settings.edit().remove(VIDEO_PAUSED).apply()
if (isInPictureInPictureMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val track = service?.playlistManager?.player?.mediaplayer?.currentVideoTrack ?: return
val ar = Rational(track.width.coerceAtMost((track.height * 2.39f).toInt()), track.height)
if (ar.isFinite && !ar.isZero) {
setPictureInPictureParams(PictureInPictureParams.Builder().setAspectRatio(ar).build())
}
}
}
private fun encounteredError() {
if (isFinishing || service?.hasNext() == true) return
/* Encountered Error, exit player with a message */
alertDialog = AlertDialog.Builder(this@VideoPlayerActivity)
.setOnCancelListener { exit(RESULT_PLAYBACK_ERROR) }
.setPositiveButton(R.string.ok) { _, _ -> exit(RESULT_PLAYBACK_ERROR) }
.setTitle(R.string.encountered_error_title)
.setMessage(R.string.encountered_error_message)
.create().apply { show() }
}
private fun handleVout(voutCount: Int) {
handler.removeCallbacks(switchAudioRunnable)
val vlcVout = service?.vout ?: return
if (displayManager.isPrimary && vlcVout.areViewsAttached() && voutCount == 0) {
handler.postDelayed(switchAudioRunnable, 4000)
}
}
override fun recreate() {
handler.removeCallbacks(switchAudioRunnable)
super.recreate()
}
fun switchToAudioMode(showUI: Boolean) {
if (service == null) return
switchingView = true
// Show the MainActivity if it is not in background.
if (showUI) {
val i = Intent().apply {
setClassName(applicationContext, if (isTv) TV_AUDIOPLAYER_ACTIVITY else MOBILE_MAIN_ACTIVITY)
}
startActivity(i)
}
exitOK()
}
override fun isInPictureInPictureMode(): Boolean {
return AndroidUtil.isNougatOrLater && super.isInPictureInPictureMode()
}
override fun setPictureInPictureParams(params: PictureInPictureParams) {
try {
super.setPictureInPictureParams(params)
} catch (e: IllegalArgumentException) {
if (BuildConfig.DEBUG) throw e
}
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode)
service?.mediaplayer?.updateVideoSurfaces()
}
internal fun sendMouseEvent(action: Int, x: Int, y: Int) {
service?.vout?.sendMouseEvent(action, 0, x, y)
}
/**
* show/hide the overlay
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
return service != null && touchDelegate.onTouchEvent(event)
}
internal fun updateViewpoint(yaw: Float, pitch: Float, fov: Float): Boolean {
return service?.updateViewpoint(yaw, pitch, 0f, fov, false) ?: false
}
internal fun initAudioVolume() = service?.let { service ->
if (service.volume <= 100) {
volume = audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()
originalVol = audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()
} else {
volume = service.volume.toFloat() * audioMax / 100
}
}
fun toggleOverlay() {
if (!isShowing) showOverlay()
else hideOverlay(true)
}
//Toast that appears only once
fun displayWarningToast() {
warningToast?.cancel()
warningToast = Toast.makeText(application, R.string.audio_boost_warning, Toast.LENGTH_SHORT).apply { show() }
}
internal fun setAudioVolume(vol: Int) {
var vol = vol
if (AndroidUtil.isNougatOrLater && (vol <= 0) xor isMute) {
mute(!isMute)
return //Android N+ throws "SecurityException: Not allowed to change Do Not Disturb state"
}
/* Since android 4.3, the safe volume warning dialog is displayed only with the FLAG_SHOW_UI flag.
* We don't want to always show the default UI volume, so show it only when volume is not set. */
service?.let { service ->
if (vol <= audioMax) {
service.setVolume(100)
if (vol != audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC)) {
try {
audiomanager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0)
// High Volume warning can block volume setting
if (audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) != vol)
audiomanager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, AudioManager.FLAG_SHOW_UI)
} catch (ignored: RuntimeException) {
}
//Some device won't allow us to change volume
}
vol = Math.round(vol * 100 / audioMax.toFloat())
} else {
vol = Math.round(vol * 100 / audioMax.toFloat())
service.setVolume(Math.round(vol.toFloat()))
}
showInfoWithVerticalBar(getString(R.string.volume) + "\n" + Integer.toString(vol) + '%'.toString(), 1000, vol, if (isAudioBoostEnabled) 200 else 100)
}
}
private fun mute(mute: Boolean) {
service?.let { service ->
isMute = mute
if (isMute) volSave = service.volume
service.setVolume(if (isMute) 0 else volSave)
}
}
private fun updateMute() {
mute(!isMute)
showInfo(if (isMute) R.string.sound_off else R.string.sound_on, 1000)
}
internal fun changeBrightness(delta: Float) {
// Estimate and adjust Brightness
val lp = window.attributes
var brightness = (lp.screenBrightness + delta).coerceIn(0.01f, 1f)
setWindowBrightness(brightness)
brightness = (brightness * 100).roundToInt().toFloat()
showInfoWithVerticalBar("${getString(R.string.brightness)}\n${brightness.toInt()}%", 1000, brightness.toInt(), 100)
}
private fun setWindowBrightness(brightness: Float) {
val lp = window.attributes
lp.screenBrightness = brightness
// Set Brightness
window.attributes = lp
}
open fun onAudioSubClick(anchor: View?) {
service?.let { service ->
var flags = 0L
if (enableSubs) {
flags = flags or CTX_DOWNLOAD_SUBTITLES_PLAYER
if (displayManager.isPrimary) flags = flags or CTX_PICK_SUBS
}
if (service.videoTracksCount > 2) flags = flags or CTX_VIDEO_TRACK
if (service.audioTracksCount > 0) flags = flags or CTX_AUDIO_TRACK
if (service.spuTracksCount > 0) flags = flags or CTX_SUBS_TRACK
if (optionsDelegate == null) optionsDelegate = PlayerOptionsDelegate(this, service)
optionsDelegate?.flags = flags
optionsDelegate?.show(PlayerOptionType.MEDIA_TRACKS)
hideOverlay(false)
}
}
override fun onPopupMenu(view: View, position: Int, item: MediaWrapper?) {
val popupMenu = PopupMenu(this, view)
popupMenu.menuInflater.inflate(R.menu.audio_player, popupMenu.menu)
popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
if (item.itemId == R.id.audio_player_mini_remove) service?.run {
remove(position)
return@OnMenuItemClickListener true
}
false
})
popupMenu.show()
}
override fun onSelectionSet(position: Int) = playlist.scrollToPosition(position)
override fun playItem(position: Int, item: MediaWrapper) {
service?.playIndex(position)
}
override fun onClick(v: View) {
when (v.id) {
R.id.orientation_toggle -> toggleOrientation()
R.id.playlist_toggle -> togglePlaylist()
R.id.player_overlay_forward -> touchDelegate.seekDelta(10000)
R.id.player_overlay_rewind -> touchDelegate.seekDelta(-10000)
R.id.ab_repeat_add_marker -> service?.playlistManager?.setABRepeatValue(hudBinding.playerOverlaySeekbar.progress.toLong())
R.id.ab_repeat_reset -> service?.playlistManager?.resetABRepeatValues()
R.id.ab_repeat_stop -> service?.playlistManager?.clearABRepeat()
R.id.player_overlay_navmenu -> showNavMenu()
R.id.player_overlay_length, R.id.player_overlay_time -> toggleTimeDisplay()
R.id.video_renderer -> if (supportFragmentManager.findFragmentByTag("renderers") == null)
RenderersDialog().show(supportFragmentManager, "renderers")
R.id.video_secondary_display -> {
clone = displayManager.isSecondary
recreate()
}
}
}
override fun onLongClick(v: View): Boolean {
when (v.id) {
R.id.orientation_toggle -> return resetOrientation()
}
return false
}
fun toggleTimeDisplay() {
sDisplayRemainingTime = !sDisplayRemainingTime
showOverlay()
settings.putSingle(KEY_REMAINING_TIME_DISPLAY, sDisplayRemainingTime)
}
fun toggleLock() {
if (isLocked)
unlockScreen()
else
lockScreen()
}
fun toggleLoop(v: View) = service?.run {
if (repeatType == PlaybackStateCompat.REPEAT_MODE_ONE) {
showInfo(getString(R.string.repeat), 1000)
repeatType = PlaybackStateCompat.REPEAT_MODE_NONE
} else {
repeatType = PlaybackStateCompat.REPEAT_MODE_ONE
showInfo(getString(R.string.repeat_single), 1000)
}
true
} ?: false
override fun onStorageAccessGranted() {
handler.sendEmptyMessage(START_PLAYBACK)
}
fun hideOptions() {
optionsDelegate?.hide()
}
private interface TrackSelectedListener {
fun onTrackSelected(trackID: Int)
}
private fun selectTrack(tracks: Array<MediaPlayer.TrackDescription>?, currentTrack: Int, titleId: Int,
listener: TrackSelectedListener?) {
if (listener == null)
throw IllegalArgumentException("listener must not be null")
if (tracks == null)
return
val nameList = arrayOfNulls<String>(tracks.size)
val idList = IntArray(tracks.size)
var listPosition = 0
for ((i, track) in tracks.withIndex()) {
idList[i] = track.id
nameList[i] = track.name
// map the track position to the list position
if (track.id == currentTrack) listPosition = i
}
if (!isFinishing) alertDialog = AlertDialog.Builder(this@VideoPlayerActivity)
.setTitle(titleId)
.setSingleChoiceItems(nameList, listPosition) { dialog, listPosition ->
var trackID = -1
// Reverse map search...
for (track in tracks) {
if (idList[listPosition] == track.id) {
trackID = track.id
break
}
}
listener.onTrackSelected(trackID)
dialog.dismiss()
}
.setOnDismissListener { this.dimStatusBar(true) }
.create().apply {
setCanceledOnTouchOutside(true)
setOwnerActivity(this@VideoPlayerActivity)
show()
}
}
fun selectVideoTrack() {
setESTrackLists()
service?.let {
selectTrack(videoTracksList, it.videoTrack, R.string.track_video,
object : TrackSelectedListener {
override fun onTrackSelected(trackID: Int) {
if (trackID < -1) return
service?.let { service ->
service.setVideoTrack(trackID)
seek(service.time)
}
}
})
}
}
fun selectAudioTrack() {
setESTrackLists()
service?.let {
selectTrack(audioTracksList, it.audioTrack, R.string.track_audio,
object : TrackSelectedListener {
override fun onTrackSelected(trackID: Int) {
if (trackID < -1) return
service?.let { service ->
service.setAudioTrack(trackID)
runIO(Runnable {
val mw = medialibrary.findMedia(service.currentMediaWrapper)
if (mw != null && mw.id != 0L) mw.setLongMeta(MediaWrapper.META_AUDIOTRACK, trackID.toLong())
})
}
}
})
}
}
fun selectSubtitles() {
setESTrackLists()
service?.let {
selectTrack(subtitleTracksList, it.spuTrack, R.string.track_text,
object : TrackSelectedListener {
override fun onTrackSelected(trackID: Int) {
if (trackID < -1 || service == null) return
runIO(Runnable { setSpuTrack(trackID) })
}
})
}
}
fun pickSubtitles() {
val uri = videoUri?: return
isShowingDialog = true
val filePickerIntent = Intent(this, FilePickerActivity::class.java)
filePickerIntent.data = Uri.parse(FileUtils.getParent(uri.toString()))
startActivityForResult(filePickerIntent, 0)
}
fun downloadSubtitles() = service?.currentMediaWrapper?.let {
MediaUtils.getSubs(this@VideoPlayerActivity, it)
}
@WorkerThread
private fun setSpuTrack(trackID: Int) {
runOnMainThread(Runnable { service?.setSpuTrack(trackID) })
val mw = medialibrary.findMedia(service?.currentMediaWrapper) ?: return
if (mw.id != 0L) mw.setLongMeta(MediaWrapper.META_SUBTITLE_TRACK, trackID.toLong())
}
private fun showNavMenu() {
if (menuIdx >= 0) service?.titleIdx = menuIdx
}
private fun updateSeekable(seekable: Boolean) {
if (!::hudBinding.isInitialized) return
hudBinding.playerOverlayRewind.isEnabled = seekable
hudBinding.playerOverlayRewind.setImageResource(if (seekable)
R.drawable.ic_rewind_player
else
R.drawable.ic_rewind_player_disabled)
hudBinding.playerOverlayForward.isEnabled = seekable
hudBinding.playerOverlayForward.setImageResource(if (seekable)
R.drawable.ic_forward_player
else
R.drawable.ic_forward_player_disabled)
if (!isLocked)
hudBinding.playerOverlaySeekbar.isEnabled = seekable
}
private fun updatePausable(pausable: Boolean) {
if (!::hudBinding.isInitialized) return
hudBinding.playerOverlayPlay.isEnabled = pausable
if (!pausable)
hudBinding.playerOverlayPlay.setImageResource(R.drawable.ic_play_player_disabled)
}
fun doPlayPause() {
if (service?.isPausable != true) return
if (service?.isPlaying == true) {
showOverlayTimeout(OVERLAY_INFINITE)
pause()
} else {
handler.sendEmptyMessageDelayed(FADE_OUT, 300L)
play()
}
}
fun seek(position: Long) {
service?.let { seek(position, it.length) }
}
internal fun seek(position: Long, length: Long) {
service?.let { service ->
forcedTime = position
lastTime = service.time
service.seek(position, length.toDouble())
service.playlistManager.player.updateProgress(position)
}
}
@SuppressLint("ClickableViewAccessibility")
private fun initSeekButton() {
if (!::hudBinding.isInitialized) return
hudBinding.playerOverlayRewind.setOnClickListener(this)
hudBinding.playerOverlayForward.setOnClickListener(this)
hudBinding.playerOverlayRewind.setOnTouchListener(OnRepeatListener(this))
hudBinding.playerOverlayForward.setOnTouchListener(OnRepeatListener(this))
}
fun resizeVideo() = service?.run {
val next = (mediaplayer.videoScale.ordinal + 1) % MediaPlayer.SURFACE_SCALES_COUNT
val scale = MediaPlayer.ScaleType.values()[next]
setVideoScale(scale)
}
internal fun setVideoScale(scale: MediaPlayer.ScaleType) = service?.run {
mediaplayer.videoScale = scale
when (scale) {
MediaPlayer.ScaleType.SURFACE_BEST_FIT -> showInfo(R.string.surface_best_fit, 1000)
MediaPlayer.ScaleType.SURFACE_FIT_SCREEN -> showInfo(R.string.surface_fit_screen, 1000)
MediaPlayer.ScaleType.SURFACE_FILL -> showInfo(R.string.surface_fill, 1000)
MediaPlayer.ScaleType.SURFACE_16_9 -> showInfo("16:9", 1000)
MediaPlayer.ScaleType.SURFACE_4_3 -> showInfo("4:3", 1000)
MediaPlayer.ScaleType.SURFACE_ORIGINAL -> showInfo(R.string.surface_original, 1000)
}
settings.putSingle(VIDEO_RATIO, scale.ordinal)
}
/**
* show overlay
* @param forceCheck: adjust the timeout in function of playing state
*/
private fun showOverlay(forceCheck: Boolean = false) {
if (forceCheck) overlayTimeout = 0
showOverlayTimeout(0)
}
/**
* show overlay
*/
fun showOverlayTimeout(timeout: Int) {
service?.let { service ->
if (isInPictureInPictureMode) return
initOverlay()
if (!::hudBinding.isInitialized) return
overlayTimeout = when {
timeout != 0 -> timeout
service.isPlaying -> OVERLAY_TIMEOUT
else -> OVERLAY_INFINITE
}
if (isNavMenu) {
isShowing = true
return
}
if (!isShowing) {
isShowing = true
if (!isLocked) {
showControls(true)
}
dimStatusBar(false)
hudBinding.progressOverlay.setVisible()
hudRightBinding.hudRightOverlay.setVisible()
if (!displayManager.isPrimary)
overlayBackground.setVisible()
updateOverlayPausePlay(true)
}
handler.removeMessages(FADE_OUT)
if (overlayTimeout != OVERLAY_INFINITE)
handler.sendMessageDelayed(handler.obtainMessage(FADE_OUT), overlayTimeout.toLong())
}
}
private fun showControls(show: Boolean) {
if (show && isInPictureInPictureMode) return
if (::hudBinding.isInitialized) {
hudBinding.playerOverlayPlay.visibility = if (show) View.VISIBLE else View.INVISIBLE
if (seekButtons) {
hudBinding.playerOverlayRewind.visibility = if (show) View.VISIBLE else View.INVISIBLE
hudBinding.playerOverlayForward.visibility = if (show) View.VISIBLE else View.INVISIBLE
}
hudBinding.orientationToggle.visibility = if (isTv || AndroidDevices.isChromeBook) View.GONE else if (show) View.VISIBLE else View.INVISIBLE
hudBinding.playerOverlayTracks.visibility = if (show) View.VISIBLE else View.INVISIBLE
hudBinding.playerOverlayAdvFunction.visibility = if (show) View.VISIBLE else View.INVISIBLE
if (hasPlaylist) {
hudBinding.playlistPrevious.visibility = if (show) View.VISIBLE else View.INVISIBLE
hudBinding.playlistNext.visibility = if (show) View.VISIBLE else View.INVISIBLE
}
}
if (::hudRightBinding.isInitialized) {
val secondary = displayManager.isSecondary
if (secondary) hudRightBinding.videoSecondaryDisplay.setImageResource(R.drawable.ic_screenshare_stop_circle_player)
hudRightBinding.videoSecondaryDisplay.visibility = if (!show) View.GONE else if (UiTools.hasSecondaryDisplay(applicationContext)) View.VISIBLE else View.GONE
hudRightBinding.videoSecondaryDisplay.contentDescription = resources.getString(if (secondary) R.string.video_remote_disable else R.string.video_remote_enable)
hudRightBinding.playlistToggle.visibility = if (show && service?.hasPlaylist() == true) View.VISIBLE else View.GONE
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun initOverlay() {
service?.let { service ->
val vscRight = findViewById<ViewStubCompat>(R.id.player_hud_right_stub)
vscRight?.let {
it.setVisible()
hudRightBinding = DataBindingUtil.bind(findViewById(R.id.hud_right_overlay)) ?: return
if (!isBenchmark && enableCloneMode && !settings.contains("enable_clone_mode")) {
UiTools.snackerConfirm(hudRightBinding.videoSecondaryDisplay, getString(R.string.video_save_clone_mode), Runnable { settings.putSingle("enable_clone_mode", true) })
}
}
val vsc = findViewById<ViewStubCompat>(R.id.player_hud_stub)
if (vsc != null) {
seekButtons = settings.getBoolean(ENABLE_SEEK_BUTTONS, false)
vsc.setVisible()
hudBinding = DataBindingUtil.bind(findViewById(R.id.progress_overlay)) ?: return
hudBinding.player = this
hudBinding.progress = service.playlistManager.player.progress
abRepeatAddMarker = hudBinding.abRepeatContainer.findViewById(R.id.ab_repeat_add_marker)
service.playlistManager.abRepeat.observe(this, Observer { abvalues ->
hudBinding.abRepeatA = if (abvalues.start == -1L) -1F else abvalues.start / service.playlistManager.player.getLength().toFloat()
hudBinding.abRepeatB = if (abvalues.stop == -1L) -1F else abvalues.stop / service.playlistManager.player.getLength().toFloat()
hudBinding.abRepeatMarkerA.visibility = if (abvalues.start == -1L) View.GONE else View.VISIBLE
hudBinding.abRepeatMarkerB.visibility = if (abvalues.stop == -1L) View.GONE else View.VISIBLE
service.manageAbRepeatStep(hudRightBinding.abRepeatReset, hudRightBinding.abRepeatStop, hudBinding.abRepeatContainer, abRepeatAddMarker)
})
service.playlistManager.abRepeatOn.observe(this, Observer {
hudBinding.abRepeatMarkerGuidelineContainer.visibility = if (it) View.VISIBLE else View.GONE
if (it) showOverlay(true)
if (it) {
hudBinding.playerOverlayLength.nextFocusUpId = R.id.ab_repeat_add_marker
hudBinding.playerOverlayTime.nextFocusUpId = R.id.ab_repeat_add_marker
}
service.manageAbRepeatStep(hudRightBinding.abRepeatReset, hudRightBinding.abRepeatStop, hudBinding.abRepeatContainer, abRepeatAddMarker)
})
service.playlistManager.delayValue.observe(this, Observer {
delayDelegate.delayChanged(it, service)
})
service.playlistManager.videoStatsOn.observe(this, Observer {
if (it) showOverlay(true)
statsDelegate.container = hudBinding.statsContainer
statsDelegate.initPlotView(hudBinding)
if (it) statsDelegate.start() else statsDelegate.stop()
})
hudBinding.statsClose.setOnClickListener { service.playlistManager.videoStatsOn.postValue(false) }
hudBinding.lifecycleOwner = this
val layoutParams = hudBinding.progressOverlay.layoutParams as RelativeLayout.LayoutParams
if (AndroidDevices.isPhone || !AndroidDevices.hasNavBar)
layoutParams.width = LayoutParams.MATCH_PARENT
else
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
hudBinding.progressOverlay.layoutParams = layoutParams
overlayBackground = findViewById(R.id.player_overlay_background)
navMenu = findViewById(R.id.player_overlay_navmenu)
if (!AndroidDevices.isChromeBook && !isTv
&& Settings.getInstance(this).getBoolean("enable_casting", true)) {
rendererBtn = findViewById(R.id.video_renderer)
PlaybackService.renderer.observe(this, Observer { rendererItem -> rendererBtn?.setImageDrawable(AppCompatResources.getDrawable(this, if (rendererItem == null) R.drawable.ic_renderer_circle_player else R.drawable.ic_renderer_on_circle_player)) })
RendererDelegate.renderers.observe(this, Observer<List<RendererItem>> { rendererItems -> rendererBtn.setVisibility(if (rendererItems.isNullOrEmpty()) View.GONE else View.VISIBLE) })
}
hudRightBinding.playerOverlayTitle.text = service.currentMediaWrapper?.title
if (seekButtons) initSeekButton()
//Set margins for TV overscan
if (isTv) {
val hm = resources.getDimensionPixelSize(R.dimen.tv_overscan_horizontal)
val vm = resources.getDimensionPixelSize(R.dimen.tv_overscan_vertical)
val lp = vsc.layoutParams as RelativeLayout.LayoutParams
lp.setMargins(hm, 0, hm, vm)
vsc.layoutParams = lp
}
resetHudLayout()
updateOverlayPausePlay(true)
updateSeekable(service.isSeekable)
updatePausable(service.isPausable)
updateNavStatus()
setListeners(true)
initPlaylistUi()
if (!displayManager.isPrimary || isTv) hudBinding.lockOverlayButton.setGone()
} else if (::hudBinding.isInitialized) {
hudBinding.progress = service.playlistManager.player.progress
hudBinding.lifecycleOwner = this
}
}
}
/**
* hider overlay
*/
internal fun hideOverlay(fromUser: Boolean) {
if (isShowing) {
handler.removeMessages(FADE_OUT)
Log.v(TAG, "remove View!")
overlayTips.setInvisible()
if (!displayManager.isPrimary) {
overlayBackground?.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out))
overlayBackground.setInvisible()
}
if (::hudBinding.isInitialized) hudBinding.progressOverlay.setInvisible()
if (::hudRightBinding.isInitialized) hudRightBinding.hudRightOverlay.setInvisible()
showControls(false)
isShowing = false
dimStatusBar(true)
playlistSearchText.editText?.setText("")
} else if (!fromUser) {
/*
* Try to hide the Nav Bar again.
* It seems that you can't hide the Nav Bar if you previously
* showed it in the last 1-2 seconds.
*/
dimStatusBar(true)
}
}
/**
* Dim the status bar and/or navigation icons when needed on Android 3.x.
* Hide it on Android 4.0 and later
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
fun dimStatusBar(dim: Boolean) {
if (isNavMenu) return
var visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
var navbar = 0
if (dim || isLocked) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
navbar = navbar or (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
if (AndroidUtil.isKitKatOrLater) visibility = visibility or View.SYSTEM_UI_FLAG_IMMERSIVE
visibility = visibility or View.SYSTEM_UI_FLAG_FULLSCREEN
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
visibility = visibility or View.SYSTEM_UI_FLAG_VISIBLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
}
if (AndroidDevices.hasNavBar)
visibility = visibility or navbar
window.decorView.systemUiVisibility = visibility
}
private fun showTitle() {
if (isNavMenu) return
var visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
var navbar = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
navbar = navbar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
if (AndroidDevices.hasNavBar) visibility = visibility or navbar
window.decorView.systemUiVisibility = visibility
}
private fun updateOverlayPausePlay(skipAnim: Boolean = false) {
if (!::hudBinding.isInitialized) return
service?.let { service ->
if (service.isPausable) {
if (skipAnim) {
hudBinding.playerOverlayPlay.setImageResource(if (service.isPlaying)
R.drawable.ic_pause_player
else
R.drawable.ic_play_player)
} else {
val drawable = if (service.isPlaying) playToPause else pauseToPlay
hudBinding.playerOverlayPlay.setImageDrawable(drawable)
if (service.isPlaying != wasPlaying) drawable.start()
}
wasPlaying = service.isPlaying
}
hudBinding.playerOverlayPlay.requestFocus()
if (::playlistAdapter.isInitialized) {
playlistAdapter.setCurrentlyPlaying(service.isPlaying)
}
}
}
private fun invalidateESTracks(type: Int) {
when (type) {
IMedia.Track.Type.Audio -> audioTracksList = null
IMedia.Track.Type.Text -> subtitleTracksList = null
}
}
private fun setESTracks() {
if (lastAudioTrack >= -1) {
service?.setAudioTrack(lastAudioTrack)
lastAudioTrack = -2
}
if (lastSpuTrack >= -1) {
service?.setSpuTrack(lastSpuTrack)
lastSpuTrack = -2
}
}
@Suppress("UNCHECKED_CAST")
private fun setESTrackLists() {
service?.let { service ->
if (audioTracksList == null && service.audioTracksCount > 0)
audioTracksList = service.audioTracks as Array<MediaPlayer.TrackDescription>?
if (subtitleTracksList == null && service.spuTracksCount > 0)
subtitleTracksList = service.spuTracks as Array<MediaPlayer.TrackDescription>?
if (videoTracksList == null && service.videoTracksCount > 0)
videoTracksList = service.videoTracks as Array<MediaPlayer.TrackDescription>?
}
}
/**
*
*/
private fun play() {
service?.play()
rootView?.run { keepScreenOn = true }
}
/**
*
*/
private fun pause() {
service?.pause()
rootView?.run { keepScreenOn = false }
}
fun next() {
service?.next()
}
fun previous() {
service?.previous(false)
}
/*
* Additionnal method to prevent alert dialog to pop up
*/
private fun loadMedia(fromStart: Boolean) {
askResume = false
intent.putExtra(PLAY_EXTRA_FROM_START, fromStart)
loadMedia()
}
/**
* External extras:
* - position (long) - position of the video to start with (in ms)
* - subtitles_location (String) - location of a subtitles file to load
* - from_start (boolean) - Whether playback should start from start or from resume point
* - title (String) - video title, will be guessed from file if not set.
*/
@SuppressLint("SdCardPath")
@TargetApi(12)
protected open fun loadMedia() {
service?.let { service ->
isPlaying = false
var title: String? = null
var fromStart = settings.getString(KEY_VIDEO_CONFIRM_RESUME, "0") == "1"
var itemTitle: String? = null
var positionInPlaylist = -1
val intent = intent
val extras = intent.extras
var startTime = 0L
val currentMedia = service.currentMediaWrapper
val hasMedia = currentMedia != null
val isPlaying = service.isPlaying
/*
* If the activity has been paused by pressing the power button, then
* pressing it again will show the lock screen.
* But onResume will also be called, even if vlc-android is still in
* the background.
* To workaround this, pause playback if the lockscreen is displayed.
*/
val km = applicationContext.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (km.inKeyguardRestrictedInputMode())
wasPaused = true
if (wasPaused && BuildConfig.DEBUG)
Log.d(TAG, "Video was previously paused, resuming in paused mode")
if (intent.data != null) videoUri = intent.data
if (extras != null) {
if (intent.hasExtra(PLAY_EXTRA_ITEM_LOCATION)) {
videoUri = extras.getParcelable(PLAY_EXTRA_ITEM_LOCATION)
intent.removeExtra(PLAY_EXTRA_ITEM_LOCATION)
}
fromStart = fromStart or extras.getBoolean(PLAY_EXTRA_FROM_START, false)
// Consume fromStart option after first use to prevent
// restarting again when playback is paused.
intent.putExtra(PLAY_EXTRA_FROM_START, false)
askResume = askResume and !fromStart
startTime = if (fromStart) 0L else extras.getLong(PLAY_EXTRA_START_TIME) // position passed in by intent (ms)
if (!fromStart && startTime == 0L) {
startTime = extras.getInt(PLAY_EXTRA_START_TIME).toLong()
}
positionInPlaylist = extras.getInt(PLAY_EXTRA_OPENED_POSITION, -1)
val path = extras.getString(PLAY_EXTRA_SUBTITLES_LOCATION)
if (!path.isNullOrEmpty()) service.addSubtitleTrack(path, true)
if (intent.hasExtra(PLAY_EXTRA_ITEM_TITLE))
itemTitle = extras.getString(PLAY_EXTRA_ITEM_TITLE)
}
if (startTime == 0L && savedTime > 0L) startTime = savedTime
val restorePlayback = hasMedia && currentMedia?.uri == videoUri
var openedMedia: MediaWrapper? = null
val resumePlaylist = service.isValidIndex(positionInPlaylist)
val continueplayback = isPlaying && (restorePlayback || positionInPlaylist == service.currentMediaPosition)
if (resumePlaylist) {
// Provided externally from AudioService
if (BuildConfig.DEBUG) Log.v(TAG, "Continuing playback from PlaybackService at index $positionInPlaylist")
openedMedia = service.media[positionInPlaylist]
itemTitle = openedMedia.title
updateSeekable(service.isSeekable)
updatePausable(service.isPausable)
}
if (videoUri != null) {
var uri = videoUri ?:return
var media: MediaWrapper? = null
if (!continueplayback) {
if (!resumePlaylist) {
// restore last position
media = medialibrary.getMedia(uri)
if (media == null && TextUtils.equals(uri.scheme, "file") &&
uri.path?.startsWith("/sdcard") == true) {
uri = FileUtils.convertLocalUri(uri)
videoUri = uri
media = medialibrary.getMedia(uri)
}
if (media != null && media.id != 0L && media.time == 0L)
media.time = media.getMetaLong(MediaWrapper.META_PROGRESS)
} else media = openedMedia
if (media != null) {
// in media library
if (askResume && !fromStart && positionInPlaylist <= 0 && media.time > 0) {
showConfirmResumeDialog()
return
}
lastAudioTrack = media.audioTrack
lastSpuTrack = media.spuTrack
} else if (!fromStart) {
// not in media library
if (askResume && startTime > 0L) {
showConfirmResumeDialog()
return
} else {
val rTime = settings.getLong(VIDEO_RESUME_TIME, -1)
if (rTime > 0) {
if (askResume) {
showConfirmResumeDialog()
return
} else {
settings.putSingle(VIDEO_RESUME_TIME, -1L)
startTime = rTime
}
}
}
}
}
// Start playback & seek
/* prepare playback */
val medialoaded = media != null
if (!medialoaded) media = if (hasMedia) currentMedia else MLServiceLocator.getAbstractMediaWrapper(uri)
itemTitle?.let { media?.title = Uri.decode(it) }
if (wasPaused) media?.addFlags(MediaWrapper.MEDIA_PAUSED)
if (intent.hasExtra(PLAY_DISABLE_HARDWARE)) media?.addFlags(MediaWrapper.MEDIA_NO_HWACCEL)
media!!.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
media.addFlags(MediaWrapper.MEDIA_VIDEO)
if (fromStart) media.addFlags(MediaWrapper.MEDIA_FROM_START)
// Set resume point
if (!continueplayback && !fromStart) {
if (startTime <= 0L && media.time > 0L) startTime = media.time
if (startTime > 0L) service.saveStartTime(startTime)
}
// Handle playback
if (resumePlaylist) {
if (continueplayback) {
if (displayManager.isPrimary) service.flush()
onPlaying()
} else service.playIndex(positionInPlaylist)
} else service.load(media)
// Get the title
if (itemTitle == null && "content" != uri.scheme) title = uri.lastPathSegment
} else if (service.hasMedia() && !displayManager.isPrimary) {
onPlaying()
} else {
service.loadLastPlaylist(PLAYLIST_TYPE_VIDEO)
}
if (itemTitle != null) title = itemTitle
if (::hudBinding.isInitialized) {
hudRightBinding.playerOverlayTitle.text = title
}
if (wasPaused) {
// XXX: Workaround to update the seekbar position
forcedTime = startTime
forcedTime = -1
showOverlay(true)
}
enableSubs()
}
}
private fun enableSubs() {
videoUri?.let {
val lastPath = it.lastPathSegment ?: return
enableSubs = (!TextUtils.isEmpty(lastPath) && !lastPath.endsWith(".ts") && !lastPath.endsWith(".m2ts")
&& !lastPath.endsWith(".TS") && !lastPath.endsWith(".M2TS"))
}
}
private fun removeDownloadedSubtitlesObserver() {
downloadedSubtitleLiveData?.removeObserver(downloadedSubtitleObserver)
downloadedSubtitleLiveData = null
}
private fun observeDownloadedSubtitles() {
service?.let { service ->
val uri = service.currentMediaWrapper?.uri ?: return
val path = uri.path ?: return
if (previousMediaPath == null || path != previousMediaPath) {
previousMediaPath = path
removeDownloadedSubtitlesObserver()
downloadedSubtitleLiveData = ExternalSubRepository.getInstance(this).getDownloadedSubtitles(uri).apply {
observe(this@VideoPlayerActivity, downloadedSubtitleObserver)
}
}
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private fun getScreenOrientation(mode: Int): Int {
when (mode) {
98 //toggle button
-> return if (currentScreenOrientation == Configuration.ORIENTATION_LANDSCAPE)
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
99 //screen orientation user
-> return if (AndroidUtil.isJellyBeanMR2OrLater)
ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR
101 //screen orientation landscape
-> return ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
102 //screen orientation portrait
-> return ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
/*
screenOrientation = 100, we lock screen at its current orientation
*/
val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val rot = screenRotation
/*
* Since getRotation() returns the screen's "natural" orientation,
* which is not guaranteed to be SCREEN_ORIENTATION_PORTRAIT,
* we have to invert the SCREEN_ORIENTATION value if it is "naturally"
* landscape.
*/
var defaultWide = display.width > display.height
if (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270)
defaultWide = !defaultWide
return if (defaultWide) {
when (rot) {
Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Surface.ROTATION_180 ->
// SCREEN_ORIENTATION_REVERSE_PORTRAIT only available since API
// Level 9+
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
Surface.ROTATION_270 ->
// SCREEN_ORIENTATION_REVERSE_LANDSCAPE only available since API
// Level 9+
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
else -> 0
}
} else {
when (rot) {
Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
Surface.ROTATION_180 ->
// SCREEN_ORIENTATION_REVERSE_PORTRAIT only available since API
// Level 9+
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
Surface.ROTATION_270 ->
// SCREEN_ORIENTATION_REVERSE_LANDSCAPE only available since API
// Level 9+
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
else -> 0
}
}
}
private fun showConfirmResumeDialog() {
if (isFinishing) return
service?.pause()
/* Encountered Error, exit player with a message */
alertDialog = AlertDialog.Builder(this@VideoPlayerActivity)
.setMessage(R.string.confirm_resume)
.setPositiveButton(R.string.resume_from_position) { _, _ -> loadMedia(false) }
.setNegativeButton(R.string.play_from_start) { _, _ -> loadMedia(true) }
.create().apply {
setCancelable(false)
setOnKeyListener(DialogInterface.OnKeyListener { dialog, keyCode, _ ->
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss()
finish()
return@OnKeyListener true
}
false
})
show()
}
}
fun showAdvancedOptions() {
if (optionsDelegate == null) service?.let { optionsDelegate = PlayerOptionsDelegate(this, it) }
optionsDelegate?.show(PlayerOptionType.ADVANCED)
hideOverlay(false)
}
private fun toggleOrientation() {
//screen is not yet locked. We invert the rotation to force locking in the current orientation
if (screenOrientation != 98) {
currentScreenOrientation = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) Configuration.ORIENTATION_LANDSCAPE else Configuration.ORIENTATION_PORTRAIT
}
screenOrientation = 98//Rotate button
requestedOrientation = getScreenOrientation(screenOrientation)
//As the current orientation may have been artificially changed above, we reset it to the real current orientation
currentScreenOrientation = resources.configuration.orientation
@StringRes val message = if (currentScreenOrientation == Configuration.ORIENTATION_LANDSCAPE)
R.string.locked_in_landscape_mode
else
R.string.locked_in_portrait_mode
rootView?.let { UiTools.snacker(it, message) }
}
private fun resetOrientation(): Boolean {
if (screenOrientation == 98) {
screenOrientation = Integer.valueOf(
settings.getString(SCREEN_ORIENTATION, "99" /*SCREEN ORIENTATION SENSOR*/)!!)
rootView?.let { UiTools.snacker(it, R.string.reset_orientation) }
requestedOrientation = getScreenOrientation(screenOrientation)
return true
}
return false
}
internal fun togglePlaylist() {
if (isPlaylistVisible) {
playlistContainer.setGone()
playlist.setOnClickListener(null)
return
}
hideOverlay(true)
playlistContainer.setVisible()
playlist.adapter = playlistAdapter
update()
}
private fun toggleBtDelay(connected: Boolean) {
service?.setAudioDelay(if (connected) settings.getLong(KEY_BLUETOOTH_DELAY, 0) else 0L)
}
/**
* Start the video loading animation.
*/
private fun startLoading() {
if (isLoading) return
isLoading = true
val anim = AnimationSet(true)
val rotate = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
rotate.duration = 800
rotate.interpolator = DecelerateInterpolator()
rotate.repeatCount = RotateAnimation.INFINITE
anim.addAnimation(rotate)
loadingImageView.setVisible()
loadingImageView?.startAnimation(anim)
}
/**
* Stop the video loading animation.
*/
private fun stopLoading() {
handler.removeMessages(LOADING_ANIMATION)
if (!isLoading) return
isLoading = false
loadingImageView.setInvisible()
loadingImageView?.clearAnimation()
}
fun onClickOverlayTips(@Suppress("UNUSED_PARAMETER") v: View) {
overlayTips.setGone()
}
fun onClickDismissTips(@Suppress("UNUSED_PARAMETER") v: View) {
overlayTips.setGone()
settings.putSingle(PREF_TIPS_SHOWN, true)
}
private fun updateNavStatus() {
if (service == null) return
menuIdx = -1
lifecycleScope.launchWhenStarted {
val titles = withContext(Dispatchers.IO) { service?.titles }
if (isFinishing) return@launchWhenStarted
isNavMenu = false
if (titles != null) {
val currentIdx = service?.titleIdx ?: return@launchWhenStarted
for (i in titles.indices) {
val title = titles[i]
if (title.isMenu) {
menuIdx = i
break
}
}
val interactive = service?.mediaplayer?.let {
it.titles[it.title].isInteractive
} ?: false
isNavMenu = menuIdx == currentIdx || interactive
}
if (isNavMenu) {
/*
* Keep the overlay hidden in order to have touch events directly
* transmitted to navigation handling.
*/
hideOverlay(false)
} else if (menuIdx != -1) setESTracks()
navMenu.setVisibility(if (menuIdx >= 0 && navMenu != null) View.VISIBLE else View.GONE)
supportInvalidateOptionsMenu()
}
}
open fun onServiceChanged(service: PlaybackService?) {
if (service != null) {
this.service = service
//We may not have the permission to access files
if (Permissions.checkReadStoragePermission(this, true) && !switchingView)
handler.sendEmptyMessage(START_PLAYBACK)
switchingView = false
handler.post {
// delay mediaplayer loading, prevent ANR
if (service.volume > 100 && !isAudioBoostEnabled) service.setVolume(100)
}
service.addCallback(this)
} else if (this.service != null) {
this.service?.removeCallback(this)
this.service = null
handler.sendEmptyMessage(AUDIO_SERVICE_CONNECTION_FAILED)
removeDownloadedSubtitlesObserver()
previousMediaPath = null
}
}
companion object {
private const val TAG = "VLC/VideoPlayerActivity"
private val ACTION_RESULT = "player.result".buildPkgString()
private const val EXTRA_POSITION = "extra_position"
private const val EXTRA_DURATION = "extra_duration"
private const val EXTRA_URI = "extra_uri"
private const val RESULT_CONNECTION_FAILED = Activity.RESULT_FIRST_USER + 1
private const val RESULT_PLAYBACK_ERROR = Activity.RESULT_FIRST_USER + 2
private const val RESULT_VIDEO_TRACK_LOST = Activity.RESULT_FIRST_USER + 3
internal const val DEFAULT_FOV = 80f
private const val KEY_TIME = "saved_time"
private const val KEY_LIST = "saved_list"
private const val KEY_URI = "saved_uri"
private const val OVERLAY_TIMEOUT = 4000
const val OVERLAY_INFINITE = -1
private const val FADE_OUT = 1
private const val FADE_OUT_INFO = 2
private const val START_PLAYBACK = 3
private const val AUDIO_SERVICE_CONNECTION_FAILED = 4
private const val RESET_BACK_LOCK = 5
private const val CHECK_VIDEO_TRACKS = 6
private const val LOADING_ANIMATION = 7
internal const val SHOW_INFO = 8
internal const val HIDE_INFO = 9
internal const val HIDE_SEEK = 10
internal const val HIDE_SETTINGS = 11
private const val KEY_REMAINING_TIME_DISPLAY = "remaining_time_display"
const val KEY_BLUETOOTH_DELAY = "key_bluetooth_delay"
private const val LOADING_ANIMATION_DELAY = 1000
@Volatile
internal var sDisplayRemainingTime: Boolean = false
private const val PREF_TIPS_SHOWN = "video_player_tips_shown"
private var clone: Boolean? = null
fun start(context: Context, uri: Uri) {
start(context, uri, null, false, -1)
}
fun start(context: Context, uri: Uri, fromStart: Boolean) {
start(context, uri, null, fromStart, -1)
}
fun start(context: Context, uri: Uri, title: String) {
start(context, uri, title, false, -1)
}
fun startOpened(context: Context, uri: Uri, openedPosition: Int) {
start(context, uri, null, false, openedPosition)
}
private fun start(context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int) {
val intent = getIntent(context, uri, title, fromStart, openedPosition)
context.startActivity(intent)
}
fun getIntent(action: String, mw: MediaWrapper, fromStart: Boolean, openedPosition: Int): Intent {
return getIntent(action, AppContextProvider.appContext, mw.uri, mw.title, fromStart, openedPosition)
}
fun getIntent(context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int): Intent {
return getIntent(PLAY_FROM_VIDEOGRID, context, uri, title, fromStart, openedPosition)
}
fun getIntent(action: String, context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int): Intent {
val intent = Intent(context, VideoPlayerActivity::class.java)
intent.action = action
intent.putExtra(PLAY_EXTRA_ITEM_LOCATION, uri)
intent.putExtra(PLAY_EXTRA_ITEM_TITLE, title)
intent.putExtra(PLAY_EXTRA_FROM_START, fromStart)
if (openedPosition != -1 || context !is Activity) {
if (openedPosition != -1)
intent.putExtra(PLAY_EXTRA_OPENED_POSITION, openedPosition)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
return intent
}
}
}
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@BindingAdapter("length", "time")
fun setPlaybackTime(view: TextView, length: Long, time: Long) {
view.text = if (VideoPlayerActivity.sDisplayRemainingTime && length > 0)
"-" + '\u00A0'.toString() + Tools.millisToString(length - time)
else
Tools.millisToString(length)
}
@BindingAdapter("constraintPercent")
fun setConstraintPercent(view: Guideline, percent: Float) {
val constraintLayout = view.parent as ConstraintLayout
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayout)
constraintSet.setGuidelinePercent(view.id, percent)
constraintSet.applyTo(constraintLayout)
}
@BindingAdapter("mediamax")
fun setProgressMax(view: SeekBar, length: Long) {
view.max = length.toInt()
}
/**
* hide the info view
*/
/**
* show overlay with the previous timeout value
*/
| gpl-2.0 | 5f52803693857e14eec44967a1e8174d | 40.421473 | 265 | 0.596555 | 4.990125 | false | false | false | false |
coinbase/coinbase-java | app/src/main/java/com/coinbase/sample/MainApplication.kt | 1 | 4474 | /*
* Copyright 2018 Coinbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.coinbase.sample
import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import com.coinbase.Coinbase
import com.coinbase.CoinbaseBuilder
import com.coinbase.errors.CoinbaseOAuthException
import com.coinbase.resources.auth.AccessToken
import com.coinbase.resources.auth.RevokeTokenResponse
import com.google.gson.Gson
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import okhttp3.logging.HttpLoggingInterceptor
import java.util.*
class MainApplication : Application() {
lateinit var coinbase: Coinbase
private set
val savedExpireDate: Date? by lazy {
val time = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getLong(KEY_EXPIRE_DATE, 0)
if (time != 0L) {
Date(time)
} else {
null
}
}
var accessToken: AccessToken
get() {
val json = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getString(KEY_ACCESS_TOKEN, null)
return if (json == null) AccessToken() else gson.fromJson(json, AccessToken::class.java)
}
set(value) {
val json = gson.toJson(value)
val expiresIn = Calendar.getInstance()
expiresIn.add(Calendar.SECOND, value.expiresIn)
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit()
.putString(KEY_ACCESS_TOKEN, json)
.putLong(KEY_EXPIRE_DATE, expiresIn.time.time)
.apply()
}
private val gson = Gson()
private val tokenUpdateListener = object : Coinbase.TokenListener {
override fun onNewTokensAvailable(accessToken: AccessToken) {
[email protected] = accessToken
}
override fun onRefreshFailed(cause: CoinbaseOAuthException) {
Log.e("CoinbaseSample", "Access token autorefresh failed, logging out", cause)
logout()
}
override fun onTokenRevoked() {
logout()
}
}
override fun onCreate() {
super.onCreate()
coinbase = buildCoinbase()
}
private fun buildCoinbase(): Coinbase {
val builder = CoinbaseBuilder.withTokenAutoRefresh(this,
BuildConfig.CLIENT_ID,
BuildConfig.CLIENT_SECRET,
accessToken.accessToken,
accessToken.refreshToken,
tokenUpdateListener
)
builder.withLoggingLevel(HttpLoggingInterceptor.Level.BODY)
return builder.withLoggingLevel(HttpLoggingInterceptor.Level.BODY).build()
}
fun revokeTokenRx(): Single<RevokeTokenResponse> {
val savedAccessToken = accessToken
return coinbase.authResource
.revokeTokenRx(savedAccessToken.accessToken)
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess {
clearToken()
}
}
fun refreshTokensRx(): Single<AccessToken> {
return coinbase.authResource
.refreshTokensRx(BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET, accessToken.refreshToken)
.observeOn(AndroidSchedulers.mainThread())
}
private fun clearToken() {
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit()
.clear()
.apply()
}
fun logout() {
clearToken()
coinbase.logout()
startActivity(Intent(this, LoginActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK))
}
companion object {
const val PREF_NAME = "Sample App"
private const val KEY_ACCESS_TOKEN = "access_token"
private const val KEY_EXPIRE_DATE = "expireDate"
}
}
| apache-2.0 | 2786e31f774c571b716112406b67ec2b | 30.957143 | 110 | 0.644613 | 4.744433 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/forms/create/CreateTrainingSetBrowseButtonActionListener.kt | 1 | 2539 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.forms.create
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.thomas.needham.neurophidea.Constants.TRAINING_SET_LOCATION_KEY
import com.thomas.needham.neurophidea.actions.ShowCreateNetworkFormAction
import com.thomas.needham.neurophidea.consumers.TrainingSetFileConsumer
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
/**
* Created by Thomas Needham on 25/05/2016.
*/
class CreateTrainingSetBrowseButtonActionListener : ActionListener {
var formInstance: CreateNetworkForm? = null
companion object Data {
val defaultPath = ""
val allowedFileTypes = arrayOf("csv", "txt", "tset")
val fileDescriptor = FileChooserDescriptor(true, false, false, false, false, false)
val consumer: TrainingSetFileConsumer? = TrainingSetFileConsumer()
val properties = PropertiesComponent.getInstance()
var chosenPath = ""
}
override fun actionPerformed(e: ActionEvent?) {
properties?.setValue(TRAINING_SET_LOCATION_KEY, defaultPath)
FileChooser.chooseFile(fileDescriptor, ShowCreateNetworkFormAction.project, null, consumer as Consumer<VirtualFile?>)
chosenPath = properties.getValue(TRAINING_SET_LOCATION_KEY, defaultPath)
formInstance?.txtTrainingData?.text = chosenPath
}
} | mit | b6b3b454d09bb64fd35427cd7436f1f4 | 42.793103 | 119 | 0.808192 | 4.446585 | false | false | false | false |
alpha-cross/ararat | library/src/main/java/org/akop/ararat/io/WSJFormatter.kt | 1 | 8516 | // Copyright (c) Akop Karapetyan
//
// 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.akop.ararat.io
import org.akop.ararat.core.Crossword
import org.akop.ararat.core.buildWord
import org.akop.ararat.util.SparseArray
import org.akop.ararat.util.stripHtmlEntities
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.*
class WSJFormatter : CrosswordFormatter {
private var encoding = Charset.forName(DEFAULT_ENCODING)
override fun setEncoding(encoding: String) {
this.encoding = Charset.forName(encoding)
}
@Throws(IOException::class)
override fun read(builder: Crossword.Builder, inputStream: InputStream) {
val json = inputStream.bufferedReader(encoding).use { it.readText() }
val obj = JSONObject(json)
val dataObj = obj.optJSONObject("data")
?: throw FormatException("Missing 'data'")
val copyObj = dataObj.optJSONObject("copy")
?: throw FormatException("Missing 'data.copy'")
val pubDate = copyObj.optString("date-publish")
val gridObj = copyObj.optJSONObject("gridsize")
?: throw FormatException("Missing 'data.copy.gridsize'")
builder.width = gridObj.optInt("cols")
builder.height = gridObj.optInt("rows")
builder.title = copyObj.optString("title")
builder.description = copyObj.optString("description")
builder.copyright = copyObj.optString("publisher")
builder.author = copyObj.optString("byline")
builder.date = PUBLISH_DATE_FORMAT.parse(pubDate)!!.time
val grid = Grid(builder.width, builder.height,
dataObj.getJSONArray("grid"))
readClues(builder, copyObj, grid)
}
@Throws(IOException::class)
override fun write(crossword: Crossword, outputStream: OutputStream) {
throw UnsupportedOperationException("Writing not supported")
}
override fun canRead(): Boolean = true
override fun canWrite(): Boolean = false
private fun readClues(builder: Crossword.Builder, copyObj: JSONObject, grid: Grid) {
val cluesArray = copyObj.optJSONArray("clues")
when {
cluesArray == null ->
throw FormatException("Missing 'data.copy.clues[]'")
cluesArray.length() != 2 ->
throw FormatException("Unexpected clues length of '${cluesArray.length()}'")
}
val wordsArray = copyObj.optJSONArray("words")
?: throw FormatException("Missing 'data.copy.words[]'")
// We'll need this to assign x/y locations to each clue
val words = SparseArray<Word>()
(0 until wordsArray.length())
.map { Word(wordsArray.optJSONObject(it)!!) }
.forEach { words[it.id] = it }
(0 until cluesArray.length())
.map { cluesArray.optJSONObject(it)!! }
.forEach {
val clueDir = it.optString("title")
val dir = when (clueDir) {
"Across" -> Crossword.Word.DIR_ACROSS
"Down" -> Crossword.Word.DIR_DOWN
else -> throw FormatException("Invalid direction: '$clueDir'")
}
val subcluesArray = it.optJSONArray("clues")!!
(0 until subcluesArray.length())
.map { subcluesArray.optJSONObject(it)!! }
.mapTo(builder.words) {
buildWord {
val word = words[it.optInt("word", -1)]!!
direction = dir
hint = it.optString("clue").stripHtmlEntities()
number = it.optInt("number")
startColumn = word.column
startRow = word.row
if (dir == Crossword.Word.DIR_ACROSS) {
(startColumn until startColumn + word.length)
.map { grid.squares[startRow][it]!! }
.forEach { c -> addCell(c.char, c.attrFlags) }
} else {
(startRow until startRow + word.length)
.map { grid.squares[it][startColumn]!! }
.forEach { c -> addCell(c.char, c.attrFlags) }
}
}
}
}
}
private class Grid(width: Int, height: Int, gridArray: JSONArray) {
val squares = Array<Array<Square?>>(height) { arrayOfNulls(width) }
init {
if (gridArray.length() != height)
throw FormatException("Grid length mismatch (got: ${gridArray.length()}; exp.: $height)")
for (i in 0 until height) {
val rowArray = gridArray.optJSONArray(i)
when {
rowArray == null -> throw FormatException("Missing 'data.grid[$i]'")
rowArray.length() != width ->
throw FormatException("Grid row $i mismatch (got: ${rowArray.length()}); exp.: $width)")
else -> (0 until width).forEach { j ->
squares[i][j] = parseSquare(rowArray.optJSONObject(j))
}
}
}
}
private fun parseSquare(squareObj: JSONObject): Square? {
val letter = squareObj.optString("Letter")
val shapeBg = squareObj.optJSONObject("style")?.optString("shapebg")
return when {
letter.isNotEmpty() -> Square(letter, when (shapeBg) {
"circle" -> Crossword.Cell.ATTR_CIRCLED
else -> 0
})
else -> null
}
}
}
private class Square(val char: String,
val attrFlags: Int = 0)
private class Word(wordObj: JSONObject) {
val id: Int = wordObj.optInt("id", -1)
val row: Int
val column: Int
val length: Int
init {
if (id == -1) throw FormatException("Word missing identifier")
val xStr: String = wordObj.optString("x")
val xDashIdx: Int = xStr.indexOf('-')
val yStr = wordObj.optString("y")
val yDashIdx = yStr.indexOf('-')
column = when {
xDashIdx != -1 -> xStr.substring(0, xDashIdx).toInt() - 1
else -> xStr.toInt() - 1
}
row = when {
yDashIdx != -1 -> yStr.substring(0, yDashIdx).toInt() - 1
else -> yStr.toInt() - 1
}
length = when {
xDashIdx != -1 -> xStr.substring(xDashIdx + 1).toInt() - column
yDashIdx != -1 -> yStr.substring(yDashIdx + 1).toInt() - row
else -> 1
}
}
}
companion object {
private const val DEFAULT_ENCODING = "UTF-8"
internal val PUBLISH_DATE_FORMAT = SimpleDateFormat("EEEE, d MMMM yyyy", Locale.US)
}
}
| mit | ba6029691858278739f832c06dafa4c2 | 39.746411 | 112 | 0.548849 | 4.757542 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/player/songlist/SelectPlaylistFragment.kt | 1 | 6566 | package be.florien.anyflow.feature.player.songlist
import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import be.florien.anyflow.R
import be.florien.anyflow.databinding.FragmentSelectPlaylistBinding
import be.florien.anyflow.databinding.ItemSelectPlaylistBinding
import be.florien.anyflow.extension.viewModelFactory
import be.florien.anyflow.injection.ActivityScope
import be.florien.anyflow.injection.UserScope
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
@ActivityScope
@UserScope
class SelectPlaylistFragment(private var songId: Long = 0L) : DialogFragment() {
lateinit var viewModel: SelectPlaylistViewModel
private lateinit var fragmentBinding: FragmentSelectPlaylistBinding
init {
arguments?.let {
songId = it.getLong("SongId")
}
if (arguments == null) {
arguments = Bundle().apply {
putLong("SongId", songId)
}
}
}
@SuppressLint("NotifyDataSetChanged")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
viewModel = ViewModelProvider(this, requireActivity().viewModelFactory).get(SelectPlaylistViewModel::class.java) //todo change get viewmodel from attach to oncreateView in other fragments
fragmentBinding = FragmentSelectPlaylistBinding.inflate(inflater, container, false)
fragmentBinding.lifecycleOwner = viewLifecycleOwner
fragmentBinding.viewModel = viewModel
fragmentBinding.songId = songId
fragmentBinding.filterList.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
fragmentBinding.filterList.adapter = FilterListAdapter()
ResourcesCompat.getDrawable(resources, R.drawable.sh_divider, requireActivity().theme)?.let {
fragmentBinding.filterList.addItemDecoration(DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL).apply { setDrawable(it) })
}
viewModel.values.observe(viewLifecycleOwner) {
if (it != null)
(fragmentBinding.filterList.adapter as FilterListAdapter).submitData(lifecycle, it)
}
viewModel.currentSelectionLive.observe(viewLifecycleOwner) {
(fragmentBinding.filterList.adapter as FilterListAdapter).notifyDataSetChanged()
}
viewModel.isCreating.observe(viewLifecycleOwner) {
if (it) {
val editText = EditText(requireActivity())
editText.inputType = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
AlertDialog.Builder(requireActivity())
.setView(editText)
.setTitle(R.string.info_action_new_playlist)
.setPositiveButton(R.string.ok) { _: DialogInterface, _: Int ->
viewModel.createPlaylist(editText.text.toString())
}
.setNegativeButton(R.string.cancel) { dialog: DialogInterface, _: Int ->
dialog.cancel()
}
.show()
}
}
viewModel.isFinished.observe(viewLifecycleOwner) {
if (it) {
dismiss()
}
}
return fragmentBinding.root
}
override fun onDismiss(dialog: DialogInterface) {
val parentFragment = parentFragment
if (parentFragment is DialogInterface.OnDismissListener) {
parentFragment.onDismiss(dialog);
}
super.onDismiss(dialog)
}
inner class FilterListAdapter : PagingDataAdapter<SelectPlaylistViewModel.SelectionItem, PlaylistViewHolder>(object : DiffUtil.ItemCallback<SelectPlaylistViewModel.SelectionItem>() {
override fun areItemsTheSame(oldItem: SelectPlaylistViewModel.SelectionItem, newItem: SelectPlaylistViewModel.SelectionItem) = oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: SelectPlaylistViewModel.SelectionItem, newItem: SelectPlaylistViewModel.SelectionItem): Boolean =
oldItem.displayName == newItem.displayName && oldItem.isSelected == (viewModel.currentSelectionLive.value?.any { it.id == newItem.id })
}), FastScrollRecyclerView.SectionedAdapter {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder = PlaylistViewHolder()
override fun onBindViewHolder(holder: PlaylistViewHolder, position: Int) {
val filter = getItem(position) ?: return
filter.isSelected = viewModel.currentSelectionLive.value?.any { it.id == filter.id } ?: false
holder.bind(filter)
}
override fun getSectionName(position: Int): String =
snapshot()[position]?.displayName?.firstOrNull()?.uppercaseChar()?.toString()
?: ""
}
inner class PlaylistViewHolder(
private val itemPlaylistBinding: ItemSelectPlaylistBinding
= ItemSelectPlaylistBinding.inflate(layoutInflater, fragmentBinding.filterList, false)
) : RecyclerView.ViewHolder(itemPlaylistBinding.root) {
fun bind(selection: SelectPlaylistViewModel.SelectionItem) {
itemPlaylistBinding.vm = viewModel
itemPlaylistBinding.lifecycleOwner = viewLifecycleOwner
itemPlaylistBinding.item = selection
setBackground(itemPlaylistBinding.root, selection)
itemPlaylistBinding.root.setOnClickListener {
viewModel.changeFilterSelection(selection)
setBackground(itemPlaylistBinding.root, selection)
}
}
private fun setBackground(view: View, selection: SelectPlaylistViewModel.SelectionItem?) {
view.setBackgroundColor(ResourcesCompat.getColor(resources, if (selection?.isSelected == true) R.color.selected else R.color.unselected, requireActivity().theme))
}
}
}
| gpl-3.0 | 8c131ab0ebce47f7c54a6b427d0797f7 | 47.279412 | 195 | 0.708955 | 5.480801 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/inspection/reference/UnresolvedReferenceInspection.kt | 1 | 2940 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.reference
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.reference.DescReference
import com.demonwav.mcdev.platform.mixin.reference.InjectionPointReference
import com.demonwav.mcdev.platform.mixin.reference.MethodReference
import com.demonwav.mcdev.platform.mixin.reference.MixinReference
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.platform.mixin.util.isWithinDynamicMixin
import com.demonwav.mcdev.util.annotationFromNameValuePair
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiArrayInitializerMemberValue
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameValuePair
class UnresolvedReferenceInspection : MixinInspection() {
override fun getStaticDescription() = "Reports unresolved references in Mixin annotations"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitNameValuePair(pair: PsiNameValuePair) {
val name = pair.name ?: PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME
val resolvers: Array<MixinReference> = when (name) {
"method" -> arrayOf(MethodReference)
"target" -> arrayOf(TargetReference)
"value" -> arrayOf(InjectionPointReference, DescReference)
else -> return
}
// Check if valid annotation
val qualifiedName = pair.annotationFromNameValuePair?.qualifiedName ?: return
val resolver = resolvers.firstOrNull { it.isValidAnnotation(qualifiedName) } ?: return
val value = pair.value ?: return
if (value is PsiArrayInitializerMemberValue) {
for (initializer in value.initializers) {
checkResolved(resolver, initializer)
}
} else {
checkResolved(resolver, value)
}
}
private fun checkResolved(resolver: MixinReference, value: PsiAnnotationMemberValue) {
if (resolver.isUnresolved(value) && !value.isWithinDynamicMixin) {
holder.registerProblem(
value,
"Cannot resolve ${resolver.description}".format(value.constantStringValue),
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
}
}
}
}
| mit | 6d9f1d255cb702c19014afb9d7cc28f6 | 39.833333 | 98 | 0.706803 | 5.20354 | false | false | false | false |
apixandru/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerManagerImpl.kt | 10 | 3789 | /*
* 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.openapi.module.impl
import com.intellij.ProjectTopics
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModulePointer
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.util.Function
import gnu.trove.THashMap
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/**
* @author nik
*/
class ModulePointerManagerImpl(private val project: Project) : ModulePointerManager() {
private val unresolved = THashMap<String, ModulePointerImpl>()
private val pointers = THashMap<Module, ModulePointerImpl>()
private val lock = ReentrantReadWriteLock()
init {
project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun beforeModuleRemoved(project: Project, module: Module) {
unregisterPointer(module)
}
override fun moduleAdded(project: Project, module: Module) {
moduleAppears(module)
}
override fun modulesRenamed(project: Project, modules: List<Module>, oldNameProvider: Function<Module, String>) {
for (module in modules) {
moduleAppears(module)
}
}
})
}
private fun moduleAppears(module: Module) {
lock.write {
unresolved.remove(module.name)?.let {
it.moduleAdded(module)
registerPointer(module, it)
}
}
}
private fun registerPointer(module: Module, pointer: ModulePointerImpl) {
pointers.put(module, pointer)
Disposer.register(module, Disposable { unregisterPointer(module) })
}
private fun unregisterPointer(module: Module) {
lock.write {
pointers.remove(module)?.let {
it.moduleRemoved(module)
unresolved.put(it.moduleName, it)
}
}
}
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
override fun create(module: Module): ModulePointer {
return lock.read { pointers.get(module) } ?: lock.write {
pointers.get(module)?.let {
return it
}
var pointer = unresolved.remove(module.name)
if (pointer == null) {
pointer = ModulePointerImpl(module, lock)
}
else {
pointer.moduleAdded(module)
}
registerPointer(module, pointer)
pointer!!
}
}
override fun create(moduleName: String): ModulePointer {
ModuleManager.getInstance(project).findModuleByName(moduleName)?.let {
return create(it)
}
return lock.read {
unresolved.get(moduleName) ?: lock.write {
unresolved.get(moduleName)?.let {
return it
}
// let's find in the pointers (if model not committed, see testDisposePointerFromUncommittedModifiableModel)
pointers.keys.firstOrNull { it.name == moduleName }?.let {
return create(it)
}
val pointer = ModulePointerImpl(moduleName, lock)
unresolved.put(moduleName, pointer)
pointer
}
}
}
}
| apache-2.0 | 1dd60660e3226d513b88bfc6c40d2487 | 29.804878 | 119 | 0.699129 | 4.330286 | false | false | false | false |
apixandru/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/psiUtil.kt | 7 | 2648 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kIN
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
/**
* @param owner modifier list owner
*
* @return
* * `true` when owner has explicit type or it's not required for owner to have explicit type
* * `false` when doesn't have explicit type and it's required to have a type or modifier
* * `defaultValue` for the other owners
*
*/
fun modifierListMayBeEmpty(owner: PsiElement?): Boolean = when (owner) {
is GrParameter -> owner.parent.let {
if (it is GrParameterList) return true
if (it is GrForClause && it.declaredVariable != owner) return true
if (it is GrForInClause && it.delimiter.node.elementType == kIN) return true
return owner.typeElementGroovy != null
}
is GrMethod -> owner.isConstructor || owner.returnTypeElementGroovy != null && !owner.hasTypeParameters()
is GrVariable -> owner.typeElementGroovy != null
is GrVariableDeclaration -> owner.typeElementGroovy != null
else -> true
}
fun GrExpression?.isSuperExpression(): Boolean {
val referenceExpression = this as? GrReferenceExpression
return referenceExpression?.referenceNameElement?.node?.elementType == GroovyTokenTypes.kSUPER
}
| apache-2.0 | 47da1493decdc7f1ad05eef0f3a3601c | 46.285714 | 107 | 0.78361 | 4.15047 | false | false | false | false |
nicolacimmino/playground | Spring/kotlin/expensesdemo/src/main/kotlin/com/nicolacimmino/expensesdemo/Extensions.kt | 1 | 761 | package com.nicolacimmino.expensesdemo
import java.time.LocalDateTime
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField
import java.util.*
fun LocalDateTime.format(): String = this.format(englishDateFormatter)
private val daysLookup = (1..31).associate { it.toLong() to getOrdinal(it) }
private val englishDateFormatter = DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.appendLiteral(" ")
.appendText(ChronoField.DAY_OF_MONTH, daysLookup)
.appendLiteral(" ")
.appendPattern("yyyy")
.toFormatter(Locale.ENGLISH)
private fun getOrdinal(n: Int) = when {
n in 11..13 -> "${n}th"
n % 10 == 1 -> "${n}st"
n % 10 == 2 -> "${n}nd"
n % 10 == 3 -> "${n}rd"
else -> "${n}th"
}
| gpl-3.0 | f598e693093f0fe088ace58f90fc3848 | 28.269231 | 76 | 0.675427 | 3.443439 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/photo/asymmetric/ImageItem.kt | 1 | 1370 | package ffc.app.photo.asymmetric
import android.os.Parcel
import android.os.Parcelable
import com.felipecsl.asymmetricgridview.AsymmetricItem
/**
* Modified from ItemImage at abhisheklunagaria/FacebookTypeImageGrid
*/
class ImageItem(
var urls: String,
var _columnSpan: Int = 1,
var _rowSpan: Int = 1
) : AsymmetricItem {
override fun getColumnSpan(): Int = _columnSpan
override fun getRowSpan(): Int = _rowSpan
fun setColumnSpan(span: Int) {
_columnSpan = span
}
fun setRowSpan(span: Int) {
_rowSpan = span
}
protected constructor(parcel: Parcel) : this(
urls = parcel.readString()!!,
_columnSpan = parcel.readInt(),
_rowSpan = parcel.readInt()
)
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(urls)
dest.writeInt(_columnSpan)
dest.writeInt(_rowSpan)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<ImageItem> = object : Parcelable.Creator<ImageItem> {
override fun createFromParcel(parcel: Parcel): ImageItem {
return ImageItem(parcel)
}
override fun newArray(size: Int): Array<ImageItem> {
return newArray(size)
}
}
}
}
| apache-2.0 | 3b107d0dd1fee1ba633439b7dc638d43 | 23.464286 | 93 | 0.619708 | 4.254658 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/holder/StatusViewHolder.kt | 1 | 32388 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.view.holder
import android.support.annotation.DrawableRes
import android.support.v4.content.ContextCompat
import android.support.v4.widget.TextViewCompat
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.RequestManager
import kotlinx.android.synthetic.main.list_item_status.view.*
import org.mariotaku.ktextension.*
import de.vanita5.microblog.library.mastodon.annotation.StatusVisibility
import de.vanita5.twittnuker.Constants.*
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.USER_TYPE_FANFOU_COM
import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter
import de.vanita5.twittnuker.constant.SharedPreferenceConstants.VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE
import de.vanita5.twittnuker.extension.loadProfileImage
import de.vanita5.twittnuker.extension.model.applyTo
import de.vanita5.twittnuker.extension.model.quoted_user_acct
import de.vanita5.twittnuker.extension.model.retweeted_by_user_acct
import de.vanita5.twittnuker.extension.model.user_acct
import de.vanita5.twittnuker.extension.setVisible
import de.vanita5.twittnuker.graphic.like.LikeAnimationDrawable
import de.vanita5.twittnuker.model.ParcelableLocation
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.task.CreateFavoriteTask
import de.vanita5.twittnuker.task.DestroyFavoriteTask
import de.vanita5.twittnuker.task.RetweetStatusTask
import de.vanita5.twittnuker.text.TwidereClickableSpan
import de.vanita5.twittnuker.util.HtmlEscapeHelper.toPlainText
import de.vanita5.twittnuker.util.HtmlSpanBuilder
import de.vanita5.twittnuker.util.ThemeUtils
import de.vanita5.twittnuker.util.UnitConvertUtils
import de.vanita5.twittnuker.util.Utils
import de.vanita5.twittnuker.util.Utils.getUserTypeIconRes
import de.vanita5.twittnuker.view.ShapedImageView
import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder
import java.lang.ref.WeakReference
class StatusViewHolder(private val adapter: IStatusesAdapter<*>, itemView: View) : ViewHolder(itemView), IStatusViewHolder {
override val profileImageView: ShapedImageView by lazy { itemView.profileImage }
override val profileTypeView: ImageView by lazy { itemView.profileType }
private val itemContent by lazy { itemView.itemContent }
private val mediaPreview by lazy { itemView.mediaPreview }
private val statusContentUpperSpace by lazy { itemView.statusContentUpperSpace }
private val summaryView by lazy { itemView.summary }
private val textView by lazy { itemView.text }
private val nameView by lazy { itemView.name }
private val itemMenu by lazy { itemView.itemMenu }
private val statusInfoLabel by lazy { itemView.statusInfoLabel }
private val statusInfoIcon by lazy { itemView.statusInfoIcon }
private val quotedNameView by lazy { itemView.quotedName }
private val timeView by lazy { itemView.time }
private val replyCountView by lazy { itemView.replyCount }
private val retweetCountView by lazy { itemView.retweetCount }
private val quotedView by lazy { itemView.quotedView }
private val quotedTextView by lazy { itemView.quotedText }
private val actionButtons by lazy { itemView.actionButtons }
private val mediaLabel by lazy { itemView.mediaLabel }
private val quotedMediaLabel by lazy { itemView.quotedMediaLabel }
private val statusContentLowerSpace by lazy { itemView.statusContentLowerSpace }
private val quotedMediaPreview by lazy { itemView.quotedMediaPreview }
private val favoriteIcon by lazy { itemView.favoriteIcon }
private val retweetIcon by lazy { itemView.retweetIcon }
private val favoriteCountView by lazy { itemView.favoriteCount }
private val replyButton by lazy { itemView.reply }
private val retweetButton by lazy { itemView.retweet }
private val favoriteButton by lazy { itemView.favorite }
private val eventListener: EventListener
private var statusClickListener: IStatusViewHolder.StatusClickListener? = null
init {
this.eventListener = EventListener(this)
if (adapter.mediaPreviewEnabled) {
View.inflate(mediaPreview.context, R.layout.layout_card_media_preview,
itemView.mediaPreview)
View.inflate(quotedMediaPreview.context, R.layout.layout_card_media_preview,
itemView.quotedMediaPreview)
}
}
fun displaySampleStatus() {
val profileImageEnabled = adapter.profileImageEnabled
profileImageView.visibility = if (profileImageEnabled) View.VISIBLE else View.GONE
statusContentUpperSpace.visibility = View.VISIBLE
adapter.requestManager.loadProfileImage(itemView.context, R.drawable.ic_account_logo_twitter,
adapter.profileImageStyle, profileImageView.cornerRadius,
profileImageView.cornerRadiusRatio).into(profileImageView)
nameView.name = TWITTNUKER_PREVIEW_NAME
nameView.screenName = "@$TWITTNUKER_PREVIEW_SCREEN_NAME"
nameView.updateText(adapter.bidiFormatter)
summaryView.hideIfEmpty()
if (adapter.linkHighlightingStyle == VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) {
textView.spannable = toPlainText(TWITTNUKER_PREVIEW_TEXT_HTML)
} else {
val linkify = adapter.twidereLinkify
val text = HtmlSpanBuilder.fromHtml(TWITTNUKER_PREVIEW_TEXT_HTML)
linkify.applyAllLinks(text, null, -1, false, adapter.linkHighlightingStyle, true)
textView.spannable = text
}
timeView.time = System.currentTimeMillis()
val showCardActions = isCardActionsShown
if (adapter.mediaPreviewEnabled) {
mediaPreview.visibility = View.VISIBLE
mediaLabel.visibility = View.GONE
} else {
mediaPreview.visibility = View.GONE
mediaLabel.visibility = View.VISIBLE
}
actionButtons.visibility = if (showCardActions) View.VISIBLE else View.GONE
itemMenu.visibility = if (showCardActions) View.VISIBLE else View.GONE
statusContentLowerSpace.visibility = if (showCardActions) View.GONE else View.VISIBLE
quotedMediaPreview.visibility = View.GONE
quotedMediaLabel.visibility = View.GONE
mediaPreview.displayMedia(R.drawable.twittnuker_feature_graphic)
}
override fun display(status: ParcelableStatus, displayInReplyTo: Boolean,
displayPinned: Boolean) {
val context = itemView.context
val requestManager = adapter.requestManager
val twitter = adapter.twitterWrapper
val linkify = adapter.twidereLinkify
val formatter = adapter.bidiFormatter
val colorNameManager = adapter.userColorNameManager
val nameFirst = adapter.nameFirst
val showCardActions = isCardActionsShown
actionButtons.visibility = if (showCardActions) View.VISIBLE else View.GONE
itemMenu.visibility = if (showCardActions) View.VISIBLE else View.GONE
statusContentLowerSpace.visibility = if (showCardActions) View.GONE else View.VISIBLE
val replyCount = status.reply_count
val retweetCount = status.retweet_count
val favoriteCount = status.favorite_count
if (displayPinned && status.is_pinned_status) {
statusInfoLabel.setText(R.string.pinned_status)
statusInfoIcon.setImageResource(R.drawable.ic_activity_action_pinned)
statusInfoLabel.visibility = View.VISIBLE
statusInfoIcon.visibility = View.VISIBLE
statusContentUpperSpace.visibility = View.GONE
} else if (status.retweet_id != null) {
val retweetedBy = colorNameManager.getDisplayName(status.retweeted_by_user_key!!,
status.retweeted_by_user_name, status.retweeted_by_user_acct!!, nameFirst)
statusInfoLabel.spannable = context.getString(R.string.name_retweeted, formatter.unicodeWrap(retweetedBy))
statusInfoIcon.setImageResource(R.drawable.ic_activity_action_retweet)
statusInfoLabel.visibility = View.VISIBLE
statusInfoIcon.visibility = View.VISIBLE
statusContentUpperSpace.visibility = View.GONE
} else if (status.in_reply_to_status_id != null && status.in_reply_to_user_key != null && displayInReplyTo) {
if (status.in_reply_to_name != null && status.in_reply_to_screen_name != null) {
val inReplyTo = colorNameManager.getDisplayName(status.in_reply_to_user_key!!,
status.in_reply_to_name, status.in_reply_to_screen_name, nameFirst)
statusInfoLabel.spannable = context.getString(R.string.in_reply_to_name, formatter.unicodeWrap(inReplyTo))
} else {
statusInfoLabel.spannable = context.getString(R.string.label_status_type_reply)
}
statusInfoIcon.setImageResource(R.drawable.ic_activity_action_reply)
statusInfoLabel.visibility = View.VISIBLE
statusInfoIcon.visibility = View.VISIBLE
statusContentUpperSpace.visibility = View.GONE
} else {
statusInfoLabel.visibility = View.GONE
statusInfoIcon.visibility = View.GONE
statusContentUpperSpace.visibility = View.VISIBLE
}
val skipLinksInText = status.extras?.support_entities ?: false
if (status.is_quote) {
quotedView.visibility = View.VISIBLE
val quoteContentAvailable = status.quoted_text_plain != null && status.quoted_text_unescaped != null
val isFanfouStatus = status.account_key.host == USER_TYPE_FANFOU_COM
if (quoteContentAvailable && !isFanfouStatus) {
quotedNameView.visibility = View.VISIBLE
quotedTextView.visibility = View.VISIBLE
val quoted_user_key = status.quoted_user_key!!
quotedNameView.name =
status.quoted_user_name
quotedNameView.screenName = "@${status.quoted_user_acct}"
val quotedDisplayEnd = status.extras?.quoted_display_text_range?.getOrNull(1) ?: -1
val quotedText: CharSequence
if (adapter.linkHighlightingStyle != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) {
quotedText = SpannableStringBuilder.valueOf(status.quoted_text_unescaped)
status.quoted_spans?.applyTo(quotedText)
linkify.applyAllLinks(quotedText, status.account_key, layoutPosition.toLong(),
status.is_possibly_sensitive, adapter.linkHighlightingStyle,
skipLinksInText)
} else {
quotedText = status.quoted_text_unescaped
}
if (quotedDisplayEnd != -1 && quotedDisplayEnd <= quotedText.length) {
quotedTextView.spannable = quotedText.subSequence(0, quotedDisplayEnd)
} else {
quotedTextView.spannable = quotedText
}
quotedTextView.hideIfEmpty()
val quoted_user_color = colorNameManager.getUserColor(quoted_user_key)
if (quoted_user_color != 0) {
quotedView.drawStart(quoted_user_color)
} else {
quotedView.drawStart(ThemeUtils.getColorFromAttribute(context,
R.attr.quoteIndicatorBackgroundColor))
}
displayQuotedMedia(requestManager, status)
} else {
quotedNameView.visibility = View.GONE
quotedTextView.visibility = View.VISIBLE
if (quoteContentAvailable) {
displayQuotedMedia(requestManager, status)
} else {
quotedMediaPreview.visibility = View.GONE
quotedMediaLabel.visibility = View.GONE
}
quotedTextView.spannable = if (!quoteContentAvailable) {
// Display 'not available' label
SpannableString.valueOf(context.getString(R.string.label_status_not_available)).apply {
setSpan(ForegroundColorSpan(ThemeUtils.getColorFromAttribute(context,
android.R.attr.textColorTertiary, textView.currentTextColor)), 0,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
} else {
// Display 'original status' label
context.getString(R.string.label_original_status)
}
quotedView.drawStart(ThemeUtils.getColorFromAttribute(context,
R.attr.quoteIndicatorBackgroundColor))
}
itemContent.drawStart(colorNameManager.getUserColor(status.user_key))
} else {
quotedView.visibility = View.GONE
val userColor = colorNameManager.getUserColor(status.user_key)
if (status.is_retweet) {
val retweetUserColor = colorNameManager.getUserColor(status.retweeted_by_user_key!!)
if (retweetUserColor == 0) {
itemContent.drawStart(userColor)
} else if (userColor == 0) {
itemContent.drawStart(retweetUserColor)
} else {
itemContent.drawStart(retweetUserColor, userColor)
}
} else {
itemContent.drawStart(userColor)
}
}
timeView.time = if (status.is_retweet) {
status.retweet_timestamp
} else {
status.timestamp
}
nameView.name = status.user_name
nameView.screenName = "@${status.user_acct}"
if (adapter.profileImageEnabled) {
profileImageView.visibility = View.VISIBLE
requestManager.loadProfileImage(context, status, adapter.profileImageStyle,
profileImageView.cornerRadius, profileImageView.cornerRadiusRatio,
adapter.profileImageSize).into(profileImageView)
profileTypeView.setImageResource(getUserTypeIconRes(status.user_is_verified, status.user_is_protected))
profileTypeView.visibility = View.VISIBLE
} else {
profileImageView.visibility = View.GONE
profileTypeView.setImageDrawable(null)
profileTypeView.visibility = View.GONE
}
if (adapter.showAccountsColor) {
itemContent.drawEnd(status.account_color)
} else {
itemContent.drawEnd()
}
val hasMediaLabel = mediaLabel.displayMediaLabel(status.card_name, status.media, status.location,
status.place_full_name, status.is_possibly_sensitive)
if (status.media.isNotNullOrEmpty()) {
if (!adapter.sensitiveContentEnabled && status.is_possibly_sensitive) {
// Sensitive content, show label instead of media view
mediaLabel.contentDescription = status.media?.firstOrNull()?.alt_text
mediaLabel.setVisible(hasMediaLabel)
mediaPreview.visibility = View.GONE
} else if (!adapter.mediaPreviewEnabled) {
// Media preview disabled, just show label
mediaLabel.contentDescription = status.media?.firstOrNull()?.alt_text
mediaLabel.setVisible(hasMediaLabel)
mediaPreview.visibility = View.GONE
} else {
// Show media
mediaLabel.visibility = View.GONE
mediaPreview.visibility = View.VISIBLE
mediaPreview.displayMedia(requestManager = requestManager,
media = status.media, accountKey = status.account_key,
mediaClickListener = this)
}
} else {
// No media, hide media preview
mediaLabel.setVisible(hasMediaLabel)
mediaPreview.visibility = View.GONE
}
summaryView.spannable = status.extras?.summary_text
summaryView.hideIfEmpty()
val text: CharSequence
val displayEnd: Int
if (!summaryView.empty && !isFullTextVisible) {
text = SpannableStringBuilder.valueOf(context.getString(R.string.label_status_show_more)).apply {
setSpan(object : TwidereClickableSpan(adapter.linkHighlightingStyle) {
override fun onClick(widget: View?) {
showFullText()
}
}, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
displayEnd = -1
} else if (adapter.linkHighlightingStyle != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) {
text = SpannableStringBuilder.valueOf(status.text_unescaped).apply {
status.spans?.applyTo(this)
linkify.applyAllLinks(this, status.account_key, layoutPosition.toLong(),
status.is_possibly_sensitive, adapter.linkHighlightingStyle,
skipLinksInText)
}
displayEnd = status.extras?.display_text_range?.getOrNull(1) ?: -1
} else {
text = status.text_unescaped
displayEnd = status.extras?.display_text_range?.getOrNull(1) ?: -1
}
if (displayEnd != -1 && displayEnd <= text.length) {
textView.spannable = text.subSequence(0, displayEnd)
} else {
textView.spannable = text
}
textView.hideIfEmpty()
if (replyCount > 0) {
replyCountView.spannable = UnitConvertUtils.calculateProperCount(replyCount)
} else {
replyCountView.spannable = null
}
replyCountView.hideIfEmpty()
when (status.extras?.visibility) {
StatusVisibility.PRIVATE -> {
retweetIcon.setImageResource(R.drawable.ic_action_lock)
}
StatusVisibility.DIRECT -> {
retweetIcon.setImageResource(R.drawable.ic_action_message)
}
else -> {
retweetIcon.setImageResource(R.drawable.ic_action_retweet)
}
}
if (twitter.isDestroyingStatus(status.account_key, status.my_retweet_id)) {
retweetIcon.isActivated = false
} else {
val creatingRetweet = RetweetStatusTask.isCreatingRetweet(status.account_key, status.id)
retweetIcon.isActivated = creatingRetweet || status.retweeted ||
Utils.isMyRetweet(status.account_key, status.retweeted_by_user_key,
status.my_retweet_id)
}
if (retweetCount > 0) {
retweetCountView.spannable = UnitConvertUtils.calculateProperCount(retweetCount)
} else {
retweetCountView.spannable = null
}
retweetCountView.hideIfEmpty()
if (DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id)) {
favoriteIcon.isActivated = false
} else {
val creatingFavorite = CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id)
favoriteIcon.isActivated = creatingFavorite || status.is_favorite
}
if (favoriteCount > 0) {
favoriteCountView.spannable = UnitConvertUtils.calculateProperCount(favoriteCount)
} else {
favoriteCountView.spannable = null
}
favoriteCountView.hideIfEmpty()
nameView.updateText(formatter)
quotedNameView.updateText(formatter)
}
private fun displayQuotedMedia(requestManager: RequestManager, status: ParcelableStatus) {
val hasMediaLabel = quotedMediaLabel.displayMediaLabel(null, status.quoted_media,
null, null, status.is_possibly_sensitive)
if (status.quoted_media.isNotNullOrEmpty()) {
if (!adapter.sensitiveContentEnabled && status.is_possibly_sensitive) {
quotedMediaLabel.setVisible(hasMediaLabel)
// Sensitive content, show label instead of media view
quotedMediaPreview.visibility = View.GONE
} else if (!adapter.mediaPreviewEnabled) {
quotedMediaLabel.setVisible(hasMediaLabel)
// Media preview disabled, just show label
quotedMediaPreview.visibility = View.GONE
} else if (status.media.isNotNullOrEmpty()) {
quotedMediaLabel.setVisible(hasMediaLabel)
// Already displaying media, show label only
quotedMediaPreview.visibility = View.GONE
} else {
quotedMediaLabel.visibility = View.GONE
// Show media
quotedMediaPreview.visibility = View.VISIBLE
quotedMediaPreview.displayMedia(requestManager = requestManager,
media = status.quoted_media, accountKey = status.account_key,
mediaClickListener = this)
}
} else {
quotedMediaLabel.setVisible(hasMediaLabel)
// No media, hide all related views
quotedMediaPreview.visibility = View.GONE
}
}
override fun onMediaClick(view: View, current: ParcelableMedia, accountKey: UserKey?, id: Long) {
if (view.parent == quotedMediaPreview) {
statusClickListener?.onQuotedMediaClick(this, view, current, layoutPosition)
} else {
statusClickListener?.onMediaClick(this, view, current, layoutPosition)
}
}
fun setOnClickListeners() {
setStatusClickListener(adapter.statusClickListener)
}
override fun setStatusClickListener(listener: IStatusViewHolder.StatusClickListener?) {
statusClickListener = listener
itemContent.setOnClickListener(eventListener)
itemContent.setOnLongClickListener(eventListener)
itemMenu.setOnClickListener(eventListener)
profileImageView.setOnClickListener(eventListener)
replyButton.setOnClickListener(eventListener)
retweetButton.setOnClickListener(eventListener)
favoriteButton.setOnClickListener(eventListener)
retweetButton.setOnLongClickListener(eventListener)
favoriteButton.setOnLongClickListener(eventListener)
mediaLabel.setOnClickListener(eventListener)
quotedView.setOnClickListener(eventListener)
}
override fun setTextSize(textSize: Float) {
nameView.setPrimaryTextSize(textSize)
quotedNameView.setPrimaryTextSize(textSize)
summaryView.textSize = textSize
textView.textSize = textSize
quotedTextView.textSize = textSize
nameView.setSecondaryTextSize(textSize * 0.85f)
quotedNameView.setSecondaryTextSize(textSize * 0.85f)
timeView.textSize = textSize * 0.85f
statusInfoLabel.textSize = textSize * 0.75f
mediaLabel.textSize = textSize * 0.95f
quotedMediaLabel.textSize = textSize * 0.95f
replyCountView.textSize = textSize
retweetCountView.textSize = textSize
favoriteCountView.textSize = textSize
}
fun setupViewOptions() {
setTextSize(adapter.textSize)
profileImageView.style = adapter.profileImageStyle
mediaPreview.style = adapter.mediaPreviewStyle
quotedMediaPreview.style = adapter.mediaPreviewStyle
// profileImageView.setStyle(adapter.getProfileImageStyle());
val nameFirst = adapter.nameFirst
nameView.nameFirst = nameFirst
quotedNameView.nameFirst = nameFirst
val favIcon: Int
val favStyle: Int
val favColor: Int
val context = itemView.context
if (adapter.useStarsForLikes) {
favIcon = R.drawable.ic_action_star
favStyle = LikeAnimationDrawable.Style.FAVORITE
favColor = ContextCompat.getColor(context, R.color.highlight_favorite)
} else {
favIcon = R.drawable.ic_action_heart
favStyle = LikeAnimationDrawable.Style.LIKE
favColor = ContextCompat.getColor(context, R.color.highlight_like)
}
val icon = ContextCompat.getDrawable(context, favIcon)
val drawable = LikeAnimationDrawable(icon,
favoriteCountView.textColors.defaultColor, favColor, favStyle)
drawable.mutate()
favoriteIcon.setImageDrawable(drawable)
timeView.showAbsoluteTime = adapter.showAbsoluteTime
favoriteIcon.activatedColor = favColor
nameView.applyFontFamily(adapter.lightFont)
timeView.applyFontFamily(adapter.lightFont)
summaryView.applyFontFamily(adapter.lightFont)
textView.applyFontFamily(adapter.lightFont)
mediaLabel.applyFontFamily(adapter.lightFont)
quotedNameView.applyFontFamily(adapter.lightFont)
quotedTextView.applyFontFamily(adapter.lightFont)
quotedMediaLabel.applyFontFamily(adapter.lightFont)
}
override fun playLikeAnimation(listener: LikeAnimationDrawable.OnLikedListener) {
var handled = false
val drawable = favoriteIcon.drawable
if (drawable is LikeAnimationDrawable) {
drawable.setOnLikedListener(listener)
drawable.start()
handled = true
}
if (!handled) {
listener.onLiked()
}
}
private val isCardActionsShown: Boolean
get() = adapter.isCardActionsShown(layoutPosition)
private val isFullTextVisible: Boolean
get() = adapter.isFullTextVisible(layoutPosition)
private fun showCardActions() {
adapter.showCardActions(layoutPosition)
}
private fun hideTempCardActions(): Boolean {
adapter.showCardActions(RecyclerView.NO_POSITION)
return !adapter.isCardActionsShown(RecyclerView.NO_POSITION)
}
private fun showFullText() {
adapter.setFullTextVisible(layoutPosition, true)
}
private fun hideFullText(): Boolean {
adapter.setFullTextVisible(layoutPosition, false)
return !adapter.isFullTextVisible(RecyclerView.NO_POSITION)
}
private fun TextView.displayMediaLabel(cardName: String?, media: Array<ParcelableMedia?>?,
location: ParcelableLocation?, placeFullName: String?, sensitive: Boolean): Boolean {
var result = false
if (media != null && media.isNotEmpty()) {
if (sensitive) {
setLabelIcon(R.drawable.ic_label_warning)
setText(R.string.label_sensitive_content)
} else when {
media.type in videoTypes -> {
setLabelIcon(R.drawable.ic_label_video)
setText(R.string.label_video)
}
media.size > 1 -> {
setLabelIcon(R.drawable.ic_label_gallery)
setText(R.string.label_photos)
}
else -> {
setLabelIcon(R.drawable.ic_label_gallery)
setText(R.string.label_photo)
}
}
result = true
} else if (cardName != null) {
if (cardName.startsWith("poll")) {
setLabelIcon(R.drawable.ic_label_poll)
setText(R.string.label_poll)
result = true
}
}
refreshDrawableState()
return result
}
private fun TextView.setLabelIcon(@DrawableRes icon: Int) {
TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(this, icon, 0,
0, 0)
}
private val Array<ParcelableMedia?>.type: Int
get() {
forEach { if (it != null) return it.type }
return 0
}
private fun hasVideo(media: Array<ParcelableMedia?>?): Boolean {
if (media == null) return false
return media.any { item ->
if (item == null) return@any false
return@any videoTypes.contains(item.type)
}
}
internal class EventListener(holder: StatusViewHolder) : OnClickListener, OnLongClickListener {
private val holderRef = WeakReference(holder)
override fun onClick(v: View) {
val holder = holderRef.get() ?: return
val listener = holder.statusClickListener ?: return
val position = holder.layoutPosition
when (v) {
holder.itemContent -> {
listener.onStatusClick(holder, position)
}
holder.quotedView -> {
listener.onQuotedStatusClick(holder, position)
}
holder.itemMenu -> {
listener.onItemMenuClick(holder, v, position)
}
holder.profileImageView -> {
listener.onUserProfileClick(holder, position)
}
holder.replyButton -> {
listener.onItemActionClick(holder, R.id.reply, position)
}
holder.retweetButton -> {
listener.onItemActionClick(holder, R.id.retweet, position)
}
holder.favoriteButton -> {
listener.onItemActionClick(holder, R.id.favorite, position)
}
holder.mediaLabel -> {
val firstMedia = holder.adapter.getStatus(position).media?.firstOrNull()
if (firstMedia != null) {
listener.onMediaClick(holder, v, firstMedia, position)
} else {
listener.onStatusClick(holder, position)
}
}
}
}
override fun onLongClick(v: View): Boolean {
val holder = holderRef.get() ?: return false
val listener = holder.statusClickListener ?: return false
val position = holder.layoutPosition
when (v) {
holder.itemContent -> {
if (!holder.isCardActionsShown) {
holder.showCardActions()
return true
} else if (holder.hideTempCardActions()) {
return true
}
return listener.onStatusLongClick(holder, position)
}
holder.favoriteButton -> {
return listener.onItemActionLongClick(holder, R.id.favorite, position)
}
holder.retweetButton -> {
return listener.onItemActionLongClick(holder, R.id.retweet, position)
}
}
return false
}
}
companion object {
const val layoutResource = R.layout.list_item_status
private val videoTypes = intArrayOf(ParcelableMedia.Type.VIDEO, ParcelableMedia.Type.ANIMATED_GIF,
ParcelableMedia.Type.EXTERNAL_PLAYER)
}
}
| gpl-3.0 | 929ee32f3a679df4d7b50daa4e92076f | 42.473826 | 124 | 0.643695 | 4.990447 | false | false | false | false |
ham1/jmeter | src/core/src/test/kotlin/org/apache/jmeter/threads/openmodel/ThreadScheduleTest.kt | 3 | 2622 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jmeter.threads.openmodel
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import kotlin.test.assertEquals
class ThreadScheduleTest {
class Case(val input: String, val expected: String) {
override fun toString() = input
}
companion object {
@JvmStatic
fun data() = listOf(
Case("rate(0/min)", "[Rate(0)]"),
Case("rate(36000/hour)", "[Rate(10)]"),
Case("random_arrivals(0) /* 0 does not require time unit */", "[Arrivals(type=RANDOM, duration=0)]"),
Case(
"rate(1/sec) random_arrivals(2 min) pause(3 min) random_arrivals(4 sec)",
"[Rate(1), Arrivals(type=RANDOM, duration=120), Rate(1), Rate(0), Arrivals(type=EVEN, duration=180), Rate(0), Rate(1), Arrivals(type=RANDOM, duration=4)]"
),
Case("rate(50.1/sec)", "[Rate(50.1)]"),
Case("even_arrivals(50 min)", "[Arrivals(type=EVEN, duration=3000)]"),
Case("even_arrivals(2d 1m 30s)", "[Arrivals(type=EVEN, duration=${2 * 86400 + 60 + 30})]"),
Case(
"rate(50/min) even_arrivals(2 hour) rate(60/min)",
"[Rate(0.8), Arrivals(type=EVEN, duration=7200), Rate(1)]"
),
Case(
"rate(0 per min) even_arrivals(30 min) rate(50 per min) random_arrivals(4 min) rate(200 per min) random_arrivals(10 sec)",
"[Rate(0), Arrivals(type=EVEN, duration=1800), Rate(0.8), Arrivals(type=RANDOM, duration=240), Rate(3.3), Arrivals(type=RANDOM, duration=10)]"
)
)
}
@ParameterizedTest
@MethodSource("data")
fun test(case: Case) {
assertEquals(case.expected, ThreadSchedule(case.input).toString(), case.input)
}
}
| apache-2.0 | e618b4e5151b62b1d8a1a6154fa0891b | 44.206897 | 170 | 0.638825 | 3.778098 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsLiteralAnnotator.kt | 2 | 2755 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.lang.ASTNode
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
class RsLiteralAnnotator : AnnotatorBase() {
override fun annotateInternal(element: PsiElement, holder: AnnotationHolder) {
if (element !is RsLitExpr) return
val literal = element.kind
// Check suffix
when (literal) {
is RsLiteralKind.Integer, is RsLiteralKind.Float, is RsLiteralKind.String, is RsLiteralKind.Char -> {
literal as RsLiteralWithSuffix
val suffix = literal.suffix
val validSuffixes = literal.validSuffixes
if (!suffix.isNullOrEmpty() && suffix !in validSuffixes) {
val message = if (validSuffixes.isNotEmpty()) {
val validSuffixesStr = validSuffixes.joinToString { "'$it'" }
"invalid suffix '$suffix' for ${literal.node.displayName}; " +
"the suffix must be one of: $validSuffixesStr"
} else {
"${literal.node.displayName} with a suffix is invalid"
}
holder.newAnnotation(HighlightSeverity.ERROR, message).create()
}
}
else -> Unit
}
// Check char literal length
if (literal is RsLiteralKind.Char) {
val value = literal.value
when {
value == null || value.isEmpty() -> "empty ${literal.node.displayName}"
value.codePointCount(0, value.length) > 1 -> "too many characters in ${literal.node.displayName}"
else -> null
}?.let { holder.newAnnotation(HighlightSeverity.ERROR, it).create() }
}
// Check delimiters
if (literal is RsTextLiteral && literal.hasUnpairedQuotes) {
holder.newAnnotation(HighlightSeverity.ERROR, "unclosed ${literal.node.displayName}").create()
}
}
}
private val ASTNode.displayName: String
get() = when (elementType) {
INTEGER_LITERAL -> "integer literal"
FLOAT_LITERAL -> "float literal"
CHAR_LITERAL -> "char literal"
BYTE_LITERAL -> "byte literal"
STRING_LITERAL -> "string literal"
BYTE_STRING_LITERAL -> "byte string literal"
RAW_STRING_LITERAL -> "raw string literal"
RAW_BYTE_STRING_LITERAL -> "raw byte string literal"
else -> toString()
}
| mit | d26c1e41901cc76ab86c9f2db757988f | 36.739726 | 113 | 0.599637 | 4.833333 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/nuklear/templates/nuklear.kt | 1 | 72700 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.nuklear.templates
import org.lwjgl.generator.*
import org.lwjgl.nuklear.*
val nuklear = "Nuklear".nativeClass(packageName = NUKLEAR_PACKAGE, prefix = "NK", prefixMethod = "nk_", library = "lwjgl_nuklear") {
nativeDirective("""#ifdef LWJGL_LINUX
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif""", beforeIncludes = true)
nativeDirective(
"""DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711 4738))
#endif
#define NK_PRIVATE
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_COMMAND_USERDATA
#ifdef LWJGL_WINDOWS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#endif
#define NK_ASSERT(expr)
#define NK_IMPLEMENTATION
#define NK_MEMSET memset
#define NK_MEMCOPY memcpy
#define NK_SQRT sqrt
#define NK_SIN sinf
#define NK_COS cosf
#include <math.h>
#include <string.h>
#include "nuklear.h"
typedef float(*nk_value_getter)(void* user, int index);
typedef void(*nk_item_getter)(void*, int, const char**);
ENABLE_WARNINGS()""")
documentation =
"""
This is a minimal state immediate mode graphical user interface single header toolkit written in ANSI C and licensed under public domain. It was
designed as a simple embeddable user interface for application and does not have any dependencies, a default renderbackend or OS window and input
handling but instead provides a very modular library approach by using simple input state for input and draw commands describing primitive shapes as
output. So instead of providing a layered library that tries to abstract over a number of platform and render backends it only focuses on the actual
UI.
<h3>VALUES</h3>
${ul(
"Immediate mode graphical user interface toolkit",
"Single header library",
"Written in C89 (ANSI C)",
"Small codebase (~15kLOC)",
"Focus on portability, efficiency and simplicity",
"No dependencies (not even the standard library if not wanted)",
"Fully skinnable and customizable",
"Low memory footprint with total memory control if needed or wanted",
"UTF-8 support",
"No global or hidden state",
"Customizable library modules (you can compile and use only what you need)",
"Optional font baker and vertex buffer output"
)}
<h3>FEATURES</h3>
${ul(
"Absolutely no platform dependent code",
"Memory management control ranging from/to",
"Ease of use by allocating everything from the standard library",
"Control every byte of memory inside the library",
"Font handling control ranging from/to",
"Use your own font implementation for everything",
"Use this libraries internal font baking and handling API",
"Drawing output control ranging from/to",
"Simple shapes for more high level APIs which already having drawing capabilities",
"Hardware accessible anti-aliased vertex buffer output",
"Customizable colors and properties ranging from/to",
"Simple changes to color by filling a simple color table",
"Complete control with ability to use skinning to decorate widgets",
"Bendable UI library with widget ranging from/to",
"Basic widgets like buttons, checkboxes, slider, ...",
"Advanced widget like abstract comboboxes, contextual menus,...",
"Compile time configuration to only compile what you need",
"Subset which can be used if you do not want to link or use the standard library",
"Can be easily modified to only update on user input instead of frame updates"
)}
"""
IntConstant(
"Constants.",
"UTF_INVALID"..0xFFFD,
"UTF_SIZE".."$NK_UTF_SIZE",
"INPUT_MAX".."16",
"MAX_NUMBER_BUFFER".."64"
)
FloatConstant(
"Constants.",
"UNDEFINED"..-1.0f,
"SCROLLBAR_HIDING_TIMEOUT"..4.0f
)
EnumConstant(
"Boolean values.",
"nk_false".enum,
"nk_true".enum
).noPrefix()
val Headings = EnumConstant(
"nk_heading",
"UP".enum,
"RIGHT".enum,
"DOWN".enum,
"LEFT".enum
).javaDocLinks
val ButtonBehaviors = EnumConstant(
"nk_button_behavior",
"BUTTON_DEFAULT".enum,
"BUTTON_REPEATER".enum
).javaDocLinks
EnumConstant(
"nk_modify",
"FIXED".enum("", "nk_false"),
"MODIFIABLE".enum("", "nk_true")
)
EnumConstant(
"nk_orientation",
"VERTICAL".enum,
"HORIZONTAL".enum
)
val CollapseStates = EnumConstant(
"nk_collapse_states",
"MINIMIZED".enum("", "nk_false"),
"MAXIMIZED".enum("", "nk_true")
).javaDocLinks
val ShowStates = EnumConstant(
"nk_show_states",
"HIDDEN".enum("", "nk_false"),
"SHOWN".enum("", "nk_true")
).javaDocLinks
val ChartTypes = EnumConstant(
"nk_chart_type",
"CHART_LINES".enum,
"CHART_COLUMN".enum,
"CHART_MAX".enum
).javaDocLinks
EnumConstant(
"nk_chart_event",
"CHART_HOVERING".enum(0x01),
"CHART_CLICKED".enum(0x02)
)
val ColorFormats = EnumConstant(
"nk_color_format",
"RGB".enum,
"RGBA".enum
).javaDocLinks
val PopupTypes = EnumConstant(
"nk_popup_type",
"POPUP_STATIC".enum,
"POPUP_DYNAMIC".enum
).javaDocLinks
val LayoutFormats = EnumConstant(
"nk_layout_format",
"DYNAMIC".enum,
"STATIC".enum
).javaDocLinks
val TreeTypes = EnumConstant(
"nk_tree_type",
"TREE_NODE".enum,
"TREE_TAB".enum
).javaDocLinks
val Antialiasing = EnumConstant(
"nk_anti_aliasing",
"ANTI_ALIASING_OFF".enum,
"ANTI_ALIASING_ON".enum
).javaDocLinks
val SymbolTypes = EnumConstant(
"nk_symbol_type",
"SYMBOL_NONE".enum,
"SYMBOL_X".enum,
"SYMBOL_UNDERSCORE".enum,
"SYMBOL_CIRCLE_SOLID".enum,
"SYMBOL_CIRCLE_OUTLINE".enum,
"SYMBOL_RECT_SOLID".enum,
"SYMBOL_RECT_OUTLINE".enum,
"SYMBOL_TRIANGLE_UP".enum,
"SYMBOL_TRIANGLE_DOWN".enum,
"SYMBOL_TRIANGLE_LEFT".enum,
"SYMBOL_TRIANGLE_RIGHT".enum,
"SYMBOL_PLUS".enum,
"SYMBOL_MINUS".enum,
"SYMBOL_MAX".enum
).javaDocLinks
val Keys = EnumConstant(
"nk_keys",
"KEY_NONE".enum,
"KEY_SHIFT".enum,
"KEY_CTRL".enum,
"KEY_DEL".enum,
"KEY_ENTER".enum,
"KEY_TAB".enum,
"KEY_BACKSPACE".enum,
"KEY_COPY".enum,
"KEY_CUT".enum,
"KEY_PASTE".enum,
"KEY_UP".enum,
"KEY_DOWN".enum,
"KEY_LEFT".enum,
"KEY_RIGHT".enum,
"KEY_TEXT_INSERT_MODE".enum,
"KEY_TEXT_REPLACE_MODE".enum,
"KEY_TEXT_RESET_MODE".enum,
"KEY_TEXT_LINE_START".enum,
"KEY_TEXT_LINE_END".enum,
"KEY_TEXT_START".enum,
"KEY_TEXT_END".enum,
"KEY_TEXT_UNDO".enum,
"KEY_TEXT_REDO".enum,
"KEY_TEXT_WORD_LEFT".enum,
"KEY_TEXT_WORD_RIGHT".enum,
"KEY_SCROLL_START".enum,
"KEY_SCROLL_END".enum,
"KEY_SCROLL_DOWN".enum,
"KEY_SCROLL_UP".enum,
"KEY_MAX".enum
).javaDocLinks { !it.name.endsWith("MAX") }
val Buttons = EnumConstant(
"nk_buttons",
"BUTTON_LEFT".enum,
"BUTTON_MIDDLE".enum,
"BUTTON_RIGHT".enum,
"BUTTON_MAX".enum
).javaDocLinks { !it.name.endsWith("MAX") }
val StyleColors = EnumConstant(
"nk_style_colors",
"COLOR_TEXT".enum,
"COLOR_WINDOW".enum,
"COLOR_HEADER".enum,
"COLOR_BORDER".enum,
"COLOR_BUTTON".enum,
"COLOR_BUTTON_HOVER".enum,
"COLOR_BUTTON_ACTIVE".enum,
"COLOR_TOGGLE".enum,
"COLOR_TOGGLE_HOVER".enum,
"COLOR_TOGGLE_CURSOR".enum,
"COLOR_SELECT".enum,
"COLOR_SELECT_ACTIVE".enum,
"COLOR_SLIDER".enum,
"COLOR_SLIDER_CURSOR".enum,
"COLOR_SLIDER_CURSOR_HOVER".enum,
"COLOR_SLIDER_CURSOR_ACTIVE".enum,
"COLOR_PROPERTY".enum,
"COLOR_EDIT".enum,
"COLOR_EDIT_CURSOR".enum,
"COLOR_COMBO".enum,
"COLOR_CHART".enum,
"COLOR_CHART_COLOR".enum,
"COLOR_CHART_COLOR_HIGHLIGHT".enum,
"COLOR_SCROLLBAR".enum,
"COLOR_SCROLLBAR_CURSOR".enum,
"COLOR_SCROLLBAR_CURSOR_HOVER".enum,
"COLOR_SCROLLBAR_CURSOR_ACTIVE".enum,
"COLOR_TAB_HEADER".enum,
"COLOR_COUNT".enum
).javaDocLinksSkipCount
val StyleCursor = EnumConstant(
"nk_style_cursor",
"CURSOR_ARROW".enum,
"CURSOR_TEXT".enum,
"CURSOR_MOVE".enum,
"CURSOR_RESIZE_VERTICAL".enum,
"CURSOR_RESIZE_HORIZONTAL".enum,
"CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT".enum,
"CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT".enum,
"CURSOR_COUNT".enum
).javaDocLinksSkipCount
EnumConstant(
"nk_widget_layout_states",
"WIDGET_INVALID".enum("The widget cannot be seen and is completely out of view"),
"WIDGET_VALID".enum("The widget is completely inside the window and can be updated and drawn"),
"WIDGET_ROM".enum("The widget is partially visible and cannot be updated")
)
EnumConstant(
"nk_widget_states",
"WIDGET_STATE_MODIFIED".enum("", 1.NK_FLAG),
"WIDGET_STATE_INACTIVE".enum("widget is neither active nor hovered", 2.NK_FLAG),
"WIDGET_STATE_ENTERED".enum("widget has been hovered on the current frame", 3.NK_FLAG),
"WIDGET_STATE_HOVER".enum("widget is being hovered", 4.NK_FLAG),
"WIDGET_STATE_ACTIVED".enum("widget is currently activated", 5.NK_FLAG),
"WIDGET_STATE_LEFT".enum("widget is from this frame on not hovered anymore", 6.NK_FLAG),
"WIDGET_STATE_HOVERED".enum("widget is being hovered", "NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED"),
"WIDGET_STATE_ACTIVE".enum("widget is currently activated", "NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED")
)
EnumConstant(
"nk_text_align",
"TEXT_ALIGN_LEFT".enum(0x01),
"TEXT_ALIGN_CENTERED".enum(0x02),
"TEXT_ALIGN_RIGHT".enum(0x04),
"TEXT_ALIGN_TOP".enum(0x08),
"TEXT_ALIGN_MIDDLE".enum(0x10),
"TEXT_ALIGN_BOTTOM".enum(0x20)
)
val TextAlignments = EnumConstant(
"nk_text_alignment",
"TEXT_LEFT".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT"),
"TEXT_CENTERED".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED"),
"TEXT_RIGHT".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT")
).javaDocLinks
val EditFlags = EnumConstant(
"nk_edit_flags",
"EDIT_DEFAULT".enum(0),
"EDIT_READ_ONLY".enum("", 0.NK_FLAG),
"EDIT_AUTO_SELECT".enum("", 1.NK_FLAG),
"EDIT_SIG_ENTER".enum("", 2.NK_FLAG),
"EDIT_ALLOW_TAB".enum("", 3.NK_FLAG),
"EDIT_NO_CURSOR".enum("", 4.NK_FLAG),
"EDIT_SELECTABLE".enum("", 5.NK_FLAG),
"EDIT_CLIPBOARD".enum("", 6.NK_FLAG),
"EDIT_CTRL_ENTER_NEWLINE".enum("", 7.NK_FLAG),
"EDIT_NO_HORIZONTAL_SCROLL".enum("", 8.NK_FLAG),
"EDIT_ALWAYS_INSERT_MODE".enum("", 9.NK_FLAG),
"EDIT_MULTILINE".enum("", 11.NK_FLAG),
"EDIT_GOTO_END_ON_ACTIVATE".enum("", 12.NK_FLAG)
).javaDocLinks
EnumConstant(
"nk_edit_types",
"EDIT_SIMPLE".enum("", "NK_EDIT_ALWAYS_INSERT_MODE"),
"EDIT_FIELD".enum("", "NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD"),
"EDIT_BOX".enum("", "NK_EDIT_ALWAYS_INSERT_MODE|NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD"),
"EDIT_EDITOR".enum("", "NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD")
)
EnumConstant(
"nk_edit_events",
"EDIT_ACTIVE".enum("edit widget is currently being modified", 0.NK_FLAG),
"EDIT_INACTIVE".enum("edit widget is not active and is not being modified", 1.NK_FLAG),
"EDIT_ACTIVATED".enum("edit widget went from state inactive to state active", 2.NK_FLAG),
"EDIT_DEACTIVATED".enum("edit widget went from state active to state inactive", 3.NK_FLAG),
"EDIT_COMMITED".enum("edit widget has received an enter and lost focus", 4.NK_FLAG)
)
val PanelFlags = EnumConstant(
"nk_panel_flags",
"WINDOW_BORDER".enum("Draws a border around the window to visually separate the window * from the background", 0.NK_FLAG),
"WINDOW_MOVABLE".enum("The movable flag indicates that a window can be moved by user input or * by dragging the window header", 1.NK_FLAG),
"WINDOW_SCALABLE".enum("The scalable flag indicates that a window can be scaled by user input * by dragging a scaler icon at the button of the window", 2.NK_FLAG),
"WINDOW_CLOSABLE".enum("adds a closable icon into the header", 3.NK_FLAG),
"WINDOW_MINIMIZABLE".enum("adds a minimize icon into the header", 4.NK_FLAG),
"WINDOW_NO_SCROLLBAR".enum("Removes the scrollbar from the window", 5.NK_FLAG),
"WINDOW_TITLE".enum("Forces a header at the top at the window showing the title", 6.NK_FLAG),
"WINDOW_SCROLL_AUTO_HIDE".enum("Automatically hides the window scrollbar if no user interaction", 7.NK_FLAG),
"WINDOW_BACKGROUND".enum("Keep window always in the background", 8.NK_FLAG)
).javaDocLinks
EnumConstant(
"nk_allocation_type",
"BUFFER_FIXED".enum,
"BUFFER_DYNAMIC".enum
)
val BufferAllocationTypes = EnumConstant(
"nk_buffer_allocation_type",
"BUFFER_FRONT".enum,
"BUFFER_BACK".enum,
"BUFFER_MAX".enum
).javaDocLinks
EnumConstant(
"nk_text_edit_type",
"TEXT_EDIT_SINGLE_LINE".enum,
"TEXT_EDIT_MULTI_LINE".enum
)
EnumConstant(
"nk_text_edit_mode",
"TEXT_EDIT_MODE_VIEW".enum,
"TEXT_EDIT_MODE_INSERT".enum,
"TEXT_EDIT_MODE_REPLACE".enum
)
EnumConstant(
"nk_font_coord_type",
"COORD_UV".enum("texture coordinates inside font glyphs are clamped between 0-1"),
"COORD_PIXEL".enum("texture coordinates inside font glyphs are in absolute pixel")
)
EnumConstant(
"nk_font_atlas_format",
"FONT_ATLAS_ALPHA8".enum,
"FONT_ATLAS_RGBA32".enum
)
EnumConstant(
"nk_command_type",
"COMMAND_NOP".enum,
"COMMAND_SCISSOR".enum,
"COMMAND_LINE".enum,
"COMMAND_CURVE".enum,
"COMMAND_RECT".enum,
"COMMAND_RECT_FILLED".enum,
"COMMAND_RECT_MULTI_COLOR".enum,
"COMMAND_CIRCLE".enum,
"COMMAND_CIRCLE_FILLED".enum,
"COMMAND_ARC".enum,
"COMMAND_ARC_FILLED".enum,
"COMMAND_TRIANGLE".enum,
"COMMAND_TRIANGLE_FILLED".enum,
"COMMAND_POLYGON".enum,
"COMMAND_POLYGON_FILLED".enum,
"COMMAND_POLYLINE".enum,
"COMMAND_TEXT".enum,
"COMMAND_IMAGE".enum
)
EnumConstant(
"nk_command_clipping",
"CLIPPING_OFF".enum("", "nk_false"),
"CLIPPING_ON".enum("", "nk_true")
)
val DrawListStrokes = EnumConstant(
"nk_draw_list_stroke",
"STROKE_OPEN".enum("build up path has no connection back to the beginning", "nk_false"),
"STROKE_CLOSED".enum("build up path has a connection back to the beginning", "nk_true")
).javaDocLinks
EnumConstant(
"nk_draw_vertex_layout_attribute",
"VERTEX_POSITION".enum,
"VERTEX_COLOR".enum,
"VERTEX_TEXCOORD".enum,
"VERTEX_ATTRIBUTE_COUNT".enum
)
EnumConstant(
"nk_draw_vertex_layout_format",
"FORMAT_SCHAR".enum,
"FORMAT_SSHORT".enum,
"FORMAT_SINT".enum,
"FORMAT_UCHAR".enum,
"FORMAT_USHORT".enum,
"FORMAT_UINT".enum,
"FORMAT_FLOAT".enum,
"FORMAT_DOUBLE".enum,
"FORMAT_R8G8B8".enum,
"FORMAT_R16G15B16".enum,
"FORMAT_R32G32B32".enum,
"FORMAT_R8G8B8A8".enum,
"FORMAT_R16G15B16A16".enum,
"FORMAT_R32G32B32A32".enum,
"FORMAT_R32G32B32A32_FLOAT".enum,
"FORMAT_R32G32B32A32_DOUBLE".enum,
"FORMAT_RGB32".enum,
"FORMAT_RGBA32".enum,
"FORMAT_COUNT".enum
)
EnumConstant(
"nk_style_item_type",
"STYLE_ITEM_COLOR".enum,
"STYLE_ITEM_IMAGE".enum
)
EnumConstant(
"nk_style_header_align",
"HEADER_LEFT".enum,
"HEADER_RIGHT".enum
)
val PanelTypes = EnumConstant(
"nk_panel_type",
"PANEL_WINDOW".enum("", 0.NK_FLAG),
"PANEL_GROUP".enum("", 1.NK_FLAG),
"PANEL_POPUP".enum("", 2.NK_FLAG),
"PANEL_CONTEXTUAL".enum("", 4.NK_FLAG),
"PANEL_COMBO".enum("", 5.NK_FLAG),
"PANEL_MENU".enum("", 6.NK_FLAG),
"PANEL_TOOLTIP".enum("", 7.NK_FLAG)
)
val PanelSet = EnumConstant(
"nk_panel_set",
"PANEL_SET_NONBLOCK".enum("", "NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP"),
"PANEL_SET_POPUP".enum("", "NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP"),
"PANEL_SET_SUB".enum("", "NK_PANEL_SET_POPUP|NK_PANEL_GROUP")
)
val WindowFlags = EnumConstant(
"nk_window_flags",
"WINDOW_PRIVATE".enum("", 10.NK_FLAG),
"WINDOW_DYNAMIC".enum("special window type growing up in height while being filled to a certain maximum height", "NK_WINDOW_PRIVATE"),
"WINDOW_ROM".enum("sets the window into a read only mode and does not allow input changes", 11.NK_FLAG),
"WINDOW_HIDDEN".enum("Hides the window and stops any window interaction and drawing can be set by user input or by closing the window", 12.NK_FLAG),
"WINDOW_CLOSED".enum("Directly closes and frees the window at the end of the frame", 13.NK_FLAG),
"WINDOW_MINIMIZED".enum("marks the window as minimized", 14.NK_FLAG),
"WINDOW_REMOVE_ROM".enum("Removes the read only mode at the end of the window", 15.NK_FLAG)
).javaDocLinks
val ctx = nk_context_p.IN("ctx", "the nuklear context");
val cctx = const..nk_context_p.IN("ctx", "the nuklear context");
{
intb(
"init_fixed",
"",
ctx,
void_p.IN("memory", ""),
AutoSize("memory")..nk_size.IN("size", ""),
nullable..const..nk_user_font_p.IN("font", "")
)
intb(
"init_custom",
"",
ctx,
nk_buffer_p.IN("cmds", ""),
nk_buffer_p.IN("pool", ""),
nullable..const..nk_user_font_p.IN("font", "")
)
intb(
"init",
"",
ctx,
nk_allocator_p.IN("allocator", ""),
nullable..const..nk_user_font_p.IN("font", "")
)
void("clear", "", ctx)
void("free", "", ctx)
void(
"set_user_data",
"",
ctx,
nullable..nk_handle.IN("handle", "")
)
intb(
"begin",
"",
ctx,
nk_panel_p.OUT("panel", ""),
const..charUTF8_p.IN("title", ""),
nk_rect.IN("bounds", ""),
nk_flags.IN("flags", "", WindowFlags, LinkMode.BITFIELD)
)
intb(
"begin_titled",
"",
ctx,
nk_panel_p.OUT("panel", ""),
const..charUTF8_p.IN("name", ""),
const..charUTF8_p.IN("title", ""),
nk_rect.IN("bounds", ""),
nk_flags.IN("flags", "", WindowFlags, LinkMode.BITFIELD)
)
void("end", "", ctx)
nk_window_p(
"window_find",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
nk_rect("window_get_bounds", "", cctx)
nk_vec2("window_get_position", "", cctx)
nk_vec2("window_get_size", "", cctx)
float("window_get_width", "", cctx)
float("window_get_height", "", cctx)
nk_panel_p("window_get_panel", "", ctx)
nk_rect("window_get_content_region", "", ctx)
nk_vec2("window_get_content_region_min", "", ctx)
nk_vec2("window_get_content_region_max", "", ctx)
nk_vec2("window_get_content_region_size", "", ctx)
nk_command_buffer_p("window_get_canvas", "", ctx)
intb("window_has_focus", "", cctx)
intb(
"window_is_collapsed",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
intb(
"window_is_closed",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
intb(
"window_is_hidden",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
intb(
"window_is_active",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
intb("window_is_hovered", "", ctx)
intb("window_is_any_hovered", "", ctx)
intb("item_is_any_active", "", ctx)
void(
"window_set_bounds",
"",
ctx,
nk_rect.IN("bounds", "")
)
void(
"window_set_position",
"",
ctx,
nk_vec2.IN("position", "")
)
void(
"window_set_size",
"",
ctx,
nk_vec2.IN("size", "")
)
void(
"window_set_focus",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
void(
"window_close",
"",
ctx,
const..charUTF8_p.IN("name", "")
)
void(
"window_collapse",
"",
ctx,
const..charUTF8_p.IN("name", ""),
nk_collapse_states.IN("c", "", CollapseStates)
)
void(
"window_show",
"",
ctx,
const..charUTF8_p.IN("name", ""),
nk_show_states.IN("s", "", ShowStates)
)
void(
"layout_row_dynamic",
"",
ctx,
float.IN("height", ""),
nk_int.IN("cols", "")
)
void(
"layout_row_static",
"",
ctx,
float.IN("height", ""),
nk_int.IN("item_width", ""),
nk_int.IN("cols", "")
)
void(
"layout_row_begin",
"",
ctx,
nk_layout_format.IN("fmt", "", LayoutFormats),
float.IN("row_height", ""),
nk_int.IN("cols", "")
)
void(
"layout_row_push",
"",
ctx,
float.IN("value", "")
)
void("layout_row_end", "", ctx)
void(
"layout_row",
"",
ctx,
nk_layout_format.IN("fmt", "", LayoutFormats),
float.IN("height", ""),
nk_int.IN("cols", ""),
const..float_p.IN("ratio", "")
)
void(
"layout_space_begin",
"",
ctx,
nk_layout_format.IN("fmt", "", LayoutFormats),
float.IN("height", ""),
nk_int.IN("widget_count", "")
)
void(
"layout_space_push",
"",
ctx,
nk_rect.IN("rect", "")
)
void("layout_space_end", "", ctx)
nk_rect("layout_space_bounds", "", ctx)
nk_vec2(
"layout_space_to_screen",
"",
ctx,
ReturnParam..nk_vec2.IN("ret", "")
)
nk_vec2(
"layout_space_to_local",
"",
ctx,
ReturnParam..nk_vec2.IN("ret", "")
)
nk_rect(
"layout_space_rect_to_screen",
"",
ctx,
ReturnParam..nk_rect.IN("ret", "")
)
nk_rect(
"layout_space_rect_to_local",
"",
ctx,
ReturnParam..nk_rect.IN("ret", "")
)
float(
"layout_ratio_from_pixel",
"",
ctx,
float.IN("pixel_width", "")
)
intb(
"group_begin",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("title", ""),
nk_flags.IN("flags", "")
)
void("group_end", "", ctx)
intb(
"tree_push_hashed",
"",
ctx,
nk_tree_type.IN("type", "", TreeTypes),
const..charUTF8_p.IN("title", ""),
nk_collapse_states.IN("initial_state", "", CollapseStates),
const..char_p.IN("hash", ""),
AutoSize("hash")..nk_int.IN("len", ""),
nk_int.IN("seed", "")
)
intb(
"tree_image_push_hashed",
"",
ctx,
nk_tree_type.IN("type", "", TreeTypes),
nk_image.IN("img", ""),
const..charUTF8_p.IN("title", ""),
nk_collapse_states.IN("initial_state", "", CollapseStates),
const..charUTF8_p.IN("hash", ""),
AutoSize("hash")..nk_int.IN("len", ""),
nk_int.IN("seed", "")
)
void("tree_pop", "", ctx)
void(
"text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..nk_int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
void(
"text_colored",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..nk_int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments),
nk_color.IN("color", "")
)
void(
"text_wrap",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..nk_int.IN("len", "")
)
void(
"text_wrap_colored",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..nk_int.IN("len", ""),
nk_color.IN("color", "")
)
void(
"label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments)
)
void(
"label_colored",
"",
ctx,
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments),
nk_color.IN("color", "")
)
void(
"label_wrap",
"",
ctx,
const..charUTF8_p.IN("str", "")
)
void(
"label_colored_wrap",
"",
ctx,
const..charUTF8_p.IN("str", ""),
nk_color.IN("color", "")
)
void(
"image",
"",
ctx,
nk_image.IN("img", "")
)
intb(
"button_text",
"",
ctx,
const..charUTF8_p.IN("title", ""),
AutoSize("title")..nk_int.IN("len", "")
)
intb(
"button_label",
"",
ctx,
const..charUTF8_p.IN("title", "")
)
intb(
"button_color",
"",
ctx,
nk_color.IN("color", "")
)
intb(
"button_symbol",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes)
)
intb(
"button_image",
"",
ctx,
nk_image.IN("img", "")
)
intb(
"button_symbol_label",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("text_alignment", "", TextAlignments)
)
intb(
"button_symbol_text",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..nk_int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"button_image_label",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("text_alignment", "", TextAlignments)
)
intb(
"button_image_text",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..nk_int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
void(
"button_set_behavior",
"",
ctx,
nk_button_behavior.IN("behavior", "", ButtonBehaviors)
)
int(
"button_push_behavior",
"",
ctx,
nk_button_behavior.IN("behavior", "", ButtonBehaviors)
)
int(
"button_pop_behavior",
"",
ctx
)
intb(
"check_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
intb.IN("active", "")
)
intb(
"check_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
intb.IN("active", "")
)
unsigned_int(
"check_flags_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
unsigned_int.IN("flags", ""),
unsigned_int.IN("value", "")
)
unsigned_int(
"check_flags_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
unsigned_int.IN("flags", ""),
unsigned_int.IN("value", "")
)
intb(
"checkbox_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
Check(1)..int_p.INOUT("active", "")
)
intb(
"checkbox_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
Check(1)..int_p.INOUT("active", "")
)
intb(
"checkbox_flags_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
Check(1)..unsigned_int_p.INOUT("flags", ""),
unsigned_int.IN("value", "")
)
intb(
"checkbox_flags_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
Check(1)..unsigned_int_p.INOUT("flags", ""),
unsigned_int.IN("value", "")
)
intb(
"radio_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
Check(1)..int_p.INOUT("active", "")
)
intb(
"radio_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
Check(1)..int_p.INOUT("active", "")
)
intb(
"option_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
intb.IN("active", "")
)
intb(
"option_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
intb.IN("active", "")
)
intb(
"selectable_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments),
Check(1)..int_p.INOUT("value", "")
)
intb(
"selectable_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
Check(1)..int_p.INOUT("value", "")
)
intb(
"selectable_image_label",
"",
ctx,
nullable..nk_image.IN("img", ""),
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments),
Check(1)..int_p.INOUT("value", "")
)
intb(
"selectable_image_text",
"",
ctx,
nullable..nk_image.IN("img", ""),
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
Check(1)..int_p.INOUT("value", "")
)
intb(
"select_label",
"",
ctx,
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments),
intb.IN("value", "")
)
intb(
"select_text",
"",
ctx,
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
intb.IN("value", "")
)
intb(
"select_image_label",
"",
ctx,
nullable..nk_image.IN("img", ""),
const..charUTF8_p.IN("str", ""),
nk_flags.IN("align", "", TextAlignments),
intb.IN("value", "")
)
intb(
"select_image_text",
"",
ctx,
nullable..nk_image.IN("img", ""),
const..charUTF8_p.IN("str", ""),
AutoSize("str")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
intb.IN("value", "")
)
float(
"slide_float",
"",
ctx,
float.IN("min", ""),
float.IN("val", ""),
float.IN("max", ""),
float.IN("step", "")
)
int(
"slide_int",
"",
ctx,
int.IN("min", ""),
int.IN("val", ""),
int.IN("max", ""),
int.IN("step", "")
)
int(
"slider_float",
"",
ctx,
float.IN("min", ""),
float_p.OUT("val", ""),
float.IN("max", ""),
float.IN("step", "")
)
int(
"slider_int",
"",
ctx,
int.IN("min", ""),
int_p.OUT("val", ""),
int.IN("max", ""),
int.IN("step", "")
)
intb(
"progress",
"",
ctx,
nk_size.p.INOUT("cur", ""),
nk_size.IN("max", ""),
intb.IN("modifyable", "")
)
nk_size(
"prog",
"",
ctx,
nk_size.IN("cur", ""),
nk_size.IN("max", ""),
intb.IN("modifyable", "")
)
nk_color(
"color_picker",
"",
ctx,
ReturnParam..nk_color.IN("color", ""),
nk_color_format.IN("fmt", "", ColorFormats)
)
intb(
"color_pick",
"",
ctx,
nk_color.p.INOUT("color", ""),
nk_color_format.IN("fmt", "", ColorFormats)
)
void(
"property_int",
"",
ctx,
const..charUTF8_p.IN("name", ""),
int.IN("min", ""),
Check(1)..int_p.INOUT("val", ""),
int.IN("max", ""),
int.IN("step", ""),
float.IN("inc_per_pixel", "")
)
void(
"property_float",
"",
ctx,
const..charUTF8_p.IN("name", ""),
float.IN("min", ""),
Check(1)..float_p.INOUT("val", ""),
float.IN("max", ""),
float.IN("step", ""),
float.IN("inc_per_pixel", "")
)
void(
"property_double",
"",
ctx,
const..charUTF8_p.IN("name", ""),
double.IN("min", ""),
Check(1)..double_p.INOUT("val", ""),
double.IN("max", ""),
double.IN("step", ""),
float.IN("inc_per_pixel", "")
)
int(
"propertyi",
"",
ctx,
const..charUTF8_p.IN("name", ""),
int.IN("min", ""),
int.IN("val", ""),
int.IN("max", ""),
int.IN("step", ""),
float.IN("inc_per_pixel", "")
)
float(
"propertyf",
"",
ctx,
const..charUTF8_p.IN("name", ""),
float.IN("min", ""),
float.IN("val", ""),
float.IN("max", ""),
float.IN("step", ""),
float.IN("inc_per_pixel", "")
)
double(
"propertyd",
"",
ctx,
const..charUTF8_p.IN("name", ""),
double.IN("min", ""),
double.IN("val", ""),
double.IN("max", ""),
double.IN("step", ""),
float.IN("inc_per_pixel", "")
)
nk_flags(
"edit_string",
"",
ctx,
nk_flags.IN("flags", "", EditFlags),
charUTF8_p.IN("memory", ""),
Check(1)..int_p.OUT("len", ""),
int.IN("max", ""),
nullable..nk_plugin_filter.IN("filter", "")
)
nk_flags(
"edit_buffer",
"",
ctx,
nk_flags.IN("flags", "", EditFlags),
nk_text_edit_p.IN("edit", ""),
nullable..nk_plugin_filter.IN("filter", "")
)
nk_flags(
"edit_string_zero_terminated",
"",
ctx,
nk_flags.IN("flags", "", EditFlags),
charUTF8_p.IN("buffer", ""),
int.IN("max", ""),
nullable..nk_plugin_filter.IN("filter", "")
)
}();
{
intb(
"chart_begin",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
int.IN("num", ""),
float.IN("min", ""),
float.IN("max", "")
)
intb(
"chart_begin_colored",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
nk_color.IN("color", ""),
nk_color.IN("active", ""),
int.IN("num", ""),
float.IN("min", ""),
float.IN("max", "")
)
void(
"chart_add_slot",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
int.IN("count", ""),
float.IN("min_value", ""),
float.IN("max_value", "")
)
void(
"chart_add_slot_colored",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
nk_color.IN("color", ""),
nk_color.IN("active", ""),
int.IN("count", ""),
float.IN("min_value", ""),
float.IN("max_value", "")
)
nk_flags(
"chart_push",
"",
ctx,
float.IN("value", "")
)
nk_flags(
"chart_push_slot",
"",
ctx,
float.IN("value", ""),
int.IN("slot", "")
)
void("chart_end", "", ctx)
void(
"plot",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
Check("offset + count")..const..float_p.IN("values", ""),
int.IN("count", ""),
int.IN("offset", "")
)
void(
"plot_function",
"",
ctx,
nk_chart_type.IN("type", "", ChartTypes),
voidptr.IN("userdata", ""),
nk_value_getter.IN("value_getter", ""),
int.IN("count", ""),
int.IN("offset", "")
)
intb(
"popup_begin",
"",
ctx,
nk_panel_p.IN("layout", ""),
nk_popup_type.IN("type", "", PopupTypes),
const..charUTF8_p.IN("title", ""),
nk_flags.IN("flags", "", PanelFlags),
nk_rect.IN("rect", "")
)
void("popup_close", "", ctx)
void("popup_end", "", ctx)
intb(
"combo",
"",
ctx,
const..charUTF8_pp.IN("items", ""),
AutoSize("items")..int.IN("count", ""),
intb.IN("selected", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_separator",
"",
ctx,
const..charUTF8_p.IN("items_separated_by_separator", ""),
int.IN("separator", ""),
intb.IN("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_string",
"",
ctx,
const..charUTF8_p.IN("items_separated_by_zeros", ""),
intb.IN("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_callback",
"",
ctx,
nk_item_getter.IN("item_getter", ""),
voidptr.IN("userdata", ""),
intb.IN("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
void(
"combobox",
"",
ctx,
const..charUTF8_pp.IN("items", ""),
AutoSize("items")..int.IN("count", ""),
Check(1)..int_p.INOUT("selected", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
void(
"combobox_string",
"",
ctx,
const..charUTF8_p.IN("items_separated_by_zeros", ""),
Check(1)..int_p.INOUT("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
void(
"combobox_separator",
"",
ctx,
const..charUTF8_p.IN("items_separated_by_separator", ""),
int.IN("separator", ""),
Check(1)..int_p.INOUT("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
void(
"combobox_callback",
"",
ctx,
nk_item_getter.IN("item_getter", ""),
voidptr.IN("userdata", ""),
Check(1)..int_p.INOUT("selected", ""),
int.IN("count", ""),
int.IN("item_height", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
AutoSize("selected")..int.IN("len", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_color",
"",
ctx,
nk_panel_p.IN("layout", ""),
nk_color.IN("color", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_symbol",
"",
ctx,
nk_panel_p.IN("layout", ""),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_symbol_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_symbol_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
AutoSize("selected")..int.IN("len", ""),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_image",
"",
ctx,
nk_panel_p.IN("layout", ""),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_image_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_begin_image_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("selected", ""),
AutoSize("selected")..int.IN("len", ""),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"combo_item_label",
"",
ctx,
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"combo_item_text",
"",
ctx,
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"combo_item_image_label",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"combo_item_image_text",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"combo_item_symbol_label",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"combo_item_symbol_text",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
void("combo_close", "", ctx)
void("combo_end", "", ctx)
intb(
"contextual_begin",
"",
ctx,
nk_panel_p.IN("layout", ""),
nk_flags.IN("flags", "", WindowFlags),
nk_vec2.IN("size", ""),
nk_rect.IN("trigger_bounds", "")
)
intb(
"contextual_item_text",
"",
ctx,
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments)
)
intb(
"contextual_item_label",
"",
ctx,
const..charUTF8_p.IN("text", ""),
nk_flags.IN("align", "", TextAlignments)
)
intb(
"contextual_item_image_label",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"contextual_item_image_text",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"contextual_item_symbol_label",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"contextual_item_symbol_text",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
void("contextual_close", "", ctx)
void("contextual_end", "", ctx)
void(
"tooltip",
"",
ctx,
const..charUTF8_p.IN("text", "")
)
intb(
"tooltip_begin",
"",
ctx,
nk_panel_p.IN("layout", ""),
float.IN("width", "")
)
void("tooltip_end", "", ctx)
void("menubar_begin", "", ctx)
void("menubar_end", "", ctx)
intb(
"menu_begin_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("align", "", TextAlignments),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_image",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_image_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_image_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("align", "", TextAlignments),
nk_image.IN("img", ""),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_symbol",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_symbol_text",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"menu_begin_symbol_label",
"",
ctx,
nk_panel_p.IN("layout", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("align", "", TextAlignments),
nk_symbol_type.IN("symbol", "", SymbolTypes),
nk_vec2.IN("size", "")
)
intb(
"menu_item_text",
"",
ctx,
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("align", "", TextAlignments)
)
intb(
"menu_item_label",
"",
ctx,
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"menu_item_image_label",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"menu_item_image_text",
"",
ctx,
nk_image.IN("img", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"menu_item_symbol_text",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
intb(
"menu_item_symbol_label",
"",
ctx,
nk_symbol_type.IN("symbol", "", SymbolTypes),
const..charUTF8_p.IN("text", ""),
nk_flags.IN("alignment", "", TextAlignments)
)
void("menu_close", "", ctx)
void("menu_end", "", ctx)
}();
{
void(
"convert",
"",
ctx,
nk_buffer_p.IN("cmds", ""),
nk_buffer_p.IN("vertices", ""),
nk_buffer_p.IN("elements", ""),
const..nk_convert_config.p.IN("config", "")
)
void("input_begin", "", ctx)
void(
"input_motion",
"",
ctx,
int.IN("x", ""),
int.IN("y", "")
)
void(
"input_key",
"",
ctx,
nk_keys.IN("key", "", Keys),
intb.IN("down", "")
)
void(
"input_button",
"",
ctx,
nk_buttons.IN("id", "", Buttons),
int.IN("x", ""),
int.IN("y", ""),
intb.IN("down", "")
)
void(
"input_scroll",
"",
ctx,
float.IN("y", "")
)
void(
"input_glyph",
"",
ctx,
Check(NK_UTF_SIZE)..nk_glyph.IN("glyph", "")
)
void(
"input_unicode",
"",
ctx,
nk_rune.IN("unicode", "")
)
void("input_end", "", ctx)
void("style_default", "", ctx)
void(
"style_from_table",
"",
ctx,
Check("NK_COLOR_COUNT")..const..nk_color.p.IN("table", "")
)
void(
"style_load_cursor",
"",
ctx,
nk_style_cursor.IN("style", "", StyleCursor),
nk_cursor_p.IN("cursor", "")
)
void(
"style_load_all_cursors",
"",
ctx,
Check("NK_CURSOR_COUNT")..nk_cursor_p.IN("cursors", "")
)
(const..charUTF8_p)(
"style_get_color_by_name",
"",
nk_style_colors.IN("c", "", StyleColors)
)
void(
"style_set_font",
"",
ctx,
const..nk_user_font_p.IN("font", "")
)
int(
"style_set_cursor",
"",
ctx,
nk_style_cursor.IN("style", "", StyleCursor)
)
void("style_show_cursor", "", ctx)
void("style_hide_cursor", "", ctx)
int(
"style_push_font",
"",
ctx,
nk_user_font_p.IN("font", "")
)
int(
"style_push_float",
"",
ctx,
float_p.IN("address", ""),
float.IN("value", "")
)
int(
"style_push_vec2",
"",
ctx,
nk_vec2.p.IN("address", ""),
nk_vec2.IN("value", "")
)
int(
"style_push_style_item",
"",
ctx,
nk_style_item.p.IN("address", ""),
nk_style_item.IN("value", "")
)
int(
"style_push_flags",
"",
ctx,
nk_flags.p.IN("address", ""),
nk_flags.IN("value", "")
)
int(
"style_push_color",
"",
ctx,
nk_color.p.IN("address", ""),
nk_color.IN("value", "")
)
int("style_pop_font", "", ctx)
int("style_pop_float", "", ctx)
int("style_pop_vec2", "", ctx)
int("style_pop_style_item", "", ctx)
int("style_pop_flags", "", ctx)
int("style_pop_color", "", ctx)
nk_rect("widget_bounds", "", ctx)
nk_vec2("widget_position", "", ctx)
nk_vec2("widget_size", "", ctx)
float("widget_width", "", ctx)
float("widget_height", "", ctx)
intb("widget_is_hovered", "", ctx)
intb(
"widget_is_mouse_clicked",
"",
ctx,
nk_buttons.IN("btn", "")
)
intb(
"widget_has_mouse_click_down",
"",
ctx,
nk_buttons.IN("btn", "", Buttons),
intb.IN("down", "")
)
void(
"spacing",
"",
ctx,
int.IN("cols", "")
)
nk_widget_layout_states(
"widget",
"",
nk_rect.p.IN("bounds", ""),
cctx
)
nk_widget_layout_states(
"widget_fitting",
"",
nk_rect.p.IN("bounds", ""),
ctx,
nk_vec2.IN("item_padding", "")
)
nk_color(
"rgb",
"",
int.IN("r", ""),
int.IN("g", ""),
int.IN("b", "")
)
nk_color(
"rgb_iv",
"",
Check(3)..const..int_p.IN("rgb", "")
)
nk_color(
"rgb_bv",
"",
Check(3)..const..nk_byte_p.IN("rgb", "")
)
nk_color(
"rgb_f",
"",
float.IN("r", ""),
float.IN("g", ""),
float.IN("b", "")
)
nk_color(
"rgb_fv",
"",
Check(3)..const..float_p.IN("rgb", "")
)
nk_color(
"rgb_hex",
"",
Check(6)..const..charASCII_p.IN("rgb", "")
)
nk_color(
"rgba",
"",
int.IN("r", ""),
int.IN("g", ""),
int.IN("b", ""),
int.IN("a", "")
)
nk_color(
"rgba_u32",
"",
nk_uint.IN("in", "")
)
nk_color(
"rgba_iv",
"",
Check(4)..const..int_p.IN("rgba", "")
)
nk_color(
"rgba_bv",
"",
Check(4)..const..nk_byte_p.IN("rgba", "")
)
nk_color(
"rgba_f",
"",
float.IN("r", ""),
float.IN("g", ""),
float.IN("b", ""),
float.IN("a", "")
)
nk_color(
"rgba_fv",
"",
Check(4)..const..float_p.IN("rgba", "")
)
nk_color(
"rgba_hex",
"",
Check(8)..const..charASCII_p.IN("rgba", "")
)
nk_color(
"hsv",
"",
int.IN("h", ""),
int.IN("s", ""),
int.IN("v", "")
)
nk_color(
"hsv_iv",
"",
Check(3)..const..int_p.IN("hsv", "")
)
nk_color(
"hsv_bv",
"",
Check(3)..const..nk_byte_p.IN("hsv", "")
)
nk_color(
"hsv_f",
"",
float.IN("h", ""),
float.IN("s", ""),
float.IN("v", "")
)
nk_color(
"hsv_fv",
"",
Check(3)..const..float_p.IN("hsv", "")
)
nk_color(
"hsva",
"",
int.IN("h", ""),
int.IN("s", ""),
int.IN("v", ""),
int.IN("a", "")
)
nk_color(
"hsva_iv",
"",
Check(4)..const..int_p.IN("hsva", "")
)
nk_color(
"hsva_bv",
"",
Check(4)..const..nk_byte_p.IN("hsva", "")
)
nk_color(
"hsva_f",
"",
float.IN("h", ""),
float.IN("s", ""),
float.IN("v", ""),
float.IN("a", "")
)
nk_color(
"hsva_fv",
"",
Check(4)..const..float_p.IN("hsva", "")
)
void(
"color_f",
"",
Check(1)..float_p.OUT("r", ""),
Check(1)..float_p.OUT("g", ""),
Check(1)..float_p.OUT("b", ""),
Check(1)..float_p.OUT("a", ""),
nk_color.IN("color", "")
)
void(
"color_fv",
"",
Check(4)..float_p.OUT("rgba_out", ""),
nk_color.IN("color", "")
)
void(
"color_d",
"",
Check(1)..double_p.OUT("r", ""),
Check(1)..double_p.OUT("g", ""),
Check(1)..double_p.OUT("b", ""),
Check(1)..double_p.OUT("a", ""),
nk_color.IN("color", "")
)
void(
"color_dv",
"",
Check(4)..double_p.OUT("rgba_out", ""),
nk_color.IN("color", "")
)
nk_uint(
"color_u32",
"",
nk_color.IN("color", "")
)
void(
"color_hex_rgba",
"",
Check(8)..char_p.OUT("output", ""),
nk_color.IN("color", "")
)
void(
"color_hex_rgb",
"",
Check(6)..char_p.OUT("output", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_i",
"",
Check(1)..int_p.OUT("out_h", ""),
Check(1)..int_p.OUT("out_s", ""),
Check(1)..int_p.OUT("out_v", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_b",
"",
Check(1)..nk_byte_p.OUT("out_h", ""),
Check(1)..nk_byte_p.OUT("out_s", ""),
Check(1)..nk_byte_p.OUT("out_v", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_iv",
"",
Check(3)..int_p.OUT("hsv_out", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_bv",
"",
Check(3)..nk_byte_p.OUT("hsv_out", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_f",
"",
Check(1)..float_p.OUT("out_h", ""),
Check(1)..float_p.OUT("out_s", ""),
Check(1)..float_p.OUT("out_v", ""),
nk_color.IN("color", "")
)
void(
"color_hsv_fv",
"",
Check(3)..float_p.OUT("hsv_out", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_i",
"",
Check(1)..int_p.OUT("h", ""),
Check(1)..int_p.OUT("s", ""),
Check(1)..int_p.OUT("v", ""),
Check(1)..int_p.OUT("a", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_b",
"",
Check(1)..nk_byte_p.OUT("h", ""),
Check(1)..nk_byte_p.OUT("s", ""),
Check(1)..nk_byte_p.OUT("v", ""),
Check(1)..nk_byte_p.OUT("a", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_iv",
"",
Check(4)..int_p.OUT("hsva_out", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_bv",
"",
Check(4)..nk_byte_p.OUT("hsva_out", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_f",
"",
Check(1)..float_p.OUT("out_h", ""),
Check(1)..float_p.OUT("out_s", ""),
Check(1)..float_p.OUT("out_v", ""),
Check(1)..float_p.OUT("out_a", ""),
nk_color.IN("color", "")
)
void(
"color_hsva_fv",
"",
Check(4)..float_p.OUT("hsva_out", ""),
nk_color.IN("color", "")
)
nk_handle(
"handle_ptr",
"",
voidptr.IN("ptr", "")
)
nk_handle(
"handle_id",
"",
int.IN("id", "")
)
nk_image(
"image_handle",
"",
nk_handle.IN("handle", "")
)
nk_image(
"image_ptr",
"",
voidptr.IN("ptr", "")
)
nk_image(
"image_id",
"",
int.IN("id", "")
)
intb(
"image_is_subimage",
"",
const..nk_image.p.IN("img", "")
)
nk_image(
"subimage_ptr",
"",
voidptr.IN("ptr", ""),
unsigned_short.IN("w", ""),
unsigned_short.IN("h", ""),
nk_rect.IN("sub_region", "")
)
nk_image(
"subimage_id",
"",
int.IN("id", ""),
unsigned_short.IN("w", ""),
unsigned_short.IN("h", ""),
nk_rect.IN("sub_region", "")
)
nk_image(
"subimage_handle",
"",
nk_handle.IN("handle", ""),
unsigned_short.IN("w", ""),
unsigned_short.IN("h", ""),
nk_rect.IN("sub_region", "")
)
nk_hash(
"murmur_hash",
"",
const..void_p.IN("key", ""),
AutoSize("key")..int.IN("len", ""),
nk_hash.IN("seed", "")
)
void(
"triangle_from_direction",
"",
nk_vec2.p.OUT("result", ""),
nk_rect.IN("r", ""),
float.IN("pad_x", ""),
float.IN("pad_y", ""),
nk_heading.IN("direction", "", Headings)
)
nk_vec2(
"vec2",
"",
float.IN("x", ""),
float.IN("y", "")
)
nk_vec2(
"vec2i",
"",
int.IN("x", ""),
int.IN("y", "")
)
nk_vec2(
"vec2v",
"",
Check(2)..const..float_p.IN("xy", "")
)
nk_vec2(
"vec2iv",
"",
Check(2)..const..int_p.IN("xy", "")
)
nk_rect(
"get_null_rect",
""
)
nk_rect(
"rect",
"",
float.IN("x", ""),
float.IN("y", ""),
float.IN("w", ""),
float.IN("h", "")
)
nk_rect(
"recti",
"",
int.IN("x", ""),
int.IN("y", ""),
int.IN("w", ""),
int.IN("h", "")
)
nk_rect(
"recta",
"",
nk_vec2.IN("pos", ""),
nk_vec2.IN("size", "")
)
nk_rect(
"rectv",
"",
Check(4)..const..float_p.IN("xywh", "")
)
nk_rect(
"rectiv",
"",
Check(4)..const..int_p.IN("xywh", "")
)
nk_vec2(
"rect_pos",
"",
nk_rect.IN("r", "")
)
nk_vec2(
"rect_size",
"",
nk_rect.IN("r", "")
)
}();
{
int(
"strlen",
"",
const..charUTF8_p.IN("str", "")
)
int(
"stricmp",
"",
const..charUTF8_p.IN("s1", ""),
const..charUTF8_p.IN("s2", "")
)
int(
"stricmpn",
"",
const..charUTF8_p.IN("s1", ""),
const..charUTF8_p.IN("s2", ""),
int.IN("n", "")
)
int(
"strtoi",
"",
const..charUTF8_p.IN("str", ""),
charUTF8_pp.OUT("endptr", "")
)
float(
"strtof",
"",
const..charUTF8_p.IN("str", ""),
charUTF8_pp.OUT("endptr", "")
)
double(
"strtod",
"",
const..charUTF8_p.IN("str", ""),
charUTF8_pp.OUT("endptr", "")
)
intb(
"strfilter",
"""
${ul(
"c - matches any literal character c",
". - matches any single character",
"^ - matches the beginning of the input string",
"$ - matches the end of the input string",
"* - matches zero or more occurrences of the previous character"
)}
""",
const..charUTF8_p.IN("str", ""),
const..charUTF8_p.IN("regexp", "")
)
intb(
"strmatch_fuzzy_string",
"""
Returns true if each character in {@code pattern} is found sequentially within {@code str} if found then {@code out_score} is also set. Score value has no
intrinsic meaning. Range varies with {@code pattern}. Can only compare scores with same search pattern.
""",
const..charUTF8_p.IN("str", ""),
const..charUTF8_p.IN("pattern", ""),
Check(1)..int_p.OUT("out_score", "")
)
int(
"strmatch_fuzzy_text",
"",
const..charUTF8_p.IN("txt", ""),
AutoSize("txt")..int.IN("txt_len", ""),
const..charUTF8_p.IN("pattern", ""),
Check(1)..int_p.OUT("out_score", "")
)
int(
"utf_decode",
"",
const..char_p.IN("c", ""),
Check(1)..nk_rune_p.OUT("u", ""),
AutoSize("c")..int.IN("clen", "")
)
int(
"utf_encode",
"",
nk_rune.IN("u", ""),
char_p.IN("c", ""),
AutoSize("c")..int.IN("clen", "")
)
int(
"utf_len",
"",
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("byte_len", "")
)
(const..char_p)(
"utf_at",
"",
const..char_p.IN("buffer", ""),
AutoSize("buffer")..int.IN("length", ""),
int.IN("index", ""),
Check(1)..nk_rune_p.OUT("unicode", ""),
AutoSizeResult..int_p.OUT("len", "")
)
void(
"buffer_init",
"",
nk_buffer_p.IN("buffer", ""),
const..nk_allocator_p.IN("allocator", ""),
nk_size.IN("size", "")
)
void(
"buffer_init_fixed",
"",
nk_buffer_p.IN("buffer", ""),
void_p.IN("memory", ""),
AutoSize("memory")..nk_size.IN("size", "")
)
void(
"buffer_info",
"",
nk_memory_status.p.OUT("status", ""),
nk_buffer_p.IN("buffer", "")
)
void(
"buffer_push",
"",
nk_buffer_p.IN("buffer", ""),
nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes),
const..void_p.IN("memory", ""),
AutoSize("memory")..nk_size.IN("size", ""),
nk_size.IN("align", "")
)
void(
"buffer_mark",
"",
nk_buffer_p.IN("buffer", ""),
nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes)
)
void(
"buffer_reset",
"",
nk_buffer_p.IN("buffer", ""),
nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes)
)
void(
"buffer_clear",
"",
nk_buffer_p.IN("buffer", "")
)
void(
"buffer_free",
"",
nk_buffer_p.IN("buffer", "")
)
voidptr(
"buffer_memory",
"",
nk_buffer_p.IN("buffer", "")
)
(const..voidptr)(
"buffer_memory_const",
"",
const..nk_buffer_p.IN("buffer", "")
)
nk_size(
"buffer_total",
"",
nk_buffer_p.IN("buffer", "")
)
void(
"str_init",
"",
nk_str_p.IN("str", ""),
const..nk_allocator_p.IN("allocator", ""),
nk_size.IN("size", "")
)
void(
"str_init_fixed",
"",
nk_str_p.IN("str", ""),
void_p.IN("memory", ""),
AutoSize("memory")..nk_size.IN("size", "")
)
void(
"str_clear",
"",
nk_str_p.IN("str", "")
)
void(
"str_free",
"",
nk_str_p.IN("str", "")
)
int(
"str_append_text_char",
"",
nk_str_p.IN("s", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_append_str_char",
"",
nk_str_p.IN("s", ""),
NullTerminated..const..char_p.IN("str", "")
)
int(
"str_append_text_utf8",
"",
nk_str_p.IN("s", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_append_str_utf8",
"",
nk_str_p.IN("s", ""),
NullTerminated..const..char_p.IN("str", "")
)
int(
"str_append_text_runes",
"",
nk_str_p.IN("s", ""),
const..nk_rune_p.IN("runes", ""),
AutoSize("runes")..int.IN("len", "")
)
int(
"str_append_str_runes",
"",
nk_str_p.IN("s", ""),
NullTerminated..const..nk_rune_p.IN("runes", "")
)
int(
"str_insert_at_char",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_insert_at_rune",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_insert_text_char",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_insert_str_char",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
NullTerminated..const..char_p.IN("str", "")
)
int(
"str_insert_text_utf8",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..char_p.IN("str", ""),
AutoSize("str")..int.IN("len", "")
)
int(
"str_insert_str_utf8",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
NullTerminated..const..char_p.IN("str", "")
)
int(
"str_insert_text_runes",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..nk_rune_p.IN("runes", ""),
AutoSize("runes")..int.IN("len", "")
)
int(
"str_insert_str_runes",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
const..nk_rune_p.IN("runes", "")
)
void(
"str_remove_chars",
"",
nk_str_p.IN("s", ""),
int.IN("len", "")
)
void(
"str_remove_runes",
"",
nk_str_p.IN("str", ""),
int.IN("len", "")
)
void(
"str_delete_chars",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
int.IN("len", "")
)
void(
"str_delete_runes",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
int.IN("len", "")
)
charUTF8_p(
"str_at_char",
"",
nk_str_p.IN("s", ""),
int.IN("pos", "")
)
char_p(
"str_at_rune",
"",
nk_str_p.IN("s", ""),
int.IN("pos", ""),
Check(1)..nk_rune_p.OUT("unicode", ""),
AutoSizeResult..int_p.OUT("len", "")
)
nk_rune(
"str_rune_at",
"",
const..nk_str_p.IN("s", ""),
int.IN("pos", "")
)
(const..charUTF8_p)(
"str_at_char_const",
"",
const..nk_str_p.IN("s", ""),
int.IN("pos", "")
)
(const..char_p)(
"str_at_const",
"",
const..nk_str_p.IN("s", ""),
int.IN("pos", ""),
Check(1)..nk_rune_p.OUT("unicode", ""),
AutoSizeResult..int_p.OUT("len", "")
)
charUTF8_p(
"str_get",
"",
nk_str_p.IN("s", "")
)
(const..charUTF8_p)(
"str_get_const",
"",
const..nk_str_p.IN("s", "")
)
int(
"str_len",
"",
nk_str_p.IN("s", "")
)
int(
"str_len_char",
"",
nk_str_p.IN("s", "")
)
intb(
"filter_default",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_ascii",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_float",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_decimal",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_hex",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_oct",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
intb(
"filter_binary",
"",
const..nk_text_edit_p.IN("edit", ""),
nk_rune.IN("unicode", "")
)
void(
"textedit_init",
"",
nk_text_edit_p.IN("box", ""),
nk_allocator_p.IN("allocator", ""),
nk_size.IN("size", "")
)
void(
"textedit_init_fixed",
"",
nk_text_edit_p.IN("box", ""),
void_p.IN("memory", ""),
AutoSize("memory")..nk_size.IN("size", "")
)
void(
"textedit_free",
"",
nk_text_edit_p.IN("box", "")
)
void(
"textedit_text",
"",
nk_text_edit_p.IN("box", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("total_len", "")
)
void(
"textedit_delete",
"",
nk_text_edit_p.IN("box", ""),
int.IN("where", ""),
int.IN("len", "")
)
void(
"textedit_delete_selection",
"",
nk_text_edit_p.IN("box", "")
)
void(
"textedit_select_all",
"",
nk_text_edit_p.IN("box", "")
)
intb(
"textedit_cut",
"",
nk_text_edit_p.IN("box", "")
)
intb(
"textedit_paste",
"",
nk_text_edit_p.IN("box", ""),
const..charUTF8_p.IN("ctext", ""),
AutoSize("ctext")..int.IN("len", "")
)
void(
"textedit_undo",
"",
nk_text_edit_p.IN("box", "")
)
void(
"textedit_redo",
"",
nk_text_edit_p.IN("box", "")
)
}();
{
void(
"stroke_line",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("x0", ""),
float.IN("y0", ""),
float.IN("x1", ""),
float.IN("y1", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"stroke_curve",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("ax", ""),
float.IN("ay", ""),
float.IN("ctrl0x", ""),
float.IN("ctrl0y", ""),
float.IN("ctrl1x", ""),
float.IN("ctrl1y", ""),
float.IN("bx", ""),
float.IN("by", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"stroke_rect",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
float.IN("rounding", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"stroke_circle",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"stroke_arc",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("cx", ""),
float.IN("cy", ""),
float.IN("radius", ""),
float.IN("a_min", ""),
float.IN("a_max", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"stroke_triangle",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("x0", ""),
float.IN("y0", ""),
float.IN("x1", ""),
float.IN("y1", ""),
float.IN("x2", ""),
float.IN("y2", ""),
float.IN("line_thichness", ""),
nk_color.IN("color", "")
)
void(
"stroke_polyline",
"",
nk_command_buffer_p.IN("b", ""),
float_p.IN("points", ""),
AutoSize("points")..int.IN("point_count", ""),
float.IN("line_thickness", ""),
nk_color.IN("col", "")
)
void(
"stroke_polygon",
"",
nk_command_buffer_p.IN("b", ""),
float_p.IN("points", ""),
AutoSize("points")..int.IN("point_count", ""),
float.IN("line_thickness", ""),
nk_color.IN("color", "")
)
void(
"fill_rect",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
float.IN("rounding", ""),
nk_color.IN("color", "")
)
void(
"fill_rect_multi_color",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
nk_color.IN("left", ""),
nk_color.IN("top", ""),
nk_color.IN("right", ""),
nk_color.IN("bottom", "")
)
void(
"fill_circle",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
nk_color.IN("color", "")
)
void(
"fill_arc",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("cx", ""),
float.IN("cy", ""),
float.IN("radius", ""),
float.IN("a_min", ""),
float.IN("a_max", ""),
nk_color.IN("color", "")
)
void(
"fill_triangle",
"",
nk_command_buffer_p.IN("b", ""),
float.IN("x0", ""),
float.IN("y0", ""),
float.IN("x1", ""),
float.IN("y1", ""),
float.IN("x2", ""),
float.IN("y2", ""),
nk_color.IN("color", "")
)
void(
"fill_polygon",
"",
nk_command_buffer_p.IN("b", ""),
float_p.IN("points", ""),
AutoSize("points")..int.IN("point_count", ""),
nk_color.IN("color", "")
)
void(
"push_scissor",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", "")
)
void(
"draw_image",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
const..nk_image.p.IN("img", ""),
nk_color.IN("color", "")
)
void(
"draw_text",
"",
nk_command_buffer_p.IN("b", ""),
nk_rect.IN("rect", ""),
const..charUTF8_p.IN("string", ""),
AutoSize("string")..int.IN("length", ""),
const..nk_user_font_p.IN("font", ""),
nk_color.IN("bg", ""),
nk_color.IN("fg", "")
)
(const..nk_command.p)(
"_next",
"",
ctx,
const..nk_command.p.IN("cmd", "")
)
(const..nk_command.p)(
"_begin",
"",
ctx
)
intb(
"input_has_mouse_click",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons)
)
intb(
"input_has_mouse_click_in_rect",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons),
nk_rect.IN("rect", "")
)
intb(
"input_has_mouse_click_down_in_rect",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons),
nk_rect.IN("rect", ""),
int.IN("down", "")
)
intb(
"input_is_mouse_click_in_rect",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons),
nk_rect.IN("rect", "")
)
intb(
"input_is_mouse_click_down_in_rect",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons),
nk_rect.IN("b", ""),
int.IN("down", "")
)
intb(
"input_any_mouse_click_in_rect",
"",
const..nk_input_p.IN("i", ""),
nk_rect.IN("rect", "")
)
intb(
"input_is_mouse_prev_hovering_rect",
"",
const..nk_input_p.IN("i", ""),
nk_rect.IN("rect", "")
)
intb(
"input_is_mouse_hovering_rect",
"",
const..nk_input_p.IN("i", ""),
nk_rect.IN("rect", "")
)
intb(
"input_mouse_clicked",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons),
nk_rect.IN("rect", "")
)
intb(
"input_is_mouse_down",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons)
)
intb(
"input_is_mouse_pressed",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons)
)
intb(
"input_is_mouse_released",
"",
const..nk_input_p.IN("i", ""),
nk_buttons.IN("id", "", Buttons)
)
intb(
"input_is_key_pressed",
"",
const..nk_input_p.IN("i", ""),
nk_keys.IN("key", "", Keys)
)
intb(
"input_is_key_released",
"",
const..nk_input_p.IN("i", ""),
nk_keys.IN("key", "", Keys)
)
intb(
"input_is_key_down",
"",
const..nk_input_p.IN("i", ""),
nk_keys.IN("key", "", Keys)
)
}();
{
void(
"draw_list_init",
"",
nk_draw_list_p.IN("list", "")
)
void(
"draw_list_setup",
"",
nk_draw_list_p.IN("canvas", ""),
const..nk_convert_config.p.IN("config", ""),
nk_buffer_p.IN("cmds", ""),
nk_buffer_p.IN("vertices", ""),
nk_buffer_p.IN("elements", "")
)
void(
"draw_list_clear",
"",
nk_draw_list_p.IN("list", "")
)
(const..nk_draw_command_p)(
"_draw_list_begin",
"",
const..nk_draw_list_p.IN("list", ""),
const..nk_buffer_p.IN("buffer", "")
)
(const..nk_draw_command_p)(
"_draw_list_next",
"",
const..nk_draw_command_p.IN("cmd", ""),
const..nk_buffer_p.IN("buffer", ""),
const..nk_draw_list_p.IN("list", "")
)
(const..nk_draw_command_p)(
"_draw_begin",
"",
cctx,
const..nk_buffer_p.IN("buffer", "")
)
(const..nk_draw_command_p)(
"_draw_end",
"",
cctx,
const..nk_buffer_p.IN("buffer", "")
)
(const..nk_draw_command_p)(
"_draw_next",
"",
const..nk_draw_command_p.IN("cmd", ""),
const..nk_buffer_p.IN("buffer", ""),
cctx
)
void(
"draw_list_path_clear",
"",
nk_draw_list_p.IN("list", "")
)
void(
"draw_list_path_line_to",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("pos", "")
)
void(
"draw_list_path_arc_to_fast",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("center", ""),
float.IN("radius", ""),
int.IN("a_min", ""),
int.IN("a_max", "")
)
void(
"draw_list_path_arc_to",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("center", ""),
float.IN("radius", ""),
float.IN("a_min", ""),
float.IN("a_max", ""),
unsigned_int.IN("segments", "")
)
void(
"draw_list_path_rect_to",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("a", ""),
nk_vec2.IN("b", ""),
float.IN("rounding", "")
)
void(
"draw_list_path_curve_to",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("p2", ""),
nk_vec2.IN("p3", ""),
nk_vec2.IN("p4", ""),
unsigned_int.IN("num_segments", "")
)
void(
"draw_list_path_fill",
"",
nk_draw_list_p.IN("list", ""),
nk_color.IN("color", "")
)
void(
"draw_list_path_stroke",
"",
nk_draw_list_p.IN("list", ""),
nk_color.IN("color", ""),
nk_draw_list_stroke.IN("closed", "", DrawListStrokes),
float.IN("thickness", "")
)
void(
"draw_list_stroke_line",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("a", ""),
nk_vec2.IN("b", ""),
nk_color.IN("color", ""),
float.IN("thickness", "")
)
void(
"draw_list_stroke_rect",
"",
nk_draw_list_p.IN("list", ""),
nk_rect.IN("rect", ""),
nk_color.IN("color", ""),
float.IN("rounding", ""),
float.IN("thickness", "")
)
void(
"draw_list_stroke_triangle",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("a", ""),
nk_vec2.IN("b", ""),
nk_vec2.IN("c", ""),
nk_color.IN("color", ""),
float.IN("thickness", "")
)
void(
"draw_list_stroke_circle",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("center", ""),
float.IN("radius", ""),
nk_color.IN("color", ""),
unsigned_int.IN("segs", ""),
float.IN("thickness", "")
)
void(
"draw_list_stroke_curve",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("p0", ""),
nk_vec2.IN("cp0", ""),
nk_vec2.IN("cp1", ""),
nk_vec2.IN("p1", ""),
nk_color.IN("color", ""),
unsigned_int.IN("segments", ""),
float.IN("thickness", "")
)
void(
"draw_list_stroke_poly_line",
"",
nk_draw_list_p.IN("list", ""),
const..nk_vec2.p.IN("pnts", ""),
unsigned_int.IN("cnt", ""),
nk_color.IN("color", ""),
nk_draw_list_stroke.IN("closed", "", DrawListStrokes),
float.IN("thickness", ""),
nk_anti_aliasing.IN("aliasing", "", Antialiasing)
)
void(
"draw_list_fill_rect",
"",
nk_draw_list_p.IN("list", ""),
nk_rect.IN("rect", ""),
nk_color.IN("color", ""),
float.IN("rounding", "")
)
void(
"draw_list_fill_rect_multi_color",
"",
nk_draw_list_p.IN("list", ""),
nk_rect.IN("rect", ""),
nk_color.IN("left", ""),
nk_color.IN("top", ""),
nk_color.IN("right", ""),
nk_color.IN("bottom", "")
)
void(
"draw_list_fill_triangle",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("a", ""),
nk_vec2.IN("b", ""),
nk_vec2.IN("c", ""),
nk_color.IN("color", "")
)
void(
"draw_list_fill_circle",
"",
nk_draw_list_p.IN("list", ""),
nk_vec2.IN("center", ""),
float.IN("radius", ""),
nk_color.IN("col", ""),
unsigned_int.IN("segs", "")
)
void(
"draw_list_fill_poly_convex",
"",
nk_draw_list_p.IN("list", ""),
const..nk_vec2.p.IN("points", ""),
AutoSize("points")..unsigned_int.IN("count", ""),
nk_color.IN("color", ""),
nk_anti_aliasing.IN("aliasing", "", Antialiasing)
)
void(
"draw_list_add_image",
"",
nk_draw_list_p.IN("list", ""),
nk_image.IN("texture", ""),
nk_rect.IN("rect", ""),
nk_color.IN("color", "")
)
void(
"draw_list_add_text",
"",
nk_draw_list_p.IN("list", ""),
const..nk_user_font_p.IN("font", ""),
nk_rect.IN("rect", ""),
const..charUTF8_p.IN("text", ""),
AutoSize("text")..int.IN("len", ""),
float.IN("font_height", ""),
nk_color.IN("color", "")
)
void(
"draw_list_push_userdata",
"",
nk_draw_list_p.IN("list", ""),
nk_handle.IN("userdata", "")
)
nk_style_item(
"style_item_image",
"",
nk_image.IN("img", "")
)
nk_style_item(
"style_item_color",
"",
nk_color.IN("color", "")
)
nk_style_item(
"style_item_hide",
""
)
}();
} | bsd-3-clause | 9eb89f0cd3830caa47fbb1be2ef7bfeb | 16.318009 | 165 | 0.529794 | 2.572905 | false | false | false | false |
rosenpin/QuickDrawEverywhere | app/src/main/java/com/tomer/draw/windows/drawings/QuickDrawView.kt | 1 | 8555 | package com.tomer.draw.windows.drawings
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.support.v4.view.ViewCompat
import android.support.v7.widget.AppCompatImageView
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.FrameLayout
import com.byox.drawview.enums.BackgroundScale
import com.byox.drawview.enums.BackgroundType
import com.byox.drawview.enums.DrawingCapture
import com.byox.drawview.enums.DrawingMode
import com.byox.drawview.views.DrawView
import com.tomer.draw.R
import com.tomer.draw.gallery.MainActivity
import com.tomer.draw.utils.circularRevealHide
import com.tomer.draw.utils.circularRevealShow
import com.tomer.draw.utils.hasPermissions
import com.tomer.draw.utils.helpers.DisplaySize
import com.tomer.draw.windows.FloatingView
import com.tomer.draw.windows.OnWindowStateChangedListener
import com.tomer.draw.windows.WindowsManager
import kotlinx.android.synthetic.main.quick_draw_view.view.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/27/17.
*/
class QuickDrawView(context: Context) : FrameLayout(context), FloatingView {
override val listeners: ArrayList<OnWindowStateChangedListener> = ArrayList()
private val displaySize = DisplaySize(context)
override var currentX: Int = 0
override var currentY: Int = 0
private var fullScreen = false
var isAttached = false
var accessibleDrawView: DrawView? = null
var onDrawingFinished: OnDrawingFinished? = null
override fun removeFromWindow(x: Int, y: Int, onWindowRemoved: Runnable?, listener: OnWindowStateChangedListener?) {
if (isAttached) {
isAttached = false
this.circularRevealHide(cx = x + if (x == 0) 50 else -50, cy = y + 50, radius = Math.hypot(displaySize.getWidth().toDouble(), displaySize.getHeight().toDouble()).toFloat(), action = Runnable {
if (tapBarMenu != null)
tapBarMenu.close()
WindowsManager.getInstance(context).removeView(this)
onWindowRemoved?.run()
triggerListeners(false)
})
}
}
override fun addToWindow(x: Int, y: Int, onWindowAdded: Runnable?, listener: OnWindowStateChangedListener?) {
if (!isAttached) {
isAttached = true
this.circularRevealShow(x + if (x == 0) 50 else -50, y + 50, Math.hypot(displaySize.getWidth().toDouble(), displaySize.getHeight().toDouble()).toFloat())
WindowsManager.getInstance(context).addView(this)
Handler().postDelayed({
onWindowAdded?.run()
triggerListeners(true)
}, 100)
}
}
fun triggerListeners(added: Boolean) {
for (l in listeners) {
if (added)
l.onWindowAdded()
else if (!added)
l.onWindowRemoved()
}
}
override fun origHeight(): Int = (displaySize.getHeight() * (if (!fullScreen) 0.8f else 0.95f)).toInt()
override fun origWidth(): Int = WindowManager.LayoutParams.MATCH_PARENT
override fun gravity() = Gravity.CENTER
init {
val drawView = LayoutInflater.from(context).inflate(R.layout.quick_draw_view, this).draw_view
drawView.setBackgroundDrawColor(Color.WHITE)
drawView.backgroundColor = Color.WHITE
drawView.setDrawViewBackgroundColor(Color.WHITE)
drawView.drawWidth = 8
drawView.drawColor = Color.GRAY
cancel.setOnClickListener { drawView.restartDrawing(); onDrawingFinished?.OnDrawingClosed() }
minimize.setOnClickListener { onDrawingFinished?.OnDrawingClosed() }
undo.setOnClickListener { if (drawView.canUndo()) drawView.undo(); refreshRedoUndoButtons(drawView) }
redo.setOnClickListener { if (drawView.canRedo()) drawView.redo(); refreshRedoUndoButtons(drawView) }
maximize.setOnClickListener {
fullScreen = !fullScreen
removeFromWindow(x = displaySize.getWidth() / 2, onWindowRemoved = Runnable {
addToWindow(x = displaySize.getWidth() / 2)
})
}
save.setOnClickListener { save(drawView) }
eraser.setOnClickListener { v ->
drawView.drawingMode =
if (drawView.drawingMode == DrawingMode.DRAW) DrawingMode.ERASER
else DrawingMode.DRAW
drawView.drawWidth =
if (drawView.drawingMode == DrawingMode.DRAW) 8
else 28
(v as AppCompatImageView).setImageResource(
if (drawView.drawingMode == DrawingMode.DRAW) R.drawable.ic_erase
else R.drawable.ic_pencil)
}
gallery.setOnClickListener {
removeFromWindow(displaySize.getWidth() / 2, 0, Runnable { context.startActivity(Intent(context, MainActivity::class.java)) })
}
tapBarMenu.setOnClickListener({
tapBarMenu.toggle()
})
tapBarMenu.moveDownOnClose = false
refreshRedoUndoButtons(drawView)
drawView.setOnDrawViewListener(object : DrawView.OnDrawViewListener {
override fun onStartDrawing() {
refreshRedoUndoButtons(drawView)
}
override fun onEndDrawing() {
refreshRedoUndoButtons(drawView)
}
override fun onClearDrawing() {
refreshRedoUndoButtons(drawView)
}
override fun onRequestText() {
}
override fun onAllMovesPainted() {
}
})
ViewCompat.setElevation(toolbar, context.resources?.getDimension(R.dimen.qda_design_appbar_elevation) ?: 6f)
ViewCompat.setElevation(tapBarMenu, context.resources?.getDimension(R.dimen.standard_elevation) ?: 8f)
accessibleDrawView = drawView
}
private fun refreshRedoUndoButtons(drawView: DrawView) {
redo.alpha = if (drawView.canRedo()) 1f else 0.4f
undo.alpha = if (drawView.canUndo()) 1f else 0.4f
}
internal fun setImage(file: File) {
accessibleDrawView?.setBackgroundImage(file, BackgroundType.FILE, BackgroundScale.CENTER_INSIDE)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_VOLUME_UP || event
.keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return super.dispatchKeyEvent(event)
}
removeFromWindow()
return super.dispatchKeyEvent(event)
}
fun undo(v: DrawView) {
v.undo()
}
fun save(v: DrawView) {
val createCaptureResponse = v.createCapture(DrawingCapture.BITMAP)
if (!context.hasPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
context.startActivity(Intent(context, AskPermissionActivity::class.java))
return
}
saveFile(createCaptureResponse[0] as Bitmap)
}
fun saveFile(bitmap: Bitmap) {
paintBitmapToBlack(bitmap)
var fileName = Calendar.getInstance().timeInMillis.toString()
try {
fileName = "drawing-$fileName.jpg"
val imageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name))
imageDir.mkdirs()
val image = File(imageDir, fileName)
val result = image.createNewFile()
val fileOutputStream = FileOutputStream(image)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
onDrawingFinished?.onDrawingSaved()
showNotification(bitmap, image)
} catch (e: IOException) {
e.printStackTrace()
onDrawingFinished?.OnDrawingSaveFailed()
}
}
private fun paintBitmapToBlack(bitmap: Bitmap) {
val allpixels = IntArray(bitmap.height * bitmap.width)
bitmap.getPixels(allpixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
(0..allpixels.size - 1)
.filter { allpixels[it] == Color.TRANSPARENT }
.forEach { allpixels[it] = Color.WHITE }
bitmap.setPixels(allpixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
}
fun clear(v: DrawView) {
v.restartDrawing()
}
fun showNotification(drawing: Bitmap, file: File) {
val notificationManager = context
.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(Uri.fromFile(file), "image/*")
val pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_ONE_SHOT)
val notification = Notification.Builder(context)
.setContentTitle(context.resources.getString(R.string.drawing_drawing_saved))
.setContentText(context.resources.getString(R.string.drawing_view_drawing))
.setStyle(Notification.BigPictureStyle().bigPicture(drawing))
.setSmallIcon(R.drawable.ic_gallery_compat)
.setContentIntent(pendingIntent).build()
notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
notificationManager.notify(1689, notification)
}
}
| gpl-3.0 | 4d1e3e3dd4105b30fbc8482c5029db1f | 34.794979 | 195 | 0.757919 | 3.670099 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.