repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ekager/focus-android | app/src/main/java/org/mozilla/focus/fragment/AddToHomescreenDialogFragment.kt | 1 | 5052 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* 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.preference.PreferenceManager
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import org.mozilla.focus.R
import org.mozilla.focus.shortcut.HomeScreen
import org.mozilla.focus.shortcut.IconGenerator
import org.mozilla.focus.telemetry.TelemetryWrapper
/**
* Fragment displaying a dialog where a user can change the title for a homescreen shortcut
*/
class AddToHomescreenDialogFragment : DialogFragment() {
@Suppress("LongMethod")
override fun onCreateDialog(bundle: Bundle?): AlertDialog {
val url = arguments!!.getString(URL)
val title = arguments!!.getString(TITLE)
val blockingEnabled = arguments!!.getBoolean(BLOCKING_ENABLED)
val requestDesktop = arguments!!.getBoolean(REQUEST_DESKTOP)
val builder = AlertDialog.Builder(activity!!, R.style.DialogStyle)
builder.setCancelable(true)
builder.setTitle(requireActivity().getString(R.string.menu_add_to_home_screen))
val inflater = requireActivity().layoutInflater
val dialogView = inflater.inflate(R.layout.add_to_homescreen, null)
builder.setView(dialogView)
// For the dialog we display the Pre Oreo version of the icon because the Oreo+
// adaptive launcher icon does not have a mask applied until we create the shortcut
val iconBitmap = IconGenerator.generateLauncherIconPreOreo(
context!!,
IconGenerator.getRepresentativeCharacter(url)
)
val iconView = dialogView.findViewById<ImageView>(R.id.homescreen_icon)
iconView.setImageBitmap(iconBitmap)
val blockIcon = dialogView.findViewById<ImageView>(R.id.homescreen_dialog_block_icon)
blockIcon.setImageResource(R.drawable.ic_tracking_protection_disabled)
val addToHomescreenDialogCancelButton =
dialogView.findViewById<Button>(R.id.addtohomescreen_dialog_cancel)
val addToHomescreenDialogConfirmButton =
dialogView.findViewById<Button>(R.id.addtohomescreen_dialog_add)
val warning = dialogView.findViewById<LinearLayout>(R.id.homescreen_dialog_warning_layout)
warning.visibility = if (blockingEnabled) View.GONE else View.VISIBLE
val editableTitle = dialogView.findViewById<EditText>(R.id.edit_title)
if (!TextUtils.isEmpty(title)) {
editableTitle.setText(title)
editableTitle.setSelection(title!!.length)
}
addToHomescreenDialogCancelButton.setOnClickListener {
TelemetryWrapper.cancelAddToHomescreenShortcutEvent()
dismiss()
}
addToHomescreenDialogConfirmButton.setOnClickListener {
HomeScreen.installShortCut(
context,
IconGenerator.generateLauncherIcon(context!!, url),
url,
editableTitle.text.toString().trim { it <= ' ' },
blockingEnabled,
requestDesktop
)
TelemetryWrapper.addToHomescreenShortcutEvent()
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putBoolean(
context!!.getString(R.string.has_added_to_home_screen),
true
).apply()
dismiss()
}
return builder.create()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val dialog = dialog
if (dialog != null) {
val window = dialog.window
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
}
}
companion object {
val FRAGMENT_TAG = "add-to-homescreen-prompt-dialog"
private val URL = "url"
private val TITLE = "title"
private val BLOCKING_ENABLED = "blocking_enabled"
private val REQUEST_DESKTOP = "request_desktop"
fun newInstance(
url: String,
title: String,
blockingEnabled: Boolean,
requestDesktop: Boolean
): AddToHomescreenDialogFragment {
val frag = AddToHomescreenDialogFragment()
val args = Bundle()
args.putString(URL, url)
args.putString(TITLE, title)
args.putBoolean(BLOCKING_ENABLED, blockingEnabled)
args.putBoolean(REQUEST_DESKTOP, requestDesktop)
frag.arguments = args
return frag
}
}
}
| mpl-2.0 | 5722908c8628e92d0c0c9a51c15463bb | 38.46875 | 98 | 0.671219 | 4.862368 | false | false | false | false |
ursjoss/scipamato | common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/component/table/column/LinkIconPanel.kt | 2 | 2149 | /*
* Copyright 2015 Viliam Repan (lazyman)
*
* 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 ch.difty.scipamato.common.web.component.table.column
import org.apache.wicket.AttributeModifier
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.ajax.markup.html.AjaxLink
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.IModel
private const val ID_LINK = "link"
private const val ID_IMAGE = "image"
/**
* @author Viliam Repan (lazyman)
*/
abstract class LinkIconPanel protected constructor(
id: String,
iconModel: IModel<String>,
private val titleModel: IModel<String>?,
) : Panel(id, iconModel) {
override fun onInitialize() {
super.onInitialize()
add(makeLink())
}
private fun makeLink(): AjaxLink<Void> = object : AjaxLink<Void>(ID_LINK) {
override fun onClick(target: AjaxRequestTarget) {
onClickPerformed(target)
}
}.apply<AjaxLink<Void>> {
add(makeImage(ID_IMAGE))
outputMarkupId = true
}
protected abstract fun onClickPerformed(target: AjaxRequestTarget)
@Suppress("SameParameterValue")
private fun makeImage(id: String): Label = Label(id, "").apply {
add(AttributeModifier.replace("class", [email protected]))
titleModel?.let { add(AttributeModifier.replace("title", it)) }
}
@Suppress("UNCHECKED_CAST")
protected val link: AjaxLink<Void>
get() = get(ID_LINK) as AjaxLink<Void>
companion object {
private const val serialVersionUID = 1L
}
}
| bsd-3-clause | a47cf9a1a847c33e42bdaf57dc78b572 | 31.560606 | 80 | 0.706375 | 4.016822 | false | false | false | false |
mgolokhov/dodroid | app/src/main/java/doit/study/droid/topic/ui/TopicViewModel.kt | 1 | 1646 | package doit.study.droid.topic.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import doit.study.droid.topic.TopicItem
import doit.study.droid.topic.domain.GetTopicItemsUseCase
import doit.study.droid.topic.domain.SaveTopicItemsUseCase
import javax.inject.Inject
import kotlinx.coroutines.launch
import timber.log.Timber
class TopicViewModel @Inject constructor(
private val getTopicItemsUseCase: GetTopicItemsUseCase,
private val saveTopicItemsUseCase: SaveTopicItemsUseCase
) : ViewModel() {
private val _items = MutableLiveData<List<TopicItem>>().apply { value = emptyList() }
val items: LiveData<List<TopicItem>> = _items
init {
loadTopics()
}
fun loadTopics(
query: String = ""
) = viewModelScope.launch {
_items.value = getTopicItemsUseCase(query)
Timber.d("post values ${_items.value?.size}")
}
fun selectTopic(
topicItem: TopicItem,
selected: Boolean
) = viewModelScope.launch {
saveTopicItemsUseCase(topicItem, selected = selected)
loadTopics()
}
fun selectAllTopics() = allTopics(selected = true)
fun deselectAllTopics() = allTopics(selected = false)
private fun allTopics(
selected: Boolean
) = viewModelScope.launch {
_items.value?.let { topicView ->
val topics = topicView.map {
it.copy(selected = selected)
}
saveTopicItemsUseCase(*topics.toTypedArray(), selected = selected)
loadTopics()
}
}
}
| mit | 4b7db1e0b6d8b2beb8ca5fbad82a8e6e | 28.927273 | 89 | 0.68712 | 4.472826 | false | false | false | false |
lettuce-io/lettuce-core | src/main/kotlin/io/lettuce/core/api/coroutines/RedisSetCoroutinesCommandsImpl.kt | 1 | 4003 | /*
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.lettuce.core.api.coroutines
import io.lettuce.core.ExperimentalLettuceCoroutinesApi
import io.lettuce.core.ScanArgs
import io.lettuce.core.ScanCursor
import io.lettuce.core.ValueScanCursor
import io.lettuce.core.api.reactive.RedisSetReactiveCommands
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.toSet
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitFirstOrNull
/**
* Coroutine executed commands (based on reactive commands) for Sets.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mikhael Sokolov
* @since 6.0
*
* @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesReactiveImplementation
*/
@ExperimentalLettuceCoroutinesApi
internal class RedisSetCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisSetReactiveCommands<K, V>) : RedisSetCoroutinesCommands<K, V> {
override suspend fun sadd(key: K, vararg members: V): Long? = ops.sadd(key, *members).awaitFirstOrNull()
override suspend fun scard(key: K): Long? = ops.scard(key).awaitFirstOrNull()
override fun sdiff(vararg keys: K): Flow<V> = ops.sdiff(*keys).asFlow()
override suspend fun sdiffstore(destination: K, vararg keys: K): Long? = ops.sdiffstore(destination, *keys).awaitFirstOrNull()
override fun sinter(vararg keys: K): Flow<V> = ops.sinter(*keys).asFlow()
override suspend fun sintercard(vararg keys: K): Long? = ops.sintercard(*keys).awaitFirstOrNull()
override suspend fun sintercard(limit: Long, vararg keys: K): Long? =
ops.sintercard(limit, *keys).awaitFirstOrNull()
override suspend fun sinterstore(destination: K, vararg keys: K): Long? = ops.sinterstore(destination, *keys).awaitFirstOrNull()
override suspend fun sismember(key: K, member: V): Boolean? = ops.sismember(key, member).awaitFirstOrNull()
override fun smembers(key: K): Flow<V> = ops.smembers(key).asFlow()
override fun smismember(key: K, vararg members: V): Flow<Boolean> = ops.smismember(key, *members).asFlow()
override suspend fun smove(source: K, destination: K, member: V): Boolean? = ops.smove(source, destination, member).awaitFirstOrNull()
override suspend fun spop(key: K): V? = ops.spop(key).awaitFirstOrNull()
override suspend fun spop(key: K, count: Long): Set<V> = ops.spop(key, count).asFlow().toSet()
override suspend fun srandmember(key: K): V? = ops.srandmember(key).awaitFirstOrNull()
override fun srandmember(key: K, count: Long): Flow<V> = ops.srandmember(key, count).asFlow()
override suspend fun srem(key: K, vararg members: V): Long? = ops.srem(key, *members).awaitFirstOrNull()
override fun sunion(vararg keys: K): Flow<V> = ops.sunion(*keys).asFlow()
override suspend fun sunionstore(destination: K, vararg keys: K): Long? = ops.sunionstore(destination, *keys).awaitFirstOrNull()
override suspend fun sscan(key: K): ValueScanCursor<V>? = ops.sscan(key).awaitFirstOrNull()
override suspend fun sscan(key: K, scanArgs: ScanArgs): ValueScanCursor<V>? = ops.sscan(key, scanArgs).awaitFirstOrNull()
override suspend fun sscan(key: K, scanCursor: ScanCursor, scanArgs: ScanArgs): ValueScanCursor<V>? = ops.sscan(key, scanCursor, scanArgs).awaitFirstOrNull()
override suspend fun sscan(key: K, scanCursor: ScanCursor): ValueScanCursor<V>? = ops.sscan(key, scanCursor).awaitFirstOrNull()
}
| apache-2.0 | 11d9db09d4fbc0714ef17ff7128fdfe2 | 42.989011 | 161 | 0.738946 | 3.765757 | false | false | false | false |
genobis/tornadofx | src/main/java/tornadofx/Messages.kt | 1 | 2996 | package tornadofx
import java.io.IOException
import java.io.InputStream
import java.security.AccessController
import java.security.PrivilegedActionException
import java.security.PrivilegedExceptionAction
import java.util.*
private fun <EXCEPTION: Throwable, RETURN> doPrivileged(privilegedAction: ()->RETURN) : RETURN = try {
AccessController.doPrivileged(
PrivilegedExceptionAction<RETURN> { privilegedAction() }
)
} catch (e: PrivilegedActionException) {
@Suppress("UNCHECKED_CAST")
throw e.exception as EXCEPTION
}
object FXResourceBundleControl : ResourceBundle.Control() {
override fun newBundle(baseName: String, locale: Locale, format: String, loader: ClassLoader, reload: Boolean): ResourceBundle {
val bundleName = toBundleName(baseName, locale)
return when (format) {
"java.class" -> try {
@Suppress("UNCHECKED_CAST")
val bundleClass = loader.loadClass(bundleName) as Class<out ResourceBundle>
// If the class isn't a ResourceBundle subclass, throw a ClassCastException.
if (ResourceBundle::class.java.isAssignableFrom(bundleClass)) bundleClass.newInstance()
else throw ClassCastException(bundleClass.name + " cannot be cast to ResourceBundle")
} catch (e: ClassNotFoundException) {null}
"java.properties" -> {
val resourceName = toResourceName(bundleName, "properties")!!
doPrivileged<IOException, InputStream?> {
if (!reload) loader.getResourceAsStream(resourceName)
else loader.getResource(resourceName)?.openConnection()?.apply {
useCaches = false // Disable caches to get fresh data for reloading.
} ?.inputStream
}?.use { FXPropertyResourceBundle(it) }
}
else -> throw IllegalArgumentException("unknown format: $format")
}!!
}
}
/**
* Convenience function to support lookup via messages["key"]
*/
operator fun ResourceBundle.get(key: String) = getString(key)
class FXPropertyResourceBundle(input: InputStream): PropertyResourceBundle(input) {
fun inheritFromGlobal() {
parent = FX.messages
}
/**
* Lookup resource in this bundle. If no value, lookup in parent bundle if defined.
* If we still have no value, return "[key]" instead of null.
*/
override fun handleGetObject(key: String?) = super.handleGetObject(key)
?: parent?.getObject(key)
?: "[$key]"
/**
* Always return true, since we want to supply a default text message instead of throwing exception
*/
override fun containsKey(key: String) = true
}
internal object EmptyResourceBundle : ResourceBundle() {
override fun getKeys(): Enumeration<String> = Collections.emptyEnumeration()
override fun handleGetObject(key: String) = "[$key]"
override fun containsKey(p0: String) = true
}
| apache-2.0 | 2ef00d10b1ca2bfb00f98ba102f707e7 | 37.909091 | 132 | 0.664553 | 4.927632 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/ui/unifiedsearch/UnifiedSearchViewModel.kt | 1 | 9550 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.unifiedsearch
import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.net.Uri
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.network.ClientFactory
import com.nextcloud.client.network.ConnectivityService
import com.owncloud.android.R
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.SearchResult
import com.owncloud.android.lib.common.SearchResultEntry
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.asynctasks.GetRemoteFileTask
import javax.inject.Inject
@Suppress("LongParameterList")
class UnifiedSearchViewModel(application: Application) : AndroidViewModel(application), IUnifiedSearchViewModel {
companion object {
private const val TAG = "UnifiedSearchViewModel"
private const val DEFAULT_LIMIT = 5
private const val FILES_PROVIDER_ID = "files"
}
private data class UnifiedSearchMetadata(
var results: MutableList<SearchResult> = mutableListOf()
) {
fun nextCursor(): Int? = results.lastOrNull()?.cursor?.toInt()
fun name(): String? = results.lastOrNull()?.name
fun isFinished(): Boolean {
if (results.isEmpty()) {
return false
}
val lastResult = results.last()
return when {
!lastResult.isPaginated -> true
lastResult.entries.size < DEFAULT_LIMIT -> true
else -> false
}
}
}
private lateinit var currentAccountProvider: CurrentAccountProvider
private lateinit var runner: AsyncRunner
private lateinit var clientFactory: ClientFactory
private lateinit var resources: Resources
private lateinit var connectivityService: ConnectivityService
private val context: Context
get() = getApplication<Application>().applicationContext
private lateinit var repository: IUnifiedSearchRepository
private var loadingStarted: Boolean = false
private var results: MutableMap<ProviderID, UnifiedSearchMetadata> = mutableMapOf()
override val isLoading = MutableLiveData(false)
override val searchResults = MutableLiveData<List<UnifiedSearchSection>>(mutableListOf())
override val error = MutableLiveData("")
override val query = MutableLiveData<String>()
override val browserUri = MutableLiveData<Uri>()
override val file = MutableLiveData<OCFile>()
@Inject
constructor(
application: Application,
currentAccountProvider: CurrentAccountProvider,
runner: AsyncRunner,
clientFactory: ClientFactory,
resources: Resources,
connectivityService: ConnectivityService
) : this(application) {
this.currentAccountProvider = currentAccountProvider
this.runner = runner
this.clientFactory = clientFactory
this.resources = resources
this.connectivityService = connectivityService
repository = UnifiedSearchRemoteRepository(
clientFactory,
currentAccountProvider,
runner
)
}
open fun startLoading(query: String) {
if (!loadingStarted) {
loadingStarted = true
this.query.value = query
initialQuery()
}
}
/**
* Clears data and queries all available providers
*/
override fun initialQuery() {
doWithConnectivityCheck {
results = mutableMapOf()
searchResults.value = mutableListOf()
val queryTerm = query.value.orEmpty()
if (isLoading.value != true && queryTerm.isNotBlank()) {
isLoading.value = true
repository.queryAll(queryTerm, this::onSearchResult, this::onError, this::onSearchFinished)
}
}
}
override fun loadMore(provider: ProviderID) {
doWithConnectivityCheck {
val queryTerm = query.value.orEmpty()
if (isLoading.value != true && queryTerm.isNotBlank()) {
results[provider]?.nextCursor()?.let { cursor ->
isLoading.value = true
repository.queryProvider(
queryTerm,
provider,
cursor,
this::onSearchResult,
this::onError,
this::onSearchFinished
)
}
}
}
}
private fun doWithConnectivityCheck(block: () -> Unit) {
when (connectivityService.connectivity.isConnected) {
false -> {
error.value = resources.getString(R.string.offline_mode)
if (isLoading.value == true) {
isLoading.value = false
}
}
else -> block()
}
}
override fun openResult(result: SearchResultEntry) {
if (result.isFile) {
openFile(result.remotePath())
} else {
this.browserUri.value = getResultUri(result)
}
}
private fun getResultUri(result: SearchResultEntry): Uri {
val uri = Uri.parse(result.resourceUrl)
return when (uri.host) {
null -> {
val serverUrl = currentAccountProvider.user.server.uri.toString()
val fullUrl = serverUrl + result.resourceUrl
Uri.parse(fullUrl)
}
else -> uri
}
}
fun openFile(fileUrl: String) {
if (isLoading.value == false) {
isLoading.value = true
val user = currentAccountProvider.user
val task = GetRemoteFileTask(
context,
fileUrl,
clientFactory.create(currentAccountProvider.user),
FileDataStorageManager(user, context.contentResolver),
user
)
runner.postQuickTask(task, onResult = this::onFileRequestResult)
}
}
open fun clearError() {
error.value = ""
}
fun onError(error: Throwable) {
Log_OC.e(TAG, "Error: " + error.stackTrace)
}
@Synchronized
fun onSearchResult(result: UnifiedSearchResult) {
if (result.success) {
val providerMeta = results[result.provider] ?: UnifiedSearchMetadata()
providerMeta.results.add(result.result)
results[result.provider] = providerMeta
genSearchResultsFromMeta()
}
Log_OC.d(TAG, "onSearchResult: Provider '${result.provider}', success: ${result.success}")
if (result.success) {
Log_OC.d(TAG, "onSearchResult: Provider '${result.provider}', result count: ${result.result.entries.size}")
}
}
private fun genSearchResultsFromMeta() {
searchResults.value = results
.filter { it.value.results.isNotEmpty() }
.map { (key, value) ->
UnifiedSearchSection(
providerID = key,
name = value.name()!!,
entries = value.results.flatMap { it.entries },
hasMoreResults = !value.isFinished()
)
}
.sortedWith { o1, o2 ->
// TODO sort with sort order from server providers?
when {
o1.providerID == FILES_PROVIDER_ID -> -1
o2.providerID == FILES_PROVIDER_ID -> 1
else -> 0
}
}
}
private fun onSearchFinished(success: Boolean) {
Log_OC.d(TAG, "onSearchFinished: success: $success")
isLoading.value = false
if (!success) {
error.value = resources.getString(R.string.search_error)
}
}
@VisibleForTesting
fun setRepository(repository: IUnifiedSearchRepository) {
this.repository = repository
}
private fun onFileRequestResult(result: GetRemoteFileTask.Result) {
isLoading.value = false
if (result.success) {
file.value = result.file
} else {
error.value = "Error showing search result"
}
}
override fun setQuery(query: String) {
this.query.value = query
}
@VisibleForTesting
fun setConnectivityService(connectivityService: ConnectivityService) {
this.connectivityService = connectivityService
}
}
| gpl-2.0 | abe7832dbabdef848f48d38c00416e86 | 33.601449 | 119 | 0.620105 | 5.098772 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/indexes/RsImplIndex.kt | 1 | 2894 | package org.rust.lang.core.resolve.indexes
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.AbstractStubIndex
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.KeyDescriptor
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.stubs.RsFileStub
import org.rust.lang.core.stubs.RsImplItemStub
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.TyFingerprint
import org.rust.lang.core.types.type
class RsImplIndex : AbstractStubIndex<TyFingerprint, RsImplItem>() {
override fun getVersion(): Int = RsFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<TyFingerprint, RsImplItem> = KEY
override fun getKeyDescriptor(): KeyDescriptor<TyFingerprint> = TyFingerprint.KeyDescriptor
companion object {
fun findImpls(project: Project, target: Ty): Collection<RsImplItem> {
fun doFind(): Collection<RsImplItem> {
val fingerprint = TyFingerprint.create(target)
?: return emptyList()
return StubIndex.getElements(
KEY,
fingerprint,
project,
GlobalSearchScope.allScope(project),
RsImplItem::class.java
).filter { impl ->
val ty = impl.typeReference?.type
// Addition class check is a temporal solution to filter impls for type parameter
// with the same name
// struct S; impl<S: Tr1> Tr2 for S {}
ty != null && ty.javaClass == target.javaClass && ty.canUnifyWith(target, project)
}
}
val implsCache = CachedValuesManager.getManager(project)
.getCachedValue(project, {
CachedValueProvider.Result.create(
ContainerUtil.newConcurrentMap<Ty, Collection<RsImplItem>>(),
PsiModificationTracker.MODIFICATION_COUNT
)
})
return implsCache.getOrPut(target) { doFind() }
}
fun index(stub: RsImplItemStub, sink: IndexSink) {
val type = stub.psi.typeReference ?: return
val key = TyFingerprint.create(type)
if (key != null) {
sink.occurrence(KEY, key)
}
}
private val KEY: StubIndexKey<TyFingerprint, RsImplItem> =
StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RustImplIndex.TraitImpls")
}
}
| mit | 1dea06ec92c0bd5339448c266a33023a | 40.942029 | 102 | 0.639599 | 4.888514 | false | false | false | false |
genobis/tornadofx | src/main/java/tornadofx/InternalWindow.kt | 1 | 7208 | package tornadofx
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.canvas.Canvas
import javafx.scene.effect.DropShadow
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.layout.BorderPane
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import tornadofx.InternalWindow.Styles.Companion.crossPath
import java.awt.Toolkit
import java.net.URL
class InternalWindow(icon: Node?, modal: Boolean, escapeClosesWindow: Boolean, closeButton: Boolean, overlayPaint : Paint = c("#000", 0.4)) : StackPane() {
private lateinit var window: BorderPane
private lateinit var coverNode: Node
private lateinit var view: UIComponent
private var titleProperty = SimpleStringProperty()
var overlay: Canvas? = null
private var indexInCoverParent: Int? = null
private var coverParent: Parent? = null
private var offsetX = 0.0
private var offsetY = 0.0
init {
if (escapeClosesWindow) {
addEventFilter(KeyEvent.KEY_PRESSED) {
if (it.code == KeyCode.ESCAPE)
close()
}
}
addClass(Styles.floatingWindowWrapper)
if (modal) {
canvas {
overlay = this
graphicsContext2D.fill = overlayPaint
setOnMouseClicked {
Toolkit.getDefaultToolkit().beep()
}
widthProperty().bind([email protected]())
heightProperty().bind([email protected]())
widthProperty().onChange { fillOverlay() }
heightProperty().onChange { fillOverlay() }
}
}
borderpane {
addClass(Styles.window)
window = this
top {
hbox(5.0) {
addClass(Styles.top)
label(titleProperty) {
graphic = icon
isMouseTransparent = true
}
spacer {
isMouseTransparent = true
}
if (closeButton) {
button {
addClass(Styles.closebutton)
setOnMouseClicked {
close()
}
graphic = svgpath(crossPath)
}
}
}
}
}
moveWindowOnDrag()
window.center = stackpane {
addClass(Styles.floatingWindowContent)
}
}
class Styles : Stylesheet() {
companion object {
val floatingWindowWrapper by cssclass()
val floatingWindowContent by cssclass()
val window by cssclass()
val top by cssclass()
val closebutton by cssclass()
val crossPath = "M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"
}
init {
floatingWindowWrapper {
window {
effect = DropShadow()
}
top {
backgroundColor += Color.WHITE
padding = box(1.px, 1.px, 2.px, 5.px)
borderColor += box(Color.TRANSPARENT, Color.TRANSPARENT, Color.GRAY, Color.TRANSPARENT)
borderWidth += box(0.2.px)
alignment = Pos.CENTER
closebutton {
padding = box(4.px, 12.px)
backgroundRadius += box(0.px)
backgroundColor += Color.WHITE
and(hover) {
backgroundColor += Color.RED
star {
fill = Color.WHITE
}
}
}
}
floatingWindowContent {
backgroundColor += c(244, 244, 244)
padding = box(5.px)
}
}
}
}
override fun getUserAgentStylesheet() = URL("css://${Styles::class.java.name}").toExternalForm()!!
fun fillOverlay() {
overlay?.graphicsContext2D.apply {
val lb = coverNode.layoutBounds
this?.clearRect(0.0, 0.0, lb.width, lb.height)
this?.fillRect(0.0, 0.0, lb.width, lb.height)
}
}
fun open(view: UIComponent, owner: Node) {
if (owner.parent is InternalWindow) return
this.view = view
this.coverNode = owner
this.coverParent = owner.parent
this.titleProperty.bind(view.titleProperty)
coverNode.uiComponent<UIComponent>()?.muteDocking = true
if (coverParent != null) {
indexInCoverParent = coverParent!!.getChildList()!!.indexOf(owner)
owner.removeFromParent()
coverParent!!.getChildList()!!.add(indexInCoverParent!!, this)
} else {
val scene = owner.scene
scene.root = this
}
coverNode.uiComponent<UIComponent>()?.muteDocking = false
(window.center as Parent) += view
children.add(0, owner)
fillOverlay()
view.callOnDock()
}
fun close() {
coverNode.uiComponent<UIComponent>()?.muteDocking = true
coverNode.removeFromParent()
removeFromParent()
if (indexInCoverParent != null) {
coverParent!!.getChildList()!!.add(indexInCoverParent!!, coverNode)
} else {
scene?.root = coverNode as Parent?
}
coverNode.uiComponent<UIComponent>()?.muteDocking = false
view.callOnUndock()
}
override fun layoutChildren() {
val lb = coverNode.layoutBounds
val prefHeight = window.prefHeight(lb.width)
val prefWidth = window.prefWidth(lb.height)
val x = (lb.width - prefWidth) / 2
val y = (lb.height - prefHeight) / 2
coverNode.resizeRelocate(0.0, 0.0, lb.width, lb.height)
if (offsetX != 0.0 || offsetY != 0.0) {
val windowX = x + offsetX
val windowY = y + offsetY
window.resizeRelocate(windowX, windowY, window.width, window.height)
} else {
val windowWidth = Math.min(prefWidth, lb.width)
val windowHeight = Math.min(prefHeight, lb.height)
window.resizeRelocate(Math.max(0.0, x), Math.max(0.0, y), windowWidth, windowHeight)
}
}
private fun moveWindowOnDrag() {
var x = 0.0
var y = 0.0
window.top.setOnMousePressed { mouseEvent ->
x = mouseEvent.x
y = mouseEvent.y
}
window.top.setOnMouseDragged { mouseEvent ->
offsetX += mouseEvent.x - x
offsetY += mouseEvent.y - y
window.top.layoutX += mouseEvent.x - x
window.top.layoutY += mouseEvent.y - y
}
}
}
| apache-2.0 | e29422554968b444fde607fe493d3ae7 | 31.468468 | 155 | 0.528996 | 4.903401 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/Line.kt | 1 | 1346 | package com.soywiz.korge.view
import com.soywiz.korge.render.*
import com.soywiz.korim.color.*
import com.soywiz.korma.geom.*
inline fun Container.line(a: Point, b: Point, color: RGBA = Colors.WHITE, callback: @ViewDslMarker Line.() -> Unit = {})
= Line(a.x, a.y, b.x, b.y, color).addTo(this, callback)
inline fun Container.line(x0: Double, y0: Double, x1: Double, y1: Double, color: RGBA = Colors.WHITE, callback: @ViewDslMarker Line.() -> Unit = {})
= Line(x0, y0, x1, y1, color).addTo(this, callback)
class Line(
x1: Double,
y1: Double,
var x2: Double,
var y2: Double,
color: RGBA = Colors.WHITE,
) : View() {
var x1: Double get() = x ; set(value) { x = value }
var y1: Double get() = y ; set(value) { y = value }
init {
x = x1
y = y1
colorMul = color
}
fun setPoints(a: Point, b: Point) = setPoints(a.x, a.y, b.x, b.y)
fun setPoints(x1: Double, y1: Double, x2: Double, y2: Double) {
this.x1 = x1
this.y1 = y1
this.x2 = x2
this.y2 = y2
}
override fun renderInternal(ctx: RenderContext) {
ctx.useLineBatcher { lines ->
lines.drawWithGlobalMatrix(globalMatrix) {
val col = renderColorMul
lines.line(0.0, 0.0, x2 - x1, y2 - y1, col, col)
}
}
}
}
| apache-2.0 | 07c546af0e1a110b6f531f55ff34f459 | 28.26087 | 148 | 0.572065 | 3.038375 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/StringHelper.kt | 1 | 4202 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver
import java.text.SimpleDateFormat
import java.util.*
/**
* Useful string utilites.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object StringHelper {
private val DIGITS: CharArray = "0123456789abcdef".toCharArray()
private val UTC: TimeZone = TimeZone.getTimeZone("UTC")
fun toHex(data: ByteArray): String {
val result: StringBuilder = StringBuilder()
for (i: Byte in data) {
result.append(DIGITS[i.toInt() shr 4 and 0x0F])
result.append(DIGITS[i.toInt() and 0x0F])
}
return result.toString()
}
fun formatDate(time: Long): String {
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
df.timeZone = UTC
return df.format(Date(time))
}
fun joinPath(path: String, localPath: String?): String {
if (localPath == null || localPath.isEmpty()) {
return normalize(path)
}
if (localPath.startsWith("/")) {
return normalize(localPath)
}
return normalize(path + (if (path.endsWith("/")) "" else "/") + localPath)
}
fun normalize(path: String): String {
if (path.isEmpty()) return ""
var result: String = path
if (result[0] != '/') {
result = "/$result"
} else if (result.length == 1) {
return ""
}
return if (result.endsWith("/")) result.substring(0, result.length - 1) else result
}
fun normalizeDir(path: String): String {
if (path.isEmpty()) return "/"
var result: String = path
if (result[0] != '/') {
result = "/$result"
} else if (result.length == 1) {
return "/"
}
return if (result.endsWith("/")) result else "$result/"
}
fun parentDir(fullPath: String): String {
val index: Int = fullPath.lastIndexOf('/')
return if (index >= 0) fullPath.substring(0, index) else ""
}
fun baseName(fullPath: String): String {
return fullPath.substring(fullPath.lastIndexOf('/') + 1)
}
/**
* Returns true, if parentPath is base path of childPath.
*
* @param parentPath Parent path.
* @param childPath Child path.
* @return Returns true, if parentPath is base path of childPath.
*/
fun isParentPath(parentPath: String, childPath: String): Boolean {
if (!childPath.startsWith(parentPath)) return false
val parentLength: Int = parentPath.length
if (childPath.length == parentLength) return true
if (childPath[parentLength] == '/') return true
return parentLength > 0 && childPath[parentLength - 1] == '/'
}
/**
* Get childPath from parentPath or null.
*
* @param parentPath Parent path.
* @param fullChildPath Full child path.
* @return Returns child path related parent path or null.
*/
fun getChildPath(parentPath: String, fullChildPath: String): String? {
if (parentPath.isEmpty()) {
if (fullChildPath.length > 1 && fullChildPath[1] == '/') {
return fullChildPath.substring(1)
}
return fullChildPath
}
if (fullChildPath.startsWith(parentPath)) {
val parentLength: Int = parentPath.length
if (fullChildPath.length == parentLength) return ""
if (fullChildPath[parentLength] == '/') return fullChildPath.substring(parentLength + 1)
if (fullChildPath[parentLength - 1] == '/') return fullChildPath.substring(parentLength)
}
return null
}
fun getFirstLine(message: String?): String? {
if (message == null) return null
val eol: Int = message.indexOf('\n')
return if (eol >= 0) message.substring(0, eol) else message
}
}
| gpl-2.0 | ab7ff2a0e87ebd1a1d1fe2a01d77c3ff | 34.016667 | 100 | 0.599476 | 4.300921 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/compiler/QueriesTypeGenerator.kt | 1 | 3023 | package app.cash.sqldelight.core.compiler
import app.cash.sqldelight.core.compiler.model.NamedExecute
import app.cash.sqldelight.core.compiler.model.NamedMutator
import app.cash.sqldelight.core.lang.DRIVER_NAME
import app.cash.sqldelight.core.lang.DRIVER_TYPE
import app.cash.sqldelight.core.lang.SUSPENDING_TRANSACTER_IMPL_TYPE
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.core.lang.TRANSACTER_IMPL_TYPE
import app.cash.sqldelight.core.lang.queriesType
import app.cash.sqldelight.dialect.api.SqlDelightDialect
import com.intellij.openapi.module.Module
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.TypeSpec
class QueriesTypeGenerator(
private val module: Module,
private val file: SqlDelightQueriesFile,
private val dialect: SqlDelightDialect,
) {
private val generateAsync = file.generateAsync
/**
* Generate the full queries object - done once per file, containing all labeled select and
* mutator queries.
*
* eg: class DataQueries(
* private val queryWrapper: QueryWrapper,
* private val driver: SqlDriver,
* transactions: ThreadLocal<Transacter.Transaction>
* ) : TransacterImpl(driver, transactions)
*/
fun generateType(packageName: String): TypeSpec? {
if (file.isEmpty()) {
return null
}
val type = TypeSpec.classBuilder(file.queriesType.simpleName)
.superclass(if (generateAsync) SUSPENDING_TRANSACTER_IMPL_TYPE else TRANSACTER_IMPL_TYPE)
val constructor = FunSpec.constructorBuilder()
// Add the driver as a constructor parameter:
constructor.addParameter(DRIVER_NAME, DRIVER_TYPE)
type.addSuperclassConstructorParameter(DRIVER_NAME)
// Add any required adapters.
// private val tableAdapter: Table.Adapter
file.requiredAdapters.forEach {
type.addProperty(it)
constructor.addParameter(it.name, it.type)
}
file.namedQueries.forEach { query ->
tryWithElement(query.select) {
val generator = SelectQueryGenerator(query)
type.addFunction(generator.customResultTypeFunction())
if (query.needsWrapper()) {
type.addFunction(generator.defaultResultTypeFunction())
}
if (query.arguments.isNotEmpty()) {
type.addType(generator.querySubtype())
}
}
}
file.namedMutators.forEach { mutator ->
type.addExecute(mutator)
}
file.namedExecutes.forEach { execute ->
type.addExecute(execute)
}
return type.primaryConstructor(constructor.build())
.build()
}
private fun TypeSpec.Builder.addExecute(execute: NamedExecute) {
tryWithElement(execute.statement) {
val generator = if (execute is NamedMutator) {
MutatorQueryGenerator(execute)
} else {
ExecuteQueryGenerator(execute)
}
addFunction(generator.function())
}
}
}
internal fun SqlDelightQueriesFile.isEmpty() = namedQueries.isEmpty() && namedMutators.isEmpty() && namedExecutes.isEmpty()
| apache-2.0 | c242e5379f73468db53c04b3440174e1 | 30.821053 | 123 | 0.722792 | 4.269774 | false | false | false | false |
matejdro/WearMusicCenter | common/src/main/java/com/matejdro/wearmusiccenter/common/CommPaths.kt | 1 | 1939 | package com.matejdro.wearmusiccenter.common
interface CommPaths {
companion object {
const val PHONE_APP_CAPABILITY = "MusicCenterPhone"
const val WATCH_APP_CAPABILITY = "MusicCenterWatch"
const val DATA_MUSIC_STATE = "/Music/State"
const val DATA_WATCH_INFO = "/WatchInfo"
const val ASSET_WATCH_INFO_BUTTON_PREFIX = "/WatchInfo/Button"
const val DATA_NOTIFICATION = "/Notification"
const val ASSET_NOTIFICATION_BACKGROUND = "/Notification/Background"
const val MESSAGES_PREFIX = "wear://*/Messages/"
const val MESSAGE_WATCH_OPENED = "/Messages/WatchOpened"
const val MESSAGE_WATCH_CLOSED = "/Messages/WatchClosed"
const val MESSAGE_WATCH_CLOSED_MANUALLY = "/Messages/WatchClosedManually"
const val MESSAGE_ACK = "/Messages/ACK"
const val MESSAGE_CHANGE_VOLUME = "/Messages/SetVolume"
const val MESSAGE_EXECUTE_ACTION = "/Messages/Action"
const val MESSAGE_EXECUTE_MENU_ACTION = "/Messages/MenuAction"
const val MESSAGE_SEND_LOGS = "/SendLogs"
const val MESSAGE_OPEN_APP = "/IdleMessages/OpenApp"
const val MESSAGE_START_SERVICE = "/IdleMessages/StartService"
const val MESSAGE_CUSTOM_LIST_ITEM_SELECTED = "/Messages/CustomListItemSelected"
const val MESSAGE_OPEN_PLAYBACK_QUEUE = "/Messages/OpenPlaybackQueue"
const val CHANNEL_LOGS = "/Channel/Logs"
const val ASSET_ALBUM_ART = "AlbumArt"
const val DATA_ACTION_CONFIG_PREFIX = "/Actions"
const val DATA_LIST_ITEMS = "/ActionList"
const val DATA_PLAYING_ACTION_CONFIG = DATA_ACTION_CONFIG_PREFIX + "/Playback"
const val DATA_STOPPING_ACTION_CONFIG = DATA_ACTION_CONFIG_PREFIX + "/Stopped"
const val ASSET_BUTTON_ICON_PREFIX = "/Button_Icon_"
const val DATA_CUSTOM_LIST = "/CustomList/List"
const val PREFERENCES_PREFIX = "/Settings"
}
}
| gpl-3.0 | b9782f700250f370a428715129cee053 | 42.088889 | 88 | 0.677669 | 4.261538 | false | true | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/screens/ScreenStackFragment.kt | 2 | 10449 | package versioned.host.exp.exponent.modules.api.screens
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.Transformation
import android.widget.LinearLayout
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.uimanager.PixelUtil
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior
class ScreenStackFragment : ScreenFragment {
private var mAppBarLayout: AppBarLayout? = null
private var mToolbar: Toolbar? = null
private var mShadowHidden = false
private var mIsTranslucent = false
var searchView: CustomSearchView? = null
var onSearchViewCreate: ((searchView: CustomSearchView) -> Unit)? = null
@SuppressLint("ValidFragment")
constructor(screenView: Screen) : super(screenView)
constructor() {
throw IllegalStateException(
"ScreenStack fragments should never be restored. Follow instructions from https://github.com/software-mansion/react-native-screens/issues/17#issuecomment-424704067 to properly configure your main activity."
)
}
fun removeToolbar() {
mAppBarLayout?.let {
mToolbar?.let { toolbar ->
if (toolbar.parent === it) {
it.removeView(toolbar)
}
}
}
mToolbar = null
}
fun setToolbar(toolbar: Toolbar) {
mAppBarLayout?.addView(toolbar)
val params = AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT
)
params.scrollFlags = 0
toolbar.layoutParams = params
mToolbar = toolbar
}
fun setToolbarShadowHidden(hidden: Boolean) {
if (mShadowHidden != hidden) {
mAppBarLayout?.targetElevation = if (hidden) 0f else PixelUtil.toPixelFromDIP(4f)
mShadowHidden = hidden
}
}
fun setToolbarTranslucent(translucent: Boolean) {
if (mIsTranslucent != translucent) {
val params = screen.layoutParams
(params as CoordinatorLayout.LayoutParams).behavior =
if (translucent) null else ScrollingViewBehavior()
mIsTranslucent = translucent
}
}
override fun onContainerUpdate() {
val headerConfig = screen.headerConfig
headerConfig?.onUpdate()
}
override fun onViewAnimationEnd() {
super.onViewAnimationEnd()
notifyViewAppearTransitionEnd()
}
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
// this means that the fragment will appear with a custom transition, in the case
// of animation: 'none', onViewAnimationStart and onViewAnimationEnd
// won't be called and we need to notify stack directly from here.
// When using the Toolbar back button this is called an extra time with transit = 0 but in
// this case we don't want to notify. The way I found to detect is case is check isHidden.
if (transit == 0 && !isHidden &&
screen.stackAnimation === Screen.StackAnimation.NONE
) {
if (enter) {
// Android dispatches the animation start event for the fragment that is being added first
// however we want the one being dismissed first to match iOS. It also makes more sense
// from a navigation point of view to have the disappear event first.
// Since there are no explicit relationships between the fragment being added / removed
// the practical way to fix this is delaying dispatching the appear events at the end of
// the frame.
UiThreadUtil.runOnUiThread {
dispatchOnWillAppear()
dispatchOnAppear()
}
} else {
dispatchOnWillDisappear()
dispatchOnDisappear()
notifyViewAppearTransitionEnd()
}
}
return null
}
private fun notifyViewAppearTransitionEnd() {
val screenStack = view?.parent
if (screenStack is ScreenStack) {
screenStack.onViewAppearTransitionEnd()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: ScreensCoordinatorLayout? =
context?.let { ScreensCoordinatorLayout(it, this) }
val params = CoordinatorLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT
)
params.behavior = if (mIsTranslucent) null else ScrollingViewBehavior()
screen.layoutParams = params
view?.addView(recycleView(screen))
mAppBarLayout = context?.let { AppBarLayout(it) }
// By default AppBarLayout will have a background color set but since we cover the whole layout
// with toolbar (that can be semi-transparent) the bar layout background color does not pay a
// role. On top of that it breaks screens animations when alfa offscreen compositing is off
// (which is the default)
mAppBarLayout?.setBackgroundColor(Color.TRANSPARENT)
mAppBarLayout?.layoutParams = AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT
)
view?.addView(mAppBarLayout)
if (mShadowHidden) {
mAppBarLayout?.targetElevation = 0f
}
mToolbar?.let { mAppBarLayout?.addView(recycleView(it)) }
setHasOptionsMenu(true)
return view
}
override fun onPrepareOptionsMenu(menu: Menu) {
updateToolbarMenu(menu)
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
updateToolbarMenu(menu)
return super.onCreateOptionsMenu(menu, inflater)
}
private fun shouldShowSearchBar(): Boolean {
val config = screen.headerConfig
val numberOfSubViews = config?.configSubviewsCount ?: 0
if (config != null && numberOfSubViews > 0) {
for (i in 0 until numberOfSubViews) {
val subView = config.getConfigSubview(i)
if (subView.type == ScreenStackHeaderSubview.Type.SEARCH_BAR) {
return true
}
}
}
return false
}
private fun updateToolbarMenu(menu: Menu) {
menu.clear()
if (shouldShowSearchBar()) {
val currentContext = context
if (searchView == null && currentContext != null) {
val newSearchView = CustomSearchView(currentContext, this)
searchView = newSearchView
onSearchViewCreate?.invoke(newSearchView)
}
val item = menu.add("")
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
item.actionView = searchView
}
}
fun canNavigateBack(): Boolean {
val container: ScreenContainer<*>? = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
return if (container.rootScreen == screen) {
// this screen is the root of the container, if it is nested we can check parent container
// if it is also a root or not
val parentFragment = parentFragment
if (parentFragment is ScreenStackFragment) {
parentFragment.canNavigateBack()
} else {
false
}
} else {
true
}
}
fun dismiss() {
val container: ScreenContainer<*>? = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
container.dismiss(this)
}
private class ScreensCoordinatorLayout(
context: Context,
private val mFragment: ScreenFragment
) : CoordinatorLayout(context) {
private val mAnimationListener: Animation.AnimationListener =
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
mFragment.onViewAnimationStart()
}
override fun onAnimationEnd(animation: Animation) {
mFragment.onViewAnimationEnd()
}
override fun onAnimationRepeat(animation: Animation) {}
}
override fun startAnimation(animation: Animation) {
// For some reason View##onAnimationEnd doesn't get called for
// exit transitions so we explicitly attach animation listener.
// We also have some animations that are an AnimationSet, so we don't wrap them
// in another set since it causes some visual glitches when going forward.
// We also set the listener only when going forward, since when going back,
// there is already a listener for dismiss action added, which would be overridden
// and also this is not necessary when going back since the lifecycle methods
// are correctly dispatched then.
// We also add fakeAnimation to the set of animations, which sends the progress of animation
val fakeAnimation = ScreensAnimation(mFragment)
fakeAnimation.duration = animation.duration
if (animation is AnimationSet && !mFragment.isRemoving) {
animation.addAnimation(fakeAnimation)
animation.setAnimationListener(mAnimationListener)
super.startAnimation(animation)
} else {
val set = AnimationSet(true)
set.addAnimation(animation)
set.addAnimation(fakeAnimation)
set.setAnimationListener(mAnimationListener)
super.startAnimation(set)
}
}
/**
* This method implements a workaround for RN's autoFocus functionality. Because of the way
* autoFocus is implemented it dismisses soft keyboard in fragment transition
* due to change of visibility of the view at the start of the transition. Here we override the
* call to `clearFocus` when the visibility of view is `INVISIBLE` since `clearFocus` triggers the
* hiding of the keyboard in `ReactEditText.java`.
*/
override fun clearFocus() {
if (visibility != INVISIBLE) {
super.clearFocus()
}
}
}
private class ScreensAnimation(private val mFragment: ScreenFragment) : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
super.applyTransformation(interpolatedTime, t)
// interpolated time should be the progress of the current transition
mFragment.dispatchTransitionProgress(interpolatedTime, !mFragment.isResumed)
}
}
}
| bsd-3-clause | 55451d28b2ddf183b3d078ab06d058ae | 36.053191 | 212 | 0.712317 | 4.848724 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/viewmodel/MainViewModel.kt | 1 | 9360 | package com.thanksmister.iot.mqtt.alarmpanel.viewmodel
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import android.graphics.Bitmap
import android.support.v7.app.AppCompatDelegate
import android.text.TextUtils
import android.widget.Toast
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkStatus
import androidx.work.Worker
import com.thanksmister.iot.mqtt.alarmpanel.BaseActivity
import com.thanksmister.iot.mqtt.alarmpanel.BaseApplication
import com.thanksmister.iot.mqtt.alarmpanel.R
import com.thanksmister.iot.mqtt.alarmpanel.network.MQTTOptions
import com.thanksmister.iot.mqtt.alarmpanel.persistence.Message
import com.thanksmister.iot.mqtt.alarmpanel.persistence.MessageDao
import com.thanksmister.iot.mqtt.alarmpanel.ui.Configuration
import com.thanksmister.iot.mqtt.alarmpanel.ui.modules.MailGunModule
import com.thanksmister.iot.mqtt.alarmpanel.ui.modules.TelegramModule
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.ALARM_STATE_TOPIC
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.ALARM_TYPE
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_AWAY
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_AWAY_PENDING
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_HOME
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_HOME_PENDING
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_AWAY_TRIGGERED_PENDING
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_HOME_TRIGGERED_PENDING
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_TRIGGERED
import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_TRIGGERED_PENDING
import com.thanksmister.iot.mqtt.alarmpanel.utils.ComponentUtils.IMAGE_CAPTURE_TYPE
import com.thanksmister.iot.mqtt.alarmpanel.utils.ComponentUtils.NOTIFICATION_TYPE
import com.thanksmister.iot.mqtt.alarmpanel.utils.DateUtils
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MainViewModel @Inject
constructor(application: Application, private val dataSource: MessageDao, private val configuration: Configuration,
private val mqttOptions: MQTTOptions) : AndroidViewModel(application) {
private val workManager = WorkManager.getInstance();
private val disposable = CompositeDisposable()
private val isNight = MutableLiveData<Boolean>()
@AlarmUtils.AlarmStates
private fun setAlarmModeFromState(state: String) {
if(state == AlarmUtils.STATE_PENDING) {
if (getAlarmMode().equals(MODE_ARM_HOME) || getAlarmMode().equals(MODE_ARM_AWAY)) {
if (getAlarmMode().equals(MODE_ARM_HOME)){
setAlarmMode(MODE_HOME_TRIGGERED_PENDING);
} else if(getAlarmMode().equals(MODE_ARM_AWAY)) {
setAlarmMode(MODE_AWAY_TRIGGERED_PENDING);
} else {
setAlarmMode(MODE_TRIGGERED_PENDING);
}
}
} else if (state == AlarmUtils.STATE_TRIGGERED) {
setAlarmMode(MODE_TRIGGERED)
}
}
fun getIsNight(): LiveData<Boolean> {
return isNight
}
fun setIsNight(night: Boolean) {
this.isNight.value = night
}
fun hasPlatform() : Boolean {
return (configuration.hasPlatformModule() && !TextUtils.isEmpty(configuration.webUrl))
}
fun hasCamera() : Boolean {
return (configuration.hasCamera() && (configuration.hasMailGunCredentials() || configuration.hasTelegramCredentials()))
}
fun hasTss() : Boolean {
return configuration.hasTssModule()
}
fun hasAlerts() : Boolean {
return configuration.hasAlertsModule()
}
fun getAlarmMode(): String {
return configuration.alarmMode
}
private fun setAlarmMode(value: String) {
configuration.alarmMode = value
}
fun getAlarmState():Flowable<String> {
return dataSource.getMessages(ALARM_TYPE)
.filter {messages -> messages.isNotEmpty()}
.map {messages -> messages[messages.size - 1]}
.map {message ->
Timber.d("state: " + message.payload)
setAlarmModeFromState(message.payload!!)
message.payload
}
}
init {
}
/**
* Insert new message into the database.
*/
fun insertMessage(messageId: String, topic: String, payload: String) {
val type = when (topic) {
mqttOptions.getCameraTopic() -> IMAGE_CAPTURE_TYPE
mqttOptions.getNotificationTopic() -> NOTIFICATION_TYPE
else -> ALARM_TYPE
}
disposable.add(Completable.fromAction {
val createdAt = DateUtils.generateCreatedAtDate()
val message = Message()
message.type = type
message.topic = topic
message.payload = payload
message.messageId = messageId
message.createdAt = createdAt
dataSource.insertMessage(message)
} .subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
}, { error -> Timber.e("Database error" + error.message) }))
}
fun sendCapturedImage(bitmap: Bitmap) {
if(configuration.hasMailGunCredentials()) {
emailImage(bitmap)
}
if(configuration.hasTelegramCredentials()) {
sendTelegram(bitmap)
}
}
private fun sendTelegram(bitmap: Bitmap) {
val token = configuration.telegramToken
val chatId = configuration.telegramChatId
val observable = Observable.create { emitter: ObservableEmitter<Any> ->
val module = TelegramModule(getApplication())
module.emailImage(token, chatId, bitmap, object : TelegramModule.CallbackListener {
override fun onComplete() {
emitter.onNext(true) // Pass on the data to subscriber
}
override fun onException(message: String?) {
emitter.onError(Throwable(message))
}
})
}
disposable.add(observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { Timber.d("Telegram Message posted successfully!"); }
.doOnError({ throwable -> Timber.e("Telegram Message error: " + throwable.message); })
.subscribe( ))
}
private fun emailImage(bitmap: Bitmap) {
val domain = configuration.getMailGunUrl()
val key = configuration.getMailGunApiKey()
val from = configuration.getMailFrom()
val to = configuration.getMailTo()
val observable = Observable.create { emitter: ObservableEmitter<Any> ->
val mailGunModule = MailGunModule(getApplication())
val fromSubject = getApplication<Application>().getString(R.string.text_camera_image_subject, "<$from>")
mailGunModule.emailImage(domain!!, key!!, fromSubject, to!!, bitmap, object : MailGunModule.CallbackListener {
override fun onComplete() {
emitter.onNext(true) // Pass on the data to subscriber
}
override fun onException(message: String?) {
emitter.onError(Throwable(message))
}
})
}
disposable.add(observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { Timber.d("Image posted successfully!"); }
.doOnError({ throwable -> Timber.e("Image error: " + throwable.message); })
.onErrorReturn { Toast.makeText(getApplication<Application>(), R.string.error_mailgun_credentials, Toast.LENGTH_LONG).show() }
.subscribe( ))
}
public override fun onCleared() {
//prevents memory leaks by disposing pending observable objects
if (!disposable.isDisposed) {
disposable.clear()
}
workManager.cancelAllWorkByTag(DAY_NIGHT_WORK_NAME);
}
/**
* Network connectivity receiver to notify client of the network disconnect issues and
* to clear any network notifications when reconnected. It is easy for network connectivity
* to run amok that is why we only notify the user once for network disconnect with
* a boolean flag.
*/
companion object {
const val DAY_NIGHT_WORK_NAME: String = "day_night_worker_tag"
}
} | apache-2.0 | c023baa65a32b104f7398208ea219c44 | 41.357466 | 142 | 0.677885 | 4.421351 | false | true | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/Limits.kt | 1 | 7156 | package com.gh0u1l5.wechatmagician.backend.plugins
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.*
import com.gh0u1l5.wechatmagician.Global.SETTINGS_SELECT_PHOTOS_LIMIT
import com.gh0u1l5.wechatmagician.R
import com.gh0u1l5.wechatmagician.backend.WechatHook
import com.gh0u1l5.wechatmagician.backend.storage.Strings
import com.gh0u1l5.wechatmagician.spellbook.C
import com.gh0u1l5.wechatmagician.spellbook.base.Hooker
import com.gh0u1l5.wechatmagician.spellbook.base.HookerProvider
import com.gh0u1l5.wechatmagician.spellbook.interfaces.IActivityHook
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.plugin.gallery.ui.Classes.AlbumPreviewUI
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.storage.Classes.ContactInfo
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.ui.contact.Classes.SelectContactUI
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.ui.transmit.Methods.SelectConversationUI_checkLimit
import com.gh0u1l5.wechatmagician.util.ViewUtil.dp2px
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge.hookMethod
import de.robv.android.xposed.XposedHelpers
import de.robv.android.xposed.XposedHelpers.findAndHookMethod
import java.lang.reflect.Field
object Limits : IActivityHook, HookerProvider {
private val pref = WechatHook.settings
override fun provideStaticHookers(): List<Hooker>? {
return listOf(onCheckSelectLimitHooker, onSelectAllContactHooker)
}
override fun onActivityCreating(activity: Activity, savedInstanceState: Bundle?) {
when (activity::class.java) {
AlbumPreviewUI -> {
// Bypass the limit on number of photos the user can select
val intent = activity.intent ?: return
val oldLimit = intent.getIntExtra("max_select_count", 9)
val newLimit = try {
pref.getString(SETTINGS_SELECT_PHOTOS_LIMIT, "1000").toInt()
} catch (_: Throwable) { 1000 }
if (oldLimit <= 9) {
intent.putExtra("max_select_count", oldLimit + newLimit - 9)
}
}
SelectContactUI -> {
// Bypass the limit on number of recipients the user can forward.
val intent = activity.intent ?: return
if (intent.getIntExtra("max_limit_num", -1) == 9) {
intent.putExtra("max_limit_num", 0x7FFFFFFF)
}
}
}
}
// Hook MMActivity.onCreateOptionsMenu to add "Select All" button.
override fun onMMActivityOptionsMenuCreated(activity: Activity, menu: Menu) {
if (activity::class.java != SelectContactUI) {
return
}
val intent = activity.intent ?: return
val checked = intent.getBooleanExtra("select_all_checked", false)
val selectAll = menu.add(0, 2, 0, "")
selectAll.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
val btnText = TextView(activity).apply {
setTextColor(Color.WHITE)
text = Strings.getString(R.string.button_select_all)
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT).apply {
marginEnd = context.dp2px(4)
}
}
val btnCheckbox = CheckBox(activity).apply {
isChecked = checked
setOnCheckedChangeListener { _, checked ->
onSelectContactUISelectAll(activity, checked)
}
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT).apply {
marginEnd = context.dp2px(6)
}
}
selectAll.actionView = LinearLayout(activity).apply {
addView(btnText)
addView(btnCheckbox)
orientation = LinearLayout.HORIZONTAL
}
}
// Hook SelectConversationUI to bypass the limit on number of recipients.
private val onCheckSelectLimitHooker = Hooker {
hookMethod(SelectConversationUI_checkLimit, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
param.result = false
}
})
}
// Hook SelectContactUI to help the "Select All" button.
private val onSelectAllContactHooker = Hooker {
findAndHookMethod(
SelectContactUI, "onActivityResult",
C.Int, C.Int, C.Intent, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val requestCode = param.args[0] as Int
val resultCode = param.args[1] as Int
val data = param.args[2] as Intent?
if (requestCode == 5) {
val activity = param.thisObject as Activity
activity.setResult(resultCode, data)
activity.finish()
param.result = null
}
}
})
}
// Handle the logic about "select all" check box in SelectContactUI
private fun onSelectContactUISelectAll(activity: Activity, isChecked: Boolean) {
val intent = activity.intent ?: return
intent.putExtra("select_all_checked", isChecked)
intent.putExtra("already_select_contact", "")
if (isChecked) {
// Search for the ListView of contacts
val listView = XposedHelpers.findFirstFieldByExactType(activity::class.java, ListView::class.java)
.get(activity) as ListView? ?: return
val adapter = (listView.adapter as HeaderViewListAdapter).wrappedAdapter
// Construct the list of user names
var contactField: Field? = null
var usernameField: Field? = null
val userList = mutableListOf<String>()
repeat(adapter.count, next@ { index ->
val item = adapter.getItem(index)
if (contactField == null) {
contactField = item::class.java.fields.firstOrNull {
it.type.name == ContactInfo.name
} ?: return@next
}
val contact = contactField?.get(item) ?: return@next
if (usernameField == null) {
usernameField = contact::class.java.fields.firstOrNull {
it.name == "field_username"
} ?: return@next
}
val username = usernameField?.get(contact) ?: return@next
userList.add(username as String)
})
intent.putExtra("already_select_contact", userList.joinToString(","))
}
activity.startActivityForResult(intent, 5)
}
} | gpl-3.0 | 297d7728c81f6711e2644b0c5ca2a384 | 41.856287 | 117 | 0.62493 | 4.643738 | false | false | false | false |
neva-dev/gradle-osgi-plugin | plugins/commons/src/main/kotlin/com/neva/osgi/toolkit/commons/utils/FileOperations.kt | 1 | 1428 | package com.neva.osgi.toolkit.commons.utils
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
object FileOperations {
fun unzip(file: File, dir: File, path: String) {
unzip(file, dir, { name ->
val prefix = "$path/"
if (!name.endsWith("/") && name.startsWith(prefix)) {
name.substringAfter(prefix)
} else {
null
}
})
}
fun unzip(file: File, dir: File, nameMapper: (String) -> String?) {
val buffer = ByteArray(1024)
val zis = ZipInputStream(FileInputStream(file))
var zipEntry: ZipEntry? = zis.nextEntry
while (zipEntry != null) {
val fileName = nameMapper(zipEntry.name)
if (fileName != null) {
val newFile = File(dir, fileName).apply { parentFile.mkdirs() }
val fos = FileOutputStream(newFile)
var len: Int
while (true) {
len = zis.read(buffer)
if (len > 0) {
fos.write(buffer, 0, len)
} else {
break
}
}
fos.close()
}
zipEntry = zis.nextEntry
}
zis.closeEntry()
zis.close()
}
}
| apache-2.0 | 0f254ae563b91ac6c628dec0e8adbfb8 | 27 | 79 | 0.492997 | 4.636364 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/spelling/RsSpellCheckerGenerateDictionariesAction.kt | 2 | 1774 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.spelling
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.roots.ModuleRootManager
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.workspace.PackageOrigin
class RsSpellCheckerGenerateDictionariesAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val module = e.getData(LangDataKeys.MODULE) ?: return
val contextRootPath = ModuleRootManager.getInstance(module).contentRoots.firstOrNull()?.path ?: return
val generator = RsSpellCheckerDictionaryGenerator(project, "$contextRootPath/dicts")
val cargoProject = project.cargoProjects.allProjects.firstOrNull() ?: return
val stdlibPackages = cargoProject.workspace?.packages.orEmpty().filter { it.origin == PackageOrigin.STDLIB }
for (pkg in stdlibPackages) {
val contentRoot = pkg.contentRoot ?: continue
generator.addFolder("rust", contentRoot)
// do not analyze "non-production" code since it contains identifiers like "aaaa", "aaba", etc.
EXCLUDE_DIRS
.mapNotNull { contentRoot.findChild(it) }
.forEach { generator.excludeFolder(it) }
}
generator.generate()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project?.cargoProjects?.hasAtLeastOneValidProject == true
}
companion object {
private val EXCLUDE_DIRS = listOf("tests", "benches")
}
}
| mit | 5843b69036c6067e40b7a63c8305a41f | 40.255814 | 116 | 0.709696 | 4.730667 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/os/Command.kt | 1 | 6236 | /*
Copyright 2017-2020 Charles Korn.
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 batect.os
import batect.config.io.ConfigurationException
import com.charleskorn.kaml.YamlInput
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.internal.StringDescriptor
import kotlinx.serialization.internal.StringSerializer
import kotlinx.serialization.list
import kotlinx.serialization.withName
@Serializable(with = Command.Companion::class)
data class Command private constructor(val originalCommand: String, val parsedCommand: List<String>) {
operator fun plus(newArguments: Iterable<String>): Command {
val formattedCommand = originalCommand + formatNewArguments(newArguments)
return Command(formattedCommand, parsedCommand + newArguments)
}
private fun formatNewArguments(newArguments: Iterable<String>): String {
if (newArguments.any()) {
return " " + newArguments
.map { it.replace("$singleQuote", "$backslash$singleQuote") }
.map { it.replace("$doubleQuote", "$backslash$doubleQuote") }
.map { if (it.contains(' ')) doubleQuote + it + doubleQuote else it }
.joinToString(" ")
} else {
return ""
}
}
@Serializer(forClass = Command::class)
companion object : KSerializer<Command> {
fun parse(command: String): Command {
val arguments = arrayListOf<String>()
val currentArgument = StringBuilder()
var currentMode = CommandParsingState.Normal
var currentIndex = 0
fun handleBackslash() {
currentIndex++
if (currentIndex > command.length - 1) {
throw danglingBackslash(command)
}
currentArgument.append(command[currentIndex])
}
while (currentIndex < command.length) {
val char = command[currentIndex]
when (currentMode) {
CommandParsingState.Normal -> when {
char == backslash -> handleBackslash()
char.isWhitespace() -> {
if (currentArgument.isNotBlank()) {
arguments += currentArgument.toString()
}
currentArgument.setLength(0)
}
char == singleQuote -> currentMode = CommandParsingState.SingleQuote
char == doubleQuote -> currentMode = CommandParsingState.DoubleQuote
else -> currentArgument.append(char)
}
CommandParsingState.SingleQuote -> when (char) {
singleQuote -> currentMode = CommandParsingState.Normal
else -> currentArgument.append(char)
}
CommandParsingState.DoubleQuote -> when (char) {
doubleQuote -> currentMode = CommandParsingState.Normal
backslash -> handleBackslash()
else -> currentArgument.append(char)
}
}
currentIndex++
}
when (currentMode) {
CommandParsingState.DoubleQuote -> throw unbalancedDoubleQuote(command)
CommandParsingState.SingleQuote -> throw unbalancedSingleQuote(command)
CommandParsingState.Normal -> {
if (currentArgument.isNotEmpty()) {
arguments.add(currentArgument.toString())
}
return Command(command, arguments)
}
}
}
private const val backslash: Char = '\\'
private const val singleQuote: Char = '\''
private const val doubleQuote: Char = '"'
private fun invalidCommandLine(command: String, message: String): Throwable =
InvalidCommandLineException("Command `$command` is invalid: $message")
private fun unbalancedDoubleQuote(command: String): Throwable =
invalidCommandLine(command, "it contains an unbalanced double quote")
private fun unbalancedSingleQuote(command: String): Throwable =
invalidCommandLine(command, "it contains an unbalanced single quote")
private fun danglingBackslash(command: String): Throwable = invalidCommandLine(
command,
"""it ends with a backslash (backslashes always escape the following character, for a literal backslash, use '\\')"""
)
private enum class CommandParsingState {
Normal,
SingleQuote,
DoubleQuote
}
override val descriptor: SerialDescriptor = StringDescriptor.withName("command")
override fun deserialize(decoder: Decoder): Command = try {
parse(decoder.decodeString())
} catch (e: InvalidCommandLineException) {
if (decoder is YamlInput) {
val location = decoder.getCurrentLocation()
throw ConfigurationException(e.message ?: "", location.line, location.column, e)
} else {
throw e
}
}
override fun serialize(encoder: Encoder, obj: Command) = StringSerializer.list.serialize(encoder, obj.parsedCommand)
}
}
class InvalidCommandLineException(message: String) : RuntimeException(message)
| apache-2.0 | e7c3ff39ff53bad32bae78f089184fc3 | 39.232258 | 129 | 0.608082 | 5.638336 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/gestures/TransformGestureDetectorTest.kt | 3 | 9436 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.gestures
import androidx.compose.ui.geometry.Offset
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class TransformGestureDetectorTest(val panZoomLock: Boolean) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun parameters() = arrayOf(false, true)
}
private var centroid = Offset.Zero
private var panned = false
private var panAmount = Offset.Zero
private var rotated = false
private var rotateAmount = 0f
private var zoomed = false
private var zoomAmount = 1f
private val util = SuspendingGestureTestUtil {
detectTransformGestures(panZoomLock = panZoomLock) { c, pan, gestureZoom, gestureAngle ->
centroid = c
if (gestureAngle != 0f) {
rotated = true
rotateAmount += gestureAngle
}
if (gestureZoom != 1f) {
zoomed = true
zoomAmount *= gestureZoom
}
if (pan != Offset.Zero) {
panned = true
panAmount += pan
}
}
}
@Before
fun setup() {
panned = false
panAmount = Offset.Zero
rotated = false
rotateAmount = 0f
zoomed = false
zoomAmount = 1f
}
/**
* Single finger pan.
*/
@Test
fun singleFingerPan() = util.executeInComposition {
val down = down(5f, 5f)
assertFalse(down.isConsumed)
assertFalse(panned)
val move1 = down.moveBy(Offset(12.7f, 12.7f))
assertFalse(move1.isConsumed)
assertFalse(panned)
val move2 = move1.moveBy(Offset(0.1f, 0.1f))
assertTrue(move2.isConsumed)
assertEquals(17.7f, centroid.x, 0.1f)
assertEquals(17.7f, centroid.y, 0.1f)
assertTrue(panned)
assertFalse(zoomed)
assertFalse(rotated)
assertTrue(panAmount.getDistance() < 1f)
panAmount = Offset.Zero
val move3 = move2.moveBy(Offset(1f, 0f))
assertTrue(move3.isConsumed)
assertEquals(Offset(1f, 0f), panAmount)
move3.up().also { assertFalse(it.isConsumed) }
assertFalse(rotated)
assertFalse(zoomed)
}
/**
* Multi-finger pan
*/
@Test
fun multiFingerPanZoom() = util.executeInComposition {
val downA = down(5f, 5f)
assertFalse(downA.isConsumed)
val downB = down(25f, 25f)
assertFalse(downB.isConsumed)
assertFalse(panned)
val moveA1 = downA.moveBy(Offset(12.8f, 12.8f))
assertFalse(moveA1.isConsumed)
val moveB1 = downB.moveBy(Offset(12.8f, 12.8f))
// Now we've averaged enough movement
assertTrue(moveB1.isConsumed)
assertEquals((5f + 25f + 12.8f) / 2f, centroid.x, 0.1f)
assertEquals((5f + 25f + 12.8f) / 2f, centroid.y, 0.1f)
assertTrue(panned)
assertTrue(zoomed)
assertFalse(rotated)
assertEquals(6.4f, panAmount.x, 0.1f)
assertEquals(6.4f, panAmount.y, 0.1f)
moveA1.up()
moveB1.up()
}
/**
* 2-pointer zoom
*/
@Test
fun zoom2Pointer() = util.executeInComposition {
val downA = down(5f, 5f)
assertFalse(downA.isConsumed)
val downB = down(25f, 5f)
assertFalse(downB.isConsumed)
val moveB1 = downB.moveBy(Offset(35.95f, 0f))
assertFalse(moveB1.isConsumed)
val moveB2 = moveB1.moveBy(Offset(0.1f, 0f))
assertTrue(moveB2.isConsumed)
assertTrue(panned)
assertTrue(zoomed)
assertFalse(rotated)
// both should be small movements
assertTrue(panAmount.getDistance() < 1f)
assertTrue(zoomAmount in 1f..1.1f)
zoomAmount = 1f
panAmount = Offset.Zero
val moveA1 = downA.moveBy(Offset(-1f, 0f))
assertTrue(moveA1.isConsumed)
val moveB3 = moveB2.moveBy(Offset(1f, 0f))
assertTrue(moveB3.isConsumed)
assertEquals(0f, panAmount.x, 0.01f)
assertEquals(0f, panAmount.y, 0.01f)
assertEquals(48f / 46f, zoomAmount, 0.01f)
moveA1.up()
moveB3.up()
}
/**
* 4-pointer zoom
*/
@Test
fun zoom4Pointer() = util.executeInComposition {
val downA = down(0f, 50f)
// just get past the touch slop
val slop1 = downA.moveBy(Offset(-1000f, 0f))
val slop2 = slop1.moveBy(Offset(1000f, 0f))
panned = false
panAmount = Offset.Zero
val downB = down(100f, 50f)
val downC = down(50f, 0f)
val downD = down(50f, 100f)
val moveA = slop2.moveBy(Offset(-50f, 0f))
val moveB = downB.moveBy(Offset(50f, 0f))
assertTrue(zoomed)
assertTrue(panned)
assertEquals(0f, panAmount.x, 0.1f)
assertEquals(0f, panAmount.y, 0.1f)
assertEquals(1.5f, zoomAmount, 0.1f)
val moveC = downC.moveBy(Offset(0f, -50f))
val moveD = downD.moveBy(Offset(0f, 50f))
assertEquals(0f, panAmount.x, 0.1f)
assertEquals(0f, panAmount.y, 0.1f)
assertEquals(2f, zoomAmount, 0.1f)
moveA.up()
moveB.up()
moveC.up()
moveD.up()
}
/**
* 2 pointer rotation.
*/
@Test
fun rotation2Pointer() = util.executeInComposition {
val downA = down(0f, 50f)
val downB = down(100f, 50f)
val moveA = downA.moveBy(Offset(50f, -50f))
val moveB = downB.moveBy(Offset(-50f, 50f))
// assume some of the above was touch slop
assertTrue(rotated)
rotateAmount = 0f
rotated = false
zoomAmount = 1f
panAmount = Offset.Zero
// now do the real rotation:
val moveA2 = moveA.moveBy(Offset(-50f, 50f))
val moveB2 = moveB.moveBy(Offset(50f, -50f))
moveA2.up()
moveB2.up()
assertTrue(rotated)
assertEquals(-90f, rotateAmount, 0.01f)
assertEquals(0f, panAmount.x, 0.1f)
assertEquals(0f, panAmount.y, 0.1f)
assertEquals(1f, zoomAmount, 0.1f)
}
/**
* 2 pointer rotation, with early panning.
*/
@Test
fun rotation2PointerLock() = util.executeInComposition {
val downA = down(0f, 50f)
// just get past the touch slop with panning
val slop1 = downA.moveBy(Offset(-1000f, 0f))
val slop2 = slop1.moveBy(Offset(1000f, 0f))
val downB = down(100f, 50f)
// now do the rotation:
val moveA2 = slop2.moveBy(Offset(50f, -50f))
val moveB2 = downB.moveBy(Offset(-50f, 50f))
moveA2.up()
moveB2.up()
if (panZoomLock) {
assertFalse(rotated)
} else {
assertTrue(rotated)
assertEquals(90f, rotateAmount, 0.01f)
}
assertEquals(0f, panAmount.x, 0.1f)
assertEquals(0f, panAmount.y, 0.1f)
assertEquals(1f, zoomAmount, 0.1f)
}
/**
* Adding or removing a pointer won't change the current values
*/
@Test
fun noChangeOnPointerDownUp() = util.executeInComposition {
val downA = down(0f, 50f)
val downB = down(100f, 50f)
val moveA = downA.moveBy(Offset(50f, -50f))
val moveB = downB.moveBy(Offset(-50f, 50f))
// now we've gotten past the touch slop
rotated = false
panned = false
zoomed = false
val downC = down(0f, 50f)
assertFalse(rotated)
assertFalse(panned)
assertFalse(zoomed)
val downD = down(100f, 50f)
assertFalse(rotated)
assertFalse(panned)
assertFalse(zoomed)
moveA.up()
moveB.up()
downC.up()
downD.up()
assertFalse(rotated)
assertFalse(panned)
assertFalse(zoomed)
}
/**
* Consuming position during touch slop will cancel the current gesture.
*/
@Test
fun touchSlopCancel() = util.executeInComposition {
down(5f, 5f)
.moveBy(Offset(50f, 0f)) { consume() }
.up()
assertFalse(panned)
assertFalse(zoomed)
assertFalse(rotated)
}
/**
* Consuming position after touch slop will cancel the current gesture.
*/
@Test
fun afterTouchSlopCancel() = util.executeInComposition {
down(5f, 5f)
.moveBy(Offset(50f, 0f))
.moveBy(Offset(50f, 0f)) { consume() }
.up()
assertTrue(panned)
assertFalse(zoomed)
assertFalse(rotated)
assertEquals(50f, panAmount.x, 0.1f)
}
} | apache-2.0 | 707756d44a53c825f2db5114fdd9208f | 25.809659 | 97 | 0.591246 | 3.675886 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/CL10.kt | 1 | 148446 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
// -- [ Reusable definitions ] --
val SUCCESS = "CL10#SUCCESS"
val TRUE = "CL10#TRUE"
val FALSE = "CL10#FALSE"
// Error codes
val INVALID_VALUE = "CL10#INVALID_VALUE"
val INVALID_DEVICE_TYPE = "CL10#INVALID_DEVICE_TYPE"
val INVALID_PLATFORM = "CL10#INVALID_PLATFORM"
val INVALID_DEVICE = "CL10#INVALID_DEVICE"
val INVALID_CONTEXT = "CL10#INVALID_CONTEXT"
val INVALID_QUEUE_PROPERTIES = "CL10#INVALID_QUEUE_PROPERTIES"
val INVALID_COMMAND_QUEUE = "CL10#INVALID_COMMAND_QUEUE"
val INVALID_HOST_PTR = "CL10#INVALID_HOST_PTR"
val INVALID_MEM_OBJECT = "CL10#INVALID_MEM_OBJECT"
val INVALID_IMAGE_FORMAT_DESCRIPTOR = "CL10#INVALID_IMAGE_FORMAT_DESCRIPTOR"
val INVALID_IMAGE_SIZE = "CL10#INVALID_IMAGE_SIZE"
val INVALID_SAMPLER = "CL10#INVALID_SAMPLER"
val INVALID_BINARY = "CL10#INVALID_BINARY"
val INVALID_BUILD_OPTIONS = "CL10#INVALID_BUILD_OPTIONS"
val INVALID_PROGRAM = "CL10#INVALID_PROGRAM"
val INVALID_PROGRAM_EXECUTABLE = "CL10#INVALID_PROGRAM_EXECUTABLE"
val INVALID_KERNEL_NAME = "CL10#INVALID_KERNEL_NAME"
val INVALID_KERNEL_DEFINITION = "CL10#INVALID_KERNEL_DEFINITION"
val INVALID_KERNEL = "CL10#INVALID_KERNEL"
val INVALID_ARG_INDEX = "CL10#INVALID_ARG_INDEX"
val INVALID_ARG_VALUE = "CL10#INVALID_ARG_VALUE"
val INVALID_ARG_SIZE = "CL10#INVALID_ARG_SIZE"
val INVALID_KERNEL_ARGS = "CL10#INVALID_KERNEL_ARGS"
val INVALID_WORK_DIMENSION = "CL10#INVALID_WORK_DIMENSION"
val INVALID_WORK_GROUP_SIZE = "CL10#INVALID_WORK_GROUP_SIZE"
val INVALID_WORK_ITEM_SIZE = "CL10#INVALID_WORK_ITEM_SIZE"
val INVALID_GLOBAL_OFFSET = "CL10#INVALID_GLOBAL_OFFSET"
val INVALID_EVENT_WAIT_LIST = "CL10#INVALID_EVENT_WAIT_LIST"
val INVALID_EVENT = "CL10#INVALID_EVENT"
val INVALID_OPERATION = "CL10#INVALID_OPERATION"
val INVALID_BUFFER_SIZE = "CL10#INVALID_BUFFER_SIZE"
val INVALID_GLOBAL_WORK_SIZE = "CL10#INVALID_GLOBAL_WORK_SIZE"
// Errors
val OORE = "CL10#OUT_OF_RESOURCES if there is a failure to allocate resources required by the OpenCL implementation on the device."
val OOHME = "CL10#OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by the OpenCL implementation on the host."
val ICQE = "$INVALID_COMMAND_QUEUE if {@code command_queue} is not a valid command-queue."
val ICE = "$INVALID_CONTEXT if {@code context} is not a valid context."
val IEWLE =
"""
$INVALID_EVENT_WAIT_LIST if {@code event_wait_list} is $NULL and {@code num_events_in_wait_list} > 0, or {@code event_wait_list} is not
$NULL and {@code num_events_in_wait_list} is 0, or if event objects in {@code event_wait_list} are not valid events.
"""
fun MSBOE(buffer: String) =
"""
CL11#MISALIGNED_SUB_BUFFER_OFFSET if {@code $buffer} is a sub-buffer object and offset specified when the sub-buffer object is created is
not aligned to CL10#DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue.
"""
fun ESEFEIWLE(operation: String) =
"""
CL11#EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST if the $operation operation is blocking and the execution status of any of the events in
{@code event_wait_list} is a negative integer value.
"""
val errcode_ret = "{@code errcode_ret}"
val param_value = "a pointer to memory where the appropriate result being queried is returned. If {@code param_value} is $NULL, it is ignored."
// Arguments
val NEWL = AutoSize("event_wait_list")..cl_uint.IN("num_events_in_wait_list", "the number of events in {@code event_wait_list}")
val EWL = nullable..const..cl_event_p.IN(
"event_wait_list",
"""
a list of events that need to complete before this particular command can be executed. If {@code event_wait_list} is $NULL, then this particular command
does not wait on any event to complete. The events specified in {@code event_wait_list} act as synchronization points. The context associated with events in
{@code event_wait_list} and {@code command_queue} must be the same.
"""
)
val EVENT = Check(1)..nullable..cl_event_p.OUT(
"event",
"""
Returns an event object that identifies this particular command and can be used to query or queue a wait for this particular command to complete.
{@code event} can be $NULL in which case it will not be possible for the application to query the status of this command or queue a wait for this command to
complete. If the {@code event_wait_list} and the {@code event} arguments are not $NULL, the event argument should not refer to an element of the
{@code event_wait_list} array.
"""
)
val ERROR_RET = Check(1)..nullable..cl_int_p.OUT(
"errcode_ret",
"will return an appropriate error code. If $errcode_ret is $NULL, no error code is returned."
)
val PARAM_VALUE_SIZE = AutoSize("param_value")..size_t.IN(
"param_value_size",
"the size in bytes of memory pointed to by {@code param_value}. This size must be ≥ size of return type. If {@code param_value} is $NULL, it is ignored."
)
val PARAM_VALUE_SIZE_RET = Check(1)..nullable..size_t_p.OUT(
"param_value_size_ret",
"the actual size in bytes of data being queried by {@code param_value}. If $NULL, it is ignored."
)
val CL10 = "CL10".nativeClassCL("CL10") {
documentation = "The core OpenCL 1.0 functionality."
IntConstant(
"Error Codes",
"SUCCESS".."0",
// We use expr here so that they are not converted to hex by the generator.
"DEVICE_NOT_FOUND".."-1",
"DEVICE_NOT_AVAILABLE".."-2",
"COMPILER_NOT_AVAILABLE".."-3",
"MEM_OBJECT_ALLOCATION_FAILURE".."-4",
"OUT_OF_RESOURCES".."-5",
"OUT_OF_HOST_MEMORY".."-6",
"PROFILING_INFO_NOT_AVAILABLE".."-7",
"MEM_COPY_OVERLAP".."-8",
"IMAGE_FORMAT_MISMATCH".."-9",
"IMAGE_FORMAT_NOT_SUPPORTED".."-10",
"BUILD_PROGRAM_FAILURE".."-11",
"MAP_FAILURE".."-12",
"INVALID_VALUE".."-30",
"INVALID_DEVICE_TYPE".."-31",
"INVALID_PLATFORM".."-32",
"INVALID_DEVICE".."-33",
"INVALID_CONTEXT".."-34",
"INVALID_QUEUE_PROPERTIES".."-35",
"INVALID_COMMAND_QUEUE".."-36",
"INVALID_HOST_PTR".."-37",
"INVALID_MEM_OBJECT".."-38",
"INVALID_IMAGE_FORMAT_DESCRIPTOR".."-39",
"INVALID_IMAGE_SIZE".."-40",
"INVALID_SAMPLER".."-41",
"INVALID_BINARY".."-42",
"INVALID_BUILD_OPTIONS".."-43",
"INVALID_PROGRAM".."-44",
"INVALID_PROGRAM_EXECUTABLE".."-45",
"INVALID_KERNEL_NAME".."-46",
"INVALID_KERNEL_DEFINITION".."-47",
"INVALID_KERNEL".."-48",
"INVALID_ARG_INDEX".."-49",
"INVALID_ARG_VALUE".."-50",
"INVALID_ARG_SIZE".."-51",
"INVALID_KERNEL_ARGS".."-52",
"INVALID_WORK_DIMENSION".."-53",
"INVALID_WORK_GROUP_SIZE".."-54",
"INVALID_WORK_ITEM_SIZE".."-55",
"INVALID_GLOBAL_OFFSET".."-56",
"INVALID_EVENT_WAIT_LIST".."-57",
"INVALID_EVENT".."-58",
"INVALID_OPERATION".."-59",
"INVALID_BUFFER_SIZE".."-61",
"INVALID_GLOBAL_WORK_SIZE".."-63"
)
IntConstant(
"OpenCL Version",
"VERSION_1_0".."1"
)
IntConstant(
"cl_bool",
"FALSE".."0",
"TRUE".."1"
)
val PlatformInfo = IntConstant(
"cl_platform_info",
"PLATFORM_PROFILE"..0x0900,
"PLATFORM_VERSION"..0x0901,
"PLATFORM_NAME"..0x0902,
"PLATFORM_VENDOR"..0x0903,
"PLATFORM_EXTENSIONS"..0x0904
).javaDocLinks + " CL21#PLATFORM_HOST_TIMER_RESOLUTION"
val DeviceTypes = IntConstant(
"cl_device_type - bitfield",
"DEVICE_TYPE_DEFAULT".."1 << 0",
"DEVICE_TYPE_CPU".."1 << 1",
"DEVICE_TYPE_GPU".."1 << 2",
"DEVICE_TYPE_ACCELERATOR".."1 << 3",
"DEVICE_TYPE_ALL"..0xFFFFFFFF.i
).javaDocLinks + " CL12#DEVICE_TYPE_CUSTOM"
val DeviceInfo = IntConstant(
"cl_device_info",
"DEVICE_TYPE"..0x1000,
"DEVICE_VENDOR_ID"..0x1001,
"DEVICE_MAX_COMPUTE_UNITS"..0x1002,
"DEVICE_MAX_WORK_ITEM_DIMENSIONS"..0x1003,
"DEVICE_MAX_WORK_GROUP_SIZE"..0x1004,
"DEVICE_MAX_WORK_ITEM_SIZES"..0x1005,
"DEVICE_PREFERRED_VECTOR_WIDTH_CHAR"..0x1006,
"DEVICE_PREFERRED_VECTOR_WIDTH_SHORT"..0x1007,
"DEVICE_PREFERRED_VECTOR_WIDTH_"..0x1008,
"DEVICE_PREFERRED_VECTOR_WIDTH_LONG"..0x1009,
"DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT"..0x100A,
"DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE"..0x100B,
"DEVICE_MAX_CLOCK_FREQUENCY"..0x100C,
"DEVICE_ADDRESS_BITS"..0x100D,
"DEVICE_MAX_READ_IMAGE_ARGS"..0x100E,
"DEVICE_MAX_WRITE_IMAGE_ARGS"..0x100F,
"DEVICE_MAX_MEM_ALLOC_SIZE"..0x1010,
"DEVICE_IMAGE2D_MAX_WIDTH"..0x1011,
"DEVICE_IMAGE2D_MAX_HEIGHT"..0x1012,
"DEVICE_IMAGE3D_MAX_WIDTH"..0x1013,
"DEVICE_IMAGE3D_MAX_HEIGHT"..0x1014,
"DEVICE_IMAGE3D_MAX_DEPTH"..0x1015,
"DEVICE_IMAGE_SUPPORT"..0x1016,
"DEVICE_MAX_PARAMETER_SIZE"..0x1017,
"DEVICE_MAX_SAMPLERS"..0x1018,
"DEVICE_MEM_BASE_ADDR_ALIGN"..0x1019,
"DEVICE_MIN_DATA_TYPE_ALIGN_SIZE"..0x101A,
"DEVICE_SINGLE_FP_CONFIG"..0x101B,
"DEVICE_GLOBAL_MEM_CACHE_TYPE"..0x101C,
"DEVICE_GLOBAL_MEM_CACHELINE_SIZE"..0x101D,
"DEVICE_GLOBAL_MEM_CACHE_SIZE"..0x101E,
"DEVICE_GLOBAL_MEM_SIZE"..0x101F,
"DEVICE_MAX_CONSTANT_BUFFER_SIZE"..0x1020,
"DEVICE_MAX_CONSTANT_ARGS"..0x1021,
"DEVICE_LOCAL_MEM_TYPE"..0x1022,
"DEVICE_LOCAL_MEM_SIZE"..0x1023,
"DEVICE_ERROR_CORRECTION_SUPPORT"..0x1024,
"DEVICE_PROFILING_TIMER_RESOLUTION"..0x1025,
"DEVICE_ENDIAN_LITTLE"..0x1026,
"DEVICE_AVAILABLE"..0x1027,
"DEVICE_COMPILER_AVAILABLE"..0x1028,
"DEVICE_EXECUTION_CAPABILITIES"..0x1029,
"DEVICE_QUEUE_PROPERTIES"..0x102A,
"DEVICE_NAME"..0x102B,
"DEVICE_VENDOR"..0x102C,
"DRIVER_VERSION"..0x102D,
"DEVICE_PROFILE"..0x102E,
"DEVICE_VERSION"..0x102F,
"DEVICE_EXTENSIONS"..0x1030,
"DEVICE_PLATFORM"..0x1031
).javaDocLinks + """ CL11#DEVICE_PREFERRED_VECTOR_WIDTH_HALF CL11#DEVICE_HOST_UNIFIED_MEMORY CL11#DEVICE_NATIVE_VECTOR_WIDTH_CHAR
CL11#DEVICE_NATIVE_VECTOR_WIDTH_SHORT CL11#DEVICE_NATIVE_VECTOR_WIDTH_INT CL11#DEVICE_NATIVE_VECTOR_WIDTH_LONG
CL11#DEVICE_NATIVE_VECTOR_WIDTH_FLOAT CL11#DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE CL11#DEVICE_NATIVE_VECTOR_WIDTH_HALF CL11#DEVICE_OPENCL_C_VERSION
CL12#DEVICE_DOUBLE_FP_CONFIG CL12#DEVICE_LINKER_AVAILABLE CL12#DEVICE_BUILT_IN_KERNELS CL12#DEVICE_IMAGE_MAX_BUFFER_SIZE CL12#DEVICE_IMAGE_MAX_ARRAY_SIZE
CL12#DEVICE_PARENT_DEVICE CL12#DEVICE_PARTITION_MAX_SUB_DEVICES CL12#DEVICE_PARTITION_PROPERTIES CL12#DEVICE_PARTITION_AFFINITY_DOMAIN
CL12#DEVICE_PARTITION_TYPE CL12#DEVICE_REFERENCE_COUNT CL12#DEVICE_PREFERRED_INTEROP_USER_SYNC CL12#DEVICE_PRINTF_BUFFER_SIZE
CL20#DEVICE_QUEUE_ON_HOST_PROPERTIES CL20#DEVICE_MAX_READ_WRITE_IMAGE_ARGS CL20#DEVICE_MAX_GLOBAL_VARIABLE_SIZE CL20#DEVICE_QUEUE_ON_DEVICE_PROPERTIES
CL20#DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE CL20#DEVICE_QUEUE_ON_DEVICE_MAX_SIZE CL20#DEVICE_MAX_ON_DEVICE_QUEUES CL20#DEVICE_MAX_ON_DEVICE_EVENTS
CL20#DEVICE_SVM_CAPABILITIES CL20#DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE CL20#DEVICE_MAX_PIPE_ARGS CL20#DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS
CL20#DEVICE_PIPE_MAX_PACKET_SIZE CL20#DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT CL20#DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT
CL20#DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT
CL21#DEVICE_IL_VERSION CL21#DEVICE_MAX_NUM_SUB_GROUPS CL21#DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS
"""
IntConstant(
"cl_device_fp_config - bitfield",
"FP_DENORM".."1 << 0",
"FP_INF_NAN".."1 << 1",
"FP_ROUND_TO_NEAREST".."1 << 2",
"FP_ROUND_TO_ZERO".."1 << 3",
"FP_ROUND_TO_INF".."1 << 4",
"FP_FMA".."1 << 5"
)
IntConstant(
"cl_device_mem_cache_type",
"NONE"..0x0,
"READ_ONLY_CACHE"..0x1,
"READ_WRITE_CACHE"..0x2
)
IntConstant(
"cl_device_local_mem_type",
"LOCAL"..0x1,
"GLOBAL"..0x2
)
IntConstant(
"cl_device_exec_capabilities - bitfield",
"EXEC_KERNEL".."1 << 0",
"EXEC_NATIVE_KERNEL".."1 << 1"
)
val CommandQueueProperties = IntConstant(
"cl_command_queue_properties - bitfield",
"QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE".."1 << 0",
"QUEUE_PROFILING_ENABLE".."1 << 1"
).javaDocLinks + " CL20#QUEUE_ON_DEVICE CL20#QUEUE_ON_DEVICE_DEFAULT"
val ContextInfo = IntConstant(
"cl_context_info",
"CONTEXT_REFERENCE_COUNT"..0x1080,
"CONTEXT_DEVICES"..0x1081,
"CONTEXT_PROPERTIES"..0x1082
).javaDocLinks + " CL11#CONTEXT_NUM_DEVICES"
val ContextProperties = IntConstant(
"cl_context_info + cl_context_properties",
"CONTEXT_PLATFORM"..0x1084
).javaDocLinks + """ CL12#CONTEXT_INTEROP_USER_SYNC KHRGLSharing#GL_CONTEXT_KHR KHRGLSharing#EGL_DISPLAY_KHR KHRGLSharing#GLX_DISPLAY_KHR
KHRGLSharing#WGL_HDC_KHR KHRGLSharing#CGL_SHAREGROUP_KHR
"""
val CommandQueueInfo = IntConstant(
"cl_command_queue_info",
"QUEUE_CONTEXT"..0x1090,
"QUEUE_DEVICE"..0x1091,
"QUEUE_REFERENCE_COUNT"..0x1092,
"QUEUE_PROPERTIES"..0x1093
).javaDocLinks + " CL20#QUEUE_SIZE CL21#QUEUE_DEVICE_DEFAULT"
val MemFlags = IntConstant(
"cl_mem_flags - bitfield",
"MEM_READ_WRITE".."1 << 0",
"MEM_WRITE_ONLY".."1 << 1",
"MEM_READ_ONLY".."1 << 2",
"MEM_USE_HOST_PTR".."1 << 3",
"MEM_ALLOC_HOST_PTR".."1 << 4",
"MEM_COPY_HOST_PTR".."1 << 5"
).javaDocLinks + " CL12#MEM_HOST_WRITE_ONLY CL12#MEM_HOST_READ_ONLY CL12#MEM_HOST_NO_ACCESS"
IntConstant(
"cl_channel_order",
"R"..0x10B0,
"A"..0x10B1,
"RG"..0x10B2,
"RA"..0x10B3,
"RGB"..0x10B4,
"RGBA"..0x10B5,
"BGRA"..0x10B6,
"ARGB"..0x10B7,
"INTENSITY"..0x10B8,
"LUMINANCE"..0x10B9
)
IntConstant(
"cl_channel_type",
"SNORM_INT8"..0x10D0,
"SNORM_INT16"..0x10D1,
"UNORM_INT8"..0x10D2,
"UNORM_INT16"..0x10D3,
"UNORM_SHORT_565"..0x10D4,
"UNORM_SHORT_555"..0x10D5,
"UNORM_INT_101010"..0x10D6,
"SIGNED_INT8"..0x10D7,
"SIGNED_INT16"..0x10D8,
"SIGNED_INT32"..0x10D9,
"UNSIGNED_INT8"..0x10DA,
"UNSIGNED_INT16"..0x10DB,
"UNSIGNED_INT32"..0x10DC,
"HALF_FLOAT"..0x10DD,
"FLOAT"..0x10DE
)
val cl_mem_object_types = "CL12#MEM_OBJECT_IMAGE1D CL12#MEM_OBJECT_IMAGE1D_BUFFER " + IntConstant(
"cl_mem_object_type",
"MEM_OBJECT_BUFFER"..0x10F0,
"MEM_OBJECT_IMAGE2D"..0x10F1,
"MEM_OBJECT_IMAGE3D"..0x10F2
).javaDocLinks + " CL12#MEM_OBJECT_IMAGE1D_ARRAY CL12#MEM_OBJECT_IMAGE2D_ARRAY CL20#MEM_OBJECT_PIPE"
val MemInfo = IntConstant(
"cl_mem_info",
"MEM_TYPE"..0x1100,
"MEM_FLAGS"..0x1101,
"MEM_SIZE"..0x1102,
"MEM_HOST_PTR"..0x1103,
"MEM_MAP_COUNT"..0x1104,
"MEM_REFERENCE_COUNT"..0x1105,
"MEM_CONTEXT"..0x1106
).javaDocLinks + " CL11#MEM_ASSOCIATED_MEMOBJECT CL11#MEM_OFFSET CL20#MEM_USES_SVM_POINTER"
val ImageInfo = IntConstant(
"cl_image_info",
"IMAGE_FORMAT"..0x1110,
"IMAGE_ELEMENT_SIZE"..0x1111,
"IMAGE_ROW_PITCH"..0x1112,
"IMAGE_SLICE_PITCH"..0x1113,
"IMAGE_WIDTH"..0x1114,
"IMAGE_HEIGHT"..0x1115,
"IMAGE_DEPTH"..0x1116
).javaDocLinks + " CL12#IMAGE_ARRAY_SIZE CL12#IMAGE_BUFFER CL12#IMAGE_NUM_MIP_LEVELS CL12#IMAGE_NUM_SAMPLES"
val AddressingModes = IntConstant(
"cl_addressing_mode",
"ADDRESS_NONE"..0x1130,
"ADDRESS_CLAMP_TO_EDGE"..0x1131,
"ADDRESS_CLAMP"..0x1132,
"ADDRESS_REPEAT"..0x1133
).javaDocLinks + " CL11#ADDRESS_MIRRORED_REPEAT"
val FilterModes = IntConstant(
"cl_filter_mode",
"FILTER_NEAREST"..0x1140,
"FILTER_LINEAR"..0x1141
).javaDocLinks
val SamplerInfo = IntConstant(
"cl_sampler_info",
"SAMPLER_REFERENCE_COUNT"..0x1150,
"SAMPLER_CONTEXT"..0x1151,
"SAMPLER_NORMALIZED_COORDS"..0x1152,
"SAMPLER_ADDRESSING_MODE"..0x1153,
"SAMPLER_FILTER_MODE"..0x1154
).javaDocLinks + " CL20#SAMPLER_MIP_FILTER_MODE CL20#SAMPLER_LOD_MIN CL20#SAMPLER_LOD_MAX"
val MapFlags = IntConstant(
"cl_map_flags - bitfield",
"MAP_READ".."1 << 0",
"MAP_WRITE".."1 << 1"
).javaDocLinks + " CL12#MAP_WRITE_INVALIDATE_REGION"
val ProgramInfo = IntConstant(
"cl_program_info",
"PROGRAM_REFERENCE_COUNT"..0x1160,
"PROGRAM_CONTEXT"..0x1161,
"PROGRAM_NUM_DEVICES"..0x1162,
"PROGRAM_DEVICES"..0x1163,
"PROGRAM_SOURCE"..0x1164,
"PROGRAM_BINARY_SIZES"..0x1165,
"PROGRAM_BINARIES"..0x1166
).javaDocLinks + " CL12#PROGRAM_NUM_KERNELS CL12#PROGRAM_KERNEL_NAMES CL21#PROGRAM_IL"
val ProgramBuildInfo = IntConstant(
"cl_program_build_info",
"PROGRAM_BUILD_STATUS"..0x1181,
"PROGRAM_BUILD_OPTIONS"..0x1182,
"PROGRAM_BUILD_LOG"..0x1183
).javaDocLinks + " CL12#PROGRAM_BINARY_TYPE CL20#PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE"
IntConstant(
"cl_build_status",
"BUILD_SUCCESS".."0",
"BUILD_NONE".."-1",
"BUILD_ERROR".."-2",
"BUILD_IN_PROGRESS".."-3"
)
val KernelInfo = IntConstant(
"cl_kernel_info",
"KERNEL_FUNCTION_NAME"..0x1190,
"KERNEL_NUM_ARGS"..0x1191,
"KERNEL_REFERENCE_COUNT"..0x1192,
"KERNEL_CONTEXT"..0x1193,
"KERNEL_PROGRAM"..0x1194
).javaDocLinks + " CL12#KERNEL_ATTRIBUTES"
val KernelWorkGroupInfo = IntConstant(
"cl_kernel_work_group_info",
"KERNEL_WORK_GROUP_SIZE"..0x11B0,
"KERNEL_COMPILE_WORK_GROUP_SIZE"..0x11B1,
"KERNEL_LOCAL_MEM_SIZE"..0x11B2
).javaDocLinks + " CL11#KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE CL11#KERNEL_PRIVATE_MEM_SIZE CL12#KERNEL_GLOBAL_WORK_SIZE"
val EventInfo = IntConstant(
"cl_event_info",
"EVENT_COMMAND_QUEUE"..0x11D0,
"EVENT_COMMAND_TYPE"..0x11D1,
"EVENT_REFERENCE_COUNT"..0x11D2,
"EVENT_COMMAND_EXECUTION_STATUS"..0x11D3
).javaDocLinks + " CL11#EVENT_CONTEXT"
IntConstant(
"cl_command_type",
"COMMAND_NDRANGE_KERNEL"..0x11F0,
"COMMAND_TASK"..0x11F1,
"COMMAND_NATIVE_KERNEL"..0x11F2,
"COMMAND_READ_BUFFER"..0x11F3,
"COMMAND_WRITE_BUFFER"..0x11F4,
"COMMAND_COPY_BUFFER"..0x11F5,
"COMMAND_READ_IMAGE"..0x11F6,
"COMMAND_WRITE_IMAGE"..0x11F7,
"COMMAND_COPY_IMAGE"..0x11F8,
"COMMAND_COPY_IMAGE_TO_BUFFER"..0x11F9,
"COMMAND_COPY_BUFFER_TO_IMAGE"..0x11FA,
"COMMAND_MAP_BUFFER"..0x11FB,
"COMMAND_MAP_IMAGE"..0x11FC,
"COMMAND_UNMAP_MEM_OBJECT"..0x11FD,
"COMMAND_MARKER"..0x11FE,
"COMMAND_ACQUIRE_GL_OBJECTS"..0x11FF,
"COMMAND_RELEASE_GL_OBJECTS"..0x1200
)
IntConstant(
"command execution status",
"COMPLETE"..0x0,
"RUNNING"..0x1,
"SUBMITTED"..0x2,
"QUEUED"..0x3
)
val ProfilingInfo = IntConstant(
"cl_profiling_info",
"PROFILING_COMMAND_QUEUED"..0x1280,
"PROFILING_COMMAND_SUBMIT"..0x1281,
"PROFILING_COMMAND_START"..0x1282,
"PROFILING_COMMAND_END"..0x1283
).javaDocLinks + " CL20#PROFILING_COMMAND_COMPLETE"
// ------------------[ OPENCL Platform Layer ]------------------
cl_int(
"GetPlatformIDs",
"Obtains the list of available platforms.",
AutoSize("platforms")..cl_uint.IN(
"num_entries",
"""
the number of {@code cl_platform_id} entries that can be added to {@code platforms}. If {@code platforms} is not $NULL, the {@code num_entries} must
be greater than zero.
"""
),
nullable..cl_platform_id_p.OUT(
"platforms",
"""
returns a list of OpenCL platforms found. The {@code cl_platform_id} values returned in {@code platforms} can be used to identify a specific OpenCL
platform. If {@code platforms} argument is $NULL, this argument is ignored. The number of OpenCL platforms returned is the minimum of the value
specified by {@code num_entries} or the number of OpenCL platforms available.
"""
),
Check(1)..nullable..cl_uint_p.OUT(
"num_platforms",
"returns the number of OpenCL platforms available. If {@code num_platforms} is $NULL, this argument is ignored."
),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code num_entries} is equal to zero and {@code platforms} is not $NULL or if both {@code num_platforms} and
{@code platforms} are $NULL.
""",
OOHME
)}
"""
)
cl_int(
"GetPlatformInfo",
"Returns information about the specified OpenCL platform.",
cl_platform_id.IN("platform", "the platform to query"),
cl_platform_info.IN("param_name", "the parameter to query", PlatformInfo),
PARAM_VALUE_SIZE,
MultiType(
PointerMapping.DATA_LONG
)..nullable..void_p.OUT("param_value", "the memory location where appropriate values for a given {@code param_name} will be returned"),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PLATFORM if {@code platform} is not a valid platform.",
"""
$INVALID_VALUE if {@code param_name} is not one of the supported values or if size in bytes specified by {@code param_value_size} is <
size of return type and {@code param_value} is not a $NULL value.
""",
OOHME
)}
"""
)
cl_int(
"GetDeviceIDs",
"Obtains the list of devices available on a platform.",
nullable..cl_platform_id.IN("platform", "the platform to query"),
cl_device_type.IN(
"device_type",
"""
a bitfield that identifies the type of OpenCL device. The {@code device_type} can be used to query specific OpenCL devices or all OpenCL devices
available.
""",
DeviceTypes, LinkMode.BITFIELD
),
AutoSize("devices")..cl_uint.IN(
"num_entries",
"""
the number of {@code cl_device_id} entries that can be added to devices. If {@code devices} is not $NULL, the {@code num_entries} must be greater
than zero.
"""
),
nullable..cl_device_id_p.OUT(
"devices",
"""
returns a list of OpenCL devices found. The {@code cl_device_id} values returned in {@code devices} can be used to identify a specific OpenCL
device. If {@code devices} argument is $NULL, this argument is ignored. The number of OpenCL devices returned is the minimum of the value specified
by {@code num_entries} or the number of OpenCL devices whose type matches {@code device_type}.
"""
),
Check(1)..nullable..cl_uint_p.OUT(
"num_devices",
"returns the number of OpenCL devices available that match {@code device_type}. If {@code num_devices} is $NULL, this argument is ignored."
),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PLATFORM if {@code platform} is not a valid platform.",
"$INVALID_DEVICE_TYPE if {@code device_type} is not a valid value.",
"$INVALID_VALUE if {@code num_entries} is equal to zero and {@code devices} is not $NULL or if both {@code num_devices} and {@code devices} are $NULL.",
"#DEVICE_NOT_FOUND if no OpenCL devices that matched {@code device_type} were found.",
OORE,
OOHME
)}
"""
)
cl_int(
"GetDeviceInfo",
"""
Returns specific information about an OpenCL device. {@code device} may be a device returned by #GetDeviceIDs() or a sub-device created by
CL12#CreateSubDevices(). If {@code device} is a sub-device, the specific information for the sub-device will be returned.
""",
cl_device_id.IN("device", "the device to query"),
cl_device_info.IN(
"param_name",
"an enumeration constant tha identifies the device information being queried",
DeviceInfo
),
PARAM_VALUE_SIZE,
MultiType(
PointerMapping.DATA_INT, PointerMapping.DATA_LONG, PointerMapping.DATA_POINTER
)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_DEVICE if {@code device} is not valid.",
"""
$INVALID_VALUE if {@code param_name} is not one of the supported values or if size in bytes specified by {@code param_value_size} is <
size of return type and {@code param_value} is not a $NULL value or if {@code param_name} is a value that is available as an extension and the
corresponding extension is not supported by the device.
""",
OORE,
OOHME
)}
"""
)
cl_context(
"CreateContext",
"""
Creates an OpenCL context. An OpenCL context is created with one or more devices. Contexts are used by the OpenCL runtime for managing objects such as
command-queues, memory, program and kernel objects and for executing kernels on one or more devices specified in the context.
""",
NullTerminated..const..cl_context_properties_p.IN(
"properties",
"""
a list of context property names and their corresponding values. Each property name is immediately followed by the corresponding desired value. The
list is terminated with 0.
""",
ContextProperties
),
AutoSize("devices")..cl_uint.IN("num_devices", "the number of devices specified in the {@code devices} argument"),
SingleValue("device")..const..cl_device_id_p.IN(
"devices",
"a list of unique devices returned by #GetDeviceIDs() or sub-devices created by CL12#CreateSubDevices() for a platform"
),
nullable..cl_context_callback.IN(
"pfn_notify",
"""
a callback function that can be registered by the application. This callback function will be used by the OpenCL implementation to report
information on errors during context creation as well as errors that occur at runtime in this context. This callback function may be called
asynchronously by the OpenCL implementation. It is the application's responsibility to ensure that the callback function is thread-safe.
If {@code pfn_notify} is $NULL, no callback function is registered.
"""
),
nullable..voidptr.IN("user_data", "will be passed as the {@code user_data} argument when {@code pfn_notify} is called. {@code user_data} can be $NULL."),
ERROR_RET,
returnDoc =
"""
a valid non-zero context and $errcode_ret is set to $SUCCESS if the context is created successfully. Otherwise, it returns a $NULL value with the
following error values returned in $errcode_ret:
${ul(
"""
$INVALID_PLATFORM if {@code properties} is $NULL and no platform could be selected or if platform value specified in properties is not a
valid platform.
""",
"""
$INVALID_PROPERTY if context property name in {@code properties} is not a supported property name, if the value specified for a
supported property name is not valid, or if the same property name is specified more than once.
""",
"$INVALID_VALUE if {@code devices} is $NULL.",
"$INVALID_VALUE if {@code num_devices} is equal to zero.",
"$INVALID_VALUE if {@code pfn_notify} is $NULL but {@code user_data} is not $NULL.",
"$INVALID_DEVICE if {@code devices} contains an invalid device.",
"#DEVICE_NOT_AVAILABLE if a device in {@code devices} is currently not available even though the device was returned by #GetDeviceIDs().",
OORE,
OOHME
)}
"""
)
cl_context(
"CreateContextFromType",
"Creates a context using devices of the specified type. See #CreateContext() for details.",
NullTerminated..const..cl_context_properties_p.IN(
"properties",
"""
a list of context property names and their corresponding values. Each property name is immediately followed by the corresponding desired value. The
list is terminated with 0.
"""
),
cl_device_type.IN("device_type", "a bit-field that identifies the type of device", DeviceTypes),
nullable..cl_context_callback.IN("pfn_notify", "a callback function that can be registered by the application"),
nullable..voidptr.IN("user_data", "will be passed as the {@code user_data} argument when {@code pfn_notify} is called. {@code user_data} can be $NULL."),
ERROR_RET
)
cl_int(
"RetainContext",
"""
Increments the context reference count.
#CreateContext() and #CreateContextFromType() perform an implicit retain. This is very helpful for 3rd party libraries, which typically get a context passed
to them by the application. However, it is possible that the application may delete the context without informing the library. Allowing functions to
attach to (i.e. retain) and release a context solves the problem of a context being used by a library no longer being valid.
""",
cl_context.IN("context", "the context to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICE,
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseContext",
"""
Decrements the context reference count.
After the context reference count becomes zero and all the objects attached to context (such as memory objects, command-queues) are released, the
context is deleted.
""",
cl_context.IN("context", "the context to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICE,
OORE,
OOHME
)}
"""
)
cl_int(
"GetContextInfo",
"Queries information about a context.",
cl_context.IN("context", "the OpenCL context being queried"),
cl_context_info.IN("param_name", "an enumeration constant that specifies the information to query", ContextInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICE,
"""
$INVALID_VALUE if {@code param_name} is not one of the supported values or if size in bytes specified by {@code param_value_size} is <
size of return type and {@code param_value} is not a $NULL value.
""",
OORE,
OOHME
)}
"""
)
// ------------------[ OPENCL Runtime ]------------------
cl_command_queue(
"CreateCommandQueue",
"""
Creates a command-queue on a specific device.
OpenCL objects such as memory, program and kernel objects are created using a context. Operations on these objects are performed using a command-queue.
The command-queue can be used to queue a set of operations (referred to as commands) in order. Having multiple command-queues allows applications to
queue multiple independent commands without requiring synchronization. Note that this should work as long as these objects are not being shared. Sharing
of objects across multiple command-queues will require the application to perform appropriate synchronization.
""",
cl_context.IN("context", "a valid OpenCL context"),
cl_device_id.IN(
"device",
"""
a device associated with context. It can either be in the list of devices specified when context is created using #CreateContext() or have the same
device type as device type specified when context is created using #CreateContextFromType().
"""
),
cl_command_queue_properties.IN("properties", "a bit-field of properties for the command-queue", CommandQueueProperties),
ERROR_RET,
returnDoc =
"""
a valid non-zero command-queue and $errcode_ret is set to $SUCCESS if the command-queue is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_DEVICE if {@code device} is not a valid device or is not associated with {@code context}.",
"$INVALID_VALUE if values specified in {@code properties} are not valid.",
"$INVALID_QUEUE_PROPERTIES if values specified in {@code properties} are valid but are not supported by the device.",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainCommandQueue",
"""
Increments the {@code command_queue} reference count.
#CreateCommandQueue() performs an implicit retain. This is very helpful for 3rd party libraries, which typically get a command-queue passed to them by the
application. However, it is possible that the application may delete the command-queue without informing the library. Allowing functions to attach to
(i.e. retain) and release a command-queue solves the problem of a command-queue being used by a library no longer being valid.
""",
cl_command_queue.IN("command_queue", "the command-queue to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseCommandQueue",
"""
Decrements the {@code command_queue} reference count.
After the {@code command_queue} reference count becomes zero and all commands queued to {@code command_queue} have finished (eg. kernel executions,
memory object updates etc.), the command-queue is deleted.
{@code clReleaseCommandQueue} performs an implicit flush to issue any previously queued OpenCL commands in command_queue.
""",
cl_command_queue.IN("command_queue", "the command-queue to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
OORE,
OOHME
)}
"""
)
cl_int(
"GetCommandQueueInfo",
"Queries information about a command-queue.",
cl_command_queue.IN("command_queue", "the command-queue being queried"),
cl_command_queue_info.IN("param_name", "the information to query", CommandQueueInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_LONG, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_VALUE if {@code param_name} is not one of the supported values or if size in bytes specified by {@code param_value_size} is <
size of return type and {@code param_value} is not a $NULL value.
""",
OORE,
OOHME
)}
"""
)
cl_mem(
"CreateBuffer",
"Creates a buffer object.",
cl_context.IN("context", "a valid OpenCL context used to create the buffer object"),
cl_mem_flags.IN(
"flags",
"""
a bit-field that is used to specify allocation and usage information such as the memory area that should be used to allocate the buffer object and
how it will be used. If value specified for flags is 0, the default is used which is #MEM_READ_WRITE.
""",
MemFlags
),
AutoSize("host_ptr")..size_t.IN("size", "the size in bytes of the buffer memory object to be allocated"),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..optional..void_p.IN(
"host_ptr",
"""
a pointer to the buffer data that may already be allocated by the application. The size of the buffer that {@code host_ptr} points to must be
≥ {@code size} bytes.
"""
),
ERROR_RET,
returnDoc =
"""
a valid non-zero buffer object and $errcode_ret is set to $SUCCESS if the buffer object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_VALUE if values specified in flags are not valid.",
"""
$INVALID_BUFFER_SIZE if size is 0. Implementations may return $INVALID_BUFFER_SIZE if size is greater than
#DEVICE_MAX_MEM_ALLOC_SIZE value all devices in context.
""",
"""
$INVALID_HOST_PTR if {@code host_ptr} is $NULL and #MEM_USE_HOST_PTR or #MEM_COPY_HOST_PTR are set in flags or if
{@code host_ptr} is not $NULL but #MEM_COPY_HOST_PTR or #MEM_USE_HOST_PTR are not set in flags.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for buffer object.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueReadBuffer",
"""
Enqueues a command to read from a buffer object to host memory.
Calling {@code clEnqueueReadBuffer} to read a region of the buffer object with the {@code ptr} argument value set to {@code host_ptr + offset}, where
{@code host_ptr} is a pointer to the memory region specified when the buffer object being read is created with #MEM_USE_HOST_PTR, must meet
the following requirements in order to avoid undefined behavior:
${ul(
"""
All commands that use this buffer object or a memory object (buffer or image) created from this buffer object have finished execution before the
read command begins execution.
""",
"The buffer object or memory objects created from this buffer object are not mapped.",
"The buffer object or memory objects created from this buffer object are not used by any command-queue until the read command has finished execution."
)}
""",
cl_command_queue.IN(
"command_queue",
"the command-queue in which the read command will be queued. {@code command_queue} and {@code buffer} must be created with the same OpenCL context."
),
cl_mem.IN("buffer", "a valid buffer object"),
cl_bool.IN(
"blocking_read",
"""
indicates if the read operation is <em>blocking</em> or <em>non-blocking</em>
If {@code blocking_read} is $TRUE i.e. the read command is blocking, {@code clEnqueueReadBuffer} does not return until the buffer data has been
read and copied into memory pointed to by {@code ptr}.
If {@code blocking_read} is $FALSE i.e. the read command is non-blocking, {@code clEnqueueReadBuffer} queues a non-blocking read command and
returns. The contents of the buffer that {@code ptr} points to cannot be used until the read command has completed. The {@code event} argument
returns an event object which can be used to query the execution status of the read command. When the read command has completed, the contents of
the buffer that {@code ptr} points to can be used by the application.
"""
),
size_t.IN("offset", "the offset in bytes in the buffer object to read from"),
AutoSize("ptr")..size_t.IN("size", "the size in bytes of data being read"),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..void_p.OUT("ptr", "the pointer to buffer in host memory where data is to be read into"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue} and {@code buffer} are not the same or if the context associated
with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code buffer} is not a valid buffer object.",
"""
$INVALID_VALUE if the region being read specified by {@code (offset, size)} is out of bounds or if {@code ptr} is a $NULL value or if
{@code size} is 0.
""",
IEWLE,
MSBOE("buffer"),
ESEFEIWLE("read"),
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with buffer.",
"""
$INVALID_OPERATION if {@code clEnqueueReadBuffer} is called on buffer which has been created with CL12#MEM_HOST_WRITE_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueWriteBuffer",
"""
Enqueues a command to write to a buffer object from host memory.
Calling {@code clEnqueueWriteBuffer} to update the latest bits in a region of the buffer object with the {@code ptr} argument value set to
{@code host_ptr + offset}, where {@code host_ptr} is a pointer to the memory region specified when the buffer object being written is created with
#MEM_USE_HOST_PTR, must meet the following requirements in order to avoid undefined behavior:
${ul(
"The host memory region given by {@code (host_ptr + offset, cb)} contains the latest bits when the enqueued write command begins execution.",
"The buffer object or memory objects created from this buffer object are not mapped.",
"The buffer object or memory objects created from this buffer object are not used by any command-queue until the write command has finished execution."
)}
""",
cl_command_queue.IN(
"command_queue",
"the command-queue in which the write command will be queued. {@code command_queue} and {@code buffer} must be created with the same OpenCL context."
),
cl_mem.IN("buffer", "a valid buffer object"),
cl_bool.IN(
"blocking_write",
"""
indicates if the write operation is <em>blocking</em> or <em>non-blocking</em>
If {@code blocking_write} is $TRUE, the OpenCL implementation copies the data referred to by {@code ptr} and enqueues the write operation in the
command-queue. The memory pointed to by {@code ptr} can be reused by the application after the {@code clEnqueueWriteBuffer} call returns.
If {@code blocking_write} is $FALSE, the OpenCL implementation will use {@code ptr} to perform a nonblocking write. As the write is non-blocking
the implementation can return immediately. The memory pointed to by {@code ptr} cannot be reused by the application after the call returns. The
{@code event} argument returns an event object which can be used to query the execution status of the write command. When the write command has
completed, the memory pointed to by {@code ptr} can then be reused by the application.
"""
),
size_t.IN("offset", "the offset in bytes in the buffer object to write to"),
AutoSize("ptr")..size_t.IN("size", "the size in bytes of data being written"),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..const..void_p.IN("ptr", "the pointer to buffer in host memory where data is to be written from"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue} and {@code buffer} are not the same or if the context associated
with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code buffer} is not a valid buffer object.",
"""
$INVALID_VALUE if the region being written specified by {@code (offset, size)} is out of bounds or if {@code ptr} is a $NULL value or if
{@code size} is 0.
""",
IEWLE,
MSBOE("buffer"),
ESEFEIWLE("write"),
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with buffer.",
"""
$INVALID_OPERATION if {@code clEnqueueWriteBuffer} is called on buffer which has been created with CL12#MEM_HOST_READ_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueCopyBuffer",
"Enqueues a command to copy a buffer object identified by {@code src_buffer} to another buffer object identified by {@code dst_buffer}.",
cl_command_queue.IN(
"command_queue",
"""
the command-queue in which the copy command will be queued. The OpenCL context associated with {@code command_queue}, {@code src_buffer} and
{@code dst_buffer} must be the same.
"""
),
cl_mem.IN("src_buffer", "the source buffer"),
cl_mem.IN("dst_buffer", "the destination buffer"),
size_t.IN("src_offset", "the offset where to begin copying data from {@code src_buffer}."),
size_t.IN("dst_offset", "the offset where to begin copying data into {@code dst_buffer}"),
size_t.IN("size", "the size in bytes to copy"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue}, {@code src_buffer} and {@code dst_buffer} are not the same or if
the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code src_buffer} and {@code dst_buffer} are not valid buffer objects.",
"""
$INVALID_VALUE if {@code src_offset}, {@code dst_offset}, {@code size}, {@code src_offset + size} or {@code dst_offset + size} require
accessing elements outside the {@code src_buffer} and {@code dst_buffer} buffer objects respectively.
""",
"$INVALID_VALUE if {@code size} is 0.",
IEWLE,
MSBOE("src_buffer"),
MSBOE("dst_buffer"),
"""
#MEM_COPY_OVERLAP if {@code src_buffer} and {@code dst_buffer} are the same buffer or sub-buffer object and the source and destination
regions overlap or if {@code src_buffer} and {@code dst_buffer} are different sub-buffers of the same associated buffer object and they overlap. The
regions overlap if ${code("src_offset ≤ dst_offset ≤ src_offset + size – 1")} or if
${code("dst_offset ≤ src_offset ≤ dst_offset + size – 1")}.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code src_buffer} or {@code dst_buffer}.",
OORE,
OOHME
)}
"""
)
(MapPointer("size")..void_p)(
"EnqueueMapBuffer",
"""
Enqueues a command to map a region of the buffer object given by buffer into the host address space and returns a pointer to this mapped region.
The pointer returned maps a region starting at {@code offset} and is at least {@code size} bytes in size. The result of a memory access outside this
region is undefined.
If the buffer object is created with #MEM_USE_HOST_PTR set in {@code mem_flags}, the following will be true:
${ul(
"""
The {@code host_ptr} specified in #CreateBuffer() is guaranteed to contain the latest bits in the region being mapped when the
{@code clEnqueueMapBuffer} command has completed.
""",
"The pointer value returned by {@code clEnqueueMapBuffer} will be derived from the {@code host_ptr} specified when the buffer object is created."
)}
Mapped buffer objects are unmapped using #EnqueueUnmapMemObject().
""",
cl_command_queue.IN("command_queue", "a valid command-queue"),
cl_mem.IN("buffer", "a valid buffer object. The OpenCL context associated with command_queue and buffer must be the same."),
cl_bool.IN(
"blocking_map",
"""
indicates if the map operation is blocking or non-blocking.
If {@code blocking_map} is $TRUE, {@code clEnqueueMapBuffer} does not return until the specified region in buffer is mapped into the host address
space and the application can access the contents of the mapped region using the pointer returned by {@code clEnqueueMapBuffer}.
If {@code blocking_map} is $FALSE i.e. map operation is non-blocking, the pointer to the mapped region returned by {@code clEnqueueMapBuffer}
cannot be used until the map command has completed. The {@code event} argument returns an event object which can be used to query the execution
status of the map command. When the map command is completed, the application can access the contents of the mapped region using the pointer
returned by {@code clEnqueueMapBuffer}.
"""
),
cl_map_flags.IN("map_flags", "a bit-field", MapFlags),
size_t.IN("offset", "the offset in bytes of the region in the buffer object that is being mapped"),
size_t.IN("size", "the size in bytes of the region in the buffer object that is being mapped"),
NEWL,
EWL,
EVENT,
ERROR_RET,
returnDoc =
"""
a pointer to the mapped region. The $errcode_ret is set to $SUCCESS. A $NULL pointer is returned otherwise with one of the following error values
returned in $errcode_ret:
${ul(
ICQE,
"""
$INVALID_CONTEXT if context associated with {@code command_queue} and {@code buffer} are not the same or if the context associated with
{@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code buffer} is not a valid buffer object.",
"""
$INVALID_VALUE if region being mapped given by {@code (offset, size)} is out of bounds or if {@code size} is 0 or if values specified in
{@code map_flags} are not valid.
""",
IEWLE,
MSBOE("buffer"),
"""
#MAP_FAILURE if there is a failure to map the requested region into the host address space. This error cannot occur for buffer objects
created with #MEM_USE_HOST_PTR or #MEM_ALLOC_HOST_PTR.
""",
ESEFEIWLE("map"),
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code buffer}.",
"""
$INVALID_OPERATION if buffer has been created with CL12#MEM_HOST_WRITE_ONLY or CL12#MEM_HOST_NO_ACCESS and
#MAP_READ is set in {@code map_flags} or if {@code buffer} has been created with CL12#MEM_HOST_READ_ONLY or
CL12#MEM_HOST_NO_ACCESS and #MAP_WRITE or CL12#MAP_WRITE_INVALIDATE_REGION is set in {@code map_flags}.
""",
OORE,
OOHME
)}
"""
)
cl_mem(
"CreateImage2D",
"Creates a 2D image object.",
cl_context.IN("context", "a valid OpenCL context on which the image object is to be created"),
cl_mem_flags.IN("flags", "a bit-field that is used to specify allocation and usage information about the image memory object being created", MemFlags),
const..cl_image_format_p.IN("image_format", "a pointer to a ##CLImageFormat structure that describes format properties of the image to be allocated"),
size_t.IN("image_width", "the width of the image in pixels"),
size_t.IN("image_height", "the height of the image in pixels"),
size_t.IN(
"image_row_pitch",
"""
the scan-line pitch in bytes. This must be 0 if {@code host_ptr} is $NULL and can be either 0 or ≥ {@code image_width * size} of element in
bytes if {@code host_ptr} is not $NULL. If {@code host_ptr} is not $NULL and {@code image_row_pitch} = 0, {@code image_row_pitch} is calculated as
{@code image_width * size of element} in bytes. If {@code image_row_pitch} is not 0, it must be a multiple of the image element size in bytes.
"""
),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT)..nullable..void_p.IN(
"host_ptr",
"""
a pointer to the image data that may already be allocated by the application. The size of the buffer that {@code host_ptr} points to must be ≥
{@code image_row_pitch * image_height}. The size of each element in bytes must be a power of 2. The image data specified by {@code host_ptr} is
stored as a linear sequence of adjacent scanlines. Each scanline is stored as a linear sequence of image elements.
"""
),
ERROR_RET,
returnDoc =
"""
a valid non-zero image object and $errcode_ret is set to $SUCCESS if the image object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_VALUE if values specified in {@code flags} are not valid.",
"$INVALID_IMAGE_FORMAT_DESCRIPTOR if values specified in {@code image_format} are not valid or if {@code image_format} is $NULL.",
"""
$INVALID_IMAGE_SIZE if {@code image_width} or {@code image_height} are 0 or if they exceed values specified in
#DEVICE_IMAGE2D_MAX_WIDTH or #DEVICE_IMAGE2D_MAX_HEIGHT respectively for all devices in {@code context} or if values specified
by {@code image_row_pitch} do not follow rules described in the argument description.
""",
"""
$INVALID_HOST_PTR if {@code host_ptr} is $NULL and #MEM_USE_HOST_PTR or #MEM_COPY_HOST_PTR are set in flags or if
{@code host_ptr} is not $NULL but #MEM_COPY_HOST_PTR or #MEM_USE_HOST_PTR are not set in flags.
""",
"#IMAGE_FORMAT_NOT_SUPPORTED if the {@code image_format} is not supported.",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for image object.",
"""
$INVALID_OPERATION if there are no devices in {@code context} that support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
OORE,
OOHME
)}
"""
)
cl_mem(
"CreateImage3D",
"Creates a 3D image object.",
cl_context.IN("context", "a valid OpenCL context on which the image object is to be created"),
cl_mem_flags.IN("flags", "a bit-field that is used to specify allocation and usage information about the image memory object being created", MemFlags),
const..cl_image_format_p.IN("image_format", "a pointer to a ##CLImageFormat structure that describes format properties of the image to be allocated"),
size_t.IN("image_width", "the width of the image in pixels"),
size_t.IN("image_height", "the height of the image in pixels"),
size_t.IN("image_depth", "the depth of the image in pixels. This must be a value > 1."),
size_t.IN(
"image_row_pitch",
"""
the scan-line pitch in bytes. This must be 0 if {@code host_ptr} is $NULL and can be either 0 or ≥ {@code image_width * size} of element in
bytes if {@code host_ptr} is not $NULL. If {@code host_ptr} is not $NULL and {@code image_row_pitch} = 0, {@code image_row_pitch} is calculated as
{@code image_width * size of element} in bytes. If {@code image_row_pitch} is not 0, it must be a multiple of the image element size in bytes.
"""
),
size_t.IN(
"image_slice_pitch",
"""
the size in bytes of each 2D slice in the 3D image. This must be 0 if {@code host_ptr} is $NULL and can be either 0 or ≥
{@code image_row_pitch * image_height} if {@code host_ptr} is not $NULL. If {@code host_ptr} is not $NULL and {@code image_slice_pitch = 0},
{@code image_slice_pitch} is calculated as {@code image_row_pitch * image_height}. If {@code image_slice_pitch} is not 0, it must be a multiple of
the {@code image_row_pitch}.
"""
),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT)..nullable..void_p.IN(
"host_ptr",
"""
a pointer to the image data that may already be allocated by the application. The size of the buffer that {@code host_ptr} points to must be ≥
{@code image_slice_pitch * image_depth}. The size of each element in bytes must be a power of 2. The image data specified by {@code host_ptr} is
stored as a linear sequence of adjacent 2D slices. Each 2D slice is a linear sequence of adjacent scanlines. Each scanline is a linear sequence of
image elements.
"""
),
ERROR_RET,
returnDoc =
"""
a valid non-zero image object and $errcode_ret is set to $SUCCESS if the image object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_VALUE if values specified in {@code flags} are not valid.",
"$INVALID_IMAGE_FORMAT_DESCRIPTOR if values specified in {@code image_format} are not valid or if {@code image_format} is $NULL.",
"""
$INVALID_IMAGE_SIZE if {@code image_width}, {@code image_height} are 0 or if {@code image_depth} ≤ 1 or if they exceed values
specified in #DEVICE_IMAGE3D_MAX_WIDTH, #DEVICE_IMAGE3D_MAX_HEIGHT or #DEVICE_IMAGE3D_MAX_DEPTH respectively for
all devices in {@code context} or if values specified by {@code image_row_pitch} and {@code image_slice_pitch} do not follow rules described in the
argument descriptions.
""",
"""
$INVALID_HOST_PTR if {@code host_ptr} is $NULL and #MEM_USE_HOST_PTR or #MEM_COPY_HOST_PTR are set in flags or if
{@code host_ptr} is not $NULL but #MEM_COPY_HOST_PTR or #MEM_USE_HOST_PTR are not set in flags.
""",
"#IMAGE_FORMAT_NOT_SUPPORTED if the {@code image_format} is not supported.",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for image object.",
"""
$INVALID_OPERATION if there are no devices in {@code context} that support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
OORE,
OOHME
)}
"""
)
cl_int(
"GetSupportedImageFormats",
"""
Can be used to get the list of image formats supported by an OpenCL implementation when the following information about an image memory object is
specified:
${ul(
"Context",
"Image type – 1D, 2D, or 3D image, 1D image buffer, 1D or 2D image array",
"Image object allocation information"
)}
{@code clGetSupportedImageFormats} returns a union of image formats supported by all devices in the context.
""",
cl_context.IN("context", "a valid OpenCL context on which the image object(s) will be created"),
cl_mem_flags.IN("flags", "a bit-field that is used to specify allocation and usage information about the image memory object being created", MemFlags),
cl_mem_object_type.IN("image_type", "the image type", cl_mem_object_types),
AutoSize("image_formats")..cl_uint.IN(
"num_entries",
"the number of entries that can be returned in the memory location given by {@code image_formats}"
),
nullable..cl_image_format_p.OUT(
"image_formats",
"""
a pointer to a memory location where the list of supported image formats are returned. Each entry describes a ##CLImageFormat structure
supported by the OpenCL implementation. If {@code image_formats} is $NULL, it is ignored.
"""
),
Check(1)..nullable..cl_uint_p.OUT(
"num_image_formats",
"""
the actual number of supported image formats for a specific context and values specified by {@code flags}. If {@code num_image_formats} is $NULL, it
is ignored.
"""
),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICE,
"$INVALID_VALUE if {@code flags} or {@code image_type} are not valid, or if {@code num_entries} is 0 and {@code image_formats} is not $NULL.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueReadImage",
"""
Enqueues a command to read from an image or image array object to host memory.
Calling {@code clEnqueueReadImage} to read a region of the image with the {@code ptr} argument value set to
${code("host_ptr + (origin[2] * image slice pitch + origin[1] * image row pitch + origin[0] * bytes per pixel)")}, where {@code host_ptr} is a pointer
to the memory region specified when the image being read is created with #MEM_USE_HOST_PTR, must meet the following requirements in order to
avoid undefined behavior:
${ul(
"All commands that use this image object have finished execution before the read command begins execution.",
"The row_pitch and slice_pitch argument values in clEnqueueReadImage must be set to the image row pitch and slice pitch.",
"The image object is not mapped.",
"The image object is not used by any command-queue until the read command has finished execution."
)}
""",
cl_command_queue.IN(
"command_queue",
"the command-queue in which the read command will be queued. {@code command_queue} and {@code image} must be created with the same OpenCL context."
),
cl_mem.IN("image", "a valid image or image array object"),
cl_bool.IN(
"blocking_read",
"""
indicates if the read operation is blocking or non-blocking.
If {@code blocking_read} is $TRUE i.e. the read command is blocking, {@code clEnqueueReadImage} does not return until the buffer data has
been read and copied into memory pointed to by {@code ptr}.
If {@code blocking_read} is $FALSE i.e. the read command is non-blocking, {@code clEnqueueReadImage} queues a non-blocking read command
and returns. The contents of the buffer that {@code ptr} points to cannot be used until the read command has completed. The {@code event} argument
returns an event object which can be used to query the execution status of the read command. When the read command has completed, the contents of
the buffer that {@code ptr} points to can be used by the application.
"""
),
Check(3)..const..size_t_p.IN(
"origin",
"""
defines the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code image} is a 2D image object, {@code origin[2]} must be 0. If {@code image}
is a 1D image or 1D image buffer object, {@code origin[1]} and {@code origin[2]} must be 0. If {@code image} is a 1D image array object,
{@code origin[2]} must be 0. If {@code image} is a 1D image array object, {@code origin[1]} describes the image index in the 1D image array. If
{@code image} is a 2D image array object, {@code origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
defines the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and
the number of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If
{@code image} is a 2D image object, {@code region[2]} must be 1. If {@code image} is a 1D image or 1D image buffer object, {@code region[1]} and
{@code region[2]} must be 1. If {@code image} is a 1D image array object, {@code region[2]} must be 1. The values in {@code region} cannot be 0.
"""
),
size_t.IN(
"row_pitch",
"""
the length of each row in bytes. This value must be greater than or equal to the {@code element size in bytes * width}. If {@code row_pitch} is set
to 0, the appropriate row pitch is calculated based on the size of each element in bytes multiplied by {@code width}.
"""
),
size_t.IN(
"slice_pitch",
"""
the size in bytes of the 2D slice of the 3D region of a 3D image or each image of a 1D or 2D image array being read. This must be 0 if {@code image}
is a 1D or 2D image. This value must be greater than or equal to {@code row_pitch * height}. If {@code slice_pitch} is set to 0, the appropriate
slice pitch is calculated based on the {@code row_pitch * height}.
"""
),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..void_p.OUT("ptr", "the pointer to a buffer in host memory where image data is to be read from"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue} and {@code image} are not the same or if the context associated
with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code image} is not a valid image object.",
"""
$INVALID_VALUE if the region being read specified by {@code origin} and {@code region} is out of bounds or if {@code ptr} is a
$NULL value.
""",
"""
$INVALID_VALUE if values in {@code origin} and {@code region} do not follow rules described in the argument description for
{@code origin} and {@code region}.
""",
IEWLE,
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code image} are not
supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code image} are not supported by device associated
with queue.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code image}.",
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
"""
$INVALID_OPERATION if {@code clEnqueueReadImage} is called on image which has been created with CL12#MEM_HOST_WRITE_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
"""
$INVALID_OPERATION if {@code clEnqueueWriteImage} is called on image which has been created with CL12#MEM_HOST_READ_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
ESEFEIWLE("read"),
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueWriteImage",
"""
Enqueues a command to write to an image or image array object from host memory.
Calling {@code clEnqueueWriteImage} to update the latest bits in a region of the image with the {@code ptr} argument value set to
${code("host_ptr + (origin[2] * image slice pitch + origin[1] * image row pitch + origin[0] * bytes per pixel)")}, where {@code host_ptr} is a pointer
to the memory region specified when the image being written is created with #MEM_USE_HOST_PTR, must meet the following requirements in order
to avoid undefined behavior:
${ul(
"The host memory region being written contains the latest bits when the enqueued write command begins execution.",
"The input_row_pitch and input_slice_pitch argument values in clEnqueueWriteImage must be set to the image row pitch and slice pitch.",
"The image object is not mapped.",
"The image object is not used by any command-queue until the write command has finished execution."
)}
""",
cl_command_queue.IN(
"command_queue",
"the command-queue in which the write command will be queued. {@code command_queue} and {@code image} must be created with the same OpenCL context."
),
cl_mem.IN("image", "a valid image or image array object"),
cl_bool.IN(
"blocking_write",
"""
indicates if the read operation is blocking or non-blocking.
If {@code blocking_write} is $TRUE, the OpenCL implementation copies the data referred to by {@code ptr} and enqueues the write command in the
command-queue. The memory pointed to by {@code ptr} can be reused by the application after the {@code clEnqueueWriteImage} call returns.
If {@code blocking_write} is $FALSE, the OpenCL implementation will use {@code ptr} to perform a non-blocking write. As the write is non-blocking
the implementation can return immediately. The memory pointed to by {@code ptr} cannot be reused by the application after the call returns. The
{@code event} argument returns an event object which can be used to query the execution status of the write command. When the write command has
completed, the memory pointed to by {@code ptr} can then be reused by the application.
"""
),
Check(3)..const..size_t_p.IN(
"origin",
"""
defines the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code image} is a 2D image object, {@code origin[2]} must be 0. If {@code image}
is a 1D image or 1D image buffer object, {@code origin[1]} and {@code origin[2]} must be 0. If {@code image} is a 1D image array object,
{@code origin[2]} must be 0. If {@code image} is a 1D image array object, {@code origin[1]} describes the image index in the 1D image array. If
{@code image} is a 2D image array object, {@code origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
defines the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and
the number of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If
{@code image} is a 2D image object, {@code region[2]} must be 1. If {@code image} is a 1D image or 1D image buffer object, {@code region[1]} and
{@code region[2]} must be 1. If {@code image} is a 1D image array object, {@code region[2]} must be 1. The values in {@code region} cannot be 0.
"""
),
size_t.IN(
"input_row_pitch",
"""
the length of each row in bytes. This value must be greater than or equal to the {@code element size in bytes * width}. If {@code input_row_pitch} is set
to 0, the appropriate row pitch is calculated based on the size of each element in bytes multiplied by {@code width}.
"""
),
size_t.IN(
"input_slice_pitch",
"""
the size in bytes of the 2D slice of the 3D region of a 3D image or each image of a 1D or 2D image array being written. This must be 0 if {@code image}
is a 1D or 2D image. This value must be greater than or equal to {@code input_row_pitch * height}. If {@code input_slice_pitch} is set to 0, the appropriate
slice pitch is calculated based on the {@code input_row_pitch * height}.
"""
),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..const..void_p.IN("ptr", "the pointer to a buffer in host memory where image data is to be written to"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue} and {@code image} are not the same or if the context associated
with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code image} is not a valid image object.",
"""
$INVALID_VALUE if the region being written specified by {@code origin} and {@code region} is out of bounds or if {@code ptr} is a
$NULL value.
""",
"""
$INVALID_VALUE if values in {@code origin} and {@code region} do not follow rules described in the argument description for
{@code origin} and {@code region}.
""",
IEWLE,
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code image} are not
supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code image} are not supported by device associated
with queue.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code image}.",
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
"""
$INVALID_OPERATION if {@code clEnqueueReadImage} is called on image which has been created with CL12#MEM_HOST_WRITE_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
"""
$INVALID_OPERATION if {@code clEnqueueWriteImage} is called on image which has been created with CL12#MEM_HOST_READ_ONLY or
CL12#MEM_HOST_NO_ACCESS.
""",
ESEFEIWLE("write"),
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueCopyImage",
"""
Enqueues a command to copy image objects. {@code src_image} and {@code dst_image} can be 1D, 2D, 3D image or a 1D, 2D image array objects allowing us to
perform the following actions:
${ul(
"Copy a 1D image object to a 1D image object.",
"Copy a 1D image object to a scanline of a 2D image object and vice-versa.",
"Copy a 1D image object to a scanline of a 2D slice of a 3D image object and vice-versa.",
"Copy a 1D image object to a scanline of a specific image index of a 1D or 2D image array object and vice-versa.",
"Copy a 2D image object to a 2D image object.",
"Copy a 2D image object to a 2D slice of a 3D image object and vice-versa.",
"Copy a 2D image object to a specific image index of a 2D image array object and vice-versa.",
"Copy images from a 1D image array object to a 1D image array object.",
"Copy images from a 2D image array object to a 2D image array object.",
"Copy a 3D image object to a 3D image object."
)}
""",
cl_command_queue.IN(
"command_queue",
"""
the command-queue in which the copy command will be queued. The OpenCL context associated with {@code command_queue}, {@code src_image} and
{@code dst_image} must be the same.
"""
),
cl_mem.IN("src_image", ""),
cl_mem.IN("dst_image", ""),
Check(3)..const..size_t_p.IN(
"src_origin",
"""
the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code src_image} is a 2D image object, {@code src_origin[2]} must be 0. If
{@code src_image} is a 1D image object, {@code src_origin[1]} and {@code src_origin[2]} must be 0. If {@code src_image} is a 1D image array object,
{@code src_origin[2]} must be 0. If {@code src_image} is a 1D image array object, {@code src_origin[1]} describes the image index in the 1D image
array. If {@code src_image} is a 2D image array object, {@code src_origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"dst_origin",
"""
the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code dst_image} is a 2D image object, {@code dst_origin[2]} must be 0. If
{@code dst_image} is a 1D image or 1D image buffer object, {@code dst_origin[1]} and {@code dst_origin[2]} must be 0. If {@code dst_image} is a 1D
image array object, {@code dst_origin[2]} must be 0. If {@code dst_image} is a 1D image array object, {@code dst_origin[1]} describes the image
index in the 1D image array. If {@code dst_image} is a 2D image array object, {@code dst_origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and the number
of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If
{@code src_image} or {@code dst_image} is a 2D image object, {@code region[2]} must be 1. If {@code src_image} or {@code dst_image} is a 1D image or
1D image buffer object, {@code region[1]} and {@code region[2]} must be 1. If {@code src_image} or {@code dst_image} is a 1D image array object,
{@code region[2]} must be 1. The values in {@code region} cannot be 0.
"""
),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue}, {@code src_image} and {@code dst_image} are not the same or if the
context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code src_image} and {@code dst_image} are not valid image objects.",
"#IMAGE_FORMAT_MISMATCH if {@code src_image} and {@code dst_image} do not use the same image format.",
"""
$INVALID_VALUE if the 2D or 3D rectangular region specified by {@code src_origin} and {@code src_origin + region} refers to a region
outside {@code src_image}, or if the 2D or 3D rectangular region specified by {@code dst_origin} and {@code dst_origin + region} refers to a region
outside {@code dst_image}.
""",
"""
$INVALID_VALUE if values in {@code src_origin}, {@code dst_origin} and {@code region} do not follow rules described in the argument
description for {@code src_origin}, {@code dst_origin} and {@code region}.
""",
IEWLE,
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code src_image} or
{@code dst_image} are not supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code src_image} or {@code dst_image} are not
supported by device associated with queue.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code src_image} or {@code dst_image}.",
OORE,
OOHME,
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
"#MEM_COPY_OVERLAP if {@code src_image} and {@code dst_image} are the same image object and the source and destination regions overlap."
)}
"""
)
cl_int(
"EnqueueCopyImageToBuffer",
"Enqueues a command to copy an image object to a buffer object.",
cl_command_queue.IN(
"command_queue",
"a valid command-queue. The OpenCL context associated with {@code command_queue}, {@code src_image} and {@code dst_buffer} must be the same."
),
cl_mem.IN("src_image", "a valid image object"),
cl_mem.IN("dst_buffer", "a valid buffer object"),
Check(3)..const..size_t_p.IN(
"src_origin",
"""
the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code src_image} is a 2D image object, {@code src_origin[2]} must be 0. If
{@code src_image} is a 1D image object, {@code src_origin[1]} and {@code src_origin[2]} must be 0. If {@code src_image} is a 1D image array object,
{@code src_origin[2]} must be 0. If {@code src_image} is a 1D image array object, {@code src_origin[1]} describes the image index in the 1D image
array. If {@code src_image} is a 2D image array object, {@code src_origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and the number
of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If
{@code src_image} is a 2D image object, {@code region[2]} must be 1. If {@code src_image} is a 1D image or 1D image buffer object, {@code region[1]}
and {@code region[2]} must be 1. If {@code src_image} is a 1D image array object, {@code region[2]} must be 1. The values in {@code region} cannot
be 0.
"""
),
size_t.IN(
"dst_offset",
"""
the offset where to begin copying data into {@code dst_buffer}. The size in bytes of the region to be copied referred to as {@code dst_cb} is
computed as ${code("width * height * depth * bytes/image element")} if {@code src_image} is a 3D image object, is computed as
${code("width * height * bytes/image element")} if {@code src_image} is a 2D image, is computed as
${code("width * height * arraysize * bytes/image element")} if {@code src_image} is a 2D image array object, is computed as
${code("width * bytes/image element")} if {@code src_image} is a 1D image or 1D image buffer object and is computed as
${code("width * arraysize * bytes/image element")} if {@code src_image} is a 1D image array object.
"""
),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue}, {@code src_image} and {@code dst_buffer} are not the same or if
the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"""
$INVALID_MEM_OBJECT if {@code src_image} is not a valid image object or {@code dst_buffer} is not a valid buffer object or if
{@code src_image} is a 1D image buffer object created from {@code dst_buffer}.
""",
"""
$INVALID_VALUE if the 1D, 2D or 3D rectangular region specified by {@code src_origin} and {@code src_origin + region} refers to a region
outside {@code src_image}, or if the region specified by {@code dst_offset} and {@code dst_offset + dst_cb} to a region outside {@code dst_buffer}.
""",
"""
$INVALID_VALUE if values in {@code src_origin} and region do not follow rules described in the argument description for
{@code src_origin} and {@code region}.
""",
IEWLE,
MSBOE("dst_buffer"),
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code src_image} are not
supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code src_image} are not supported by device
associated with queue.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code src_image} or {@code dst_buffer}.",
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueCopyBufferToImage",
"Enqueues a command to copy a buffer object to an image object.",
cl_command_queue.IN(
"command_queue",
"a valid command-queue. The OpenCL context associated with {@code command_queue}, {@code src_buffer} and {@code dst_image} must be the same."
),
cl_mem.IN("src_buffer", "a valid buffer object"),
cl_mem.IN("dst_image", "a valid image object"),
size_t.IN("src_offset", "the offset where to begin copying data from {@code src_buffer}"),
Check(3)..const..size_t_p.IN(
"dst_origin",
"""
the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code dst_image} is a 2D image object, {@code dst_origin[2]} must be 0. If
{@code dst_image} is a 1D image or 1D image buffer object, {@code dst_origin[1]} and {@code dst_origin[2]} must be 0. If {@code dst_image} is a 1D
image array object, {@code dst_origin[2]} must be 0. If {@code dst_image} is a 1D image array object, {@code dst_origin[1]} describes the image
index in the 1D image array. If {@code dst_image} is a 2D image array object, {@code dst_origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and the number
of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If
{@code dst_image} is a 2D image object, {@code region[2]} must be 1. If {@code dst_image} is a 1D image or
1D image buffer object, {@code region[1]} and {@code region[2]} must be 1. If {@code dst_image} is a 1D image array object,
{@code region[2]} must be 1. The values in {@code region} cannot be 0.
"""
),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"""
$INVALID_CONTEXT if the context associated with {@code command_queue}, {@code src_buffer} and {@code dst_image} are not the same or if
the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"""
$INVALID_MEM_OBJECT if {@code src_buffer} is not a valid buffer object or {@code dst_image} is not a valid image object or if
{@code dst_image} is a 1D image buffer object created from {@code src_buffer}.
""",
"""
$INVALID_VALUE if the 1D, 2D or 3D rectangular region specified by {@code dst_origin} and {@code dst_origin + region} refer to a region
outside {@code dst_image}, or if the region specified by {@code src_offset} and {@code src_offset + src_cb refer} to a region outside
{@code src_buffer}.
""",
"""
$INVALID_VALUE if values in {@code dst_origin} and {@code region} do not follow rules described in the argument description for
{@code dst_origin} and {@code region}.
""",
IEWLE,
MSBOE("src_buffer"),
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code dst_image} are not
supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code dst_image} are not supported by device
associated with queue.
""",
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code src_buffer} or {@code dst_image}.",
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
OORE,
OOHME
)}
"""
)
customMethod("""
private static long getMemObjectInfoPointer(long cl_mem, int param_name) {
try ( MemoryStack stack = stackPush() ) {
PointerBuffer pp = stack.pointers(0);
return clGetMemObjectInfo(cl_mem, param_name, pp, null) == CL_SUCCESS ? pp.get(0) : NULL;
}
}
""")
(MapPointer("(int)getMemObjectInfoPointer(image, CL_MEM_SIZE)")..void_p)(
"EnqueueMapImage",
"""
Enqueues a command to map a region in the image object given by {@code image} into the host address space and returns a pointer to this mapped region.
The pointer returned maps a 1D, 2D or 3D region starting at {@code origin} and is at least {@code region[0]} pixels in size for a 1D image, 1D image
buffer or 1D image array, {@code (image_row_pitch * region[1])} pixels in size for a 2D image or 2D image array, and
{@code (image_slice_pitch * region[2])} pixels in size for a 3D image. The result of a memory access outside this region is undefined.
If the image object is created with #MEM_USE_HOST_PTR set in {@code mem_flags}, the following will be true:
${ul(
"""
The {@code host_ptr} specified in CL12#CreateImage() is guaranteed to contain the latest bits in the region being mapped when the
{@code clEnqueueMapImage} command has completed.
""",
"The pointer value returned by {@code clEnqueueMapImage} will be derived from the {@code host_ptr} specified when the image object is created."
)}
Mapped image objects are unmapped using #EnqueueUnmapMemObject().
""",
cl_command_queue.IN("command_queue", "a valid command-queue"),
cl_mem.IN("image", "a valid image object. The OpenCL context associated with {@code command_queue} and {@code image} must be the same."),
cl_bool.IN(
"blocking_map",
"""
indicates if the map operation is blocking or non-blocking.
If {@code blocking_map} is $TRUE, {@code clEnqueueMapImage} does not return until the specified region in image is mapped into the host address
space and the application can access the contents of the mapped region using the pointer returned by {@code clEnqueueMapImage}.
If {@code blocking_map} is $FALSE i.e. map operation is non-blocking, the pointer to the mapped region returned by {@code clEnqueueMapImage}
cannot be used until the map command has completed. The {@code event} argument returns an event object which can be used to query the execution
status of the map command. When the map command is completed, the application can access the contents of the mapped region using the pointer
returned by {@code clEnqueueMapImage}.
"""
),
cl_map_flags.IN("map_flags", "a bit-field", MapFlags),
Check(3)..const..size_t_p.IN(
"origin",
"""
the {@code (x, y, z)} offset in pixels in the 1D, 2D or 3D image, the {@code (x, y)} offset and the image index in the 2D image array or the
{@code (x)} offset and the image index in the 1D image array. If {@code image} is a 2D image object, {@code origin[2]} must be 0. If {@code image}
is a 1D image or 1D image buffer object, {@code origin[1]} and {@code origin[2]} must be 0. If {@code image} is a 1D image array object,
{@code origin[2]} must be 0. If {@code image} is a 1D image array object, {@code origin[1]} describes the image index in the 1D image array. If
{@code image} is a 2D image array object, {@code origin[2]} describes the image index in the 2D image array.
"""
),
Check(3)..const..size_t_p.IN(
"region",
"""
the {@code (width, height, depth)} in pixels of the 1D, 2D or 3D rectangle, the {@code (width, height)} in pixels of the 2D rectangle and the number
of images of a 2D image array or the {@code (width)} in pixels of the 1D rectangle and the number of images of a 1D image array. If {@code image} is
a 2D image object, {@code region[2]} must be 1. If {@code image} is a 1D image or 1D image buffer object, {@code region[1]} and {@code region[2]}
must be 1. If {@code image} is a 1D image array object, {@code region[2]} must be 1. The values in {@code region} cannot be 0.
"""
),
Check(1)..size_t_p.OUT("image_row_pitch", "the scan-line pitch in bytes for the mapped region. This must be a non-$NULL value."),
Check(1)..nullable..size_t_p.OUT(
"image_slice_pitch",
"""
returns the size in bytes of each 2D slice of a 3D image or the size of each 1D or 2D image in a 1D or 2D image array for the mapped region. For a
1D and 2D image, zero is returned if this argument is not $NULL. For a 3D image, 1D and 2D image array, {@code image_slice_pitch} must be a non-$NULL
value.
"""
),
NEWL,
EWL,
EVENT,
ERROR_RET,
returnDoc =
"""
a pointer to the mapped region. The $errcode_ret is set to $SUCCESS. A $NULL pointer is returned otherwise with one of the following error values
returned in $errcode_ret:
${ul(
ICQE,
"""
$INVALID_CONTEXT if context associated with {@code command_queue} and image are not the same or if context associated with
{@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_MEM_OBJECT if {@code image} is not a valid image object.",
"""
$INVALID_VALUE if region being mapped given by {@code (origin, origin+region)} is out of bounds or if values specified in
{@code map_flags} are not valid.
""",
"""
$INVALID_VALUE if values in {@code origin} and {@code region} do not follow rules described in the argument description for {@code origin}
and {@code region}.
""",
"$INVALID_VALUE if {@code image_row_pitch} is $NULL.",
"$INVALID_VALUE if {@code image} is a 3D image, 1D or 2D image array object and {@code image_slice_pitch} is $NULL.",
IEWLE,
"""
$INVALID_IMAGE_SIZE if image dimensions (image width, height, specified or compute row and/or slice pitch) for {@code image} are not
supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if image format (image channel order and data type) for {@code image} are not supported by device associated
with queue.
""",
"""
#MAP_FAILURE if there is a failure to map the requested region into the host address space. This error cannot occur for image objects
created with #MEM_USE_HOST_PTR or #MEM_ALLOC_HOST_PTR.
""",
ESEFEIWLE("map"),
"#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with {@code image}.",
"""
$INVALID_OPERATION if the device associated with {@code command_queue} does not support images (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
"""
$INVALID_OPERATION if {@code image} has been created with CL12#MEM_HOST_WRITE_ONLY or CL12#MEM_HOST_NO_ACCESS and
#MAP_READ is set in {@code map_flags} or if image has been created with CL12#MEM_HOST_READ_ONLY or
CL12#MEM_HOST_NO_ACCESS and #MAP_WRITE or CL12#MAP_WRITE_INVALIDATE_REGION is set in {@code map_flags}.
""",
OORE,
OOHME
)}
"""
)
cl_int(
"GetImageInfo",
"Returns information specific to an image object.",
cl_mem.IN("image", "the image object being queried"),
cl_image_info.IN("param_name", "the information to query", ImageInfo),
PARAM_VALUE_SIZE,
MultiType(
PointerMapping.DATA_INT,
PointerMapping.DATA_POINTER
)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_MEM_OBJECT if {@code image} is a not a valid image object.",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainMemObject",
"""
Increments the {@code memobj} reference count.
#CreateBuffer(), CL11#CreateSubBuffer() and CL12#CreateImage() perform an implicit retain.
""",
cl_mem.IN("memobj", "the memory object to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_MEM_OBJECT if {@code memobj} is not a valid memory object (buffer or image object).",
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseMemObject",
"""
Decrements the {@code memobj} reference count.
After the {@code memobj} reference count becomes zero and commands queued for execution on a command-queue(s) that use {@code memobj} have finished, the
memory object is deleted. If {@code memobj} is a buffer object, {@code memobj} cannot be deleted until all sub-buffer objects associated with
{@code memobj} are deleted.
""",
cl_mem.IN("memobj", "the memory object to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_MEM_OBJECT if {@code memobj} is not a valid memory object.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueUnmapMemObject",
"""
Enqueues a command to unmap a previously mapped region of a memory object. Reads or writes from the host using the pointer returned by
#EnqueueMapBuffer() or #EnqueueMapImage() are considered to be complete.
#EnqueueMapBuffer(), and #EnqueueMapImage() increments the mapped count of the memory object. The initial mapped count value of the memory object is zero.
Multiple calls to #EnqueueMapBuffer(), or #EnqueueMapImage() on the same memory object will increment this mapped count by appropriate number of calls.
{@code clEnqueueUnmapMemObject} decrements the mapped count of the memory object. #EnqueueMapBuffer(), and #EnqueueMapImage() act as synchronization points
for a region of the buffer object being mapped.
""",
cl_command_queue.IN("command_queue", "a valid command-queue"),
cl_mem.IN("memobj", "a valid memory object. The OpenCL context associated with {@code command_queue} and {@code memobj} must be the same."),
void_p.IN("mapped_ptr", "the host address returned by a previous call to #EnqueueMapBuffer(), or #EnqueueMapImage() for {@code memobj}"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"$INVALID_MEM_OBJECT if {@code memobj} is not a valid memory object.",
"$INVALID_VALUE if {@code mapped_ptr} is not a valid pointer returned by #EnqueueMapBuffer(), or #EnqueueMapImage() for {@code memobj}.",
IEWLE,
OORE,
OOHME,
"""
$INVALID_CONTEXT if context associated with {@code command_queue} and {@code memobj} are not the same or if the context associated with
{@code command_queue} and events in {@code event_wait_list} are not the same.
"""
)}
"""
)
cl_int(
"GetMemObjectInfo",
"Returns information that is common to all memory objects (buffer and image objects).",
cl_mem.IN("memobj", "the memory object being queried"),
cl_mem_info.IN("param_name", "the information to query", MemInfo),
PARAM_VALUE_SIZE,
MultiType(
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_POINTER
)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_MEM_OBJECT if {@code memobj} is a not a valid memory object.",
OORE,
OOHME
)}
"""
)
cl_sampler(
"CreateSampler",
"""
Creates a sampler object.
A sampler object describes how to sample an image when the image is read in the kernel. The built-in functions to read from an image in a kernel take a
sampler as an argument. The sampler arguments to the image read function can be sampler objects created using OpenCL functions and passed as argument
values to the kernel or can be samplers declared inside a kernel.
""",
cl_context.IN("context", "a valid OpenCL context"),
cl_bool.IN("normalized_coords", "determines if the image coordinates specified are normalized or not"),
cl_addressing_mode.IN("addressing_mode", "specifies how out-of-range image coordinates are handled when reading from an image", AddressingModes),
cl_filter_mode.IN("filter_mode", "the type of filter that must be applied when reading an image", FilterModes),
ERROR_RET,
returnDoc =
"""
a valid non-zero sampler object and $errcode_ret is set to $SUCCESS if the sampler object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"""
$INVALID_VALUE if {@code addressing_mode}, {@code filter_mode} or {@code normalized_coords} or combination of these argument values are
not valid.
""",
"""
$INVALID_OPERATION if images are not supported by any device associated with {@code context} (i.e. #DEVICE_IMAGE_SUPPORT is
$FALSE).
""",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainSampler",
"Increments the sampler reference count. #CreateSampler() performs an implicit retain.",
cl_sampler.IN("sampler", "the sample object to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_SAMPLER if sampler is not a valid sampler object.",
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseSampler",
"""
Decrements the sampler reference count. The sampler object is deleted after the reference count becomes zero and commands queued for execution on a
command-queue(s) that use sampler have finished.
""",
cl_sampler.IN("sampler", "the sample object to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_SAMPLER if {@code sampler} is not a valid sampler object.",
OORE,
OOHME
)}
"""
)
cl_int(
"GetSamplerInfo",
"Returns information about a sampler object.",
cl_sampler.IN("sampler", "the sampler being queried"),
cl_sampler_info.IN("param_name", "the information to query", SamplerInfo),
PARAM_VALUE_SIZE,
MultiType(
PointerMapping.DATA_INT,
PointerMapping.DATA_POINTER
)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_SAMPLER if {@code sampler} is a not a valid sampler object.",
OORE,
OOHME
)}
"""
)
cl_program(
"CreateProgramWithSource",
"""
Creates a program object for a context, and loads the source code specified by the text strings in the strings array into the program object. The
devices associated with the program object are the devices associated with {@code context}. The source code specified by strings is either an OpenCL C
program source, header or implementation-defined source for custom devices that support an online compiler.
""",
cl_context.IN("context", "a valid OpenCL context"),
AutoSize("strings", "lengths")..cl_uint.IN("count", "the number of elements in the {@code strings} and {@code lengths} arrays"),
PointerArray(cl_charUTF8_p, "string", "lengths")..const..cl_charUTF8_pp.IN(
"strings",
"an array of {@code count} pointers to optionally null-terminated character strings that make up the source code"
),
nullable..const..size_t_p.IN(
"lengths",
"""
an array with the number of chars in each string (the string length). If an element in {@code lengths} is zero, its accompanying string is
null-terminated. If {@code lengths} is $NULL, all strings in the {@code strings} argument are considered null-terminated. Any length value passed in
that is greater than zero excludes the null terminator in its count.
"""
),
ERROR_RET,
returnDoc =
"""
a valid non-zero program object and $errcode_ret is set to $SUCCESS if the program object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_VALUE if {@code count} is zero or if {@code strings} or any entry in {@code strings} is $NULL.",
OORE,
OOHME
)}
"""
)
cl_program(
"CreateProgramWithBinary",
"""
Creates a program object for a context, and loads the binary bits specified by {@code binary} into the program object.
The program binaries specified by {@code binaries} contain the bits that describe one of the following:
${ul(
"a program executable to be run on the device(s) associated with {@code context},",
"a compiled program for device(s) associated with {@code context}, or",
"a library of compiled programs for device(s) associated with {@code context}."
)}
The program binary can consist of either or both:
${ul(
"Device-specific code and/or,",
"Implementation-specific intermediate representation (IR) which will be converted to the device-specific code."
)}
OpenCL allows applications to create a program object using the program source or binary and build appropriate program executables. This can be very
useful as it allows applications to load program source and then compile and link to generate a program executable online on its first instance for
appropriate OpenCL devices in the system. These executables can now be queried and cached by the application. Future instances of the application
launching will no longer need to compile and link the program executables. The cached executables can be read and loaded by the application, which can
help significantly reduce the application initialization time.
""",
cl_context.IN("context", "a valid OpenCL context"),
AutoSize("binaries", "device_list", "lengths", "binary_status")..cl_uint.IN("num_devices", "the number of devices listed in {@code device_list}"),
const..cl_device_id_p.IN(
"device_list",
"""
a pointer to a list of devices that are in {@code context}. device_list must be a non-$NULL value. The binaries are loaded for devices specified in
this list.
"""
),
const..size_t_p.IN(
"lengths",
"an array of the size in bytes of the program binaries to be loaded for devices specified by {@code device_list}."
),
PointerArray(cl_uchar_p, "binary", "lengths")..const..cl_uchar_pp.IN(
"binaries",
"""
an array of pointers to program binaries to be loaded for devices specified by {@code device_list}. For each device given by {@code device_list[i]},
the pointer to the program binary for that device is given by {@code binaries[i]} and the length of this corresponding binary is given by
{@code lengths[i]}. {@code lengths[i]} cannot be zero and {@code binaries[i]} cannot be a $NULL pointer.
"""
),
nullable..cl_int_p.OUT(
"binary_status",
"""
returns whether the program binary for each device specified in device_list was loaded successfully or not. It is an array of {@code num_devices}
entries and returns $SUCCESS in {@code binary_status[i]} if binary was successfully loaded for device specified by {@code device_list[i]};
otherwise returns $INVALID_VALUE if {@code lengths[i]} is zero or if {@code binaries[i]} is a $NULL value or $INVALID_BINARY in
{@code binary_status[i]} if program binary is not a valid binary for the specified device. If {@code binary_status} is $NULL, it is ignored.
"""
),
ERROR_RET,
returnDoc =
"""
a valid non-zero program object and $errcode_ret is set to $SUCCESS if the program object is created successfully. Otherwise, it returns a $NULL
value with one of the following error values returned in $errcode_ret:
${ul(
ICE,
"$INVALID_VALUE if {@code device_list} is $NULL or {@code num_devices} is zero.",
"$INVALID_DEVICE if OpenCL devices listed in {@code device_list} are not in the list of devices associated with {@code context}.",
"$INVALID_VALUE if {@code lengths} or {@code binaries} are $NULL or if any entry in {@code lengths[i]} is zero or {@code binaries[i]} is $NULL.",
"$INVALID_BINARY if an invalid program binary was encountered for any device. {@code binary_status} will return specific status for each device.",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainProgram",
"Increments the {@code program} reference count. {@code clCreateProgram} does an implicit retain.",
cl_program.IN("program", "the program object to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PROGRAM if {@code program} is not a valid program object.",
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseProgram",
"""
Decrements the {@code program} reference count. The program object is deleted after all kernel objects associated with program have been deleted and the
program reference count becomes zero.
""",
cl_program.IN("program", "the program object to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PROGRAM if {@code program} is not a valid program object.",
OORE,
OOHME
)}
"""
)
cl_int(
"BuildProgram",
"""
Builds (compiles & links) a program executable from the program source or binary for all the devices or a specific device(s) in the OpenCL context
associated with {@code program}. OpenCL allows program executables to be built using the source or the binary. {@code clBuildProgram} must be called for
{@code program} created using either #CreateProgramWithSource() or #CreateProgramWithBinary() to build the program executable for one or more devices
associated with {@code program}. If {@code program} is created with #CreateProgramWithBinary(), then the program binary must be an executable binary (not
a compiled binary or library).
The executable binary can be queried using #GetProgramInfo() and can be specified to #CreateProgramWithBinary() to create a new program object.
""",
cl_program.IN("program", "the program object"),
AutoSize("device_list")..cl_uint.IN("num_devices", "the number of devices listed in {@code device_list}"),
SingleValue("device")..nullable..const..cl_device_id_p.IN(
"device_list",
"""
a pointer to a list of devices associated with {@code program}. If {@code device_list} is a $NULL value, the program executable is built for all
devices associated with {@code program} for which a source or binary has been loaded. If {@code device_list} is a non-$NULL value, the program
executable is built for devices specified in this list for which a source or binary has been loaded.
"""
),
const..cl_charASCII_p.IN(
"options",
"a pointer to a null-terminated string of characters that describes the build options to be used for building the program executable"
),
nullable..cl_program_callback.IN(
"pfn_notify",
"""
a function pointer to a notification routine. The notification routine is a callback function that an application can register and which will be
called when the program executable has been built (successfully or unsuccessfully). If {@code pfn_notify} is not $NULL, {@code clBuildProgram} does
not need to wait for the build to complete and can return immediately once the build operation can begin. The build operation can begin if the
context, program whose sources are being compiled and linked, list of devices and build options specified are all valid and appropriate host and
device resources needed to perform the build are available. If {@code pfn_notify} is $NULL, {@code clBuildProgram} does not return until the build
has completed. This callback function may be called asynchronously by the OpenCL implementation. It is the application's responsibility to ensure
that the callback function is thread-safe.
"""
),
nullable..voidptr.IN("user_data", "will be passed as an argument when {@code pfn_notify} is called. {@code user_data} can be $NULL."),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PROGRAM if {@code program} is not a valid program object.",
"$INVALID_VALUE if {@code device_list} is $NULL and {@code num_devices} is > 0, or if {@code device_list} is not $NULL and {@code num_devices} is 0.",
"$INVALID_VALUE if {@code pfn_notify} is $NULL but {@code user_data} is not $NULL.",
"$INVALID_DEVICE if OpenCL devices listed in {@code device_list} are not in the list of devices associated with program.",
"""
$INVALID_BINARY if {@code program} is created with #CreateProgramWithBinary() and devices listed in {@code device_list} do not have a valid
program binary loaded.
""",
"$INVALID_BUILD_OPTIONS if the build options specified by {@code options} are invalid.",
"""
$INVALID_OPERATION if the build of a program executable for any of the devices listed in {@code device_list} by a previous call to
{@code clBuildProgram} for {@code program} has not completed.
""",
"""
#COMPILER_NOT_AVAILABLE if {@code program} is created with #CreateProgramWithSource() and a compiler is not available i.e.
#DEVICE_COMPILER_AVAILABLE is set to $FALSE.
""",
"""
#BUILD_PROGRAM_FAILURE if there is a failure to build the program executable. This error will be returned if {@code clBuildProgram} does
not return until the build has completed.
""",
"$INVALID_OPERATION if there are kernel objects attached to {@code program}.",
"$INVALID_OPERATION if program was not created with #CreateProgramWithSource() or #CreateProgramWithBinary().",
OORE,
OOHME
)}
"""
)
cl_int(
"UnloadCompiler",
"""
Allows the implementation to release the resources allocated by the OpenCL compiler. This is a hint from the application and does not guarantee that the
compiler will not be used in the future or that the compiler will actually be unloaded by the implementation.
Calls to #BuildProgram() after #UnloadCompiler() will reload the compiler, if necessary, to build the appropriate program executable.
""",
returnDoc = "always $SUCCESS"
)
cl_int(
"GetProgramInfo",
"Returns information about a program object.",
cl_program.IN("program", "the program object being queried"),
cl_program_info.IN("param_name", "the information to query", ProgramInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_PROGRAM if {@code program} is a not a valid program object.",
"""
$INVALID_PROGRAM_EXECUTABLE if {@code param_name} is CL12#PROGRAM_NUM_KERNELS or CL12#PROGRAM_KERNEL_NAMES and a
successful program executable has not been built for at least one device in the list of devices associated with {@code program}.
""",
OORE,
OOHME
)}
"""
)
cl_int(
"GetProgramBuildInfo",
"Returns build information for each device in the program object.",
cl_program.IN("program", "the program object being queried"),
cl_device_id.IN("device", "the device for which build information is being queried. {@code device} must be a valid device associated with {@code program}."),
cl_program_info.IN("param_name", "the information to query", ProgramBuildInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_DEVICE if {@code device} is not in the list of devices associated with program.",
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_PROGRAM if {@code program} is a not a valid program object.",
OORE,
OOHME
)}
"""
)
cl_kernel(
"CreateKernel",
"""
Creates a kernel object.
A kernel is a function declared in a program. A kernel is identified by the {@code __kernel} qualifier applied to any function in a program. A kernel
object encapsulates the specific {@code __kernel} function declared in a program and the argument values to be used when executing this {@code __kernel}
function.
Kernel objects can only be created once you have a program object with a valid program source or binary loaded into the program object and the program
executable has been successfully built for one or more devices associated with program. No changes to the program executable are allowed while there are
kernel objects associated with a program object. This means that calls to #BuildProgram() and CL12#CompileProgram() return
$INVALID_OPERATION if there are kernel objects attached to a program object. The OpenCL context associated with program will be the context
associated with kernel. The list of devices associated with program are the devices associated with kernel. Devices associated with a program object for
which a valid program executable has been built can be used to execute kernels declared in the program object.
""",
cl_program.IN("program", "a program object with a successfully built executable"),
const..cl_charASCII_p.IN("kernel_name", "a function name in the program declared with the {@code __kernel} qualifier"),
ERROR_RET,
returnDoc =
"""
a valid non-zero kernel object and $errcode_ret is set to $SUCCESS if the kernel object is created successfully. Otherwise, it returns a $NULL value
with one of the following error values returned in $errcode_ret:
${ul(
"$INVALID_PROGRAM if {@code program} is not a valid program object.",
"$INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for {@code program}.",
"$INVALID_KERNEL_NAME if {@code kernel_name} is not found in {@code program}.",
"""
$INVALID_KERNEL_DEFINITION if the function definition for {@code __kernel} function given by {@code kernel_name} such as the number of
arguments, the argument types are not the same for all devices for which the program executable has been built.
""",
"$INVALID_VALUE if {@code kernel_name} is $NULL.",
OORE,
OOHME
)}
"""
)
cl_int(
"CreateKernelsInProgram",
"""
Creates kernel objects for all kernel functions in {@code program}. Kernel objects are not created for any {@code __kernel} functions in {@code program}
that do not have the same function definition across all devices for which a program executable has been successfully built.
See #CreateKernel() for more details.
""",
cl_program.IN("program", "a program object with a successfully built executable"),
AutoSize("kernels")..cl_uint.IN("num_kernels", "the size of memory pointed to by kernels specified as the number of cl_kernel entries"),
nullable..cl_kernel_p.OUT(
"kernels",
"""
the buffer where the kernel objects for kernels in {@code program} will be returned. If {@code kernels} is $NULL, it is ignored. If {@code kernels}
is not $NULL, {@code num_kernels} must be greater than or equal to the number of kernels in {@code program}.
"""
),
Check(1)..nullable..cl_uint_p.OUT(
"num_kernels_ret",
"the number of kernels in {@code program}. If {@code num_kernels_ret} is $NULL, it is ignored."
),
returnDoc =
"""
$SUCCESS if the kernel objects were successfully allocated. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PROGRAM if {@code program} is not a valid program object.",
"$INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for any device in {@code program}.",
"$INVALID_VALUE if {@code kernels} is not $NULL and {@code num_kernels} is less than the number of kernels in {@code program}.",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainKernel",
"Increments the {@code kernel} reference count. #CreateKernel() or #CreateKernelsInProgram() do an implicit retain.",
cl_kernel.IN("kernel", "the kernel to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_KERNEL if kernel is not a valid kernel object.",
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseKernel",
"""
Decrements the {@code kernel} reference count.
The kernel object is deleted once the number of instances that are retained to {@code kernel} become zero and the kernel object is no longer needed by
any enqueued commands that use {@code kernel}.
""",
cl_kernel.IN("kernel", "the kernel to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_KERNEL if kernel is not a valid kernel object.",
OORE,
OOHME
)}
"""
)
cl_int(
"SetKernelArg",
"Set the argument value for a specific argument of a kernel.",
cl_kernel.IN("kernel", "a valid kernel object"),
cl_uint.IN(
"arg_index",
"""
the argument index. Arguments to the kernel are referred by indices that go from 0 for the leftmost argument to {@code n - 1}, where {@code n} is
the total number of arguments declared by a kernel.
For example, consider the following kernel:
${codeBlock("""
kernel void image_filter (
int n, int m,
__constant float *filter_weights,
__read_only image2d_t src_image,
__write_only image2d_t dst_image
) {
…
}
""")}
Argument index values for image_filter will be 0 for {@code n}, 1 for {@code m}, 2 for {@code filter_weights}, 3 for {@code src_image} and 4 for
{@code dst_image}.
<strong>NOTE</strong>: A kernel object does not update the reference count for objects such as memory, sampler objects specified as argument values
by {@code clSetKernelArg}, Users may not rely on a kernel object to retain objects specified as argument values to the kernel.
"""
),
AutoSize("arg_value")..size_t.IN(
"arg_size",
"""
the size of the argument value. If the argument is a memory object, the size is the size of the buffer or image object type. For arguments declared
with the {@code __local} qualifier, the size specified will be the size in bytes of the buffer that must be allocated for the {@code __local}
argument. If the argument is of type {@code sampler_t}, the {@code arg_size} value must be equal to {@code sizeof(cl_sampler)}. For all other
arguments, the size will be the size of argument type.
"""
),
// optional generates clSetKernelArg(long kernel, int arg_index, long arg_size)
// MultiType generates clSetKernalArg(long kernel, int arg_index, <type>Buffer arg_value)
// SingleValue generates clSetKernelArg<xp>(long kernel, int arg_index, <p> arg<x-1>, ...), where x = 1..4
optional..MultiTypeAll..SingleValue("arg")..const..void_p.IN(
"arg_value",
"""
a pointer to data that should be used as the argument value for argument specified by {@code arg_index}. The argument data pointed to by
{@code arg_value} is copied and the {@code arg_value} pointer can therefore be reused by the application after {@code clSetKernelArg} returns. The
argument value specified is the value used by all API calls that enqueue kernel (#EnqueueNDRangeKernel() and #EnqueueTask()) until
the argument value is changed by a call to {@code clSetKernelArg} for {@code kernel}.
If the argument is a memory object (buffer, image or image array), the {@code arg_value} entry will be a pointer to the appropriate buffer, image or
image array object. The memory object must be created with the context associated with the kernel object. If the argument is a buffer object, the
{@code arg_value} pointer can be $NULL or point to a $NULL value in which case a $NULL value will be used as the value for the argument declared as
a pointer to {@code __global} or {@code __constant} memory in the kernel. If the argument is declared with the {@code __local} qualifier, the
{@code arg_value} entry must be $NULL. If the argument is of type {@code sampler_t}, the {@code arg_value} entry must be a pointer to the sampler
object.
If the argument is declared to be a pointer of a built-in scalar or vector type, or a user defined structure type in the global or constant address
space, the memory object specified as argument value must be a buffer object (or $NULL). If the argument is declared with the {@code __constant}
qualifier, the size in bytes of the memory object cannot exceed #DEVICE_MAX_CONSTANT_BUFFER_SIZE and the number of arguments declared as
pointers to {@code __constant} memory cannot exceed #DEVICE_MAX_CONSTANT_ARGS.
The memory object specified as argument value must be a 2D image object if the argument is declared to be of type {@code image2d_t}. The memory
object specified as argument value must be a 3D image object if argument is declared to be of type {@code image3d_t}. The memory object specified as
argument value must be a 1D image object if the argument is declared to be of type {@code image1d_t}. The memory object specified as argument value
must be a 1D image buffer object if the argument is declared to be of type {@code image1d_buffer_t}. The memory object specified as argument value
must be a 1D image array object if argument is declared to be of type {@code image1d_array_t}. The memory object specified as argument value must be
a 2D image array object if argument is declared to be of type {@code image2d_array_t}.
For all other kernel arguments, the {@code arg_value} entry must be a pointer to the actual data to be used as argument value.
"""
),
returnDoc =
"""
$SUCCESS if the function was executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_KERNEL if {@code kernel} is not a valid kernel object.",
"$INVALID_ARG_INDEX if {@code arg_index} is not a valid argument index.",
"$INVALID_ARG_VALUE if {@code arg_value} specified is not a valid value.",
"$INVALID_MEM_OBJECT for an argument declared to be a memory object when the specified {@code arg_value} is not a valid memory object.",
"$INVALID_SAMPLER for an argument declared to be of type {@code sampler_t} when the specified {@code arg_value} is not a valid sampler object.",
"""
$INVALID_ARG_SIZE if {@code arg_size} does not match the size of the data type for an argument that is not a memory object or if the
argument is a memory object and {@code arg_size != sizeof(cl_mem)} or if {@code arg_size} is zero and the argument is declared with the
{@code __local} qualifier or if the argument is a sampler and {@code arg_size != sizeof(cl_sampler)}.
""",
"""
$INVALID_ARG_VALUE if the argument is an image declared with the {@code read_only} qualifier and {@code arg_value} refers to an image
object created with {@code cl_mem_flags} of #MEM_WRITE_ONLY or if the image argument is declared with the {@code write_only} qualifier
and {@code arg_value} refers to an image object created with {@code cl_mem_flags} of #MEM_READ_ONLY.
""",
OORE,
OOHME
)}
"""
)
cl_int(
"GetKernelInfo",
"Returns information about a kernel object.",
cl_kernel.IN("kernel", "the kernel object being queried"),
cl_kernel_info.IN("param_name", "the information to query", KernelInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_KERNEL if {@code kernel} is a not a valid kernel object.",
OORE,
OOHME
)}
"""
)
cl_int(
"GetKernelWorkGroupInfo",
"Returns information about the kernel object that may be specific to a device.",
cl_kernel.IN("kernel", "the kernel object being queried"),
cl_device_id.IN(
"device",
"""
identifies a specific device in the list of devices associated with {@code kernel}. The list of devices is the list of devices in the OpenCL context
that is associated with {@code kernel}. If the list of devices associated with {@code kernel} is a single device, {@code device} can be a $NULL value.
"""
),
cl_kernel_work_group_info.IN("param_name", "the information to query", KernelWorkGroupInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_LONG, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_DEVICE if {@code device} is not in the list of devices associated with {@code kernel} or if {@code device} is $NULL but there is
more than one device associated with {@code kernel}.
""",
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"""
$INVALID_VALUE if {@code param_name} is CL12#KERNEL_GLOBAL_WORK_SIZE and {@code device} is not a custom device or kernel is
not a built-in kernel.
""",
"$INVALID_KERNEL if {@code kernel} is a not a valid kernel object.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueNDRangeKernel",
"Enqueues a command to execute a kernel on a device.",
cl_command_queue.IN("command_queue", "a valid command-queue. The kernel will be queued for execution on the device associated with {@code command_queue}."),
cl_kernel.IN("kernel", "a valid kernel object. The OpenCL context associated with {@code kernel} and {@code command_queue} must be the same."),
cl_uint.IN(
"work_dim",
"""
the number of dimensions used to specify the global work-items and work-items in the work-group. {@code work_dim} must be greater than zero and less
than or equal to #DEVICE_MAX_WORK_ITEM_DIMENSIONS.
"""
),
Check("work_dim")..nullable..const..size_t_p.IN(
"global_work_offset",
"""
can be used to specify an array of {@code work_dim} unsigned values that describe the offset used to calculate the global ID of a work-item. If
{@code global_work_offset} is $NULL, the global IDs start at offset ${code("(0, 0, … 0)")}.
"""
),
Check("work_dim")..nullable..const..size_t_p.IN(
"global_work_size",
"""
points to an array of {@code work_dim} unsigned values that describe the number of global work-items in {@code work_dim} dimensions that will
execute the kernel function. The total number of global work-items is computed as ${code("global_work_size[0] * … * global_work_size[work_dim – 1]")}.
"""
),
const..Check("work_dim")..nullable..size_t_p.IN(
"local_work_size",
"""
points to an array of {@code work_dim} unsigned values that describe the number of work-items that make up a work-group (also referred to as the
size of the work-group) that will execute the kernel specified by {@code kernel}. The total number of work-items in a work-group is computed as
${code("local_work_size[0] * … * local_work_size[work_dim – 1]")}. The total number of work-items in the work-group must be less than or equal to
the #DEVICE_MAX_WORK_GROUP_SIZE value and the number of work-items specified in ${code("local_work_size[0], … local_work_size[work_dim – 1]")}
must be less than or equal to the corresponding values specified by #DEVICE_MAX_WORK_ITEM_SIZES${code("[0]")}, …
#DEVICE_MAX_WORK_ITEM_SIZES${code("[work_dim – 1]")}. The explicitly specified {@code local_work_size} will be used to determine how to
break the global work-items specified by {@code global_work_size} into appropriate work-group instances. If {@code local_work_size} is specified, the
values specified in ${code("global_work_size[0], … global_work_size[work_dim - 1]")} must be evenly divisible by the corresponding values
specified in ${code("local_work_size[0], … local_work_size[work_dim – 1]")}.
The work-group size to be used for kernel can also be specified in the program source using the
${code("__attribute__((reqd_work_group_size(X, Y, Z)))")} qualifier. In this case the size of work group specified by {@code local_work_size} must
match the value specified by the {@code reqd_work_group_size} attribute qualifier.
{@code local_work_size} can also be a $NULL value in which case the OpenCL implementation will determine how to be break the global work-items into
appropriate work-group instances.
"""
),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the kernel execution was successfully queued. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_PROGRAM_EXECUTABLE if there is no successfully built program executable available for device associated with {@code command_queue}.",
ICQE,
"$INVALID_KERNEL if {@code kernel} is not a valid kernel object.",
"""
$INVALID_CONTEXT if context associated with {@code command_queue} and {@code kernel} are not the same or if the context associated with
{@code command_queue} and events in {@code event_wait_list} are not the same.
""",
"$INVALID_KERNEL_ARGS if the kernel argument values have not been specified.",
"$INVALID_WORK_DIMENSION if {@code work_dim} is not a valid value (i.e. a value between 1 and 3).",
"""
$INVALID_GLOBAL_WORK_SIZE if {@code global_work_size} is $NULL, or if any of the values specified in
${code("global_work_size[0], … global_work_size[work_dim – 1]")} are 0 or exceed the range given by the {@code sizeof(size_t)} for the device
on which the kernel execution will be enqueued.
""",
"""
$INVALID_GLOBAL_OFFSET if the value specified in {@code global_work_size} + the corresponding values in {@code global_work_offset} for
any dimensions is greater than the {@code sizeof(size_t)} for the device on which the kernel execution will be enqueued.
""",
"""
$INVALID_WORK_GROUP_SIZE if {@code local_work_size} is specified and number of work-items specified by {@code global_work_size} is not
evenly divisible by size of work-group given by {@code local_work_size} or does not match the work-group size specified for kernel using the
${code("__attribute__((reqd_work_group_size(X, Y, Z)))")} qualifier in program source.
""",
"""
$INVALID_WORK_GROUP_SIZE if {@code local_work_size} is specified and the total number of work-items in the work-group computed as
${code("local_work_size[0] * … * local_work_size[work_dim – 1]")} is greater than the value specified by #DEVICE_MAX_WORK_GROUP_SIZE
""",
"""
$INVALID_WORK_GROUP_SIZE if {@code local_work_size} is $NULL and the ${code("__attribute__((reqd_work_group_size(X, Y, Z)))")} qualifier
is used to declare the work-group size for kernel in the program source.
""",
"""
$INVALID_WORK_ITEM_SIZE if the number of work-items specified in any of ${code("local_work_size[0], … local_work_size[work_dim – 1]")}
is greater than the corresponding values specified by #DEVICE_MAX_WORK_ITEM_SIZES{@code [0]}, … #DEVICE_MAX_WORK_ITEM_SIZES{@code [work_dim – 1]}.
""",
"""
CL11#MISALIGNED_SUB_BUFFER_OFFSET if a sub-buffer object is specified as the value for an argument that is a buffer object and the offset
specified when the sub-buffer object is created is not aligned to #DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue.
""",
"""
$INVALID_IMAGE_SIZE if an image object is specified as an argument value and the image dimensions (image width, height, specified or
compute row and/or slice pitch) are not supported by device associated with queue.
""",
"""
#IMAGE_FORMAT_NOT_SUPPORTED if an image object is specified as an argument value and the image format (image channel order and data type)
is not supported by device associated with queue.
""",
"""
#OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources
needed to execute the kernel. For example, the explicitly specified {@code local_work_size} causes a failure to execute the kernel because of
insufficient resources such as registers or local memory. Another example would be the number of read-only image args used in kernel exceed the
#DEVICE_MAX_READ_IMAGE_ARGS value for device or the number of write-only image args used in kernel exceed the
#DEVICE_MAX_WRITE_IMAGE_ARGS value for device or the number of samplers used in kernel exceed #DEVICE_MAX_SAMPLERS for device.
""",
"""
#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with image or buffer objects specified
as arguments to kernel.
""",
IEWLE,
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueTask",
"""
Enqueues a command to execute a kernel on a device. The kernel is executed using a single work-item.
{@code clEnqueueTask} is equivalent to calling #EnqueueNDRangeKernel() with {@code work_dim = 1}, {@code global_work_offset = NULL},
{@code global_work_size[0]} set to 1 and {@code local_work_size[0]} set to 1.
""",
cl_command_queue.IN("command_queue", "a valid command-queue. The kernel will be queued for execution on the device associated with {@code command_queue}."),
cl_kernel.IN("kernel", "a valid kernel object. The OpenCL context associated with {@code kernel} and {@code command_queue} must be the same."),
NEWL,
EWL,
EVENT,
returnDoc = "$SUCCESS if the kernel execution was successfully queued. Otherwise, see #EnqueueNDRangeKernel()."
)
cl_int(
"EnqueueNativeKernel",
"Enqueues a command to execute a native C/C++ function not compiled using the OpenCL compiler.",
cl_command_queue.IN(
"command_queue",
"""
a valid command-queue. A native user function can only be executed on a command-queue created on a device that has #EXEC_NATIVE_KERNEL
capability set in #DEVICE_EXECUTION_CAPABILITIES.
"""
),
cl_native_kernel.IN("user_func", "a pointer to a host-callable user function"),
nullable..void_p.IN("args", "a pointer to the args list that {@code user_func} should be called with"),
AutoSize("args")..size_t.IN(
"cb_args",
"""
the size in bytes of the args list that {@code args} points to.
The data pointed to by {@code args} and {@code cb_args} bytes in size will be copied and a pointer to this copied region will be passed to
{@code user_func}. The copy needs to be done because the memory objects (cl_mem values) that args may contain need to be modified and replaced by
appropriate pointers to global memory. When {@code clEnqueueNativeKernel} returns, the memory region pointed to by args can be reused by the
application.
"""
),
AutoSize("mem_list", "args_mem_loc")..cl_uint.IN("num_mem_objects", "the number of buffer objects that are passed in {@code args}"),
SingleValue("memobj")..nullable..const..cl_mem_p.IN(
"mem_list",
"""
a list of valid buffer objects, if {@code num_mem_objects} > 0. The buffer object values specified in {@code mem_list} are memory object handles
(cl_mem values) returned by #CreateBuffer() or $NULL.
"""
),
SingleValue("memobj_loc")..nullable..const..void_pp.IN(
"args_mem_loc",
"""
a pointer to appropriate locations that {@code args} points to where memory object handles (cl_mem values) are stored. Before the user function is
executed, the memory object handles are replaced by pointers to global memory.
"""
),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the user function execution instance was successfully queued. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"$INVALID_CONTEXT if context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.",
"$INVALID_VALUE if {@code user_func} is $NULL.",
"""
$INVALID_VALUE if {@code args} is a $NULL value and {@code cb_args} > 0, or if {@code args} is a $NULL value and
{@code num_mem_objects} > 0.
""",
"$INVALID_VALUE if {@code args} is not $NULL and {@code cb_args} is 0.",
"$INVALID_VALUE if {@code num_mem_objects} > 0 and {@code mem_list} or {@code args_mem_loc} are $NULL.",
"$INVALID_VALUE if {@code num_mem_objects} = 0 and {@code mem_list} or {@code args_mem_loc} are not $NULL.",
"$INVALID_OPERATION if the device associated with {@code command_queue} cannot execute the native kernel.",
"$INVALID_MEM_OBJECT if one or more memory objects specified in {@code mem_list} are not valid or are not buffer objects.",
"""
#OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources
needed to execute the kernel.
""",
"""
#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with buffer objects specified as
arguments to kernel.
""",
IEWLE,
OORE,
OOHME
)}
"""
)
cl_int(
"WaitForEvents",
"""
Waits on the host thread for commands identified by event objects in {@code event_list} to complete. A command is considered complete if its execution
status is #COMPLETE or a negative value. The events specified in {@code event_list} act as synchronization points.
""",
AutoSize("event_list")..cl_uint.IN("num_events", "the number of events in {@code event_list}"),
SingleValue("event")..const..cl_event_p.IN("event_list", "the list of events"),
returnDoc =
"""
$SUCCESS if the execution status of all events in event_list is #COMPLETE. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_VALUE if {@code num_events} is zero or {@code event_list} is $NULL.",
"$INVALID_CONTEXT if events specified in {@code event_list} do not belong to the same context.",
"$INVALID_EVENT if event objects specified in {@code event_list} are not valid event objects.",
"CL11#EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST if the execution status of any of the events in {@code event_list} is a negative integer value.",
OORE,
OOHME
)}
"""
)
cl_int(
"GetEventInfo",
"""
Returns information about an event object.
Using {@code clGetEventInfo} to determine if a command identified by event has finished execution (i.e. #EVENT_COMMAND_EXECUTION_STATUS
returns #COMPLETE) is not a synchronization point. There are no guarantees that the memory objects being modified by command associated with
event will be visible to other enqueued commands.
""",
cl_event.IN("event", "the event object being queried"),
cl_event_info.IN("param_name", "the information to query", EventInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_INT, PointerMapping.DATA_POINTER)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_VALUE if information to query given in {@code param_name} cannot be queried for event.",
"$INVALID_EVENT if {@code event} is a not a valid event object.",
OORE,
OOHME
)}
"""
)
cl_int(
"RetainEvent",
"Increments the event reference count. The OpenCL commands that return an event perform an implicit retain.",
cl_event.IN("event", "the event to retain"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_EVENT if {@code event} is not a valid event object.",
OORE,
OOHME
)}
"""
)
cl_int(
"ReleaseEvent",
"""
Decrements the event reference count.
The event object is deleted once the reference count becomes zero, the specific command identified by this event has completed (or terminated) and there
are no commands in the command-queues of a context that require a wait for this event to complete.
<strong>NOTE</strong>: Developers should be careful when releasing their last reference count on events created by CL11#CreateUserEvent() that
have not yet been set to status of #COMPLETE or an error. If the user event was used in the {@code event_wait_list} argument passed to a
clEnqueue*** API or another application host thread is waiting for it in #WaitForEvents(), those commands and host threads will continue to wait for the
event status to reach #COMPLETE or error, even after the user has released the object. Since in this scenario the developer has released his
last reference count to the user event, it would be in principle no longer valid for him to change the status of the event to unblock all the other
machinery. As a result the waiting tasks will wait forever, and associated events, cl_mem objects, command queues and contexts are likely to leak.
In-order command-queues caught up in this deadlock may cease to do any work.
""",
cl_event.IN("event", "the event to release"),
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_EVENT if {@code event} is not a valid event object.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueMarker",
"""
Enqueues a marker command to {@code command_queue}. The marker command is not completed until all commands enqueued before it have completed. The marker
command returns an event which can be waited on, i.e. this event can be waited on to insure that all commands, which have been queued before the marker
command, have been completed.
""",
cl_command_queue.IN("command_queue", "the command-queue to insert the marker to"),
EVENT,
returnDoc =
"""
$SUCCESS if the function is successfully executed. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"$INVALID_VALUE if {@code event} is a $NULL value.",
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueBarrier",
"""
Enqueues a barrier operation. The {@code clEnqueueBarrier} command ensures that all queued commands in {@code command_queue} have finished execution
before the next batch of commands can begin execution. The {@code clEnqueueBarrier} command is a synchronization point.
""",
cl_command_queue.IN("command_queue", "the command-queue to insert the barrier to"),
returnDoc =
"""
$SUCCESS if the function is successfully executed. Otherwise, it returns one of the following errors:
${ul(
ICQE,
OORE,
OOHME
)}
"""
)
cl_int(
"EnqueueWaitForEvents",
"Enqueues a wait for a specific event or a list of events to complete before any future commands queued in the command-queue are executed.",
cl_command_queue.IN("command_queue", "the command-queue"),
AutoSize("event_list")..cl_uint.IN("num_events", "the number of events in {@code event_list}"),
SingleValue("event")..const..cl_event_p.IN("event_list", "the list of events"),
returnDoc =
"""
$SUCCESS if the function was successfully executed. Otherwise, it returns one of the following errors:
${ul(
ICQE,
"$INVALID_CONTEXT if the context associated with {@code command_queue} and events in {@code event_list} are not the same.",
"$INVALID_VALUE if {@code num_events} is zero or {@code event_list} is $NULL.",
"$INVALID_EVENT if event objects specified in {@code event_list} are not valid events.",
OORE,
OOHME
)}
"""
)
cl_int(
"GetEventProfilingInfo",
"Returns profiling information for the command associated with {@code event}.",
cl_event.IN("event", "the event object"),
cl_profiling_info.IN("param_name", "the profiling data to query", ProfilingInfo),
PARAM_VALUE_SIZE,
MultiType(PointerMapping.DATA_LONG)..nullable..void_p.OUT("param_value", param_value),
PARAM_VALUE_SIZE_RET,
returnDoc =
"""
$SUCCESS if the function is executed successfully and the profiling information has been recorded. Otherwise, it returns one of the following errors:
${ul(
"""
#PROFILING_INFO_NOT_AVAILABLE if the #QUEUE_PROFILING_ENABLE flag is not set for the command-queue, if the execution status of
the command identified by {@code event} is not #COMPLETE or if {@code event} is a user event object.
""",
"""
$INVALID_VALUE if {@code param_name} is not valid, or if size in bytes specified by {@code param_value_size} is < size of return type
and {@code param_value} is not $NULL.
""",
"$INVALID_EVENT if {@code event} is a not a valid event object.",
OORE,
OOHME
)}
"""
)
cl_int(
"Flush",
"""
Issues all previously queued OpenCL commands in {@code command_queue} to the device associated with {@code command_queue}. {@code clFlush} only
guarantees that all queued commands to {@code command_queue} will eventually be submitted to the appropriate device. There is no guarantee that they
will be complete after {@code clFlush} returns.
Any blocking commands queued in a command-queue and #ReleaseCommandQueue() perform an implicit flush of the command-queue. These blocking commands are
#EnqueueReadBuffer(), CL11#EnqueueReadBufferRect(), #EnqueueReadImage(), with {@code blocking_read} set to $TRUE; #EnqueueWriteBuffer(),
CL11#EnqueueWriteBufferRect(), #EnqueueWriteImage() with {@code blocking_write} set to $TRUE; #EnqueueMapBuffer(), #EnqueueMapImage() with
{@code blocking_map} set to $TRUE; or #WaitForEvents().
To use event objects that refer to commands enqueued in a command-queue as event objects to wait on by commands enqueued in a different command-queue,
the application must call a {@code clFlush} or any blocking commands that perform an implicit flush of the command-queue where the commands that refer
to these event objects are enqueued.
""",
cl_command_queue.IN("command_queue", "the command-queue"),
returnDoc =
"""
$SUCCESS if the function call was executed successfully. Otherwise, it returns one of the following errors:
${ul(
ICQE,
OORE,
OOHME
)}
"""
)
cl_int(
"Finish",
"""
Blocks until all previously queued OpenCL commands in {@code command_queue} are issued to the associated device and have completed. {@code clFinish}
does not return until all previously queued commands in {@code command_queue} have been processed and completed. {@code clFinish} is also a
synchronization point.
""",
cl_command_queue.IN("command_queue", "the command-queue")
)
voidptr(
"GetExtensionFunctionAddress",
"""
Returns the address of the extension function named by {@code funcname}. The pointer returned should be cast to a function pointer type matching the
extension function's definition defined in the appropriate extension specification and header file. A return value of $NULL indicates that the specified
function does not exist for the implementation. A non-$NULL return value for {@code clGetExtensionFunctionAddress} does not guarantee that an extension
function is actually supported. The application must also make a corresponding query using ${code("clGetPlatformInfo(platform, CL_PLATFORM_EXTENSIONS, … )")}
or ${code("clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, … )")} to determine if an extension is supported by the OpenCL implementation.
{@code clGetExtensionFunctionAddress} may not be queried for core (non-extension) functions in OpenCL. For functions that are queryable with
{@code clGetExtensionFunctionAddress}, implementations may choose to also export those functions statically from the object libraries implementing those
functions. However, portable applications cannot rely on this behavior.
""",
const..cl_charASCII_p.IN("funcname", "the extension function name"),
returnDoc = "the extension function address"
)
} | bsd-3-clause | c9d0e564ecbcbb47e2166f89406e6c8f | 43.239344 | 223 | 0.704471 | 3.494585 | false | false | false | false |
codetoart/FolioReader-Android | folioreader/src/main/java/com/folioreader/ui/view/ConfigBottomSheetDialogFragment.kt | 2 | 11684 | package com.folioreader.ui.view
import android.animation.Animator
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.folioreader.Config
import com.folioreader.Constants
import com.folioreader.R
import com.folioreader.model.event.ReloadDataEvent
import com.folioreader.ui.activity.FolioActivity
import com.folioreader.ui.activity.FolioActivityCallback
import com.folioreader.ui.fragment.MediaControllerFragment
import com.folioreader.util.AppUtil
import com.folioreader.util.UiUtil
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.android.synthetic.main.view_config.*
import org.greenrobot.eventbus.EventBus
/**
* Created by mobisys2 on 11/16/2016.
*/
class ConfigBottomSheetDialogFragment : BottomSheetDialogFragment() {
companion object {
const val FADE_DAY_NIGHT_MODE = 500
@JvmField
val LOG_TAG: String = ConfigBottomSheetDialogFragment::class.java.simpleName
}
private lateinit var config: Config
private var isNightMode = false
private lateinit var activityCallback: FolioActivityCallback
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.view_config, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (activity is FolioActivity)
activityCallback = activity as FolioActivity
view.viewTreeObserver.addOnGlobalLayoutListener {
val dialog = dialog as BottomSheetDialog
val bottomSheet =
dialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
val behavior = BottomSheetBehavior.from(bottomSheet!!)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
behavior.peekHeight = 0
}
config = AppUtil.getSavedConfig(activity)!!
initViews()
}
override fun onDestroy() {
super.onDestroy()
view?.viewTreeObserver?.addOnGlobalLayoutListener(null)
}
private fun initViews() {
inflateView()
configFonts()
view_config_font_size_seek_bar.progress = config.fontSize
configSeekBar()
selectFont(config.font, false)
isNightMode = config.isNightMode
if (isNightMode) {
container.setBackgroundColor(ContextCompat.getColor(context!!, R.color.night))
} else {
container.setBackgroundColor(ContextCompat.getColor(context!!, R.color.white))
}
if (isNightMode) {
view_config_ib_day_mode.isSelected = false
view_config_ib_night_mode.isSelected = true
UiUtil.setColorIntToDrawable(config.themeColor, view_config_ib_night_mode.drawable)
UiUtil.setColorResToDrawable(R.color.app_gray, view_config_ib_day_mode.drawable)
} else {
view_config_ib_day_mode.isSelected = true
view_config_ib_night_mode.isSelected = false
UiUtil.setColorIntToDrawable(config.themeColor, view_config_ib_day_mode!!.drawable)
UiUtil.setColorResToDrawable(R.color.app_gray, view_config_ib_night_mode.drawable)
}
}
private fun inflateView() {
if (config.allowedDirection != Config.AllowedDirection.VERTICAL_AND_HORIZONTAL) {
view5.visibility = View.GONE
buttonVertical.visibility = View.GONE
buttonHorizontal.visibility = View.GONE
}
view_config_ib_day_mode.setOnClickListener {
isNightMode = true
toggleBlackTheme()
view_config_ib_day_mode.isSelected = true
view_config_ib_night_mode.isSelected = false
setToolBarColor()
setAudioPlayerBackground()
UiUtil.setColorResToDrawable(R.color.app_gray, view_config_ib_night_mode.drawable)
UiUtil.setColorIntToDrawable(config.themeColor, view_config_ib_day_mode.drawable)
}
view_config_ib_night_mode.setOnClickListener {
isNightMode = false
toggleBlackTheme()
view_config_ib_day_mode.isSelected = false
view_config_ib_night_mode.isSelected = true
UiUtil.setColorResToDrawable(R.color.app_gray, view_config_ib_day_mode.drawable)
UiUtil.setColorIntToDrawable(config.themeColor, view_config_ib_night_mode.drawable)
setToolBarColor()
setAudioPlayerBackground()
}
if (activityCallback.direction == Config.Direction.HORIZONTAL) {
buttonHorizontal.isSelected = true
} else if (activityCallback.direction == Config.Direction.VERTICAL) {
buttonVertical.isSelected = true
}
buttonVertical.setOnClickListener {
config = AppUtil.getSavedConfig(context)!!
config.direction = Config.Direction.VERTICAL
AppUtil.saveConfig(context, config)
activityCallback.onDirectionChange(Config.Direction.VERTICAL)
buttonHorizontal.isSelected = false
buttonVertical.isSelected = true
}
buttonHorizontal.setOnClickListener {
config = AppUtil.getSavedConfig(context)!!
config.direction = Config.Direction.HORIZONTAL
AppUtil.saveConfig(context, config)
activityCallback.onDirectionChange(Config.Direction.HORIZONTAL)
buttonHorizontal.isSelected = true
buttonVertical.isSelected = false
}
}
private fun configFonts() {
val colorStateList = UiUtil.getColorList(
config.themeColor,
ContextCompat.getColor(context!!, R.color.grey_color)
)
buttonVertical.setTextColor(colorStateList)
buttonHorizontal.setTextColor(colorStateList)
view_config_font_andada.setTextColor(colorStateList)
view_config_font_lato.setTextColor(colorStateList)
view_config_font_lora.setTextColor(colorStateList)
view_config_font_raleway.setTextColor(colorStateList)
view_config_font_andada.setOnClickListener { selectFont(Constants.FONT_ANDADA, true) }
view_config_font_lato.setOnClickListener { selectFont(Constants.FONT_LATO, true) }
view_config_font_lora.setOnClickListener { selectFont(Constants.FONT_LORA, true) }
view_config_font_raleway.setOnClickListener { selectFont(Constants.FONT_RALEWAY, true) }
}
private fun selectFont(selectedFont: Int, isReloadNeeded: Boolean) {
when (selectedFont) {
Constants.FONT_ANDADA -> setSelectedFont(true, false, false, false)
Constants.FONT_LATO -> setSelectedFont(false, true, false, false)
Constants.FONT_LORA -> setSelectedFont(false, false, true, false)
Constants.FONT_RALEWAY -> setSelectedFont(false, false, false, true)
}
config.font = selectedFont
if (isAdded && isReloadNeeded) {
AppUtil.saveConfig(activity, config)
EventBus.getDefault().post(ReloadDataEvent())
}
}
private fun setSelectedFont(andada: Boolean, lato: Boolean, lora: Boolean, raleway: Boolean) {
view_config_font_andada.isSelected = andada
view_config_font_lato.isSelected = lato
view_config_font_lora.isSelected = lora
view_config_font_raleway.isSelected = raleway
}
private fun toggleBlackTheme() {
val day = ContextCompat.getColor(context!!, R.color.white)
val night = ContextCompat.getColor(context!!, R.color.night)
val colorAnimation = ValueAnimator.ofObject(
ArgbEvaluator(),
if (isNightMode) night else day, if (isNightMode) day else night
)
colorAnimation.duration = FADE_DAY_NIGHT_MODE.toLong()
colorAnimation.addUpdateListener { animator ->
val value = animator.animatedValue as Int
container.setBackgroundColor(value)
}
colorAnimation.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {}
override fun onAnimationEnd(animator: Animator) {
isNightMode = !isNightMode
config.isNightMode = isNightMode
AppUtil.saveConfig(activity, config)
EventBus.getDefault().post(ReloadDataEvent())
}
override fun onAnimationCancel(animator: Animator) {}
override fun onAnimationRepeat(animator: Animator) {}
})
colorAnimation.duration = FADE_DAY_NIGHT_MODE.toLong()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val attrs = intArrayOf(android.R.attr.navigationBarColor)
val typedArray = activity?.theme?.obtainStyledAttributes(attrs)
val defaultNavigationBarColor = typedArray?.getColor(
0,
ContextCompat.getColor(context!!, R.color.white)
)
val black = ContextCompat.getColor(context!!, R.color.black)
val navigationColorAnim = ValueAnimator.ofObject(
ArgbEvaluator(),
if (isNightMode) black else defaultNavigationBarColor,
if (isNightMode) defaultNavigationBarColor else black
)
navigationColorAnim.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Int
activity?.window?.navigationBarColor = value
}
navigationColorAnim.duration = FADE_DAY_NIGHT_MODE.toLong()
navigationColorAnim.start()
}
colorAnimation.start()
}
private fun configSeekBar() {
val thumbDrawable = ContextCompat.getDrawable(activity!!, R.drawable.seekbar_thumb)
UiUtil.setColorIntToDrawable(config.themeColor, thumbDrawable)
UiUtil.setColorResToDrawable(R.color.grey_color, view_config_font_size_seek_bar.progressDrawable)
view_config_font_size_seek_bar.thumb = thumbDrawable
view_config_font_size_seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
config.fontSize = progress
AppUtil.saveConfig(activity, config)
EventBus.getDefault().post(ReloadDataEvent())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
}
private fun setToolBarColor() {
if (isNightMode) {
activityCallback.setDayMode()
} else {
activityCallback.setNightMode()
}
}
private fun setAudioPlayerBackground() {
var mediaControllerFragment: Fragment? = fragmentManager?.findFragmentByTag(MediaControllerFragment.LOG_TAG)
?: return
mediaControllerFragment = mediaControllerFragment as MediaControllerFragment
if (isNightMode) {
mediaControllerFragment.setDayMode()
} else {
mediaControllerFragment.setNightMode()
}
}
}
| bsd-3-clause | ca293d4051ced9fd229d89f833114ca6 | 38.877133 | 116 | 0.672544 | 4.874426 | false | true | false | false |
esofthead/mycollab | mycollab-dao/src/main/java/com/mycollab/db/arguments/DateTimeSearchField.kt | 3 | 1188 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.db.arguments
import java.time.LocalDate
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
class DateTimeSearchField(operation: String, var comparison: String, var value: LocalDate) : SearchField(operation) {
companion object {
const val LESS_THAN = "<"
const val LESS_THAN_EQUAL = "<="
const val GREATER_THAN = ">"
const val GREATER_THAN_EQUAL = ">="
const val EQUAL = "="
const val NOT_EQUAL = "<>"
}
} | agpl-3.0 | e7baf0e82cc1de706cebd6be75b087af | 29.461538 | 117 | 0.68829 | 4.194346 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/DeadCodeCheck.kt | 1 | 2645 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.typeIs
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MAJOR, tags = [Tags.UNUSED])
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class DeadCodeCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(*CheckUtils.terminationStatements)
subscribeTo(PlSqlGrammar.METHOD_CALL)
}
override fun visitNode(node: AstNode) {
if (CheckUtils.isTerminationStatement(node)) {
var parent = node.parent
while (!checkNode(parent)) {
parent = parent.parent
}
}
}
private fun checkNode(node: AstNode?): Boolean {
if (!shouldCheckNode(node) || node == null) {
return true
}
val nextSibling = node.nextSiblingOrNull
if (nextSibling != null && nextSibling.typeIs(PlSqlGrammar.STATEMENT)) {
addIssue(nextSibling, getLocalizedMessage())
return true
}
return false
}
private fun shouldCheckNode(node: AstNode?): Boolean {
if (node == null || CheckUtils.isProgramUnit(node)) {
return false
}
return if (node.typeIs(STATEMENT_OR_CALL)) {
true
} else {
node.typeIs(STATEMENT_SECTION) && !node.hasDirectChildren(PlSqlGrammar.EXCEPTION_HANDLER)
}
}
companion object {
val STATEMENT_OR_CALL = arrayOf(PlSqlGrammar.STATEMENT, PlSqlGrammar.BLOCK_STATEMENT, PlSqlGrammar.CALL_STATEMENT)
val STATEMENT_SECTION = arrayOf(PlSqlGrammar.STATEMENTS_SECTION, PlSqlGrammar.STATEMENTS)
}
}
| lgpl-3.0 | 92892f84fc5e6d03802dbb6db778bd84 | 33.802632 | 122 | 0.680151 | 4.467905 | false | false | false | false |
sybila/ode-generator | src/test/kotlin/com/github/sybila/ode/generator/smt/Util.kt | 1 | 837 | package com.github.sybila.ode.generator.smt
/*
fun Nodes<IDNode, SMTColors>.normalize(): List<Pair<IDNode, SMTColors>>
= this.entries.map { Pair(it.key, it.value) }.sortedBy { it.first.id }
//semantically compare the formulas
fun assertEquals(a: List<Pair<IDNode, SMTColors>>, b: List<Pair<IDNode, SMTColors>>) {
if (a.size != b.size) {
error("Expected $a, got $b")
} else {
a.zip(b).forEach {
val (left, right) = it
if (left.first != right.first) {
error("Expected $left, got $right in $a != $b")
} else {
if (!left.second.normalize().solverEquals(right.second.normalize())) {
error("Expected ${left.second.normalize()}, got ${right.second.normalize()} in $a != $b")
}
}
}
}
}*/ | gpl-3.0 | f6d5f3c2c5ec358c4ab75714e81a1420 | 35.434783 | 109 | 0.547192 | 3.502092 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/collections/mutableList.kt | 5 | 2489 | // TARGET_BACKEND: JVM
// FILE: J.java
import java.util.*;
public class J {
private static class MyList<E> extends KList<E> {}
public static String foo() {
Collection<String> collection = new MyList<String>();
if (!collection.contains("ABCDE")) return "fail 1";
if (!collection.containsAll(Arrays.asList(1, 2, 3))) return "fail 2";
return "OK";
}
}
// FILE: test.kt
open class KList<E> : MutableList<E> {
override fun add(e: E): Boolean {
throw UnsupportedOperationException()
}
override fun remove(o: E): Boolean {
throw UnsupportedOperationException()
}
override fun addAll(c: Collection<E>): Boolean {
throw UnsupportedOperationException()
}
override fun addAll(index: Int, c: Collection<E>): Boolean {
throw UnsupportedOperationException()
}
override fun removeAll(c: Collection<E>): Boolean {
throw UnsupportedOperationException()
}
override fun retainAll(c: Collection<E>): Boolean {
throw UnsupportedOperationException()
}
override fun clear() {
throw UnsupportedOperationException()
}
override fun set(index: Int, element: E): E {
throw UnsupportedOperationException()
}
override fun add(index: Int, element: E) {
throw UnsupportedOperationException()
}
override fun removeAt(index: Int): E {
throw UnsupportedOperationException()
}
override fun listIterator(): MutableListIterator<E> {
throw UnsupportedOperationException()
}
override fun listIterator(index: Int): MutableListIterator<E> {
throw UnsupportedOperationException()
}
override fun subList(fromIndex: Int, toIndex: Int): MutableList<E> {
throw UnsupportedOperationException()
}
override fun iterator(): MutableIterator<E> {
throw UnsupportedOperationException()
}
override val size: Int
get() = throw UnsupportedOperationException()
override fun isEmpty(): Boolean {
throw UnsupportedOperationException()
}
override fun contains(o: E) = true
override fun containsAll(c: Collection<E>) = true
override fun get(index: Int): E {
throw UnsupportedOperationException()
}
override fun indexOf(o: E): Int {
throw UnsupportedOperationException()
}
override fun lastIndexOf(o: E): Int {
throw UnsupportedOperationException()
}
}
fun box() = J.foo()
| apache-2.0 | 8de57f0efb77ae0bbfaa321b739a9d9f | 23.643564 | 77 | 0.64765 | 4.968064 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/defaultArgs.kt | 5 | 964 | val global = "OK"
class A {
val prop: String
constructor(arg1: String = global) {
prop = arg1
}
constructor(arg1: String = global, arg2: Long) {
prop = "$arg1#$arg2"
}
constructor(arg1: String = global, argDouble: Double, arg3: Long = 1L) {
prop = "$arg1#$argDouble#$arg3"
}
}
fun box(): String {
val a1 = A()
if (a1.prop != "OK") return "fail1: ${a1.prop}"
val a2 = A("A")
if (a2.prop != "A") return "fail2: ${a2.prop}"
val a3 = A(arg2=123)
if (a3.prop != "OK#123") return "fail3: ${a3.prop}"
val a4 = A("A", arg2=123)
if (a4.prop != "A#123") return "fail4: ${a4.prop}"
val a5 = A(argDouble=23.1)
if (a5.prop != "OK#23.1#1") return "fail5: ${a5.prop}"
val a6 = A("A", argDouble=23.1)
if (a6.prop != "A#23.1#1") return "fail6: ${a6.prop}"
val a7 = A("A", arg3=2L, argDouble=23.1)
if (a7.prop != "A#23.1#2") return "fail7: ${a7.prop}"
return "OK"
}
| apache-2.0 | e26603d28d4073e27f6904c6c6e7a872 | 27.352941 | 76 | 0.529046 | 2.490956 | false | false | false | false |
suchaHassle/kotNES | src/Emulator.kt | 1 | 1660 | package kotNES
import kotNES.mapper.MMC3
import kotNES.mapper.NROM
import kotNES.mapper.UxROM
import kotNES.ui.HeavyDisplayPanel
import java.lang.Long.max
import java.nio.file.Path
import java.util.concurrent.locks.LockSupport
class Emulator(path: Path) {
var cartridge = Cartridge(path)
var memory = CpuMemory(this)
var cpu = CPU(memory)
var ppu = PPU(this)
var controller = Controller()
var mapper: Mapper
var evenOdd: Boolean = false
val codeExecutionThread = Thread(Runnable { this.start() })
lateinit var display: HeavyDisplayPanel
init {
when (cartridge.mapper) {
0 -> mapper = NROM(this)
2 -> mapper = UxROM(this)
4 -> mapper = MMC3(this)
else -> throw UnsupportedMapper("${cartridge.mapper} mapper is not supported")
}
}
fun start() {
cpu.reset()
ppu.reset()
while (true) {
val startTime = System.currentTimeMillis()
stepSeconds()
val endTime = System.currentTimeMillis()
var sleepTime: Long = (((1000.0) / 60.0) - (endTime - startTime)).toLong()
sleepTime = max(sleepTime, 0)
// A better alternative to Thread.sleep
LockSupport.parkNanos(sleepTime * 1000000)
}
}
fun stepSeconds() {
val orig = evenOdd
while (orig == evenOdd) step()
}
fun step() {
val cpuCycles = cpu.tick()
val ppuCycles = cpuCycles * 3
for (i in 0..(ppuCycles - 1)) {
ppu.step()
mapper.step()
}
}
class UnsupportedMapper(s: String) : Throwable(s)
} | mit | d659caa2e10438cf51f4a338ecd59d33 | 25.365079 | 90 | 0.587349 | 3.952381 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/srli.kt | 1 | 257 | package venus.riscv.insts
import venus.riscv.insts.dsl.ShiftImmediateInstruction
val srli = ShiftImmediateInstruction(
name = "srli",
funct3 = 0b101,
funct7 = 0b0000000,
eval32 = { a, b -> if (b == 0) a else (a ushr b) }
)
| mit | d3b8385d72f1d45a708d6bb14d942d0e | 24.7 | 58 | 0.622568 | 3.253165 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/ResetPasswordFragment.kt | 1 | 7426 | package com.rolandvitezhu.todocloud.ui.activity.main.fragment
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputLayout
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.app.AppController
import com.rolandvitezhu.todocloud.app.AppController.Companion.showWhiteTextSnackbar
import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao
import com.rolandvitezhu.todocloud.databinding.FragmentResetpasswordBinding
import com.rolandvitezhu.todocloud.helper.GeneralHelper.validateField
import com.rolandvitezhu.todocloud.helper.applyOrientationFullSensor
import com.rolandvitezhu.todocloud.helper.applyOrientationPortrait
import com.rolandvitezhu.todocloud.helper.hideSoftInput
import com.rolandvitezhu.todocloud.network.ApiService
import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.fragment_resetpassword.*
import kotlinx.android.synthetic.main.fragment_resetpassword.view.*
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import javax.inject.Inject
class ResetPasswordFragment : Fragment() {
private val TAG = javaClass.simpleName
private lateinit var apiService: ApiService
@Inject
lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao
@Inject
lateinit var retrofit: Retrofit
private val userViewModel by lazy {
ViewModelProvider(this).get(UserViewModel::class.java)
}
override fun onAttach(context: Context) {
super.onAttach(context)
(requireActivity().application as AppController)
.appComponent.fragmentComponent().create().inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
apiService = retrofit.create(ApiService::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentResetpasswordBinding: FragmentResetpasswordBinding =
FragmentResetpasswordBinding.inflate(inflater, container, false)
val view: View = fragmentResetpasswordBinding.root
applyTextChangedEvents(view)
fragmentResetpasswordBinding.lifecycleOwner = this
fragmentResetpasswordBinding.resetPasswordFragment = this
fragmentResetpasswordBinding.userViewModel = userViewModel
fragmentResetpasswordBinding.executePendingBindings()
return view
}
override fun onResume() {
super.onResume()
(activity as MainActivity?)?.onSetActionBarTitle(getString(R.string.all_reset_password))
applyOrientationPortrait()
}
private fun applyTextChangedEvents(view: View) {
view.textinputedittext_resetpassword_email?.addTextChangedListener(
MyTextWatcher(view.textinputedittext_resetpassword_email!!))
}
private fun handleResetPassword() {
if (validateEmail()) {
lifecycleScope.launch {
try {
userViewModel.onResetPassword()
onFinishResetPassword()
} catch (cause: Throwable) {
showErrorMessage(cause.message)
}
}
}
}
override fun onPause() {
super.onPause()
applyOrientationFullSensor()
}
/**
* Check whether the email address is valid and show an error message, if necessary. The email
* address is valid, if it is provided and it has a valid email address pattern.
*/
private fun validateEmail(): Boolean {
if (view != null && view?.textinputlayout_resetpassword_email != null) {
return validateField(userViewModel.isEmailValid(),
view?.textinputlayout_resetpassword_email as TextInputLayout,
getString(R.string.registeruser_entervalidemailhint))
}
return false
}
private fun onFinishResetPassword() {
hideFormSubmissionErrors()
(activity as MainActivity?)?.onFinishResetPassword()
}
private fun showErrorMessage(errorMessage: String?) {
if (errorMessage != null) {
val upperCaseErrorMessage = errorMessage.toUpperCase()
if (upperCaseErrorMessage.contains("FAILED TO CONNECT") ||
upperCaseErrorMessage.contains("UNABLE TO RESOLVE HOST") ||
upperCaseErrorMessage.contains("TIMEOUT")) {
hideFormSubmissionErrors()
showFailedToConnectError()
} else if (upperCaseErrorMessage.contains("FAILED TO RESET PASSWORD. PLEASE TRY AGAIN!")) {
showFailedToResetPasswordError()
} else {
hideFormSubmissionErrors()
showAnErrorOccurredError()
}
}
}
private fun hideFormSubmissionErrors() {
try {
this.textview_resetpassword_formsubmissionerrors?.text = ""
this.textview_resetpassword_formsubmissionerrors?.visibility = View.GONE
} catch (e: NullPointerException) {
// TextView doesn't exists already.
}
}
private fun showFailedToConnectError() {
try {
val snackbar = Snackbar.make(
this.constraintlayout_resetpassword!!,
R.string.all_failedtoconnect,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
private fun showFailedToResetPasswordError() {
try {
this.textview_resetpassword_formsubmissionerrors?.setText(R.string.modifypassword_failedtoresetpassword)
this.textview_resetpassword_formsubmissionerrors?.visibility = View.VISIBLE
} catch (e: NullPointerException) {
// TextView doesn't exists already.
}
}
private fun showAnErrorOccurredError() {
try {
val snackbar = Snackbar.make(
this.constraintlayout_resetpassword!!,
R.string.all_anerroroccurred,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
fun onButtonSubmitClick() {
hideSoftInput()
handleResetPassword()
}
private inner class MyTextWatcher(private val view: View) : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
when (view.id) {
R.id.textinputedittext_resetpassword_email -> validateEmail()
}
}
}
} | mit | fd27827defa8c46fdb3805cc2e322037 | 35.950249 | 116 | 0.67533 | 5.28165 | false | false | false | false |
prt2121/android-workspace | Section/app/src/main/kotlin/com/prt2121/capstone/RetryWithDelay.kt | 1 | 2376 | package com.prt2121.capstone
import rx.Observable
import rx.Observable.Transformer
import rx.functions.Func1
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit
/**
* Created by pt2121 on 2/16/16.
*/
class RetryWithDelay(maxRetries: Int, retryDelayMillis: Long) : Func1<Observable<out Throwable>, Observable<*>> {
private var maxRetries: Int = 0
private var retryDelayMillis: Long = 0
private var retryCount: Int = 0
init {
this.maxRetries = maxRetries
this.retryDelayMillis = retryDelayMillis
this.retryCount = 0
}
override fun call(attempts: Observable<out Throwable>): Observable<*> {
return attempts.flatMap { throwable ->
if (++retryCount < maxRetries) {
// When this Observable calls onNext, the original
// Observable will be retried (i.e. re-subscribed).
Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS)
} else
// Max retries hit. Just pass the error along.
Observable.error(throwable as Throwable?)
}
}
}
/**
* @param interval The base interval to start backing off from. The function is: attemptNum^2 * intervalTime
* @param units The units for interval
* @param retryAttempts The max number of attempts to retry this task or -1 to try MAX_INT times,
*/
fun <T> backoff(interval: Long, units: TimeUnit, retryAttempts: Int): Observable.Transformer<T, T> =
Transformer { observable ->
observable.retryWhen(
retryFunc(interval, units, retryAttempts),
Schedulers.immediate())
}
private fun retryFunc(interval: Long, units: TimeUnit, attempts: Int): Func1<in Observable<out Throwable>, out Observable<*>> =
Func1<rx.Observable<out Throwable>, rx.Observable<Long>> { observable ->
// zip our number of retries to the incoming errors so that we only produce retries
// when there's been an error
observable.zipWith(
Observable.range(1, if (attempts > 0) attempts else Int.MAX_VALUE),
{ throwable, attemptNumber -> attemptNumber }
)
.flatMap {
var newInterval = interval * (it.toLong() * it.toLong())
if (newInterval < 0) {
newInterval = Long.MAX_VALUE
}
// use Schedulers#immediate() to keep on same thread
Observable.timer(newInterval, units, Schedulers.immediate())
}
} | apache-2.0 | 09bd72ebb43a66f88e20aec7f03e5946 | 36.140625 | 127 | 0.673822 | 4.383764 | false | false | false | false |
Maccimo/intellij-community | python/src/com/jetbrains/python/run/target/PySdkTargetPaths.kt | 3 | 6080 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PySdkTargetPaths")
package com.jetbrains.python.run.target
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.target.value.constant
import com.intellij.execution.target.value.getTargetEnvironmentValueForLocalPath
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.remote.RemoteMappingsManager
import com.intellij.remote.RemoteSdkAdditionalData
import com.jetbrains.python.console.PyConsoleOptions
import com.jetbrains.python.console.PyConsoleOptions.PyConsoleSettings
import com.jetbrains.python.console.getPathMapper
import com.jetbrains.python.remote.PyRemotePathMapper
import com.jetbrains.python.remote.PythonRemoteInterpreterManager
import com.jetbrains.python.remote.PythonRemoteInterpreterManager.appendBasicMappings
import com.jetbrains.python.target.PyTargetAwareAdditionalData
/**
* @param pathMapper corresponds to the path mappings specified in the run configuration
* @throws IllegalArgumentException if [localPath] cannot be found neither in SDK additional data nor within the registered uploads in the
* request
*/
fun getTargetPathForPythonScriptExecution(targetEnvironmentRequest: TargetEnvironmentRequest,
project: Project,
sdk: Sdk?,
pathMapper: PyRemotePathMapper?,
localPath: String): TargetEnvironmentFunction<String> {
val initialPathMapper = pathMapper ?: PyRemotePathMapper()
val targetPath = initialPathMapper.extendPythonSdkPathMapper(project, sdk).convertToRemoteOrNull(localPath)
return targetPath?.let { constant(it) } ?: targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath)
}
private fun PyRemotePathMapper.extendPythonSdkPathMapper(project: Project, sdk: Sdk?): PyRemotePathMapper {
val pathMapper = PyRemotePathMapper.cloneMapper(this)
val sdkAdditionalData = sdk?.sdkAdditionalData as? RemoteSdkAdditionalData<*>
if (sdkAdditionalData != null) {
appendBasicMappings(project, pathMapper, sdkAdditionalData)
}
return pathMapper
}
/**
* Returns the function that resolves the given [localPath] to the path on the target by the target environment. The resolution happens in
* the following order:
* 1. Using the given [pathMapper]. This mapper usually encapsulates the path mappings declared by user in the run configuration.
* 2. Using the project-wide path mappings settings for Python Console.
* 3. Using the path mappings declared in the given [sdk] including the mappings for PyCharm helpers.
* 4. Using the uploads declared in the target environment.
*
* @param pathMapper corresponds to the path mappings specified in the run configuration
* @throws IllegalArgumentException if [localPath] cannot be found neither in SDK additional data nor within the registered uploads in the
* request
*/
fun getTargetPathForPythonConsoleExecution(targetEnvironmentRequest: TargetEnvironmentRequest,
project: Project,
sdk: Sdk?,
pathMapper: PyRemotePathMapper?,
localPath: String): TargetEnvironmentFunction<String> {
val targetPath = pathMapper?.convertToRemoteOrNull(localPath)
?: getPythonConsolePathMapper(project, sdk)?.convertToRemoteOrNull(localPath)
return targetPath?.let { constant(it) } ?: targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath)
}
fun getTargetPathForPythonConsoleExecution(project: Project,
sdk: Sdk?,
pathMapper: PyRemotePathMapper?,
localPath: String): TargetEnvironmentFunction<String> {
val targetPath = pathMapper?.convertToRemoteOrNull(localPath)
?: getPythonConsolePathMapper(project, sdk)?.convertToRemoteOrNull(localPath)
return targetPath?.let { constant(it) } ?: getTargetEnvironmentValueForLocalPath(localPath)
}
/**
* Note that the returned mapper includes the path mappings collected by the execution of [appendBasicMappings].
*/
private fun getPythonConsolePathMapper(project: Project, sdk: Sdk?): PyRemotePathMapper? =
getPathMapper(project, sdk, PyConsoleOptions.getInstance(project).pythonConsoleSettings)
private fun PyRemotePathMapper.convertToRemoteOrNull(localPath: String): String? =
takeIf { it.canReplaceLocal(localPath) }?.convertToRemote(localPath)
fun getPathMapper(project: Project, consoleSettings: PyConsoleSettings, data: PyTargetAwareAdditionalData): PyRemotePathMapper {
val remotePathMapper = appendBasicMappings(project, null, data)
consoleSettings.mappingSettings?.let { mappingSettings ->
remotePathMapper.addAll(mappingSettings.pathMappings, PyRemotePathMapper.PyPathMappingType.USER_DEFINED)
}
return remotePathMapper
}
private fun appendBasicMappings(project: Project?,
pathMapper: PyRemotePathMapper?,
data: PyTargetAwareAdditionalData): PyRemotePathMapper {
val newPathMapper = PyRemotePathMapper.cloneMapper(pathMapper)
PythonRemoteInterpreterManager.addHelpersMapping(data, newPathMapper)
newPathMapper.addAll(data.pathMappings.pathMappings, PyRemotePathMapper.PyPathMappingType.SYS_PATH)
if (project != null) {
val mappings = RemoteMappingsManager.getInstance(project).getForServer(PythonRemoteInterpreterManager.PYTHON_PREFIX, data.sdkId)
if (mappings != null) {
newPathMapper.addAll(mappings.settings, PyRemotePathMapper.PyPathMappingType.USER_DEFINED)
}
}
return newPathMapper
} | apache-2.0 | e44c9f160d0b93d3b0475c5bd91d6501 | 55.831776 | 140 | 0.737993 | 5.477477 | false | false | false | false |
Yubico/yubioath-desktop | android/app/src/main/kotlin/com/yubico/authenticator/device/Version.kt | 1 | 1798 | /*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator.device
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ByteArraySerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializable(with = VersionSerializer::class)
data class Version(
val major: Byte,
val minor: Byte,
val micro: Byte
)
object VersionSerializer : KSerializer<Version> {
override val descriptor: SerialDescriptor = ByteArraySerializer().descriptor
override fun serialize(encoder: Encoder, value: Version) {
encoder.encodeSerializableValue(
ByteArraySerializer(),
byteArrayOf(value.major, value.minor, value.micro)
)
}
override fun deserialize(decoder: Decoder): Version {
val byteArray = decoder.decodeSerializableValue(ByteArraySerializer())
val major = if (byteArray.isNotEmpty()) byteArray[0] else 0
val minor = if (byteArray.size > 1) byteArray[1] else 0
val micro = if (byteArray.size > 2) byteArray[2] else 0
return Version(major, minor, micro)
}
} | apache-2.0 | 4e064b4b6e614fe416f1d7f7ffa62572 | 34.98 | 80 | 0.734705 | 4.551899 | false | false | false | false |
duncte123/SkyBot | src/main/kotlin/ml/duncte123/skybot/commands/fun/ChatCommand.kt | 1 | 7764 | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.`fun`
import gnu.trove.map.hash.TLongObjectHashMap
import me.duncte123.botcommons.messaging.MessageConfig
import me.duncte123.botcommons.messaging.MessageUtils.sendMsg
import me.duncte123.botcommons.web.WebParserUtils
import me.duncte123.botcommons.web.WebUtils
import me.duncte123.botcommons.web.requests.FormRequestBody
import ml.duncte123.skybot.Settings.NO_STATIC
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandCategory
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.utils.MapUtils
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import org.jsoup.Jsoup
import java.io.InputStream
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.TimeUnit.MINUTES
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory
class ChatCommand : Command() {
private val sessions = MapUtils.newLongObjectMap<ChatSession>()
private val MAX_DURATION = MILLISECONDS.convert(20, MINUTES)
private val responses = arrayOf(
"My prefix in this guild is *`{PREFIX}`*",
"Thanks for asking, my prefix here is *`{PREFIX}`*",
"That should be *`{PREFIX}`*",
"It was *`{PREFIX}`* if I'm not mistaken",
"In this server my prefix is *`{PREFIX}`*"
)
init {
this.category = CommandCategory.FUN
this.name = "chat"
this.help = "Have a chat with DuncteBot"
this.usage = "<message>"
// needed for reactions
this.botPermissions = arrayOf(
Permission.MESSAGE_HISTORY
)
SERVICE.scheduleAtFixedRate(
{
val temp = TLongObjectHashMap(sessions)
val now = Date()
var cleared = 0
for (it in temp.keys()) {
val duration = now.time - sessions.get(it).time.time
if (duration >= MAX_DURATION) {
sessions.remove(it)
cleared++
}
}
LOGGER.debug("Removed $cleared chat sessions that have been inactive for 20 minutes.")
},
1L, 1L, TimeUnit.HOURS
)
}
override fun execute(ctx: CommandContext) {
val event = ctx.event
ctx.channel.sendTyping().queue()
if (ctx.message.contentRaw.lowercase().contains("prefix")) {
sendMsg(
MessageConfig.Builder.fromCtx(ctx)
.replyTo(ctx.message)
.setMessage(responses.random().replace("{PREFIX}", ctx.prefix))
)
return
}
if (ctx.args.isEmpty()) {
this.sendUsageInstructions(ctx)
return
}
val time = System.currentTimeMillis()
var message = ctx.argsJoined
message = replaceStuff(event, message)
if (!sessions.containsKey(event.author.idLong)) {
sessions.put(event.author.idLong, ChatSession(event.author.idLong))
// sessions[event.author.id]?.session =
}
val session = sessions[event.author.idLong] ?: return
LOGGER.debug("Message: \"$message\"")
// Set the current date in the object
session.time = Date()
session.think(message) {
val response = parseATags(it)
LOGGER.debug("New response: \"$response\", this took ${System.currentTimeMillis() - time}ms")
if (response.isEmpty() || response.isBlank()) {
sendMsg(
MessageConfig.Builder.fromCtx(ctx)
.replyTo(ctx.message)
.setMessage("$NO_STATIC Chatbot error: no content returned, this is likely due to the chatbot banning you (we are working on a fix)")
)
return@think
}
sendMsg(
MessageConfig.Builder.fromCtx(ctx)
.replyTo(ctx.message)
.setMessage(response)
)
}
}
private fun parseATags(response: String): String {
var response1 = response
for (element in Jsoup.parse(response1).getElementsByTag("a")) {
response1 = response1.replace(
oldValue = element.toString(),
newValue = "${element.text()}(<${element.attr("href")}>)"
)
}
return response1
}
private fun replaceStuff(event: GuildMessageReceivedEvent, m: String): String {
var message = m
for (it in event.message.mentionedChannels) {
message = message.replace(it.asMention, it.name)
}
for (it in event.message.mentionedRoles) {
message = message.replace(it.asMention, it.name)
}
for (it in event.message.mentionedUsers) {
message = message.replace(it.asMention, it.name)
}
for (it in event.message.emotes) {
message = message.replace(it.asMention, it.name)
}
message = message.replace("@here", "here").replace("@everyone", "everyone")
return message
}
}
class ChatSession(userId: Long) {
private val body = FormRequestBody()
init {
body.append("botid", "b0dafd24ee35a477")
body.append("custid", userId.toString())
}
var time = Date()
fun think(text: String, response: (String) -> Unit) {
body.append("input", text)
WebUtils.ins.postRequest("https://www.pandorabots.com/pandora/talk-xml", body)
.build({ it.body()!!.byteStream() }, WebParserUtils::handleError)
.async {
try {
response.invoke(xPathSearch(it, "//result/that/text()"))
} catch (e: Exception) {
response.invoke(
"""An Error occurred, please report this message my developers
|```
|${e.message}
|```
""".trimMargin()
)
}
}
}
@Suppress("SameParameterValue")
private fun xPathSearch(input: InputStream, expression: String): String {
val documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
val xPath = XPathFactory.newInstance().newXPath()
val xPathExpression = xPath.compile(expression)
return input.use {
val document = documentBuilder.parse(it)
val output = xPathExpression.evaluate(document, XPathConstants.STRING)
val outputString = (output as? String) ?: "Error on xpath, this should never be shown"
return@use outputString.trim { s -> s <= ' ' }
}
}
}
| agpl-3.0 | a4d3b94470b2d837067f5cc70b38e4a1 | 35.280374 | 157 | 0.604199 | 4.50087 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/adapters/ManageTransportAdapter.kt | 2 | 4558 | package com.rohitsuratekar.NCBSinfo.adapters
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.hideMe
import com.rohitsuratekar.NCBSinfo.common.inflate
import com.rohitsuratekar.NCBSinfo.common.showMe
import com.rohitsuratekar.NCBSinfo.models.Route
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class ManageTransportAdapter(private val routeList: List<Route>, private val listener: OnOptionClicked) :
RecyclerView.Adapter<ManageTransportAdapter.ViewHolder>() {
private val inputFormat = SimpleDateFormat(Constants.FORMAT_SERVER_TIMESTAMP, Locale.ENGLISH)
private val outputFormat = SimpleDateFormat(Constants.FORMAT_MODIFIED, Locale.ENGLISH)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.fragment_manage_transport_item))
}
override fun getItemCount(): Int {
return routeList.size
}
private fun format(string: String?): String {
string?.let {
return try {
outputFormat.format(inputFormat.parse(it))
} catch (e: ParseException) {
"N/A"
}
}
return "N/A"
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val route = routeList[position]
val context = holder.itemView.context
holder.apply {
name.text = context.getString(R.string.tp_route_name, route.routeData.origin, route.routeData.destination)
.toUpperCase(Locale.getDefault())
type.text = route.routeData.type
modified.text = context.getString(R.string.mt_last_modified, format(route.routeData.modifiedOn))
}
if (route.isExpanded) {
holder.apply {
optionsLayout.showMe()
expand.rotation = 0f
routeIcon.setImageResource(R.color.colorAccent)
setColor(context, edit.compoundDrawables, R.color.colorPrimary)
setColor(context, delete.compoundDrawables, R.color.red)
setColor(context, report.compoundDrawables, R.color.yellow)
edit.setOnClickListener { listener.edit(route) }
delete.setOnClickListener { listener.delete(route) }
report.setOnClickListener { listener.report(route) }
}
} else {
holder.apply {
optionsLayout.hideMe()
expand.rotation = 180f
routeIcon.setImageResource(R.color.colorPrimary)
}
}
holder.mainLayout.setOnClickListener { listener.expand(route) }
}
//TODO: Handle setColorFilter
private fun setColor(context: Context, drawables: Array<Drawable>, color: Int) {
drawables[1].mutate()
drawables[1].setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.mt_item_name)
var type: TextView = itemView.findViewById(R.id.mt_item_type)
var modified: TextView = itemView.findViewById(R.id.mt_item_modified)
var edit: TextView = itemView.findViewById(R.id.mt_item_edit)
var delete: TextView = itemView.findViewById(R.id.mt_item_delete)
var report: TextView = itemView.findViewById(R.id.mt_item_report)
var expand: ImageView = itemView.findViewById(R.id.mt_item_expand)
var routeIcon: ImageView = itemView.findViewById(R.id.mt_item_route_icon)
var optionsLayout: LinearLayout = itemView.findViewById(R.id.mt_item_options)
var mainLayout: ConstraintLayout = itemView.findViewById(R.id.mt_main_layout)
}
interface OnOptionClicked {
fun expand(route: Route)
fun edit(route: Route)
fun delete(route: Route)
fun report(route: Route)
}
} | mit | 4e26875198a98cc54ba66c572ac6ba03 | 38.353982 | 118 | 0.671566 | 4.562563 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleKotlinTestUtils.kt | 1 | 3602 | // 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.codeInsight.gradle
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion
import org.jetbrains.kotlin.tooling.core.isSnapshot
import org.jetbrains.kotlin.tooling.core.isStable
import org.jetbrains.plugins.gradle.tooling.util.VersionMatcher
import java.io.File
object GradleKotlinTestUtils {
fun listRepositories(useKts: Boolean, gradleVersion: String, kotlinVersion: String? = null) =
listRepositories(useKts, GradleVersion.version(gradleVersion), kotlinVersion?.let(::KotlinToolingVersion))
fun listRepositories(useKts: Boolean, gradleVersion: GradleVersion, kotlinVersion: KotlinToolingVersion? = null): String {
if (useKts && kotlinVersion != null)
return listKtsRepositoriesOptimized(gradleVersion, kotlinVersion)
fun gradleVersionMatches(version: String): Boolean =
VersionMatcher(gradleVersion).isVersionMatch(version, true)
fun MutableList<String>.addUrl(url: String) {
this += if (useKts) "maven(\"$url\")" else "maven { url '$url' }"
}
val repositories = mutableListOf<String>()
repositories.add("mavenLocal()")
repositories.addUrl("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2/")
repositories.addUrl("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap")
repositories.addUrl("https://cache-redirector.jetbrains.com/dl.google.com.android.maven2/")
repositories.addUrl("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2/")
if (!gradleVersionMatches("7.0+")) {
repositories.addUrl("https://cache-redirector.jetbrains.com/jcenter/")
}
return repositories.joinToString("\n")
}
private fun listKtsRepositoriesOptimized(gradleVersion: GradleVersion, kotlinVersion: KotlinToolingVersion): String {
val repositories = mutableListOf<String>()
operator fun String.unaryPlus() = repositories.add(this)
if (kotlinVersion.isSnapshot) {
+"mavenLocal()"
}
if (!kotlinVersion.isStable) {
if (localKotlinGradlePluginExists(kotlinVersion)) {
+"mavenLocal()"
} else +"""
maven("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap") {
content {
includeVersionByRegex(".*jetbrains.*", ".*", "$kotlinVersion")
}
}
""".trimIndent()
}
+"""maven("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2/")"""
+"""maven("https://cache-redirector.jetbrains.com/dl.google.com.android.maven2/")"""
+"""maven("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2/")"""
if (!VersionMatcher(gradleVersion).isVersionMatch("7.0+", true)) {
+"""maven("https://cache-redirector.jetbrains.com/jcenter/")"""
}
return repositories.joinToString("\n")
}
}
private fun localKotlinGradlePluginExists(kotlinGradlePluginVersion: KotlinToolingVersion): Boolean {
val localKotlinGradlePlugin = File(System.getProperty("user.home"))
.resolve(".m2/repository")
.resolve("org/jetbrains/kotlin/kotlin-gradle-plugin/$kotlinGradlePluginVersion")
return localKotlinGradlePlugin.exists()
}
| apache-2.0 | 9fc10a0ed253cc9905933a3f079e21ce | 44.594937 | 158 | 0.679622 | 4.582697 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/model/MenuData.kt | 1 | 1101 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.model
import com.google.gson.annotations.SerializedName
import se.creotec.chscardbalance2.Constants
class MenuData {
@SerializedName("language")
var language: String = Constants.PREFS_MENU_LANGUAGE_DEFAULT
@SerializedName("menu")
var menu: List<Restaurant> = ArrayList()
get() = field.sorted()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
val menuData = other as MenuData
return menu == menuData.menu && language == menuData.language
}
override fun hashCode(): Int {
var result = language.hashCode()
result = 31 * result + menu.hashCode()
return result
}
override fun toString(): String {
return "MenuData{" +
"language='" + language + '\'' +
", menu=" + menu +
'}'
}
}
| mit | 8a29fa785f7fd6249b93b56c450ae97e | 29.555556 | 70 | 0.619091 | 4.417671 | false | false | false | false |
mdaniel/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/EditorCodingAssistanceLesson.kt | 2 | 4323 | // 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 training.learn.lesson.general.assistance
import com.intellij.ide.IdeBundle
import com.intellij.ui.HyperlinkLabel
import org.apache.commons.lang.StringEscapeUtils
import org.jetbrains.annotations.Nls
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.util.isToStringContains
import java.awt.Rectangle
import javax.swing.JEditorPane
abstract class EditorCodingAssistanceLesson(private val sample: LessonSample) :
KLesson("CodeAssistance.EditorCodingAssistance", LessonsBundle.message("editor.coding.assistance.lesson.name")) {
protected abstract val errorIntentionText: String
protected abstract val warningIntentionText: String
protected abstract val errorFixedText: String
protected abstract val warningFixedText: String
protected abstract val variableNameToHighlight: String
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
actionTask("GotoNextError") {
restoreIfModifiedOrMoved(sample)
LessonsBundle.message("editor.coding.assistance.goto.next.error", action(it))
}
task("ShowIntentionActions") {
text(getFixErrorTaskText())
stateCheck { editor.document.charsSequence.contains(errorFixedText) }
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
invokeIntention(errorIntentionText)
}
}
task("GotoNextError") {
text(LessonsBundle.message("editor.coding.assistance.goto.next.warning", action(it)))
trigger(it)
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
actions(it)
}
}
task("ShowErrorDescription") {
text(LessonsBundle.message("editor.coding.assistance.show.warning.description", action(it)))
// escapeHtml required in case of hieroglyph localization
val inspectionInfoLabelText = StringEscapeUtils.escapeHtml(IdeBundle.message("inspection.message.inspection.info"))
triggerUI().component { ui: JEditorPane ->
ui.text.isToStringContains(inspectionInfoLabelText)
}
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
invokeActionViaShortcut("CONTROL F1")
invokeActionViaShortcut("CONTROL F1")
}
}
task {
text(LessonsBundle.message("editor.coding.assistance.fix.warning") + " " + getFixWarningText())
triggerAndBorderHighlight().componentPart { ui: HyperlinkLabel ->
if (ui.text == warningIntentionText) {
Rectangle(ui.x - 20, ui.y - 10, ui.width + 125, ui.height + 10)
}
else null
}
stateCheck { editor.document.charsSequence.contains(warningFixedText) }
restoreByUi()
test {
Thread.sleep(500)
invokeActionViaShortcut("ALT SHIFT ENTER")
}
}
caret(variableNameToHighlight)
task("HighlightUsagesInFile") {
text(LessonsBundle.message("editor.coding.assistance.highlight.usages", action(it)))
trigger(it) { checkSymbolAtCaretIsLetter() }
restoreIfModifiedOrMoved()
test { actions(it) }
}
}
protected open fun LearningDslBase.getFixErrorTaskText(): @Nls String {
return LessonsBundle.message("editor.coding.assistance.fix.error", action("ShowIntentionActions"),
strong(errorIntentionText))
}
protected abstract fun getFixWarningText(): @Nls String
private fun TaskTestContext.invokeIntention(intentionText: String) {
actions("ShowIntentionActions")
ideFrame {
jList(intentionText).clickItem(intentionText)
}
}
private fun TaskRuntimeContext.checkSymbolAtCaretIsLetter(): Boolean {
val caretOffset = editor.caretModel.offset
val sequence = editor.document.charsSequence
return caretOffset != sequence.length && sequence[caretOffset].isLetter()
}
override val suitableTips = listOf("HighlightUsagesInFile", "NextPrevError", "NavigateBetweenErrors")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("editor.coding.assistance.help.link"),
LessonUtil.getHelpLink("working-with-source-code.html")),
)
} | apache-2.0 | 233e4bdbd09d61bfef35b382ddcff9a2 | 34.442623 | 140 | 0.720796 | 4.868243 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/abl-api-client/src/main/kotlin/dev/mfazio/abl/api/services/AndroidBaseballLeagueService.kt | 1 | 3213 | package dev.mfazio.abl.api.services
import dev.mfazio.abl.api.models.*
import retrofit2.http.*
import java.time.LocalDate
import java.time.LocalDateTime
interface AndroidBaseballLeagueService {
@GET("teams")
suspend fun getTeams(): List<TeamApiModel>
@GET("games")
suspend fun getGames(
@Query("currentDateTime") currentDateTime: LocalDateTime? = null,
@Query("requestedDate") requestedDate: LocalDate? = null,
@Query("teamId") teamId: String? = null
): List<ScheduledGameApiModel>
@GET("players")
suspend fun getPlayers(
@Query("pageNumber") pageNumber: Int? = null,
@Query("pageSize") pageSize: Int? = null,
@Query("query") query: String? = null,
@Query("teamId") teamId: String? = null,
@Query("position") position: PositionApiModel? = null,
@Query("isPitcher") isPitcher: Boolean? = null,
@Query("isOutfielder") isOutfielder: Boolean? = null
): List<PlayerApiModel>
@GET("players/{playerId}")
suspend fun getSinglePlayer(
@Path("playerId") playerId: String,
@Query("currentDate") currentDate: LocalDate? = null
): BoxScoreItemsApiModel
@GET("standings")
suspend fun getStandings(@Query("currentDate") currentDate: LocalDate? = null): List<TeamStandingApiModel>
@GET("stats/batting")
suspend fun getBattingStats(
@Query("currentDate") currentDate: LocalDate? = null,
@Query("pageNumber") pageNumber: Int? = null,
@Query("pageSize") pageSize: Int? = null,
@Query("sortStat") sortStat: String? = null,
@Query("sortDescending") sortDescending: Boolean? = null,
@Query("teamId") teamId: String? = null,
@Query("position") position: PositionApiModel? = null
): List<BatterBoxScoreItemApiModel>
@GET("stats/pitching")
suspend fun getPitchingStats(
@Query("currentDate") currentDate: LocalDate? = null,
@Query("pageNumber") pageNumber: Int? = null,
@Query("pageSize") pageSize: Int? = null,
@Query("sortStat") sortStat: String? = null,
@Query("sortDescending") sortDescending: Boolean? = null,
@Query("teamId") teamId: String? = null,
@Query("position") position: PositionApiModel? = null
): List<PitcherBoxScoreItemApiModel>
@GET("leaders/batting")
suspend fun getBattingLeaders(
@Query("currentDate") currentDate: LocalDate? = null
): List<BatterBoxScoreItemApiModel>
@GET("leaders/pitching")
suspend fun getPitchingLeaders(
@Query("currentDate") currentDate: LocalDate? = null
): List<PitcherBoxScoreItemApiModel>
@POST("app/notifications")
suspend fun sendNotificationToPhone(
@Query("notificationType") notificationType: NotificationTypeApiModel,
@Query("phoneToken") phoneToken: String,
@Query("itemId") itemId: String,
@Query("dataOnly") dataOnly: Boolean = false
)
@GET("app/settings")
suspend fun getAppSettingsForUser(
@Query("userId") userId: String
): AppSettingsApiModel
@POST("app/settings")
suspend fun saveAppSettings(
@Body settings: AppSettingsApiModel
): AppSettingsApiModel
} | apache-2.0 | ba26abebdbb3b9a10ff2eb303cf03d8e | 35.11236 | 110 | 0.659819 | 4.194517 | false | false | false | false |
WeAreFrancis/auth-service | src/test/kotlin/com/wearefrancis/auth/security/JwtUserServiceTest.kt | 1 | 1731 | package com.wearefrancis.auth.security
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import com.wearefrancis.auth.domain.User
import com.wearefrancis.auth.repository.UserRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.springframework.security.core.userdetails.UsernameNotFoundException
class JwtUserServiceTest {
private lateinit var jwtUserService: JwtUserService
@Mock
private lateinit var userRepository: UserRepository
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
jwtUserService = JwtUserService(userRepository)
}
@Test
fun loadUserByUsernameShouldThrowUsernameNotFoundExceptionIfUserIsNotFound() {
// GIVEN
val username = "gleroy"
try {
// WHEN
jwtUserService.loadUserByUsername(username)
// THEN
verify(userRepository).findByUsername(username)
fail()
} catch (exception: UsernameNotFoundException) {
assertThat(exception.message).isEqualTo("User $username not found")
}
}
@Test
fun loadUserByUsernameShouldReturnTheUserThatHasTheGivenUsername() {
// GIVEN
val user = User(
username = "gleroy"
)
whenever(userRepository.findByUsername(user.username)).thenReturn(user)
// WHEN
val jwtUser = jwtUserService.loadUserByUsername(user.username)
// THEN
assertThat(jwtUser).isSameAs(user)
verify(userRepository).findByUsername(user.username)
}
} | apache-2.0 | 24eacbea776eae629f8c77f5c622101a | 27.866667 | 82 | 0.701906 | 4.974138 | false | true | false | false |
InsideZhou/Instep | dao/src/main/kotlin/instep/dao/sql/impl/DefaultTableSelectPlan.kt | 1 | 5944 | package instep.dao.sql.impl
import instep.dao.sql.*
open class DefaultTableSelectPlan(override val from: Table) : TableSelectPlan, AbstractTablePlan<TableSelectPlan>() {
protected open val selectWords get() = if (distinct) "SELECT DISTINCT" else "SELECT"
protected open val baseSql: String
get() {
val selectTexts = if (select.isEmpty()) {
"*"
}
else {
select.joinToString(",") {
var txt = it.text
if (it.alias.isNotBlank()) {
txt += " AS ${it.alias}"
}
txt
}
}
return "$selectWords $selectTexts FROM ${from.tableName}"
}
protected open fun joinTypeToStr(joinType: JoinType): String = when (joinType) {
JoinType.Left -> "LEFT JOIN"
JoinType.Right -> "RIGHT JOIN"
JoinType.Inner -> "JOIN"
JoinType.Outer -> "OUTER JOIN"
}
protected open val joinTxt: String
get() {
val txt = join.joinToString("\n") { "${joinTypeToStr(it.joinType)} ${it.text} ON ${it.joinCondition.text}" }
return if (txt.isEmpty()) "" else "\n$txt"
}
protected open val whereTxt: String
get() {
return if (where.text.isBlank()) {
""
}
else {
"\nWHERE ${where.text}"
}
}
protected open val groupByTxt: String
get() {
return if (groupBy.isEmpty()) {
""
}
else {
val txt = groupBy.joinToString(",") {
if (it.table == from) {
it.name
}
else {
it.qualifiedName
}
}
"\nGROUP BY $txt"
}
}
protected open val havingTxt: String
get() {
return if (having.text.isBlank()) {
""
}
else {
"\nHAVING ${having.text}"
}
}
val orderByTxt: String
get() {
val txt = orderBy.map {
val result = if (it.descending) "${it.column.qualifiedName} DESC" else it.column.qualifiedName
return@map if (it.nullFirst) "$result NULL FIRST" else result
}.joinToString(",")
return if (txt.isEmpty()) "" else "\nORDER BY $txt"
}
override val statement: String
get() {
val sql = baseSql + joinTxt + whereTxt + groupByTxt + havingTxt + orderByTxt
return from.dialect.pagination.statement(sql, limit, offset)
}
override val parameters: List<Any?>
get() {
val params = join.flatMap { it.parameters + it.joinCondition.parameters } + where.parameters + having.parameters
return from.dialect.pagination.parameters(params, limit, offset)
}
override var select = emptyList<SelectExpression>()
override var distinct: Boolean = false
override var join = emptyList<JoinItem<*>>()
override var where: Condition = Condition.empty
override var groupBy = emptyList<Column<*>>()
override var having: Condition = Condition.empty
override var orderBy: List<OrderBy> = emptyList()
override var limit: Int = -1
override var offset: Int = 0
override var alias: String = ""
override fun selectExpression(vararg selectExpression: SelectExpression): TableSelectPlan {
this.select += selectExpression.toList()
return this
}
override fun distinct(): TableSelectPlan {
this.distinct = true
return this
}
override fun groupBy(vararg columns: Column<*>): TableSelectPlan {
this.groupBy += columns
return this
}
override fun having(vararg conditions: Condition): TableSelectPlan {
this.having = if (this.having.text.isBlank()) {
conditions.reduce(Condition::and)
}
else {
this.having.and(conditions.reduce(Condition::and).grouped())
}
return this
}
override fun orderBy(vararg orderBys: OrderBy): TableSelectPlan {
this.orderBy += orderBys
return this
}
override fun limit(limit: Int): TableSelectPlan {
this.limit = limit
return this
}
override fun offset(offset: Int): TableSelectPlan {
this.offset = offset
return this
}
override fun join(joinItem: JoinItem<*>): TableSelectPlan {
this.join += listOf(joinItem)
return this
}
override fun join(from: Column<*>, to: Column<*>): TableSelectPlan {
val condition = Condition("${from.table.tableName}.${from.name} = ${to.table.tableName}.${to.name}")
return join(TableJoinItem(JoinType.Inner, to, condition))
}
override fun join(to: Column<*>): TableSelectPlan {
val from = this.from.primaryKey ?: throw IllegalArgumentException("primary column required as join from")
return join(from, to)
}
override fun leftJoin(from: Column<*>, to: Column<*>): TableSelectPlan {
val condition = Condition("${from.table.tableName}.${from.name} = ${to.table.tableName}.${to.name}")
return join(TableJoinItem(JoinType.Left, from, condition))
}
override fun rightJoin(from: Column<*>, to: Column<*>): TableSelectPlan {
val condition = Condition("${from.table.tableName}.${from.name} = ${to.table.tableName}.${to.name}")
return join(TableJoinItem(JoinType.Right, from, condition))
}
override fun outerJoin(from: Column<*>, to: Column<*>): TableSelectPlan {
val condition = Condition("${from.table.tableName}.${from.name} = ${to.table.tableName}.${to.name}")
return join(TableJoinItem(JoinType.Outer, from, condition))
}
} | bsd-2-clause | f81f18cfc56995a61e1aa4a751127679 | 29.963542 | 124 | 0.558546 | 4.629283 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | ui/ui_doorbell_list/src/androidTest/kotlin/siarhei/luskanau/iot/doorbell/ui/doorbelllist/DoorbellListFragmentTest.kt | 1 | 1612 | package siarhei.luskanau.iot.doorbell.ui.doorbelllist
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle
import androidx.paging.PagingData
import com.karumi.shot.ScreenshotTest
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import siarhei.luskanau.iot.doorbell.data.model.DoorbellData
import kotlin.test.Test
import siarhei.luskanau.iot.doorbell.ui.common.R as CommonR
class DoorbellListFragmentTest : ScreenshotTest {
private fun createFragment(pagingData: PagingData<DoorbellData>) = DoorbellListFragment {
mockk(relaxed = true, relaxUnitFun = true) {
every { doorbellListFlow } returns flowOf(pagingData)
}
}
@Test
fun testNormalState() {
val scenario = launchFragmentInContainer(themeResId = CommonR.style.AppTheme) {
createFragment(PagingData.from(listOf(DoorbellData(doorbellId = "doorbellId"))))
}
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".normal"
)
}
}
@Test
fun testEmptyState() {
val scenario = launchFragmentInContainer(themeResId = CommonR.style.AppTheme) {
createFragment(PagingData.empty())
}
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".empty"
)
}
}
}
| mit | 372c7d4e0a4cf8a0034df3d5eb297256 | 31.897959 | 93 | 0.671836 | 4.855422 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/OverridesAndGenerics.kt | 4 | 1142 | interface MyTrait<T> {
fun foo(t: T) : T
}
abstract class MyAbstractClass<T> {
abstract fun bar(t: T) : T
}
open class MyGenericClass<T> : MyTrait<T>, MyAbstractClass<T>() {
override fun foo(t: T) = t
override fun bar(t: T) = t
}
class MyChildClass : MyGenericClass<Int>() {}
class MyChildClass1<T> : MyGenericClass<T>() {}
class MyChildClass2<T> : MyGenericClass<T>() {
fun <error>foo</error>(t: T) = t
override fun bar(t: T) = t
}
open class MyClass : MyTrait<Int>, MyAbstractClass<String>() {
override fun foo(t: Int) = t
override fun bar(t: String) = t
}
<error>class MyIllegalGenericClass1</error><T> : MyTrait<T>, MyAbstractClass<T>() {}
<error>class MyIllegalGenericClass2</error><T, R> : MyTrait<T>, MyAbstractClass<R>() {
<error>override</error> fun foo(r: R) = r
}
<error>class MyIllegalClass1</error> : MyTrait<Int>, MyAbstractClass<String>() {}
<error>class MyIllegalClass2</error><T> : MyTrait<Int>, MyAbstractClass<Int>() {
fun foo(t: T) = t
fun bar(t: T) = t
}
| apache-2.0 | 38f705191b9ca813ade11fa69f852c97 | 31.628571 | 90 | 0.58669 | 3.291066 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CallableUsageReplacementStrategy.kt | 4 | 3642 | // 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.codeInliner
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.intentions.isInvokeOperator
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
private val LOG = Logger.getInstance(CallableUsageReplacementStrategy::class.java)
class CallableUsageReplacementStrategy(
private val replacement: CodeToInline,
private val inlineSetter: Boolean = false
) : UsageReplacementStrategy {
override fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? {
val bindingContext = usage.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = usage.getResolvedCall(bindingContext) ?: return null
if (!resolvedCall.status.isSuccess) return null
val callElement = when (resolvedCall) {
is VariableAsFunctionResolvedCall -> {
val callElement = resolvedCall.variableCall.call.callElement
if (resolvedCall.resultingDescriptor.isInvokeOperator &&
replacement.mainExpression?.getPossiblyQualifiedCallExpression() != null
) {
callElement.parent as? KtCallExpression ?: callElement
} else {
callElement
}
}
else -> resolvedCall.call.callElement
}
if (!CodeInliner.canBeReplaced(callElement)) return null
val languageVersionSettings = usage.getResolutionFacade().languageVersionSettings
//TODO: precheck pattern correctness for annotation entry
return when {
usage is KtArrayAccessExpression || usage is KtCallExpression -> {
{
val nameExpression = OperatorToFunctionIntention.convert(usage).second
createReplacer(nameExpression)?.invoke()
}
}
usage is KtOperationReferenceExpression && usage.getReferencedNameElementType() != KtTokens.IDENTIFIER -> {
{
val nameExpression = OperatorToFunctionIntention.convert(usage.parent as KtExpression).second
createReplacer(nameExpression)?.invoke()
}
}
usage is KtSimpleNameExpression -> {
{
CodeInliner(languageVersionSettings, usage, bindingContext, resolvedCall, callElement, inlineSetter, replacement).doInline()
}
}
else -> {
val exceptionWithAttachments = KotlinExceptionWithAttachments("Unsupported usage")
.withAttachment("type", usage)
.withPsiAttachment("usage.kt", usage)
LOG.error(exceptionWithAttachments)
null
}
}
}
}
| apache-2.0 | 7eed3418e0d0e87bd627f93de9a08d01 | 45.101266 | 158 | 0.681219 | 6.009901 | false | false | false | false |
Abdel-RhmanAli/Inventory-App | app/src/main/java/com/example/android/inventory/util/IntentExtentionFunctions.kt | 1 | 1112 | package com.example.android.inventory.util
import android.content.Intent
import com.example.android.inventory.model.Item
fun Intent.setItem(item: Item) {
with(StringHelper) {
with(item) {
putExtra(ITEM_ID_KEY, id)
putExtra(ITEM_NAME_KEY, name)
putExtra(iTEM_TYPE_KEY, type)
putExtra(ITEM_SUPPLIER_KEY, amount)
putExtra(ITEM_AMOUNT_KEY, supplier)
val converters = Converters()
putExtra(ITEM_PICTURE_KEY, converters.bitmapToByteArray(picture))
}
}
}
fun Intent.getItem(): Item {
val item = Item()
with(StringHelper) {
val converters = Converters()
item.apply {
id = getIntExtra(ITEM_ID_KEY, -1)
name = getStringExtra(ITEM_NAME_KEY)
type = getStringExtra(iTEM_TYPE_KEY)
amount = getStringExtra(ITEM_SUPPLIER_KEY)
supplier = getStringExtra(ITEM_AMOUNT_KEY)
picture = converters.byteArrayToBitmap(getByteArrayExtra(ITEM_PICTURE_KEY))
}
}
return item
}
| apache-2.0 | c1eccb390fba4e925d490e15617e9850 | 27.263158 | 87 | 0.592626 | 4.103321 | false | false | false | false |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/DependentResolver.kt | 3 | 2300 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.PsiPolyVariantReference
import com.intellij.util.Consumer
import com.intellij.util.SmartList
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
abstract class DependentResolver<T : GroovyReference> : GroovyResolver<T> {
companion object {
/**
* Given: resolve was called on a reference a.r1.r2...rN.
* Its dependencies: a, a.r1, a.r1.r2, ... , a.r1.r2...rN-1.
* We resolve dependencies in a loop.
* Assume currently resolving dependency is a.r1.r2...rK, K < N.
* By the time it is being processed all its dependencies are already resolved and the resolve results are stored in a list,
* so we do not need to collect/resolve its dependencies again.
* This field is needed to memoize currently resolving dependencies.
*/
private val resolvingDependencies = ThreadLocal.withInitial { mutableSetOf<PsiPolyVariantReference>() }
}
final override fun resolve(ref: T, incomplete: Boolean): Collection<GroovyResolveResult> {
val dependencies = resolveDependencies(ref, incomplete)
val result = doResolve(ref, incomplete)
dependencies?.clear()
return result
}
private fun resolveDependencies(ref: T, incomplete: Boolean): MutableCollection<Any>? {
if (ref in resolvingDependencies.get()) return null
return collectDependencies(ref)?.mapNotNullTo(mutableListOf()) {
if (ref === it) return@mapNotNullTo null
try {
resolvingDependencies.get().add(it)
it.multiResolve(incomplete)
}
finally {
resolvingDependencies.get().remove(it)
}
}
}
protected open fun collectDependencies(ref: T): Collection<PsiPolyVariantReference>? {
val result = SmartList<PsiPolyVariantReference>()
collectDependencies(ref, Consumer {
result += it
})
return result
}
protected open fun collectDependencies(ref: T, consumer: Consumer<in PsiPolyVariantReference>) {}
protected abstract fun doResolve(ref: T, incomplete: Boolean): Collection<GroovyResolveResult>
} | apache-2.0 | 8fd18c118e8ba664b4a9e4e6a28c139a | 39.368421 | 140 | 0.726957 | 4.483431 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/util/connection.kt | 1 | 2166 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@file:Suppress("unused")
package io.github.pdvrieze.kotlinsql.direct
import java.sql.Connection
import java.sql.ResultSet
import java.sql.Statement
/**
* Executes the given [block] function on this resource and then closes it down correctly whether an exception
* is thrown or not.
*
* @param block a function to process this closable resource.
* @return the result of [block] function on this closable resource.
*/
inline fun <T : Connection, R> T.use(block: (T) -> R) = useHelper({ it.close() }, block)
@Suppress("unused")
inline fun <T : Connection, R> T.useTransacted(block: (T) -> R): R = useHelper({ it.close() }) {
it.autoCommit = false
try {
val result = block(it)
it.commit()
return result
} catch (e: Exception) {
it.rollback()
throw e
}
}
@PublishedApi
internal inline fun <T, R> T.useHelper(close: (T) -> Unit, block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close(this)
} catch (closeException: Exception) {
// drop for now.
}
throw e
} finally {
if (!closed) {
close(this)
}
}
}
inline fun <T : Statement, R> T.use(block: (T) -> R) = useHelper({ it.close() }, block)
inline fun <T : ResultSet, R> T.use(block: (T) -> R) = useHelper({ it.close() }, block)
| apache-2.0 | 4a30e2ddbae933096d87832b055cb354 | 28.671233 | 110 | 0.638966 | 3.664975 | false | false | false | false |
ftomassetti/kolasu | emf/src/main/kotlin/com/strumenta/kolasu/emf/Model.kt | 1 | 19115 | package com.strumenta.kolasu.emf
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.strumenta.kolasu.model.*
import com.strumenta.kolasu.parsing.ParseTreeOrigin
import com.strumenta.kolasu.validation.Issue
import com.strumenta.kolasu.validation.Result
import org.eclipse.emf.common.util.EList
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.*
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.emfcloud.jackson.resource.JsonResourceFactory
import java.io.ByteArrayOutputStream
import java.io.File
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
fun EPackage.getEClass(javaClass: Class<*>): EClass {
return this.getEClass(javaClass.eClassifierName)
}
fun EPackage.getEClass(klass: KClass<*>): EClass {
return this.getEClass(klass.eClassifierName)
}
fun EPackage.getEClass(name: String): EClass {
return (this.eClassifiers.find { it.name == name } ?: throw IllegalArgumentException("EClass not found: $name"))
as EClass
}
fun EPackage.getEDataType(name: String): EDataType {
return (this.eClassifiers.find { it.name == name } ?: throw IllegalArgumentException("EDataType not found: $name"))
as EDataType
}
fun EPackage.getEEnum(javaClass: Class<*>): EEnum {
return (
this.eClassifiers.find { it.name == javaClass.eClassifierName } ?: throw IllegalArgumentException(
"Class not found: $javaClass"
)
) as EEnum
}
fun Any.dataToEObject(ePackage: EPackage): EObject {
val ec = ePackage.getEClass(this::class)
val eo = ePackage.eFactoryInstance.create(ec)
ec.eAllAttributes.forEach { attr ->
val prop = this::class.memberProperties.find { it.name == attr.name } as KProperty1<Any, *>?
if (prop != null) {
val value = prop.getValue(this, prop)
eo.eSet(attr, value)
} else {
throw RuntimeException("Unable to set attribute $attr in $this")
}
}
return eo
}
fun Point.toEObject(): EObject {
val ec = STARLASU_METAMODEL.getEClass("Point")
val eo = STARLASU_METAMODEL.eFactoryInstance.create(ec)
eo.eSet(ec.getEStructuralFeature("line"), this.line)
eo.eSet(ec.getEStructuralFeature("column"), this.column)
return eo
}
fun Position.toEObject(): EObject {
val ec = STARLASU_METAMODEL.getEClass("Position")
val eo = STARLASU_METAMODEL.eFactoryInstance.create(ec)
eo.eSet(ec.getEStructuralFeature("start"), this.start.toEObject())
eo.eSet(ec.getEStructuralFeature("end"), this.end.toEObject())
return eo
}
fun <T : Node> Result<T>.toEObject(astPackage: EPackage): EObject {
val resultEO = makeResultEObject(this)
val rootSF = resultEO.eClass().eAllStructuralFeatures.find { it.name == "root" }!!
if (root != null) {
resultEO.eSet(rootSF, root!!.getOrCreateEObject(astPackage))
}
return resultEO
}
private fun makeResultEObject(result: Result<*>): EObject {
val resultEC = STARLASU_METAMODEL.getEClass(Result::class.java)
val resultEO = STARLASU_METAMODEL.eFactoryInstance.create(resultEC)
val issuesSF = resultEC.eAllStructuralFeatures.find { it.name == "issues" }!!
val issues = resultEO.eGet(issuesSF) as MutableList<EObject>
result.issues.forEach {
issues.add(it.toEObject())
}
return resultEO
}
fun <T : Node> Result<T>.toEObject(
resource: Resource,
kolasuToEMFMapping: KolasuToEMFMapping = KolasuToEMFMapping()
): EObject {
val resultEO = makeResultEObject(this)
val rootSF = resultEO.eClass().eAllStructuralFeatures.find { it.name == "root" }!!
if (root != null) {
resultEO.eSet(rootSF, kolasuToEMFMapping.getOrCreate(root!!, resource))
}
return resultEO
}
fun Issue.toEObject(): EObject {
val ec = STARLASU_METAMODEL.getEClass(Issue::class.java)
val eo = STARLASU_METAMODEL.eFactoryInstance.create(ec)
val et = STARLASU_METAMODEL.getEClassifier("IssueType")
val es = STARLASU_METAMODEL.getEClassifier("IssueSeverity")
val typeSF = ec.eAllStructuralFeatures.find { it.name == "type" }!!
eo.eSet(typeSF, (et as EEnum).getEEnumLiteral(type.ordinal))
val severitySF = ec.eAllStructuralFeatures.find { it.name == "severity" }!!
eo.eSet(severitySF, (es as EEnum).getEEnumLiteral(severity.ordinal))
val messageSF = ec.eAllStructuralFeatures.find { it.name == "message" }!!
eo.eSet(messageSF, message)
val positionSF = ec.eAllStructuralFeatures.find { it.name == "position" }!!
if (position != null) {
eo.eSet(positionSF, position!!.toEObject())
}
return eo
}
private fun toValue(ePackage: EPackage, value: Any?, kolasuToEMFMapping: KolasuToEMFMapping = KolasuToEMFMapping()):
Any? {
val pdValue: Any? = value
when (pdValue) {
is Enum<*> -> {
val ee = ePackage.getEEnum(pdValue.javaClass)
return ee.getEEnumLiteral(pdValue.name)
}
is LocalDate -> {
return toLocalDateObject(pdValue)
}
is LocalTime -> {
return toLocalTimeObject(pdValue)
}
is LocalDateTime -> {
val eClass = STARLASU_METAMODEL.getEClass("LocalDateTime")
val eObject = STARLASU_METAMODEL.eFactoryInstance.create(eClass)
val dateComponent = toLocalDateObject(pdValue.toLocalDate())
val timeComponent = toLocalTimeObject(pdValue.toLocalTime())
eObject.eSet(eClass.getEStructuralFeature("date"), dateComponent)
eObject.eSet(eClass.getEStructuralFeature("time"), timeComponent)
return eObject
}
else -> {
// this could be not a primitive value but a value that we mapped to an EClass
val eClass = if (pdValue != null) {
ePackage.eClassifiers.filterIsInstance<EClass>().find {
it.name == pdValue.javaClass.simpleName
}
} else null
return when {
eClass != null -> {
pdValue!!.dataToEObject(ePackage)
}
pdValue is ReferenceByName<*> -> {
val refEC = STARLASU_METAMODEL.getEClass("ReferenceByName")
val refEO = STARLASU_METAMODEL.eFactoryInstance.create(refEC)
refEO.eSet(refEC.getEStructuralFeature("name")!!, pdValue.name)
// Note that we could either find references to nodes we have already encountered and to nodes
// that we have not yet encountered
// In one case, the EObject for the referenced Node already exist in the kolasuToEMFMapping, so
// we just retrieve it.
// In the other case, we create the EObject right now and add it to the mapping, so that later the
// same EObject can be inserted in the containment relation where it belongs.
refEO.eSet(
refEC.getEStructuralFeature("referenced")!!,
(pdValue.referred as? Node)?.getOrCreateEObject(ePackage, kolasuToEMFMapping)
)
refEO
}
pdValue is Result<*> -> {
val resEC = STARLASU_METAMODEL.getEClass("Result")
val resEO = STARLASU_METAMODEL.eFactoryInstance.create(resEC)
if (pdValue.root is Node) {
resEO.eSet(
resEC.getEStructuralFeature("root"),
(pdValue.root as Node)
.getOrCreateEObject(ePackage, kolasuToEMFMapping)
)
} else {
resEO.eSet(resEC.getEStructuralFeature("root"), toValue(ePackage, pdValue.root))
}
val issues = resEO.eGet(resEC.getEStructuralFeature("issues")) as EList<EObject>
issues.addAll(pdValue.issues.map { it.toEObject() })
resEO
}
else -> pdValue
}
}
}
}
private fun toLocalTimeObject(value: LocalTime): EObject {
val eClass = STARLASU_METAMODEL.getEClass("LocalTime")
val eObject = STARLASU_METAMODEL.eFactoryInstance.create(eClass)
eObject.eSet(eClass.getEStructuralFeature("hour"), value.hour)
eObject.eSet(eClass.getEStructuralFeature("minute"), value.minute)
eObject.eSet(eClass.getEStructuralFeature("second"), value.second)
eObject.eSet(eClass.getEStructuralFeature("nanosecond"), value.nano)
return eObject
}
private fun toLocalDateObject(value: LocalDate): EObject {
val eClass = STARLASU_METAMODEL.getEClass("LocalDate")
val eObject = STARLASU_METAMODEL.eFactoryInstance.create(eClass)
eObject.eSet(eClass.getEStructuralFeature("year"), value.year)
eObject.eSet(eClass.getEStructuralFeature("month"), value.monthValue)
eObject.eSet(eClass.getEStructuralFeature("dayOfMonth"), value.dayOfMonth)
return eObject
}
fun packageName(klass: KClass<*>): String =
klass.qualifiedName!!.substring(0, klass.qualifiedName!!.lastIndexOf("."))
fun EPackage.findEClass(klass: KClass<*>): EClass? {
return this.findEClass(klass.eClassifierName)
}
fun EPackage.findEClass(name: String): EClass? {
return this.eClassifiers.find { it is EClass && it.name == name } as EClass?
}
fun Resource.findEClass(klass: KClass<*>): EClass? {
val eClass = findEClassJustInThisResource(klass)
if (eClass == null) {
val otherResources = this.resourceSet?.resources?.filter { it != this } ?: emptyList()
for (r in otherResources) {
val c = r.findEClassJustInThisResource(klass)
if (c != null) {
return c
}
}
return null
} else {
return eClass
}
}
fun Resource.findEClassJustInThisResource(klass: KClass<*>): EClass? {
val ePackage = this.contents.find { it is EPackage && it.name == packageName(klass) } as EPackage?
return ePackage?.findEClass(klass)
}
fun Resource.getEClass(klass: KClass<*>): EClass = this.findEClass(klass)
?: throw ClassNotFoundException(klass.qualifiedName)
fun Node.toEObject(ePackage: EPackage, mapping: KolasuToEMFMapping = KolasuToEMFMapping()): EObject =
toEObject(ePackage.eResource(), mapping)
/**
* This method retrieves the EObject already built for this Node or create it if it does not exist.
*/
fun Node.getOrCreateEObject(ePackage: EPackage, mapping: KolasuToEMFMapping = KolasuToEMFMapping()): EObject =
getOrCreateEObject(ePackage.eResource(), mapping)
fun EClass.instantiate(): EObject {
return this.ePackage.eFactoryInstance.create(this)
}
class KolasuToEMFMapping {
private val nodeToEObjects = IdentityHashMap<Node, EObject>()
fun associate(node: Node, eo: EObject) {
nodeToEObjects[node] = eo
}
fun getAssociatedEObject(node: Node): EObject? {
return nodeToEObjects[node]
}
/**
* If a corresponding EObject for the node has been already created, then it is returned.
* Otherwise the EObject is created and returned. The same EObject is also stored and associated with the Node,
* so that future calls to this method will return that EObject.
*/
fun getOrCreate(node: Node, eResource: Resource): EObject {
val existing = getAssociatedEObject(node)
return if (existing != null) {
existing
} else {
val eo = node.toEObject(eResource, this)
associate(node, eo)
eo
}
}
val size
get() = nodeToEObjects.size
}
/**
* This method retrieves the EObject already built for this Node or create it if it does not exist.
*/
fun Node.getOrCreateEObject(eResource: Resource, mapping: KolasuToEMFMapping = KolasuToEMFMapping()): EObject {
return mapping.getOrCreate(this, eResource)
}
private fun setOrigin(
eo: EObject,
origin: Origin?,
resource: Resource,
mapping: KolasuToEMFMapping = KolasuToEMFMapping()
) {
if (origin == null) {
return
}
val astNode = STARLASU_METAMODEL.getEClass("ASTNode")
val originSF = astNode.getEStructuralFeature("origin")
when (origin) {
is Node -> {
val nodeOriginClass = STARLASU_METAMODEL.getEClass("NodeOrigin")
val nodeSF = nodeOriginClass.getEStructuralFeature("node")
val nodeOrigin = nodeOriginClass.instantiate()
val eoCorrespondingToOrigin = mapping.getAssociatedEObject(origin) ?: throw IllegalStateException(
"No EObject mapped to origin $origin. " +
"Mapping contains ${mapping.size} entries"
)
nodeOrigin.eSet(nodeSF, eoCorrespondingToOrigin)
eo.eSet(originSF, nodeOrigin)
}
is ParseTreeOrigin -> {
// The ParseTreeOrigin is not saved in EMF as we do not want to replicate the whole parse-tree
eo.eSet(originSF, null)
}
else -> {
throw IllegalStateException("Only origins representing Nodes or ParseTreeOrigins are currently supported")
}
}
}
private fun setDestination(
eo: EObject,
destination: Destination?,
eResource: Resource,
mapping: KolasuToEMFMapping = KolasuToEMFMapping()
) {
val astNode = STARLASU_METAMODEL.getEClass("ASTNode")
when (destination) {
null -> return
is Node -> {
val nodeDestination = STARLASU_METAMODEL.getEClass("NodeDestination")
val nodeDestinationInstance = nodeDestination.instantiate()
val nodeSF = nodeDestination.getEStructuralFeature("node")
val eoCorrespondingToOrigin = destination.getOrCreateEObject(eResource, mapping)
nodeDestinationInstance.eSet(nodeSF, eoCorrespondingToOrigin)
val destinationSF = astNode.getEStructuralFeature("destination")
eo.eSet(destinationSF, nodeDestinationInstance)
}
is TextFileDestination -> {
val textFileInstance = STARLASU_METAMODEL.getEClass("TextFileDestination").instantiate()
val positionSF = STARLASU_METAMODEL.getEClass("TextFileDestination").getEStructuralFeature("position")
textFileInstance.eSet(positionSF, destination.position?.toEObject())
val destinationSF = astNode.getEStructuralFeature("destination")
eo.eSet(destinationSF, textFileInstance)
}
else -> {
throw IllegalStateException(
"Only destinations represented Nodes or TextFileDestinations are currently supported"
)
}
}
}
/**
* Translates this node – and, recursively, its descendants – into an [EObject] (EMF/Ecore representation).
*
* The classes of the node are resolved against the provided [Resource]. That is, the resource must contain:
* - the [Kolasu metamodel package][STARLASU_METAMODEL]
* - every [EPackage] containing the definitions of the node classes in the tree.
*/
fun Node.toEObject(eResource: Resource, mapping: KolasuToEMFMapping = KolasuToEMFMapping()): EObject {
try {
val ec = eResource.getEClass(this::class)
val eo = ec.ePackage.eFactoryInstance.create(ec)
mapping.associate(this, eo)
val astNode = STARLASU_METAMODEL.getEClass("ASTNode")
val position = astNode.getEStructuralFeature("position")
val positionValue = this.position?.toEObject()
eo.eSet(position, positionValue)
setOrigin(eo, this.origin, eResource, mapping)
setDestination(eo, this.destination, eResource, mapping)
this.processProperties { pd ->
val esf = ec.eAllStructuralFeatures.find { it.name == pd.name }!!
if (pd.provideNodes) {
if (pd.multiple) {
val elist = eo.eGet(esf) as MutableList<EObject?>
(pd.value as List<*>?)?.forEach {
try {
val childEO = (it as Node?)?.getOrCreateEObject(eResource, mapping)
elist.add(childEO)
} catch (e: Exception) {
throw RuntimeException("Unable to map to EObject child $it in property $pd of $this", e)
}
}
} else {
if (pd.value == null) {
eo.eSet(esf, null)
} else {
eo.eSet(esf, (pd.value as Node).getOrCreateEObject(eResource, mapping))
}
}
} else {
if (pd.multiple) {
val elist = eo.eGet(esf) as MutableList<Any>
(pd.value as List<*>?)?.forEach {
try {
val childValue = toValue(ec.ePackage, it, mapping)
elist.add(childValue!!)
} catch (e: Exception) {
throw RuntimeException("Unable to map to EObject child $it in property $pd of $this", e)
}
}
} else try {
eo.eSet(esf, toValue(ec.ePackage, pd.value, mapping))
} catch (e: Exception) {
throw RuntimeException("Unable to set property $pd. Structural feature: $esf", e)
}
}
}
return eo
} catch (e: Exception) {
throw RuntimeException("Unable to map to EObject $this", e)
}
}
fun EObject.saveXMI(xmiFile: File) {
val resource: Resource = createResource(URI.createFileURI(xmiFile.absolutePath))!!
resource.contents.add(this)
resource.save(null)
}
fun EPackage.saveAsJson(jsonFile: File, restoringURI: Boolean = true) {
val startURI = this.eResource().uri
(this as EObject).saveAsJson(jsonFile)
if (restoringURI) {
this.setResourceURI(startURI.toString())
}
}
fun EObject.saveAsJson(jsonFile: File) {
val resource: Resource = createResource(URI.createFileURI(jsonFile.absolutePath))!!
resource.contents.add(this)
resource.save(null)
}
fun EObject.saveAsJson(): String {
val uri: URI = URI.createURI("dummy-URI")
val resource: Resource = JsonResourceFactory().createResource(uri)
resource.contents.add(this)
val output = ByteArrayOutputStream()
resource.save(output, null)
return output.toString(Charsets.UTF_8.name())
}
fun EObject.saveAsJsonObject(): JsonObject {
return JsonParser.parseString(this.saveAsJson()).asJsonObject
}
fun EObject.eGet(name: String): Any? {
val sfs = this.eClass().eAllStructuralFeatures.filter { it.name == name }
when (sfs.size) {
0 -> throw IllegalArgumentException("No feature $name found")
1 -> return this.eGet(sfs.first())
else -> throw IllegalArgumentException("Feature $name is ambiguous")
}
}
| apache-2.0 | 1173b3fb3e2c4932b0eda6ddd4f3b286 | 38.649378 | 119 | 0.636492 | 3.898613 | false | true | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/browse/fragment/BrowseFragment.kt | 1 | 3778 | package io.casey.musikcube.remote.ui.browse.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.ViewPager
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.ui.browse.adapter.BrowseFragmentAdapter
import io.casey.musikcube.remote.ui.browse.constant.Browse
import io.casey.musikcube.remote.ui.shared.activity.IFabConsumer
import io.casey.musikcube.remote.ui.shared.activity.IFilterable
import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider
import io.casey.musikcube.remote.ui.shared.activity.ITransportObserver
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin
class BrowseFragment: BaseFragment(), ITransportObserver, IFilterable, ITitleProvider {
private lateinit var adapter: BrowseFragmentAdapter
private lateinit var playback: PlaybackMixin
override val title: String
get() = getString(R.string.app_name)
override fun onCreate(savedInstanceState: Bundle?) {
playback = mixin(PlaybackMixin())
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.browse_fragment, container, false).apply {
val fab = findViewById<FloatingActionButton>(R.id.fab)
val pager = findViewById<ViewPager>(R.id.view_pager)
val tabs = findViewById<TabLayout>(R.id.tab_layout)
val showFabIfNecessary = { pos: Int ->
adapter.fragmentAt(pos)?.let {
when (it is IFabConsumer) {
true -> {
when (it.fabVisible) {
true -> fab.show()
false -> fab.hide()
}
}
false -> fab.hide()
}
}
}
fab.setOnClickListener {
(adapter.fragmentAt(pager.currentItem) as? IFabConsumer)?.onFabPress(fab)
}
adapter = BrowseFragmentAdapter(
appCompatActivity,
playback,
childFragmentManager,
R.id.content_container)
adapter.onFragmentInstantiated = { pos ->
if (pos == pager.currentItem) {
showFabIfNecessary(pos)
}
}
pager.adapter = adapter
pager.currentItem = adapter.indexOf(extras.getString(Browse.Extras.INITIAL_CATEGORY_TYPE))
tabs.setupWithViewPager(pager)
pager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(pos: Int, offset: Float, offsetPixels: Int) {
}
override fun onPageSelected(pos: Int) {
showFabIfNecessary(pos)
}
})
showFabIfNecessary(pager.currentItem)
}
override fun onTransportChanged() =
adapter.onTransportChanged()
override val addFilterToToolbar: Boolean
get() = true
override fun setFilter(filter: String) {
adapter.filter = filter
}
companion object {
const val TAG = "BrowseFragment"
fun create(extras: Bundle): BrowseFragment =
BrowseFragment().apply { arguments = extras }
}
} | bsd-3-clause | b264eced0e3514c50e022b6c46c5a3af | 35.336538 | 116 | 0.623875 | 5.003974 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/userprefs/particlescale/ParticleScalePreference.kt | 1 | 2107 | /*
* Copyright (C) 2017 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.userprefs.particlescale
import android.content.Context
import android.util.AttributeSet
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.doctoror.particleswallpaper.framework.di.inject
import com.doctoror.particleswallpaper.framework.preference.SeekBarPreference
import com.doctoror.particleswallpaper.framework.preference.SeekBarPreferenceView
import org.koin.core.parameter.parametersOf
class ParticleScalePreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) :
SeekBarPreference(context, attrs, defStyle),
SeekBarPreferenceView,
LifecycleObserver {
private val presenter: ParticleScalePreferencePresenter by inject(
context = context,
parameters = { parametersOf(this as SeekBarPreferenceView) }
)
init {
isPersistent = false
setOnPreferenceChangeListener { _, v ->
presenter.onPreferenceChange(v as Int?)
true
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
presenter.onStart()
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
presenter.onStop()
}
override fun setMaxInt(max: Int) {
this.max = max
}
override fun setProgressInt(progress: Int) {
this.progress = progress
}
override fun getMaxInt() = max
}
| apache-2.0 | 72e3d4507f53ac90d26ff3f96385eba8 | 29.536232 | 81 | 0.725202 | 4.713647 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/vulkan/VulkanRenderer.kt | 1 | 96984 | package graphics.scenery.backends.vulkan
import graphics.scenery.*
import graphics.scenery.backends.*
import graphics.scenery.attribute.renderable.Renderable
import graphics.scenery.attribute.material.Material
import graphics.scenery.attribute.renderable.DelegatesRenderable
import graphics.scenery.spirvcrossj.Loader
import graphics.scenery.spirvcrossj.libspirvcrossj
import graphics.scenery.textures.Texture
import graphics.scenery.utils.*
import graphics.scenery.volumes.VolumeManager
import io.github.classgraph.ClassGraph
import kotlinx.coroutines.*
import org.joml.*
import org.lwjgl.PointerBuffer
import org.lwjgl.glfw.GLFW.glfwGetError
import org.lwjgl.glfw.GLFW.glfwInit
import org.lwjgl.glfw.GLFWVulkan.glfwGetRequiredInstanceExtensions
import org.lwjgl.glfw.GLFWVulkan.glfwVulkanSupported
import org.lwjgl.system.Configuration
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.MemoryUtil.*
import org.lwjgl.system.Platform
import org.lwjgl.vulkan.*
import org.lwjgl.vulkan.EXTDebugReport.*
import org.lwjgl.vulkan.EXTDebugUtils.*
import org.lwjgl.vulkan.KHRSurface.VK_KHR_SURFACE_EXTENSION_NAME
import org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
import org.lwjgl.vulkan.KHRWin32Surface.VK_KHR_WIN32_SURFACE_EXTENSION_NAME
import org.lwjgl.vulkan.KHRXlibSurface.VK_KHR_XLIB_SURFACE_EXTENSION_NAME
import org.lwjgl.vulkan.MVKMacosSurface.VK_MVK_MACOS_SURFACE_EXTENSION_NAME
import org.lwjgl.vulkan.VK10.*
import java.awt.image.BufferedImage
import java.awt.image.DataBufferByte
import java.io.File
import java.nio.ByteBuffer
import java.nio.IntBuffer
import java.nio.LongBuffer
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.locks.ReentrantLock
import javax.imageio.ImageIO
import kotlin.concurrent.thread
import kotlin.concurrent.withLock
import kotlin.reflect.full.*
import kotlin.system.measureTimeMillis
import kotlin.time.ExperimentalTime
/**
* Vulkan Renderer
*
* @param[hub] Hub instance to use and attach to.
* @param[applicationName] The name of this application.
* @param[scene] The [Scene] instance to initialize first.
* @param[windowWidth] Horizontal window size.
* @param[windowHeight] Vertical window size.
* @param[embedIn] An optional [SceneryPanel] in which to embed the renderer instance.
* @param[renderConfigFile] The file to create a [RenderConfigReader.RenderConfig] from.
*
* @author Ulrik Günther <[email protected]>
*/
@OptIn(ExperimentalTime::class)
@Suppress("MemberVisibilityCanBePrivate")
open class VulkanRenderer(hub: Hub,
applicationName: String,
scene: Scene,
windowWidth: Int,
windowHeight: Int,
final override var embedIn: SceneryPanel? = null,
renderConfigFile: String) : Renderer(), AutoCloseable {
protected val logger by LazyLogger()
// helper classes
data class PresentHelpers(
var signalSemaphore: LongBuffer = memAllocLong(1),
var waitSemaphore: LongBuffer = memAllocLong(2),
var commandBuffers: PointerBuffer = memAllocPointer(1),
var waitStages: IntBuffer = memAllocInt(2),
var submitInfo: VkSubmitInfo = VkSubmitInfo.calloc(),
var imageUsageFence: Long = -1L
)
enum class VertexDataKinds {
None,
PositionNormalTexcoord,
PositionTexcoords,
PositionNormal
}
enum class StandardSemaphores {
RenderComplete,
ImageAvailable,
PresentComplete
}
data class VertexDescription(
val state: VkPipelineVertexInputStateCreateInfo,
val attributeDescription: VkVertexInputAttributeDescription.Buffer?,
val bindingDescription: VkVertexInputBindingDescription.Buffer?
)
data class CommandPools(
var Standard: Long = -1L,
var Render: Long = -1L,
var Compute: Long = -1L,
var Transfer: Long = -1L
)
data class DeviceAndGraphicsQueueFamily(
val device: VkDevice? = null,
val graphicsQueue: Int = 0,
val computeQueue: Int = 0,
val presentQueue: Int = 0,
val transferQueue: Int = 0,
val memoryProperties: VkPhysicalDeviceMemoryProperties? = null
)
class Pipeline {
internal var pipeline: Long = 0
internal var layout: Long = 0
internal var type: VulkanPipeline.PipelineType = VulkanPipeline.PipelineType.Graphics
}
sealed class DescriptorSet(val id: Long = 0L, val name: String = "") {
object None: DescriptorSet(0L)
data class Set(val setId: Long, val setName: String = "") : DescriptorSet(setId, setName)
data class DynamicSet(val setId: Long, val offset: Int, val setName: String = "") : DescriptorSet(setId, setName)
companion object {
fun setOrNull(id: Long?, setName: String): DescriptorSet? {
return if(id == null) {
null
} else {
Set(id, setName)
}
}
}
}
private val lateResizeInitializers = ConcurrentHashMap<Renderable, () -> Any>()
inner class SwapchainRecreator {
var mustRecreate = true
var afterRecreateHook: (SwapchainRecreator) -> Unit = {}
private val lock = ReentrantLock()
@Synchronized fun recreate() {
if(lock.tryLock() && !shouldClose) {
logger.info("Recreating Swapchain at frame $frames (${swapchain.javaClass.simpleName})")
// create new swapchain with changed surface parameters
vkQueueWaitIdle(queue)
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
// Create the swapchain (this will also add a memory barrier to initialize the framebuffer images)
swapchain.create(oldSwapchain = swapchain)
endCommandBuffer([email protected], commandPools.Standard, queue, flush = true, dealloc = true)
this
}
VulkanRenderpass.createPipelineCache(device)
val refreshResolutionDependentResources = {
renderpasses.values.forEach { it.close() }
renderpasses.clear()
settings.set("Renderer.displayWidth", (window.width * settings.get<Float>("Renderer.SupersamplingFactor")).toInt())
settings.set("Renderer.displayHeight", (window.height * settings.get<Float>("Renderer.SupersamplingFactor")).toInt())
val flowAndPasses = VulkanRenderpass.prepareRenderpassesFromConfig(renderConfig, device, commandPools, queue, vertexDescriptors, swapchain, window.width, window.height, settings)
flow = flowAndPasses.first
flowAndPasses.second.forEach { (k, v) -> renderpasses.put(k, v) }
semaphores.forEach { it.value.forEach { semaphore -> device.removeSemaphore(semaphore) }}
semaphores = prepareStandardSemaphores(device)
// Create render command buffers
vkResetCommandPool(device.vulkanDevice, commandPools.Render, VK_FLAGS_NONE)
scene.findObserver()?.let { cam ->
when(cam.projectionType) {
Camera.ProjectionType.Orthographic ->
cam.orthographicCamera(cam.fov, window.width, window.height, cam.nearPlaneDistance, cam.farPlaneDistance)
Camera.ProjectionType.Perspective ->
cam.perspectiveCamera(cam.fov, window.width, window.height, cam.nearPlaneDistance, cam.farPlaneDistance)
Camera.ProjectionType.Undefined -> {
logger.warn("Camera ${cam.name} has undefined projection type, using default perspective projection")
cam.perspectiveCamera(cam.fov, window.width, window.height, cam.nearPlaneDistance, cam.farPlaneDistance)
}
}
}
logger.debug("Calling late resize initializers for ${lateResizeInitializers.keys.joinToString(", ")}")
lateResizeInitializers.map { it.value.invoke() }
}
refreshResolutionDependentResources.invoke()
totalFrames = 0
mustRecreate = false
afterRecreateHook.invoke(this)
settings.set("VulkanRenderer.swapchainImageCount", swapchain.images.size)
lock.unlock()
}
}
}
var debugCallbackUtils = callback@ { severity: Int, type: Int, callbackDataPointer: Long, _: Long ->
val dbg = if (type and VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT == VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
" (performance)"
} else if(type and VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT == VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
" (validation)"
} else {
""
}
val callbackData = VkDebugUtilsMessengerCallbackDataEXT.create(callbackDataPointer)
val obj = callbackData.pMessageIdNameString()
val message = callbackData.pMessageString()
val objectType = 0
when (severity) {
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT ->
logger.error("!! $obj($objectType) Validation$dbg: $message")
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT ->
logger.warn("!! $obj($objectType) Validation$dbg: $message")
VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT ->
logger.info("!! $obj($objectType) Validation$dbg: $message")
else -> logger.info("!! $obj($objectType) Validation (unknown message type)$dbg: $message")
}
// trigger exception and delay if strictValidation is activated in general, or only for specific object types
if(strictValidation.first && strictValidation.second.isEmpty() ||
strictValidation.first && strictValidation.second.contains(objectType)) {
if(severity < VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
return@callback VK_FALSE
}
// set 15s of delay until the next frame is rendered if a validation error happens
renderDelay = System.getProperty("scenery.VulkanRenderer.DefaultRenderDelay", "1500").toLong()
try {
throw VulkanValidationLayerException("Vulkan validation layer exception, see validation layer error messages above. To disable these exceptions, set scenery.VulkanRenderer.StrictValidation=false. Stack trace:")
} catch (e: VulkanValidationLayerException) {
logger.error(e.message)
e.printStackTrace()
}
}
// return false here, otherwise the application would quit upon encountering a validation error.
return@callback VK_FALSE
}
/** Debug callback to be used upon encountering validation messages or errors */
var debugCallback = object : VkDebugReportCallbackEXT() {
override operator fun invoke(flags: Int, objectType: Int, obj: Long, location: Long, messageCode: Int, pLayerPrefix: Long, pMessage: Long, pUserData: Long): Int {
val dbg = if (flags and VK_DEBUG_REPORT_DEBUG_BIT_EXT == VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
" (debug)"
} else {
""
}
when {
flags and VK_DEBUG_REPORT_ERROR_BIT_EXT == VK_DEBUG_REPORT_ERROR_BIT_EXT ->
logger.error("!! $obj($objectType) Validation$dbg: " + getString(pMessage))
flags and VK_DEBUG_REPORT_WARNING_BIT_EXT == VK_DEBUG_REPORT_WARNING_BIT_EXT ->
logger.warn("!! $obj($objectType) Validation$dbg: " + getString(pMessage))
flags and VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT == VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT ->
logger.error("!! $obj($objectType) Validation (performance)$dbg: " + getString(pMessage))
flags and VK_DEBUG_REPORT_INFORMATION_BIT_EXT == VK_DEBUG_REPORT_INFORMATION_BIT_EXT ->
logger.info("!! $obj($objectType) Validation$dbg: " + getString(pMessage))
else ->
logger.info("!! $obj($objectType) Validation (unknown message type)$dbg: " + getString(pMessage))
}
// trigger exception and delay if strictValidation is activated in general, or only for specific object types
if(strictValidation.first && strictValidation.second.isEmpty() ||
strictValidation.first && strictValidation.second.contains(objectType)) {
if(!(flags and VK_DEBUG_REPORT_ERROR_BIT_EXT == VK_DEBUG_REPORT_ERROR_BIT_EXT)) {
return VK_FALSE
}
// set 15s of delay until the next frame is rendered if a validation error happens
renderDelay = System.getProperty("scenery.VulkanRenderer.DefaultRenderDelay", "1500").toLong()
try {
throw VulkanValidationLayerException("Vulkan validation layer exception, see validation layer error messages above. To disable these exceptions, set scenery.VulkanRenderer.StrictValidation=false. Stack trace:")
} catch (e: VulkanValidationLayerException) {
logger.error(e.message)
e.printStackTrace()
}
}
// return false here, otherwise the application would quit upon encountering a validation error.
return VK_FALSE
}
}
// helper classes end
final override var hub: Hub? = null
protected var applicationName = ""
final override var settings: Settings = Settings()
override var shouldClose = false
private var toggleFullscreen = false
override var managesRenderLoop = false
override var lastFrameTime = System.nanoTime() * 1.0f
final override var initialized = false
override var firstImageReady: Boolean = false
private var screenshotRequested = false
private var screenshotOverwriteExisting = false
private var screenshotFilename = ""
var screenshotBuffer: VulkanBuffer? = null
var imageBuffer: ByteBuffer? = null
var encoder: VideoEncoder? = null
private var movieFilename = ""
private var recordMovie: Boolean = false
private var recordMovieOverwrite: Boolean = false
override var pushMode: Boolean = false
var scene: Scene = Scene()
protected var sceneArray: HashSet<Node> = HashSet(256)
protected var commandPools = CommandPools()
protected val renderpasses: MutableMap<String, VulkanRenderpass> = Collections.synchronizedMap(LinkedHashMap<String, VulkanRenderpass>())
protected var validation = java.lang.Boolean.parseBoolean(System.getProperty("scenery.VulkanRenderer.EnableValidations", "false"))
protected val strictValidation = getStrictValidation()
protected val wantsOpenGLSwapchain = java.lang.Boolean.parseBoolean(System.getProperty("scenery.VulkanRenderer.UseOpenGLSwapchain", "false"))
protected val defaultValidationLayers = arrayOf("VK_LAYER_KHRONOS_validation")
protected var instance: VkInstance
protected var device: VulkanDevice
protected var debugCallbackHandle: Long = -1L
// Create static Vulkan resources
protected var queue: VkQueue
protected var transferQueue: VkQueue
protected var swapchain: Swapchain
protected var ph = PresentHelpers()
final override var window: SceneryWindow = SceneryWindow.UninitializedWindow()
protected val swapchainRecreator: SwapchainRecreator
protected var pipelineCache: Long = -1L
protected var vertexDescriptors = ConcurrentHashMap<VertexDataKinds, VertexDescription>()
protected var sceneUBOs = ArrayList<Node>()
protected var geometryPool: VulkanBufferPool
protected var stagingPool: VulkanBufferPool
protected var semaphores = ConcurrentHashMap<StandardSemaphores, Array<Long>>()
data class DefaultBuffers(var UBOs: VulkanBuffer,
var LightParameters: VulkanBuffer,
var VRParameters: VulkanBuffer,
var ShaderProperties: VulkanBuffer)
protected var buffers: DefaultBuffers
protected var defaultUBOs = ConcurrentHashMap<String, VulkanUBO>()
protected var textureCache = ConcurrentHashMap<Texture, VulkanTexture>()
protected var defaultTextures = ConcurrentHashMap<String, VulkanTexture>()
protected var descriptorSetLayouts = ConcurrentHashMap<String, Long>()
protected var descriptorSets = ConcurrentHashMap<String, Long>()
protected var lastTime = System.nanoTime()
protected var time = 0.0f
var fps = 0
protected set
protected var frames = 0
protected var totalFrames = 0L
protected var renderDelay = 0L
protected var heartbeatTimer = Timer()
protected var gpuStats: GPUStats? = null
private var renderConfig: RenderConfigReader.RenderConfig
private var flow: List<String> = listOf()
private val vulkanProjectionFix =
Matrix4f(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.5f, 0.0f,
0.0f, 0.0f, 0.5f, 1.0f)
final override var renderConfigFile: String = ""
set(config) {
field = config
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
// check for null as this is used in the constructor as well where
// the swapchain recreator is not yet initialized
@Suppress("SENSELESS_COMPARISON")
if (swapchainRecreator != null) {
swapchainRecreator.mustRecreate = true
logger.info("Loaded ${renderConfig.name} (${renderConfig.description ?: "no description"})")
}
}
companion object {
private const val VK_FLAGS_NONE: Int = 0
private const val UINT64_MAX: Long = -1L
private const val MATERIAL_HAS_DIFFUSE = 0x0001
private const val MATERIAL_HAS_AMBIENT = 0x0002
private const val MATERIAL_HAS_SPECULAR = 0x0004
private const val MATERIAL_HAS_NORMAL = 0x0008
private const val MATERIAL_HAS_ALPHAMASK = 0x0010
init {
Loader.loadNatives()
libspirvcrossj.initializeProcess()
Runtime.getRuntime().addShutdownHook(object: Thread() {
override fun run() {
logger.debug("Finalizing libspirvcrossj")
libspirvcrossj.finalizeProcess()
}
})
}
fun getStrictValidation(): Pair<Boolean, List<Int>> {
val strict = System.getProperty("scenery.VulkanRenderer.StrictValidation")
val separated = strict?.split(",")?.asSequence()?.mapNotNull { it.toIntOrNull() }?.toList()
return when {
strict == null -> false to emptyList()
strict == "true" -> true to emptyList()
strict == "false" -> false to emptyList()
separated != null && separated.count() > 0 -> true to separated
else -> false to emptyList()
}
}
}
fun getCurrentScene(): Scene {
return scene
}
init {
this.hub = hub
val hmd = hub.getWorkingHMDDisplay()
if (hmd != null) {
logger.debug("Setting window dimensions to bounds from HMD")
val bounds = hmd.getRenderTargetSize()
window.width = bounds.x() * 2
window.height = bounds.y()
} else {
window.width = windowWidth
window.height = windowHeight
}
this.applicationName = applicationName
this.scene = scene
this.settings = loadDefaultRendererSettings((hub.get(SceneryElement.Settings) as Settings))
logger.debug("Loading rendering config from $renderConfigFile")
this.renderConfigFile = renderConfigFile
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
logger.info("Loaded ${renderConfig.name} (${renderConfig.description ?: "no description"})")
if((System.getenv("ENABLE_VULKAN_RENDERDOC_CAPTURE")?.toInt() == 1 || Renderdoc.renderdocAttached)&& validation) {
logger.warn("Validation Layers requested, but Renderdoc capture and Validation Layers are mutually incompatible. Disabling validations layers.")
validation = false
}
// explicitly create VK, to make GLFW pick up MoltenVK on OS X
if(ExtractsNatives.getPlatform() == ExtractsNatives.Platform.MACOS) {
try {
Configuration.VULKAN_EXPLICIT_INIT.set(true)
VK.create()
} catch (e: IllegalStateException) {
logger.warn("IllegalStateException during Vulkan initialisation")
}
}
// Create the Vulkan instance
val headlessRequested = System.getProperty("scenery.Headless")?.toBoolean() ?: false
instance = if(embedIn != null || headlessRequested) {
logger.debug("Running embedded or headless, skipping GLFW initialisation.")
createInstance(
null,
validation,
headless = headlessRequested,
embedded = embedIn != null
)
} else {
if (!glfwInit()) {
val buffer = PointerBuffer.allocateDirect(255)
val error = glfwGetError(buffer)
val description = if(error != 0) {
buffer.stringUTF8
} else {
"no error"
}
throw RendererUnavailableException("Failed to initialize GLFW: $description ($error)")
}
if (!glfwVulkanSupported()) {
throw RendererUnavailableException("Failed to find Vulkan loader. Is Vulkan supported by your GPU and do you have the most recent graphics drivers installed?")
}
/* Look for instance extensions */
val requiredExtensions = glfwGetRequiredInstanceExtensions() ?: throw RendererUnavailableException("Failed to find list of required Vulkan extensions")
createInstance(requiredExtensions, validation)
}
debugCallbackHandle = if(validation) {
setupDebuggingDebugUtils(instance,
VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT
or VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
or VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT
or VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT,
debugCallbackUtils)
} else {
-1L
}
val requestedValidationLayers = if(validation) {
if(wantsOpenGLSwapchain) {
logger.warn("Requested OpenGL swapchain, validation layers disabled.")
emptyArray()
} else {
defaultValidationLayers
}
} else {
emptyArray()
}
// get available swapchains, but remove default swapchain, will always be there as fallback
val start = System.nanoTime()
val swapchains = ClassGraph()
.acceptPackages("graphics.scenery.backends.vulkan")
.enableClassInfo()
.scan()
.getClassesImplementing("graphics.scenery.backends.vulkan.Swapchain")
.filter { cls -> cls.simpleName != "VulkanSwapchain" }
.loadClasses()
val duration = System.nanoTime() - start
logger.debug("Finding swapchains took ${duration/10e6} ms")
logger.debug("Available special-purpose swapchains are: ${swapchains.joinToString { it.simpleName }}")
val selectedSwapchain = swapchains.firstOrNull { (it.kotlin.companionObjectInstance as SwapchainParameters).usageCondition.invoke(embedIn) }
val headless = (selectedSwapchain?.kotlin?.companionObjectInstance as? SwapchainParameters)?.headless ?: false
device = VulkanDevice.fromPhysicalDevice(instance,
physicalDeviceFilter = { _, device -> "${device.vendor} ${device.name}".contains(System.getProperty("scenery.Renderer.Device", "DOES_NOT_EXIST"))},
additionalExtensions = { physicalDevice -> hub.getWorkingHMDDisplay()?.getVulkanDeviceExtensions(physicalDevice)?.toTypedArray() ?: arrayOf() },
validationLayers = requestedValidationLayers,
headless = headless,
debugEnabled = validation
)
logger.debug("Device creation done")
if(device.deviceData.vendor.lowercase().contains("nvidia") && ExtractsNatives.getPlatform() == ExtractsNatives.Platform.WINDOWS) {
try {
gpuStats = NvidiaGPUStats()
} catch(e: NullPointerException) {
logger.warn("Could not initialize Nvidia GPU stats")
if(logger.isDebugEnabled) {
logger.warn("Reason: ${e.message}, traceback follows:")
e.printStackTrace()
}
}
}
queue = VU.createDeviceQueue(device, device.queues.graphicsQueue.first)
logger.debug("Creating transfer queue with ${device.queues.transferQueue.first} (vs ${device.queues.graphicsQueue})")
transferQueue = VU.createDeviceQueue(device, device.queues.transferQueue.first)
with(commandPools) {
Render = device.createCommandPool(device.queues.graphicsQueue.first)
Standard = device.createCommandPool(device.queues.graphicsQueue.first)
Compute = device.createCommandPool(device.queues.computeQueue.first)
Transfer = device.createCommandPool(device.queues.transferQueue.first)
}
logger.debug("Creating command pools done")
swapchainRecreator = SwapchainRecreator()
swapchain = when {
selectedSwapchain != null -> {
logger.info("Using swapchain ${selectedSwapchain.simpleName}")
val params = selectedSwapchain.kotlin.primaryConstructor!!.parameters.associate { param ->
param to when(param.name) {
"device" -> device
"queue" -> queue
"commandPools" -> commandPools
"renderConfig" -> renderConfig
"useSRGB" -> renderConfig.sRGB
else -> null
}
}.filter { it.value != null }
selectedSwapchain
.kotlin
.primaryConstructor!!
.callBy(params) as Swapchain
}
else -> {
logger.info("Using default swapchain")
VulkanSwapchain(
device, queue, commandPools,
renderConfig = renderConfig, useSRGB = renderConfig.sRGB,
vsync = !settings.get<Boolean>("Renderer.DisableVsync"),
undecorated = settings.get("Renderer.ForceUndecoratedWindow"))
}
}.apply {
embedIn(embedIn)
window = createWindow(window, swapchainRecreator)
}
logger.debug("Created swapchain")
vertexDescriptors = prepareStandardVertexDescriptors()
logger.debug("Created vertex descriptors")
descriptorSetLayouts = prepareDefaultDescriptorSetLayouts(device)
logger.debug("Prepared default DSLs")
buffers = prepareDefaultBuffers(device)
logger.debug("Prepared default buffers")
prepareDescriptorSets(device)
logger.debug("Prepared default descriptor sets")
prepareDefaultTextures(device)
logger.debug("Prepared default textures")
heartbeatTimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
if (window.shouldClose) {
shouldClose = true
return
}
fps = frames
frames = 0
if(!pushMode) {
(hub.get(SceneryElement.Statistics) as? Statistics)?.add("Renderer.fps", fps, false)
}
gpuStats?.let {
it.update(0)
hub.get(SceneryElement.Statistics).let { s ->
val stats = s as Statistics
stats.add("GPU", it.get("GPU"), isTime = false)
stats.add("GPU bus", it.get("Bus"), isTime = false)
stats.add("GPU mem", it.get("AvailableDedicatedVideoMemory"), isTime = false)
}
if (settings.get("Renderer.PrintGPUStats")) {
logger.info(it.utilisationToString())
logger.info(it.memoryUtilisationToString())
}
}
val validationsEnabled = if (validation) {
" - VALIDATIONS ENABLED"
} else {
""
}
if(embedIn == null) {
window.title = "$applicationName [${[email protected]}, ${[email protected]}] $validationsEnabled - $fps fps"
}
}
}, 0, 1000)
lastTime = System.nanoTime()
time = 0.0f
if(System.getProperty("scenery.RunFullscreen","false")?.toBoolean() == true) {
toggleFullscreen = true
}
geometryPool = VulkanBufferPool(
device,
usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT or VK_BUFFER_USAGE_INDEX_BUFFER_BIT or VK_BUFFER_USAGE_TRANSFER_DST_BIT
)
stagingPool = VulkanBufferPool(
device,
usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
bufferSize = 64*1024*1024
)
initialized = true
logger.info("Renderer initialisation complete.")
}
// source: http://stackoverflow.com/questions/34697828/parallel-operations-on-kotlin-collections
// Thanks to Holger :-)
@Suppress("UNUSED")
fun <T, R> Iterable<T>.parallelMap(
numThreads: Int = Runtime.getRuntime().availableProcessors(),
exec: ExecutorService = Executors.newFixedThreadPool(numThreads),
transform: (T) -> R): List<R> {
// default size is just an inlined version of kotlin.collections.collectionSizeOrDefault
val defaultSize = if (this is Collection<*>) this.size else 10
val destination = Collections.synchronizedList(ArrayList<R>(defaultSize))
for (item in this) {
exec.submit { destination.add(transform(item)) }
}
exec.shutdown()
exec.awaitTermination(1, TimeUnit.DAYS)
return ArrayList<R>(destination)
}
@Suppress("UNUSED")
fun setCurrentScene(scene: Scene) {
this.scene = scene
}
/**
* This function should initialize the current scene contents.
*/
override fun initializeScene() {
logger.info("Scene initialization started.")
val start = System.nanoTime()
this.scene.discover(this.scene, { it !is Light })
// .parallelMap(numThreads = System.getProperty("scenery.MaxInitThreads", "1").toInt()) { node ->
.map { node ->
// skip initialization for nodes that are only instance slaves
logger.debug("Initializing object '${node.name}'")
initializeNode(node)
}
scene.initialized = true
logger.info("Scene initialization complete, took ${(System.nanoTime() - start)/10e6} ms.")
}
fun Boolean.toInt(): Int {
return if (this) {
1
} else {
0
}
}
fun updateNodeGeometry(node: Node) {
val renderable = node.renderableOrNull() ?: return
node.ifGeometry {
if (vertices.remaining() > 0) {
renderable.rendererMetadata()?.let { s ->
VulkanNodeHelpers.createVertexBuffers(
device,
node,
s,
stagingPool,
geometryPool,
commandPools,
queue
)
}
}
}
}
/**
* Returns the material type flag for a Node, considering it's [Material]'s textures.
*/
protected fun Material.materialTypeFromTextures(s: VulkanObjectState): Int {
var materialType = 0
if (this.textures.containsKey("ambient") && !s.defaultTexturesFor.contains("ambient")) {
materialType = materialType or MATERIAL_HAS_AMBIENT
}
if (this.textures.containsKey("diffuse") && !s.defaultTexturesFor.contains("diffuse")) {
materialType = materialType or MATERIAL_HAS_DIFFUSE
}
if (this.textures.containsKey("specular") && !s.defaultTexturesFor.contains("specular")) {
materialType = materialType or MATERIAL_HAS_SPECULAR
}
if (this.textures.containsKey("normal") && !s.defaultTexturesFor.contains("normal")) {
materialType = materialType or MATERIAL_HAS_NORMAL
}
if (this.textures.containsKey("alphamask") && !s.defaultTexturesFor.contains("alphamask")) {
materialType = materialType or MATERIAL_HAS_ALPHAMASK
}
return materialType
}
/**
* Initialises a given [Node] with the metadata required by the [VulkanRenderer].
*/
fun initializeNode(node: Node): Boolean {
val renderable = node.renderableOrNull() ?: return false
val material = node.materialOrNull() ?: return false
if(node is DelegatesRenderable) {
logger.debug("Initialising node $node with delegate $renderable (state=${node.state})")
} else {
logger.debug("Initialising node $node")
}
if(renderable.rendererMetadata() == null) {
renderable.metadata["VulkanRenderer"] = VulkanObjectState()
}
var s: VulkanObjectState = renderable.rendererMetadata() ?: throw IllegalStateException("Node ${node.name} does not contain metadata object")
if(node.state != State.Ready) {
logger.info("Not initialising Renderable $renderable because state=${node.state}")
return false
}
if (s.initialized) return true
s.flags.add(RendererFlags.Seen)
node.ifGeometry {
logger.debug("Initializing geometry for ${node.name} (${vertices.remaining() / vertexSize} vertices/${indices.remaining()} indices)")
// determine vertex input type
s.vertexInputType = when {
vertices.remaining() > 0 && normals.remaining() > 0 && texcoords.remaining() > 0 -> VertexDataKinds.PositionNormalTexcoord
vertices.remaining() > 0 && normals.remaining() > 0 && texcoords.remaining() == 0 -> VertexDataKinds.PositionNormal
vertices.remaining() > 0 && normals.remaining() == 0 && texcoords.remaining() > 0 -> VertexDataKinds.PositionTexcoords
else -> VertexDataKinds.PositionNormalTexcoord
}
// create custom vertex description if necessary, else use one of the defaults
s.vertexDescription = if (node is InstancedNode) {
VulkanNodeHelpers.updateInstanceBuffer(device, node, s, commandPools, queue)
// TODO: Rewrite shader in case it does not conform to coord/normal/texcoord vertex description
s.vertexInputType = VertexDataKinds.PositionNormalTexcoord
s.instanced = true
vertexDescriptionFromInstancedNode(node, vertexDescriptors.getValue(VertexDataKinds.PositionNormalTexcoord))
} else {
s.instanced = false
s.vertexBuffers["instance"]?.close()
s.vertexBuffers.remove("instance")
s.vertexBuffers["instanceStaging"]?.close()
s.vertexBuffers.remove("instanceStaging")
vertexDescriptors.getValue(s.vertexInputType)
}
s = VulkanNodeHelpers.createVertexBuffers(device, node, s, stagingPool, geometryPool, commandPools, queue)
}
val matricesDescriptorSet = getDescriptorCache().getOrPut("Matrices") {
SimpleTimestamped(device.createDescriptorSetDynamic(
descriptorSetLayouts["Matrices"]!!, 1,
buffers.UBOs))
}
val materialPropertiesDescriptorSet = getDescriptorCache().getOrPut("MaterialProperties") {
SimpleTimestamped(device.createDescriptorSetDynamic(
descriptorSetLayouts["MaterialProperties"]!!, 1,
buffers.UBOs))
}
val matricesUbo = VulkanUBO(device, backingBuffer = buffers.UBOs)
with(matricesUbo) {
name = "Matrices"
node.ifSpatial {
add("ModelMatrix", { world })
add("NormalMatrix", { Matrix4f(world).invert().transpose() })
}
add("isBillboard", { renderable.isBillboard.toInt() })
createUniformBuffer()
sceneUBOs.add(node)
s.UBOs.put(name, matricesDescriptorSet.contents to this)
}
try {
VulkanNodeHelpers.initializeCustomShadersForNode(device, node, true, renderpasses, lateResizeInitializers, buffers)
} catch (e: ShaderCompilationException) {
logger.error("Compilation of custom shader failed: ${e.message}")
logger.error("Node ${node.name} will use default shader for render pass.")
if (logger.isDebugEnabled) {
e.printStackTrace()
}
}
val (_, descriptorUpdated) = VulkanNodeHelpers.loadTexturesForNode(device, node, s, defaultTextures, textureCache, commandPools, queue)
if(descriptorUpdated) {
s.texturesToDescriptorSets(device,
renderpasses.filter { it.value.passConfig.type != RenderConfigReader.RenderpassType.quad },
renderable)
}
s.materialHashCode = material.materialHashCode()
val materialUbo = VulkanUBO(device, backingBuffer = buffers.UBOs)
with(materialUbo) {
name = "MaterialProperties"
add("materialType", { material.materialTypeFromTextures(s) })
add("Ka", { material.ambient })
add("Kd", { material.diffuse })
add("Ks", { material.specular })
add("Roughness", { material.roughness})
add("Metallic", { material.metallic})
add("Opacity", { material.blending.opacity })
createUniformBuffer()
s.UBOs.put("MaterialProperties", materialPropertiesDescriptorSet.contents to this)
}
s.initialized = true
s.flags.add(RendererFlags.Initialised)
node.initialized = true
renderable.metadata["VulkanRenderer"] = s
return true
}
protected fun destroyNode(node: Node, onShutdown: Boolean = false) {
logger.trace("Destroying node ${node.name}...")
val renderable = node.renderableOrNull()
if (!(renderable?.metadata?.containsKey("VulkanRenderer") ?: false)) {
return
}
lateResizeInitializers.remove(renderable)
node.initialized = false
renderable?.rendererMetadata()?.UBOs?.forEach { it.value.second.close() }
node.ifGeometry {
renderable?.rendererMetadata()?.vertexBuffers?.forEach {
it.value.close()
}
}
if(onShutdown) {
renderable?.rendererMetadata()?.textures?.forEach { it.value.close() }
}
renderable?.metadata?.remove("VulkanRenderer")
}
protected fun prepareDefaultDescriptorSetLayouts(device: VulkanDevice): ConcurrentHashMap<String, Long> {
val m = ConcurrentHashMap<String, Long>()
m["Matrices"] = device.createDescriptorSetLayout(
listOf(Pair(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1)),
0,
VK_SHADER_STAGE_ALL)
m["MaterialProperties"] = device.createDescriptorSetLayout(
listOf(Pair(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1)),
0,
VK_SHADER_STAGE_ALL)
m["LightParameters"] = device.createDescriptorSetLayout(
listOf(Pair(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)),
0,
VK_SHADER_STAGE_ALL)
m["VRParameters"] = device.createDescriptorSetLayout(
listOf(Pair(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)),
0,
VK_SHADER_STAGE_ALL)
return m
}
protected fun prepareDescriptorSets(device: VulkanDevice) {
this.descriptorSets["Matrices"] = device.createDescriptorSetDynamic(
descriptorSetLayouts["Matrices"]!!, 1,
buffers.UBOs)
this.descriptorSets["MaterialProperties"] = device.createDescriptorSetDynamic(
descriptorSetLayouts["MaterialProperties"]!!, 1,
buffers.UBOs)
val lightUbo = VulkanUBO(device)
lightUbo.add("ViewMatrix0", { Matrix4f().identity() })
lightUbo.add("ViewMatrix1", { Matrix4f().identity() })
lightUbo.add("InverseViewMatrix0", { Matrix4f().identity() })
lightUbo.add("InverseViewMatrix1", { Matrix4f().identity() })
lightUbo.add("ProjectionMatrix", { Matrix4f().identity() })
lightUbo.add("InverseProjectionMatrix", { Matrix4f().identity() })
lightUbo.add("CamPosition", { Vector3f(0.0f) })
lightUbo.createUniformBuffer()
lightUbo.populate()
defaultUBOs["LightParameters"] = lightUbo
this.descriptorSets["LightParameters"] = device.createDescriptorSet(
descriptorSetLayouts["LightParameters"]!!, 1,
lightUbo.descriptor)
val vrUbo = VulkanUBO(device)
vrUbo.add("projection0", { Matrix4f().identity() } )
vrUbo.add("projection1", { Matrix4f().identity() } )
vrUbo.add("inverseProjection0", { Matrix4f().identity() } )
vrUbo.add("inverseProjection1", { Matrix4f().identity() } )
vrUbo.add("headShift", { Matrix4f().identity() })
vrUbo.add("IPD", { 0.0f })
vrUbo.add("stereoEnabled", { 0 })
vrUbo.createUniformBuffer()
vrUbo.populate()
defaultUBOs["VRParameters"] = vrUbo
this.descriptorSets["VRParameters"] = device.createDescriptorSet(
descriptorSetLayouts["VRParameters"]!!, 1,
vrUbo.descriptor)
}
protected fun prepareStandardVertexDescriptors(): ConcurrentHashMap<VertexDataKinds, VertexDescription> {
val map = ConcurrentHashMap<VertexDataKinds, VertexDescription>()
VertexDataKinds.values().forEach { kind ->
val attributeDesc: VkVertexInputAttributeDescription.Buffer?
var stride = 0
when (kind) {
VertexDataKinds.None -> {
stride = 0
attributeDesc = null
}
VertexDataKinds.PositionNormal -> {
stride = 3 + 3
attributeDesc = VkVertexInputAttributeDescription.calloc(2)
attributeDesc.get(1)
.binding(0)
.location(1)
.format(VK_FORMAT_R32G32B32_SFLOAT)
.offset(3 * 4)
}
VertexDataKinds.PositionNormalTexcoord -> {
stride = 3 + 3 + 2
attributeDesc = VkVertexInputAttributeDescription.calloc(3)
attributeDesc.get(1)
.binding(0)
.location(1)
.format(VK_FORMAT_R32G32B32_SFLOAT)
.offset(3 * 4)
attributeDesc.get(2)
.binding(0)
.location(2)
.format(VK_FORMAT_R32G32_SFLOAT)
.offset(3 * 4 + 3 * 4)
}
VertexDataKinds.PositionTexcoords -> {
stride = 3 + 2
attributeDesc = VkVertexInputAttributeDescription.calloc(2)
attributeDesc.get(1)
.binding(0)
.location(1)
.format(VK_FORMAT_R32G32_SFLOAT)
.offset(3 * 4)
}
}
attributeDesc?.let {
if(it.capacity() > 0) {
it.get(0).binding(0).location(0).format(VK_FORMAT_R32G32B32_SFLOAT).offset(0)
}
}
val bindingDesc: VkVertexInputBindingDescription.Buffer? = if (attributeDesc != null) {
VkVertexInputBindingDescription.calloc(1)
.binding(0)
.stride(stride * 4)
.inputRate(VK_VERTEX_INPUT_RATE_VERTEX)
} else {
null
}
val inputState = VkPipelineVertexInputStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO)
.pNext(NULL)
.pVertexAttributeDescriptions(attributeDesc)
.pVertexBindingDescriptions(bindingDesc)
map[kind] = VertexDescription(inputState, attributeDesc, bindingDesc)
}
return map
}
/** Data class for encapsulation of shader vertex attributes */
data class AttributeInfo(val format: Int, val elementByteSize: Int, val elementCount: Int)
/**
* Calculates the formats and required sizes for the elements contained in this hash map when
* used as definition for vertex attributes in a shader.
*/
protected fun HashMap<String, () -> Any>.getFormatsAndRequiredAttributeSize(): List<AttributeInfo> {
return this.map {
val value = it.value.invoke()
when (value.javaClass) {
Vector2f::class.java -> AttributeInfo(VK_FORMAT_R32G32_SFLOAT, 4 * 2, 1)
Vector3f::class.java -> AttributeInfo(VK_FORMAT_R32G32B32_SFLOAT, 3 * 4, 1)
Vector4f::class.java -> AttributeInfo(VK_FORMAT_R32G32B32A32_SFLOAT, 4 * 4, 1)
Matrix4f::class.java -> AttributeInfo(VK_FORMAT_R32G32B32A32_SFLOAT, 4 * 4, 4 * 4 / 4)
else -> {
logger.error("Unsupported type for instancing: ${value.javaClass.simpleName}")
AttributeInfo(-1, -1, -1)
}
}
}
}
protected fun vertexDescriptionFromInstancedNode(node: InstancedNode, template: VertexDescription): VertexDescription {
logger.debug("Creating instanced vertex description for ${node.name}")
if(template.attributeDescription == null || template.bindingDescription == null) {
return template
}
val attributeDescs = template.attributeDescription
val bindingDescs = template.bindingDescription
val formatsAndAttributeSizes = node.instancedProperties.getFormatsAndRequiredAttributeSize()
val newAttributesNeeded = formatsAndAttributeSizes.map { it.elementCount }.sum()
val newAttributeDesc = VkVertexInputAttributeDescription
.calloc(attributeDescs.capacity() + newAttributesNeeded)
var position: Int
var offset = 0
for(i in 0 until attributeDescs.capacity()) {
newAttributeDesc[i].set(attributeDescs[i])
offset += newAttributeDesc[i].offset()
logger.debug("location(${newAttributeDesc[i].location()})")
logger.debug(" .offset(${newAttributeDesc[i].offset()})")
position = i
}
position = 3
offset = 0
formatsAndAttributeSizes.zip(node.instancedProperties.toList().reversed()).forEach {
val attribInfo = it.first
val property = it.second
for(i in (0 until attribInfo.elementCount)) {
newAttributeDesc[position]
.binding(1)
.location(position)
.format(attribInfo.format)
.offset(offset)
logger.debug("location($position, $i/${attribInfo.elementCount}) for ${property.first}, type: ${property.second.invoke().javaClass.simpleName}")
logger.debug(" .format(${attribInfo.format})")
logger.debug(" .offset($offset)")
offset += attribInfo.elementByteSize
position++
}
}
logger.debug("stride($offset), ${bindingDescs.capacity()}")
val newBindingDesc = VkVertexInputBindingDescription.calloc(bindingDescs.capacity() + 1)
newBindingDesc[0].set(bindingDescs[0])
newBindingDesc[1]
.binding(1)
.stride(offset)
.inputRate(VK_VERTEX_INPUT_RATE_INSTANCE)
val inputState = VkPipelineVertexInputStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO)
.pNext(NULL)
.pVertexAttributeDescriptions(newAttributeDesc)
.pVertexBindingDescriptions(newBindingDesc)
return VertexDescription(inputState, newAttributeDesc, newBindingDesc)
}
protected fun prepareDefaultTextures(device: VulkanDevice) {
val t = VulkanTexture.loadFromFile(device, commandPools, queue, queue,
Renderer::class.java.getResourceAsStream("DefaultTexture.png"), "png", true, true)
// TODO: Do an asset manager or sth here?
defaultTextures["DefaultTexture"] = t
}
protected fun prepareStandardSemaphores(device: VulkanDevice): ConcurrentHashMap<StandardSemaphores, Array<Long>> {
val map = ConcurrentHashMap<StandardSemaphores, Array<Long>>()
StandardSemaphores.values().forEach {
map[it] = swapchain.images.map { i ->
device.createSemaphore()
}.toTypedArray()
}
return map
}
/**
* Polls for window events and triggers swapchain recreation if necessary.
* Returns true if the swapchain has been recreated, or false if not.
*/
private fun pollEvents(): Boolean {
window.pollEvents()
(swapchain as? HeadlessSwapchain)?.queryResize()
if (swapchainRecreator.mustRecreate) {
swapchainRecreator.recreate()
frames = 0
return true
}
return false
}
private fun beginFrame(): Pair<Long, Long>? {
previousFrame = currentFrame
val semaphoreAndFence= swapchain.next(timeout = UINT64_MAX)
if(semaphoreAndFence == null) {
swapchainRecreator.mustRecreate = true
return null
}
//logger.info("Prev: $previousFrame, Current: $currentFrame, will signal ${semaphores.getValue(StandardSemaphores.ImageAvailable)[previousFrame].toHexString()}")
return semaphoreAndFence
}
var presentationFence = -1L
@Suppress("unused")
override fun recordMovie(filename: String, overwrite: Boolean) {
if(recordMovie) {
encoder?.finish()
encoder = null
recordMovie = false
recordMovieOverwrite = overwrite
} else {
movieFilename = filename
recordMovie = true
}
}
private suspend fun submitFrame(queue: VkQueue, pass: VulkanRenderpass, commandBuffer: VulkanCommandBuffer, present: PresentHelpers) {
if(swapchainRecreator.mustRecreate) {
return
}
val stats = hub?.get(SceneryElement.Statistics) as? Statistics
present.submitInfo
.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
.pNext(NULL)
.waitSemaphoreCount(present.waitSemaphore.capacity())
.pWaitSemaphores(present.waitSemaphore)
.pWaitDstStageMask(present.waitStages)
.pCommandBuffers(present.commandBuffers)
.pSignalSemaphores(present.signalSemaphore)
val q = (swapchain as? VulkanSwapchain)?.presentQueue ?: queue
// Submit to the graphics queue
// vkResetFences(device.vulkanDevice, swapchain.currentFence)
VU.run("Submit viewport render queue", { vkQueueSubmit(q, present.submitInfo, swapchain.currentFence) })
// submit to OpenVR if attached
if(hub?.getWorkingHMDDisplay()?.hasCompositor() == true) {
hub?.getWorkingHMDDisplay()?.wantsVR(settings)?.submitToCompositorVulkan(
window.width, window.height,
swapchain.format,
instance, device, queue,
swapchain.images[pass.getReadPosition()])
}
val startPresent = System.nanoTime()
commandBuffer.submitted = true
swapchain.present(waitForSemaphores = present.signalSemaphore)
vkWaitForFences(device.vulkanDevice, swapchain.currentFence, true, -1L)
vkResetFences(device.vulkanDevice, swapchain.currentFence)
presentationFence = swapchain.currentFence
swapchain.postPresent(pass.getReadPosition())
if(textureRequests.isNotEmpty()) {
val request = try {
logger.info("Polling requests")
textureRequests.poll()
} catch(e: NoSuchElementException) {
null
}
request?.let { req ->
logger.info("Working on texture request for texture ${req.first}")
val buffer = req.first.contents ?: return@let
val ref = VulkanTexture.getReference(req.first)
if(ref != null) {
ref.copyTo(buffer)
req.second.send(req.first)
req.second.close()
logger.info("Sent updated texture")
} else {
logger.info("Texture not accessible")
}
}
}
if (recordMovie || screenshotRequested || imageRequests.isNotEmpty()) {
val request = try {
imageRequests.poll()
} catch(e: NoSuchElementException) {
null
}
// default image format is 32bit BGRA
val imageByteSize = window.width * window.height * 4L
if(screenshotBuffer == null || screenshotBuffer?.size != imageByteSize) {
logger.debug("Reallocating screenshot buffer")
screenshotBuffer = VulkanBuffer(device, imageByteSize,
VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
wantAligned = true)
}
if(imageBuffer == null || imageBuffer?.capacity() != imageByteSize.toInt()) {
logger.debug("Reallocating image buffer")
imageBuffer = memAlloc(imageByteSize.toInt())
}
// finish encoding if a resize was performed
if(recordMovie) {
if (encoder != null && (encoder?.frameWidth != window.width || encoder?.frameHeight != window.height)) {
encoder?.finish()
}
if (encoder == null || encoder?.frameWidth != window.width || encoder?.frameHeight != window.height) {
val file = SystemHelpers.addFileCounter(if(movieFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.mp4")
} else {
File(movieFilename)
}, recordMovieOverwrite)
encoder = VideoEncoder(
(window.width * settings.get<Float>("Renderer.SupersamplingFactor")).toInt(),
(window.height* settings.get<Float>("Renderer.SupersamplingFactor")).toInt(),
file.absolutePath,
hub = hub)
}
}
screenshotBuffer?.let { sb ->
with(VU.newCommandBuffer(device, commandPools.Render, autostart = true)) {
val subresource = VkImageSubresourceLayers.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
val regions = VkBufferImageCopy.calloc(1)
.bufferRowLength(0)
.bufferImageHeight(0)
.imageOffset(VkOffset3D.calloc().set(0, 0, 0))
.imageExtent(VkExtent3D.calloc().set(window.width, window.height, 1))
.imageSubresource(subresource)
val image = swapchain.images[pass.getReadPosition()]
VulkanTexture.transitionLayout(image,
from = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
to = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
srcStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
dstStage = VK_PIPELINE_STAGE_HOST_BIT,
dstAccessMask = VK_ACCESS_HOST_READ_BIT,
commandBuffer = this)
vkCmdCopyImageToBuffer(this, image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
sb.vulkanBuffer,
regions)
VulkanTexture.transitionLayout(image,
from = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
to = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
srcAccessMask = VK_ACCESS_HOST_READ_BIT,
dstStage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
dstAccessMask = 0,
commandBuffer = this)
endCommandBuffer([email protected], commandPools.Render, queue,
flush = true, dealloc = true)
}
if(screenshotRequested || request != null) {
sb.copyTo(imageBuffer!!)
}
if(recordMovie) {
encoder?.encodeFrame(sb.mapIfUnmapped().getByteBuffer(imageByteSize.toInt()))
}
if((screenshotRequested || request != null) && !recordMovie) {
sb.close()
screenshotBuffer = null
}
}
if(screenshotRequested || request != null) {
val writeToFile = screenshotRequested
val overwrite = screenshotOverwriteExisting
// reorder bytes for screenshot in a separate thread
thread {
imageBuffer?.let { ib ->
try {
val file = SystemHelpers.addFileCounter(if(screenshotFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.png")
} else {
File(screenshotFilename)
}, overwrite)
file.createNewFile()
ib.rewind()
val imageArray = ByteArray(ib.remaining())
ib.get(imageArray)
val shifted = ByteArray(imageArray.size)
ib.flip()
// swizzle BGRA -> ABGR
for (i in 0 until shifted.size step 4) {
shifted[i] = imageArray[i + 3]
shifted[i + 1] = imageArray[i]
shifted[i + 2] = imageArray[i + 1]
shifted[i + 3] = imageArray[i + 2]
}
val image = BufferedImage(window.width, window.height, BufferedImage.TYPE_4BYTE_ABGR)
val imgData = (image.raster.dataBuffer as DataBufferByte).data
System.arraycopy(shifted, 0, imgData, 0, shifted.size)
if(request != null && request is RenderedImage.RenderedRGBAImage) {
request.width = window.width
request.height = window.height
request.data = imgData
}
if(writeToFile) {
ImageIO.write(image, "png", file)
logger.info("Screenshot saved to ${file.absolutePath}")
}
} catch (e: Exception) {
logger.error("Unable to take screenshot: ")
e.printStackTrace()
} finally {
// memFree(ib)
}
}
}
screenshotOverwriteExisting = false
screenshotRequested = false
}
}
if(hub?.getWorkingHMDDisplay()?.hasCompositor() == true) {
hub?.getWorkingHMDDisplay()?.wantsVR(settings)?.update()
}
val presentDuration = System.nanoTime() - startPresent
stats?.add("Renderer.viewportSubmitAndPresent", presentDuration)
firstImageReady = true
}
private var currentFrame = 0
private var previousFrame = 0
private var currentNow = 0L
/**
* This function renders the scene
*/
override fun render(activeCamera: Camera, sceneNodes: List<Node>) = runBlocking {
val profiler = hub?.get<Profiler>()
// profiler?.begin("Renderer.Housekeeping")
val swapchainChanged = pollEvents()
if(shouldClose) {
closeInternal()
return@runBlocking
}
val stats = hub?.get(SceneryElement.Statistics) as? Statistics
// check whether scene is already initialized
if (scene.children.count() == 0 || !scene.initialized) {
initializeScene()
delay(200)
return@runBlocking
}
if (toggleFullscreen) {
vkDeviceWaitIdle(device.vulkanDevice)
switchFullscreen()
toggleFullscreen = false
return@runBlocking
}
if (window.shouldClose) {
shouldClose = true
// stop all
vkDeviceWaitIdle(device.vulkanDevice)
return@runBlocking
}
if (renderDelay > 0) {
logger.warn("Delaying next frame for $renderDelay ms, as one or more validation error have occured in the previous frame.")
delay(renderDelay)
}
// profiler?.end()
profiler?.begin("Renderer.updateUBOs")
val startUboUpdate = System.nanoTime()
val ubosUpdated = updateDefaultUBOs(device, activeCamera)
stats?.add("Renderer.updateUBOs", System.nanoTime() - startUboUpdate)
profiler?.end()
profiler?.begin("Renderer.updateInstanceBuffers")
val startInstanceUpdate = System.nanoTime()
val instancesUpdated = updateInstanceBuffers(sceneNodes)
stats?.add("Renderer.updateInstanceBuffers", System.nanoTime() - startInstanceUpdate)
profiler?.end()
// flag set to true if command buffer re-recording is necessary,
// e.g. because of scene or pipeline changes
var forceRerecording = instancesUpdated
val rerecordingCauses = ArrayList<String>(20)
profiler?.begin("Renderer.PreDraw")
// here we discover the objects in the scene that could be relevant for the scene
var texturesUpdated: Boolean by StickyBoolean(false)
if (renderpasses.filter { it.value.passConfig.type != RenderConfigReader.RenderpassType.quad }.any()) {
sceneNodes.forEach { node ->
val renderable = node.renderableOrNull() ?: return@forEach
val material = node.materialOrNull() ?: return@forEach
// if a node is not initialized yet, it'll be initialized here and it's UBO updated
// in the next round
if (renderable.rendererMetadata() == null || node.state == State.Created || renderable.rendererMetadata()?.initialized == false) {
logger.debug("${node.name} is not initialized, doing that now")
renderable.metadata["VulkanRenderer"] = VulkanObjectState()
initializeNode(node)
return@forEach
}
if(!renderable.preDraw()) {
renderable.rendererMetadata()?.preDrawSkip = true
return@forEach
} else {
renderable.rendererMetadata()?.preDrawSkip = false
}
// the current command buffer will be forced to be re-recorded if either geometry, blending or
// texturing of a given node have changed, as these might change pipelines or descriptor sets, leading
// to the original command buffer becoming obsolete.
renderable.rendererMetadata()?.let { metadata ->
node.ifGeometry {
if (dirty) {
logger.debug("Force command buffer re-recording, as geometry for {} has been updated", node.name)
renderable.preUpdate(this@VulkanRenderer, hub)
updateNodeGeometry(node)
dirty = false
rerecordingCauses.add(node.name)
forceRerecording = true
}
}
// this covers cases where a master node is not given any instanced properties in the beginning
// but only later, or when instancing is removed at some point.
if((!metadata.instanced && node is InstancedNode) ||
metadata.instanced && node !is InstancedNode) {
metadata.initialized = false
initializeNode(node)
return@forEach
}
val reloadTime = measureTimeMillis {
val (texturesUpdatedForNode, descriptorUpdated) = VulkanNodeHelpers.loadTexturesForNode(device, node, metadata, defaultTextures, textureCache, commandPools, queue)
if(descriptorUpdated) {
metadata.texturesToDescriptorSets(device,
renderpasses.filter { it.value.passConfig.type != RenderConfigReader.RenderpassType.quad },
renderable)
logger.trace("Force command buffer re-recording, as reloading textures for ${node.name}")
rerecordingCauses.add(node.name)
forceRerecording = true
}
texturesUpdated = texturesUpdatedForNode
}
if(texturesUpdated) {
logger.debug("Updating textures for {} took {}ms", node.name, reloadTime)
}
if (material.materialHashCode() != metadata.materialHashCode || (material is ShaderMaterial && material.shaders.stale)) {
val reloaded = VulkanNodeHelpers.initializeCustomShadersForNode(device, node, true, renderpasses, lateResizeInitializers, buffers)
logger.debug("{}: Material is stale, re-recording, reloaded={}", node.name, reloaded)
metadata.materialHashCode = material.materialHashCode()
// if we reloaded the node's shaders, we might need to recreate its texture descriptor sets
if(reloaded) {
renderable.rendererMetadata()?.texturesToDescriptorSets(device,
renderpasses.filter { pass -> pass.value.passConfig.type != RenderConfigReader.RenderpassType.quad },
renderable)
}
rerecordingCauses.add(node.name)
forceRerecording = true
(material as? ShaderMaterial)?.shaders?.stale = false
}
}
}
if(pushMode) {
val newSceneArray = sceneNodes.toHashSet()
if (!newSceneArray.equals(sceneArray)) {
forceRerecording = true
}
sceneArray = newSceneArray
}
}
profiler?.end()
getDescriptorCache().forEachChanged(buffers.UBOs.updated) {
if(it.value.updated < buffers.UBOs.updated) {
logger.debug("Canceling current frame, UBO backing buffers updated.")
renderpasses.forEach { (_, pass) ->
pass.invalidateCommandBuffers()
}
return@runBlocking
}
}
profiler?.begin("Renderer.BeginFrame")
val presentedFrames = swapchain.presentedFrames()
// return if neither UBOs were updated, nor the scene was modified
if (pushMode && !swapchainChanged && !ubosUpdated && !forceRerecording && !screenshotRequested && !recordMovie && !texturesUpdated && totalFrames > 3 && presentedFrames > 3) {
logger.trace("UBOs have not been updated, returning (pushMode={}, swapchainChanged={}, ubosUpdated={}, texturesUpdated={}, forceRerecording={}, screenshotRequested={})", pushMode, swapchainChanged, ubosUpdated, texturesUpdated, forceRerecording, totalFrames)
delay(2)
return@runBlocking
}
val submitInfo = VkSubmitInfo.calloc(flow.size-1)
val (_, fence) = beginFrame() ?: return@runBlocking
var waitSemaphore = -1L
profiler?.end()
flow.take(flow.size - 1).forEachIndexed { i, t ->
val si = submitInfo[i]
profiler?.begin("Renderer.$t")
logger.trace("Running pass {}", t)
val target = renderpasses[t]!!
val commandBuffer = target.commandBuffer
if (commandBuffer.submitted) {
commandBuffer.waitForFence()
commandBuffer.submitted = false
commandBuffer.resetFence()
stats?.add("Renderer.$t.gpuTiming", commandBuffer.runtime)
}
val start = System.nanoTime()
when (target.passConfig.type) {
RenderConfigReader.RenderpassType.geometry -> VulkanScenePass.record(hub!!, target, commandBuffer, commandPools, descriptorSets, renderConfig, renderpasses, sceneNodes, { it !is Light }, forceRerecording)
RenderConfigReader.RenderpassType.lights -> VulkanScenePass.record(hub!!, target, commandBuffer, commandPools, descriptorSets, renderConfig, renderpasses, sceneNodes, { it is Light }, forceRerecording)
RenderConfigReader.RenderpassType.quad -> VulkanPostprocessPass.record(target, commandBuffer, commandPools, sceneUBOs, descriptorSets)
RenderConfigReader.RenderpassType.compute -> VulkanComputePass.record(target, commandBuffer, commandPools, sceneUBOs, descriptorSets)
}
stats?.add("VulkanRenderer.$t.recordCmdBuffer", System.nanoTime() - start)
target.updateShaderParameters()
val targetSemaphore = target.semaphore
target.submitCommandBuffers.put(0, commandBuffer.commandBuffer!!)
target.signalSemaphores.put(0, targetSemaphore)
target.waitSemaphores.put(0, waitSemaphore)
target.waitStages.put(0, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
si.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
.pNext(NULL)
.waitSemaphoreCount(0)
.pWaitDstStageMask(target.waitStages)
.pCommandBuffers(target.submitCommandBuffers)
.pSignalSemaphores(target.signalSemaphores)
if(waitSemaphore != -1L) {
si
.waitSemaphoreCount(1)
.pWaitSemaphores(target.waitSemaphores)
}
if(swapchainRecreator.mustRecreate) {
return@runBlocking
}
// logger.info("Submitting pass $t waiting on semaphore ${target.waitSemaphores.get(0).toHexString()}")
VU.run("Submit pass $t render queue", { vkQueueSubmit(queue, si, commandBuffer.getFence() )})
commandBuffer.submitted = true
waitSemaphore = targetSemaphore
profiler?.end()
}
submitInfo.free()
profiler?.begin("Renderer.${renderpasses.keys.last()}")
val viewportPass = renderpasses.values.last()
val viewportCommandBuffer = viewportPass.commandBuffer
logger.trace("Running viewport pass {}", renderpasses.keys.last())
val start = System.nanoTime()
/*if(viewportCommandBuffer.submitted) {
viewportCommandBuffer.waitForFence()
viewportCommandBuffer.submitted = false
viewportCommandBuffer.resetFence()
stats?.add("Renderer.${viewportPass.name}.gpuTiming", viewportCommandBuffer.runtime)
}*/
when (viewportPass.passConfig.type) {
RenderConfigReader.RenderpassType.geometry -> VulkanScenePass.record(hub!!, viewportPass, viewportCommandBuffer, commandPools, descriptorSets, renderConfig, renderpasses, sceneNodes, { it !is Light }, forceRerecording)
RenderConfigReader.RenderpassType.lights -> VulkanScenePass.record(hub!!, viewportPass, viewportCommandBuffer, commandPools, descriptorSets, renderConfig, renderpasses, sceneNodes, { it is Light }, forceRerecording)
RenderConfigReader.RenderpassType.quad -> VulkanPostprocessPass.record(viewportPass, viewportCommandBuffer, commandPools, sceneUBOs, descriptorSets)
RenderConfigReader.RenderpassType.compute -> VulkanComputePass.record(viewportPass, viewportCommandBuffer, commandPools, sceneUBOs, descriptorSets)
}
stats?.add("VulkanRenderer.${viewportPass.name}.recordCmdBuffer", System.nanoTime() - start)
viewportPass.updateShaderParameters()
ph.commandBuffers.put(0, viewportCommandBuffer.commandBuffer!!)
ph.waitStages.put(0, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
ph.waitStages.put(1, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
ph.signalSemaphore.put(0, semaphores.getValue(StandardSemaphores.RenderComplete)[currentFrame])
ph.waitSemaphore.put(0, waitSemaphore)
ph.waitSemaphore.put(1, swapchain.imageAvailableSemaphore)
profiler?.end()
profiler?.begin("Renderer.SubmitFrame")
vkWaitForFences(device.vulkanDevice, fence, true, -1L)
vkResetFences(device.vulkanDevice, fence)
submitFrame(queue, viewportPass, viewportCommandBuffer, ph)
updateTimings()
profiler?.end()
currentNow = System.nanoTime()
}
private fun updateTimings() {
val thisTime = System.nanoTime()
val duration = thisTime - lastTime
time += duration / 1E9f
lastTime = thisTime
// scene.activeObserver?.deltaT = duration / 10E6f
frames++
totalFrames++
}
private fun createInstance(requiredExtensions: PointerBuffer? = null, enableValidations: Boolean = false, headless: Boolean = false, embedded: Boolean = false): VkInstance {
return stackPush().use { stack ->
val appInfo = VkApplicationInfo.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_APPLICATION_INFO)
.pApplicationName(stack.UTF8(applicationName))
.pEngineName(stack.UTF8("scenery"))
.apiVersion(VK_MAKE_VERSION(1, 1, 0))
val additionalExts = ArrayList<String>()
hub?.getWorkingHMDDisplay()?.getVulkanInstanceExtensions()?.forEach { additionalExts.add(it) }
if(enableValidations) {
additionalExts.add(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)
}
val utf8Exts = additionalExts.map { stack.UTF8(it) }
logger.debug("HMD required instance exts: ${additionalExts.joinToString(", ")} ${additionalExts.size}")
// allocate enough pointers for already pre-required extensions, plus HMD-required extensions, plus the debug extension
val size = requiredExtensions?.remaining() ?: 0
val enabledExtensionNames = if(!headless) {
val buffer = stack.callocPointer(size + additionalExts.size + 2)
val platformSurfaceExtension = when {
Platform.get() === Platform.WINDOWS -> stack.UTF8(VK_KHR_WIN32_SURFACE_EXTENSION_NAME)
Platform.get() === Platform.LINUX -> stack.UTF8(VK_KHR_XLIB_SURFACE_EXTENSION_NAME)
Platform.get() === Platform.MACOSX -> stack.UTF8(VK_MVK_MACOS_SURFACE_EXTENSION_NAME)
else -> throw RendererUnavailableException("Vulkan is not supported on ${Platform.get()}")
}
buffer.put(platformSurfaceExtension)
buffer.put(stack.UTF8(VK_KHR_SURFACE_EXTENSION_NAME))
buffer
} else {
stack.callocPointer(size + additionalExts.size)
}
if(requiredExtensions != null) {
enabledExtensionNames.put(requiredExtensions)
}
utf8Exts.forEach { enabledExtensionNames.put(it) }
enabledExtensionNames.flip()
val enabledLayerNames = if(!wantsOpenGLSwapchain && validation) {
val pointers = stack.callocPointer(defaultValidationLayers.size)
defaultValidationLayers.forEach { pointers.put(stack.UTF8(it)) }
pointers
} else {
stack.callocPointer(0)
}
enabledLayerNames.flip()
val createInfo = VkInstanceCreateInfo.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO)
.pNext(NULL)
.pApplicationInfo(appInfo)
.ppEnabledExtensionNames(enabledExtensionNames)
.ppEnabledLayerNames(enabledLayerNames)
val extensions = (0 until enabledExtensionNames.remaining()).map {
memUTF8(enabledExtensionNames.get(it))
}
val layers = (0 until enabledLayerNames.remaining()).map {
memUTF8(enabledLayerNames.get(it))
}
logger.info("Creating Vulkan instance with extensions ${extensions.joinToString(",")} and layers ${layers.joinToString(",")}")
val instance = VU.getPointer("Creating Vulkan instance",
{ vkCreateInstance(createInfo, null, this) }, {})
VkInstance(instance, createInfo)
}
}
@Suppress("SameParameterValue")
private fun setupDebuggingDebugUtils(instance: VkInstance, severity: Int, callback: (Int, Int, Long, Long) -> Int): Long {
val messengerCreateInfo = VkDebugUtilsMessengerCreateInfoEXT.calloc()
.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT)
.pfnUserCallback(callback)
.messageType(VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
or VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
or VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT)
.messageSeverity(severity)
.flags(0)
return try {
val messenger = VU.getLong("Create debug messenger", { vkCreateDebugUtilsMessengerEXT(instance,
messengerCreateInfo,
null,
this
)}, {})
messenger
} catch(e: NullPointerException) {
logger.warn("Caught NPE on creating debug callback, is extension $VK_EXT_DEBUG_UTILS_EXTENSION_NAME available?")
-1
}
}
@Suppress("SameParameterValue", "unused")
private fun setupDebuggingDebugReport(instance: VkInstance, flags: Int, callback: VkDebugReportCallbackEXT): Long {
val dbgCreateInfo = VkDebugReportCallbackCreateInfoEXT.calloc()
.sType(VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT)
.pNext(NULL)
.pfnCallback(callback)
.pUserData(NULL)
.flags(flags)
val pCallback = memAllocLong(1)
return try {
val err = vkCreateDebugReportCallbackEXT(instance, dbgCreateInfo, null, pCallback)
val callbackHandle = pCallback.get(0)
memFree(pCallback)
dbgCreateInfo.free()
if (err != VK_SUCCESS) {
throw RuntimeException("Failed to create VkInstance with debugging enabled: " + VU.translate(err))
}
callbackHandle
} catch(e: NullPointerException) {
logger.warn("Caught NPE on creating debug callback, is extension ${VK_EXT_DEBUG_REPORT_EXTENSION_NAME} available?")
-1
}
}
private fun prepareDefaultBuffers(device: VulkanDevice): DefaultBuffers {
logger.debug("Creating buffers")
return DefaultBuffers(
UBOs = VulkanBuffer(device,
5 * 1024 * 1024,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = true),
LightParameters = VulkanBuffer(device,
5 * 1024 * 1024,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = true),
VRParameters = VulkanBuffer(device,
256 * 10,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = true),
ShaderProperties = VulkanBuffer(device,
4 * 1024 * 1024,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = true))
}
private fun Renderable.rendererMetadata(): VulkanObjectState? {
return this.metadata["VulkanRenderer"] as? VulkanObjectState
}
private fun updateInstanceBuffers(sceneObjects: List<Node>) = runBlocking {
val instanceMasters = sceneObjects.filter { it is InstancedNode }.parallelMap { it as InstancedNode }
instanceMasters.forEach { parent ->
val metadata = parent.renderableOrNull()?.rendererMetadata()
if(metadata != null && metadata.initialized) {
VulkanNodeHelpers.updateInstanceBuffer(device, parent, metadata, commandPools, queue)
}
}
instanceMasters.isNotEmpty()
}
fun Matrix4f.applyVulkanCoordinateSystem(): Matrix4f {
val m = Matrix4f(vulkanProjectionFix)
m.mul(this)
return m
}
private fun getDescriptorCache(): TimestampedConcurrentHashMap<String, SimpleTimestamped<Long>> {
@Suppress("UNCHECKED_CAST")
return scene.metadata.getOrPut("DescriptorCache") {
TimestampedConcurrentHashMap<String, SimpleTimestamped<Long>>()
} as? TimestampedConcurrentHashMap<String, SimpleTimestamped<Long>> ?: throw IllegalStateException("Could not retrieve descriptor cache from scene")
}
private fun updateDefaultUBOs(device: VulkanDevice, cam: Camera): Boolean = runBlocking {
if(shouldClose) {
return@runBlocking false
}
logger.trace("Updating default UBOs for {}", device)
// sticky boolean
var updated: Boolean by StickyBoolean(initial = false)
if (!cam.lock.tryLock()) {
return@runBlocking false
}
val hmd = hub?.getWorkingHMDDisplay()?.wantsVR(settings)
val now = System.nanoTime()
getDescriptorCache().forEachChanged(now = buffers.UBOs.updated) {
if(it.value.updated < buffers.UBOs.updated) {
logger.debug("Updating descriptor set for ${it.key} as the backing buffer has changed")
VU.updateDynamicDescriptorSetBuffer(device, it.value.contents, 1, buffers.UBOs)
it.value.updated = now
}
}
val camSpatial = cam.spatial()
camSpatial.view = camSpatial.getTransformation()
// cam.updateWorld(true, false)
buffers.VRParameters.reset()
val vrUbo = defaultUBOs["VRParameters"]!!
vrUbo.add("projection0", {
(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).applyVulkanCoordinateSystem()
})
vrUbo.add("projection1", {
(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).applyVulkanCoordinateSystem()
})
vrUbo.add("inverseProjection0", {
(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).applyVulkanCoordinateSystem().invert()
})
vrUbo.add("inverseProjection1", {
(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).applyVulkanCoordinateSystem().invert()
})
vrUbo.add("headShift", { hmd?.getHeadToEyeTransform(0) ?: Matrix4f().identity() })
vrUbo.add("IPD", { hmd?.getIPD() ?: 0.05f })
vrUbo.add("stereoEnabled", { renderConfig.stereoEnabled.toInt() })
updated = vrUbo.populate()
buffers.UBOs.reset()
buffers.ShaderProperties.reset()
sceneUBOs.forEach { node ->
val renderable = node.renderableOrNull() ?: return@forEach
val spatial = node.spatialOrNull()
node.lock.withLock {
var nodeUpdated: Boolean by StickyBoolean(initial = false)
if (!renderable.metadata.containsKey("VulkanRenderer")) {
return@forEach
}
val s = renderable.rendererMetadata() ?: return@forEach
val ubo = s.UBOs["Matrices"]!!.second
ubo.offsets.limit(1)
var bufferOffset = ubo.backingBuffer!!.advance()
ubo.offsets.put(0, bufferOffset)
ubo.offsets.limit(1)
// spatial.projection.copyFrom(cam.projection.applyVulkanCoordinateSystem())
spatial?.view?.set(camSpatial.view)
nodeUpdated = ubo.populate(offset = bufferOffset.toLong())
val materialUbo = s.UBOs["MaterialProperties"]!!.second
bufferOffset = ubo.backingBuffer!!.advance()
materialUbo.offsets.put(0, bufferOffset)
materialUbo.offsets.limit(1)
nodeUpdated = materialUbo.populate(offset = bufferOffset.toLong())
s.UBOs.filter { it.key.contains("ShaderProperties") && it.value.second.memberCount() > 0 }.forEach {
// if(s.requiredDescriptorSets.keys.any { it.contains("ShaderProperties") }) {
val propertyUbo = it.value.second
val offset = propertyUbo.backingBuffer!!.advance()
nodeUpdated = propertyUbo.populate(offset = offset.toLong())
propertyUbo.offsets.put(0, offset)
propertyUbo.offsets.limit(1)
}
if(nodeUpdated && node.getScene()?.onNodePropertiesChanged?.isNotEmpty() == true) {
GlobalScope.launch { node.getScene()?.onNodePropertiesChanged?.forEach { it.value.invoke(node) } }
}
updated = nodeUpdated
s.flags.add(RendererFlags.Updated)
}
}
buffers.UBOs.copyFromStagingBuffer()
val lightUbo = defaultUBOs["LightParameters"]!!
lightUbo.add("ViewMatrix0", { camSpatial.getTransformationForEye(0) })
lightUbo.add("ViewMatrix1", { camSpatial.getTransformationForEye(1) })
lightUbo.add("InverseViewMatrix0", { camSpatial.getTransformationForEye(0).invert() })
lightUbo.add("InverseViewMatrix1", { camSpatial.getTransformationForEye(1).invert() })
lightUbo.add("ProjectionMatrix", { camSpatial.projection.applyVulkanCoordinateSystem() })
lightUbo.add("InverseProjectionMatrix", { camSpatial.projection.applyVulkanCoordinateSystem().invert() })
lightUbo.add("CamPosition", { camSpatial.position })
updated = lightUbo.populate()
buffers.ShaderProperties.copyFromStagingBuffer()
// updateDescriptorSets()
cam.lock.unlock()
return@runBlocking updated
}
@Suppress("UNUSED")
override fun screenshot(filename: String, overwrite: Boolean) {
screenshotRequested = true
screenshotOverwriteExisting = overwrite
screenshotFilename = filename
}
fun Int.toggle(): Int {
if (this == 0) {
return 1
} else if (this == 1) {
return 0
}
logger.warn("Property is not togglable.")
return this
}
@Suppress("UNUSED")
fun toggleDebug() {
settings.getAllSettings().forEach {
if (it.lowercase().contains("debug")) {
try {
val property = settings.get<Int>(it).toggle()
settings.set(it, property)
} catch(e: Exception) {
logger.warn("$it is a property that is not togglable.")
}
}
}
}
/**
* Closes the current instance of [VulkanRenderer].
*/
override fun close() {
shouldClose = true
}
fun closeInternal() {
if(!initialized) {
return
}
initialized = false
logger.info("Renderer teardown started.")
vkQueueWaitIdle(queue)
logger.debug("Closing nodes...")
scene.discover(scene, { true }).forEach {
destroyNode(it, onShutdown = true)
}
// The hub might contain elements that are both in the scene graph,
// and in the hub, e.g. a VolumeManager. We clean them here as well.
hub?.find { it is Node }?.forEach { (_, node) ->
(node as? Node)?.let { destroyNode(it, onShutdown = true) }
}
scene.metadata.remove("DescriptorCache")
scene.initialized = false
logger.debug("Cleaning texture cache...")
textureCache.forEach {
logger.debug("Cleaning ${it.key}...")
it.value.close()
}
logger.debug("Closing buffers...")
buffers.LightParameters.close()
buffers.ShaderProperties.close()
buffers.UBOs.close()
buffers.VRParameters.close()
logger.debug("Closing default UBOs...")
defaultUBOs.forEach { ubo ->
ubo.value.close()
}
logger.debug("Closing memory pools ...")
geometryPool.close()
stagingPool.close()
logger.debug("Closing vertex descriptors ...")
vertexDescriptors.forEach {
logger.debug("Closing vertex descriptor ${it.key}...")
it.value.attributeDescription?.free()
it.value.bindingDescription?.free()
it.value.state.free()
}
logger.debug("Closing descriptor sets and pools...")
// descriptorSetLayouts.forEach { vkDestroyDescriptorSetLayout(device.vulkanDevice, it.value, null) }
logger.debug("Closing command buffers...")
ph.commandBuffers.free()
memFree(ph.signalSemaphore)
memFree(ph.waitSemaphore)
memFree(ph.waitStages)
semaphores.forEach { it.value.forEach { semaphore -> device.removeSemaphore(semaphore) }}
logger.debug("Closing swapchain...")
swapchain.close()
logger.debug("Closing renderpasses...")
renderpasses.forEach { _, vulkanRenderpass -> vulkanRenderpass.close() }
logger.debug("Clearing shader module cache...")
VulkanShaderModule.clearCache()
logger.debug("Closing command pools...")
with(commandPools) {
device.destroyCommandPool(Render)
device.destroyCommandPool(Compute)
device.destroyCommandPool(Standard)
device.destroyCommandPool(Transfer)
}
VulkanRenderpass.destroyPipelineCache(device)
if (validation && debugCallbackHandle != -1L) {
vkDestroyDebugUtilsMessengerEXT(instance, debugCallbackHandle, null)
}
debugCallback.free()
logger.debug("Closing device $device...")
device.close()
if(System.getProperty("scenery.Workarounds.DontCloseVulkanInstances")?.toBoolean() == true) {
logger.warn("Not closing Vulkan instances explicitly requested as workaround for Nvidia driver issue.")
} else {
logger.debug("Closing instance...")
vkDestroyInstance(instance, null)
}
heartbeatTimer.cancel()
heartbeatTimer.purge()
logger.info("Renderer teardown complete.")
}
override fun reshape(newWidth: Int, newHeight: Int) {
}
@Suppress("UNUSED")
fun toggleFullscreen() {
toggleFullscreen = !toggleFullscreen
}
fun switchFullscreen() {
hub?.let { hub -> swapchain.toggleFullscreen(hub, swapchainRecreator) }
}
/**
* Sets the rendering quality, if the loaded renderer config file supports it.
*
* @param[quality] The [RenderConfigReader.RenderingQuality] to be set.
*/
override fun setRenderingQuality(quality: RenderConfigReader.RenderingQuality) {
fun setConfigSetting(key: String, value: Any) {
val setting = "Renderer.$key"
logger.debug("Setting $setting: ${settings.get<Any>(setting)} -> $value")
settings.set(setting, value)
}
if(renderConfig.qualitySettings.isNotEmpty()) {
logger.info("Setting rendering quality to $quality")
renderConfig.qualitySettings[quality]?.forEach { setting ->
if(setting.key.endsWith(".shaders") && setting.value is List<*>) {
val pass = setting.key.substringBeforeLast(".shaders")
@Suppress("UNCHECKED_CAST") val shaders = setting.value as? List<String> ?: return@forEach
renderConfig.renderpasses[pass]?.shaders = shaders
@Suppress("SENSELESS_COMPARISON")
if(swapchainRecreator != null) {
swapchainRecreator.mustRecreate = true
swapchainRecreator.afterRecreateHook = { swapchainRecreator ->
renderConfig.qualitySettings[quality]?.filter { !it.key.endsWith(".shaders") }?.forEach {
setConfigSetting(it.key, it.value)
}
swapchainRecreator.afterRecreateHook = {}
}
}
} else {
setConfigSetting(setting.key, setting.value)
}
}
} else {
logger.warn("The current renderer config, $renderConfigFile, does not support setting quality options.")
}
}
}
| lgpl-3.0 | 452b4154f38aaab65e43c80486b08727 | 40.428022 | 270 | 0.593908 | 4.953419 | false | false | false | false |
Scavi/BrainSqueeze | src/main/kotlin/com/scavi/brainsqueeze/adventofcode/util/FileHelper.kt | 1 | 1445 | package com.scavi.brainsqueeze.adventofcode.util
import java.io.File
class FileHelper {
companion object {
fun fileForUnitTest(relativePath: String): File {
val path = File(System.getProperty("user.dir"), relativePath)
if (!path.exists()) {
throw IllegalArgumentException(
"The input file '${path.absolutePath}' doesn't exist!")
}
return path.absoluteFile
}
fun readAsIntList(filePath: File): MutableList<Int> {
val result = mutableListOf<Int>()
filePath.reader().forEachLine {
result.add(it.toInt())
}
return result
}
fun readAsIntSet(filePath: File): Set<Int> {
val result = mutableSetOf<Int>()
filePath.reader().forEachLine {
result.add(it.toInt())
}
return result
}
fun readAsLongList(filePath: File): List<Long> {
val result = mutableListOf<Long>()
filePath.reader().forEachLine {
result.add(it.toLong())
}
return result
}
fun readAsCharArray(filePath: File): List<CharArray> {
val result = mutableListOf<CharArray>()
filePath.reader().forEachLine {
result.add(it.toCharArray())
}
return result
}
}
}
| apache-2.0 | 36d2b2ba8f469ff3370b0d55ccbf51ed | 28.489796 | 79 | 0.524567 | 5.179211 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/AuditInfoNestedObject.kt | 1 | 1989 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firestore.schema
import com.google.firebase.Timestamp
import com.google.firebase.firestore.ServerTimestamp
/** User details and timestamp for creation or modification of a model object. */
data class AuditInfoNestedObject(
/**
* The user initiating the related action. This should never be missing, but we handle null values
* anyway since the Firestore is schema-less.
*/
val user: UserNestedObject? = null,
/**
* The time at which the user action was initiated, according to the user's device. See
* [System.currentTimestamp] for details. This should never be missing, but we handle null values
* anyway since the Firestore is schema-less.
*/
val clientTimestamp: Timestamp? = null,
/**
* The time at which the server received the requested change according to the server's internal
* clock, or the updated server time was not yet received. See [System.currentTimestamp] for
* details. This will be null until the server updates the write time and syncs it back to the
* client.
*/
@ServerTimestamp val serverTimestamp: Timestamp? = null
) {
companion object {
private val EPOCH = Timestamp(0, 0)
/** Value used to degrade gracefully when missing in remote db. */
@JvmField
val FALLBACK_VALUE = AuditInfoNestedObject(UserNestedObject.UNKNOWN_USER, EPOCH, EPOCH)
}
}
| apache-2.0 | 5c48a7db79ea236daefbbbe81c6b930c | 38 | 100 | 0.738059 | 4.286638 | false | false | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsViewModel.kt | 1 | 3790 | package org.thoughtcrime.securesms.components.settings.app.internal
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import org.thoughtcrime.securesms.keyvalue.InternalValues
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.livedata.Store
class InternalSettingsViewModel(private val repository: InternalSettingsRepository) : ViewModel() {
private val preferenceDataStore = SignalStore.getPreferenceDataStore()
private val store = Store(getState())
init {
repository.getEmojiVersionInfo { version ->
store.update { it.copy(emojiVersion = version) }
}
}
val state: LiveData<InternalSettingsState> = store.stateLiveData
fun setSeeMoreUserDetails(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.RECIPIENT_DETAILS, enabled)
refresh()
}
fun setGv2DoNotCreateGv2Groups(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DO_NOT_CREATE_GV2, enabled)
refresh()
}
fun setGv2ForceInvites(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_FORCE_INVITES, enabled)
refresh()
}
fun setGv2IgnoreServerChanges(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_SERVER_CHANGES, enabled)
refresh()
}
fun setGv2IgnoreP2PChanges(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_P2P_CHANGES, enabled)
refresh()
}
fun setDisableAutoMigrationInitiation(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_INITIATION, enabled)
refresh()
}
fun setDisableAutoMigrationNotification(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_NOTIFICATION, enabled)
refresh()
}
fun setForceCensorship(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.FORCE_CENSORSHIP, enabled)
refresh()
}
fun setUseBuiltInEmoji(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.FORCE_BUILT_IN_EMOJI, enabled)
refresh()
}
fun setRemoveSenderKeyMinimum(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.REMOVE_SENDER_KEY_MINIMUM, enabled)
refresh()
}
fun setInternalGroupCallingServer(server: String?) {
preferenceDataStore.putString(InternalValues.CALLING_SERVER, server)
refresh()
}
private fun refresh() {
store.update { getState().copy(emojiVersion = it.emojiVersion) }
}
private fun getState() = InternalSettingsState(
seeMoreUserDetails = SignalStore.internalValues().recipientDetails(),
gv2doNotCreateGv2Groups = SignalStore.internalValues().gv2DoNotCreateGv2Groups(),
gv2forceInvites = SignalStore.internalValues().gv2ForceInvites(),
gv2ignoreServerChanges = SignalStore.internalValues().gv2IgnoreServerChanges(),
gv2ignoreP2PChanges = SignalStore.internalValues().gv2IgnoreP2PChanges(),
disableAutoMigrationInitiation = SignalStore.internalValues().disableGv1AutoMigrateInitiation(),
disableAutoMigrationNotification = SignalStore.internalValues().disableGv1AutoMigrateNotification(),
forceCensorship = SignalStore.internalValues().forcedCensorship(),
callingServer = SignalStore.internalValues().groupCallingServer(),
useBuiltInEmojiSet = SignalStore.internalValues().forceBuiltInEmoji(),
emojiVersion = null,
removeSenderKeyMinimium = SignalStore.internalValues().removeSenderKeyMinimum()
)
class Factory(private val repository: InternalSettingsRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return requireNotNull(modelClass.cast(InternalSettingsViewModel(repository)))
}
}
}
| gpl-3.0 | af065d5e2caf9ab7c5347fdeb53a87df | 36.156863 | 104 | 0.783113 | 4.803549 | false | false | false | false |
cdietze/klay | klay-scene/src/main/kotlin/klay/scene/LayerUtil.kt | 1 | 9175 | package klay.scene
import euklid.f.Point
import euklid.f.XY
import euklid.util.NoninvertibleTransformException
import klay.core.Clock
import klay.core.Log
import klay.core.PaintClock
import react.Closeable
import react.Signal
import react.Slot
/**
* Utility class for transforming coordinates between [Layer]s.
*/
object LayerUtil {
/**
* Converts the supplied point from coordinates relative to the specified layer to screen
* coordinates. The results are stored into `into`, which is returned for convenience.
*/
fun layerToScreen(layer: Layer, point: XY, into: Point): Point {
return layerToParent(layer, null, point, into)
}
/**
* Converts the supplied point from coordinates relative to the specified
* layer to screen coordinates.
*/
fun layerToScreen(layer: Layer, x: Float, y: Float): Point {
val into = Point(x, y)
return layerToScreen(layer, into, into)
}
/**
* Converts the supplied point from coordinates relative to the specified
* child layer to coordinates relative to the specified parent layer. The
* results are stored into `into`, which is returned for convenience.
*/
fun layerToParent(layer: Layer?, parent: Layer?, point: XY, into: Point): Point {
var _layer = layer
into.set(point)
while (_layer !== parent) {
if (_layer == null) {
throw IllegalArgumentException(
"Failed to find parent, perhaps you passed parent, layer instead of " + "layer, parent?")
}
into.x -= _layer.originX()
into.y -= _layer.originY()
_layer.transform().transform(into, into)
_layer = _layer.parent()
}
return into
}
/**
* Converts the supplied point from coordinates relative to the specified
* child layer to coordinates relative to the specified parent layer.
*/
fun layerToParent(layer: Layer, parent: Layer, x: Float, y: Float): Point {
val into = Point(x, y)
return layerToParent(layer, parent, into, into)
}
/**
* Converts the supplied point from screen coordinates to coordinates
* relative to the specified layer. The results are stored into `into`
* , which is returned for convenience.
*/
fun screenToLayer(layer: Layer, point: XY, into: Point): Point {
val parent = layer.parent()
val cur = if (parent == null) point else screenToLayer(parent, point, into)
return parentToLayer(layer, cur, into)
}
/**
* Converts the supplied point from screen coordinates to coordinates
* relative to the specified layer.
*/
fun screenToLayer(layer: Layer, x: Float, y: Float): Point {
val into = Point(x, y)
return screenToLayer(layer, into, into)
}
/**
* Converts the supplied point from coordinates relative to its parent
* to coordinates relative to the specified layer. The results are stored
* into `into`, which is returned for convenience.
*/
fun parentToLayer(layer: Layer, point: XY, into: Point): Point {
layer.transform().inverseTransform(into.set(point), into)
into.x += layer.originX()
into.y += layer.originY()
return into
}
/**
* Converts the supplied point from coordinates relative to the specified parent to coordinates
* relative to the specified child child. The results are stored into `into`, which is
* returned for convenience.
*/
fun parentToLayer(parent: Layer, child: Layer, point: XY, into: Point): Point {
into.set(point)
val immediateParent = child.parent()
if (immediateParent !== parent) parentToLayer(parent, immediateParent ?: error("Supplied layers are not parent and child [parent is not a parent of child [parent=$parent, child=$child]"), into, into)
parentToLayer(child, into, into)
return into
}
/**
* Returns the layer hit by (screen) position `p` (or null) in the scene graph rooted at
* `root`, using [Layer.hitTest]. Note that `p` is mutated by this call.
*/
fun getHitLayer(root: Layer, p: Point): Layer? {
root.transform().inverseTransform(p, p)
p.x += root.originX()
p.y += root.originY()
return root.hitTest(p)
}
/**
* Returns true if an [XY] touches a [Layer]. Note: if the supplied layer has no
* size, this will always return false.
*/
fun hitTest(layer: Layer, pos: XY): Boolean {
return hitTest(layer, pos.x, pos.y)
}
/**
* Returns true if a coordinate on the screen touches a [Layer]. Note: if the supplied
* layer has no size, this will always return false.
*/
fun hitTest(layer: Layer, x: Float, y: Float): Boolean {
val point = screenToLayer(layer, x, y)
return point.x >= 0 && point.y >= 0 &&
point.x <= layer.width() && point.y <= layer.height()
}
/**
* Gets the layer underneath the given screen coordinates, ignoring hit testers. This is
* useful for inspecting the scene graph for debugging purposes, and is not intended for use
* in shipped code. The layer returned is the one that has a size and is the deepest within
* the graph and contains the coordinate.
*/
fun layerUnderPoint(root: Layer, x: Float, y: Float): Layer? {
val p = Point(x, y)
root.transform().inverseTransform(p, p)
p.x += root.originX()
p.y += root.originY()
return layerUnderPoint(root, p)
}
/**
* Returns the index of the given layer within its parent, or -1 if the parent is null.
*/
fun indexInParent(layer: Layer): Int {
val parent = layer.parent() ?: return -1
for (ii in parent.children() - 1 downTo 0) {
if (parent.childAt(ii) === layer) return ii
}
throw AssertionError()
}
/**
* Automatically connects `onPaint` to `paint` when `layer` is added to a scene
* graph, and disconnects it when `layer` is removed.
*/
fun bind(layer: Layer, paint: Signal<PaintClock>, onPaint: Slot<PaintClock>) {
var _pcon = Closeable.Util.NOOP
layer.state.connectNotify { state: Layer.State ->
_pcon = Closeable.Util.close(_pcon)
if (state === Layer.State.ADDED) _pcon = paint.connect(onPaint)
}
}
/**
* Automatically connects `onUpdate` to `update`, and `onPaint` to `paint` when `layer` is added to a scene graph, and disconnects them when `layer`
* is removed.
*/
fun bind(layer: Layer, update: Signal<Clock>, onUpdate: Slot<Clock>,
paint: Signal<Clock>, onPaint: Slot<Clock>) {
var _ucon = Closeable.Util.NOOP
var _pcon = Closeable.Util.NOOP
layer.state.connectNotify { state: Layer.State ->
_pcon = Closeable.Util.close(_pcon)
_ucon = Closeable.Util.close(_ucon)
if (state === Layer.State.ADDED) {
_ucon = update.connect(onUpdate)
_pcon = paint.connect(onPaint)
}
}
}
/**
* Returns the depth of the given layer in its local scene graph. A root layer (one with null
* parent) will always return 0.
*/
fun graphDepth(layer: Layer?): Int {
var _layer = layer
var depth = -1
while (_layer != null) {
_layer = _layer.parent()
depth++
}
return depth
}
/**
* Prints the layer heirarchy starting at `layer`, using [Log.debug].
*/
fun print(log: Log, layer: Layer) {
print(log, layer, "")
}
/** Performs the recursion for [.layerUnderPoint]. */
private fun layerUnderPoint(layer: Layer, pt: Point): Layer? {
val x = pt.x
val y = pt.y
if (layer is GroupLayer) {
val gl = layer
for (ii in gl.children() - 1 downTo 0) {
val child = gl.childAt(ii)
if (!child.visible()) continue // ignore invisible children
try {
// transform the point into the child's coordinate system
child.transform().inverseTransform(pt.set(x, y), pt)
pt.x += child.originX()
pt.y += child.originY()
val l = layerUnderPoint(child, pt)
if (l != null)
return l
} catch (nte: NoninvertibleTransformException) {
continue
}
}
}
if (x >= 0 && x < layer.width() && y >= 0 && y < layer.height()) {
return layer
}
return null
}
private fun print(log: Log, layer: Layer, prefix: String) {
log.debug(prefix + layer)
if (layer is GroupLayer) {
val gprefix = prefix + " "
val glayer = layer
var ii = 0
val ll = glayer.children()
while (ii < ll) {
print(log, glayer.childAt(ii), gprefix)
ii++
}
}
}
}
| apache-2.0 | 1f2baba0b7e40ab2af31fbc83ca1b405 | 34.700389 | 207 | 0.58594 | 4.218391 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/components/ItemComponent.kt | 1 | 4690 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
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.ore.infinium.components
import com.artemis.Component
import com.badlogic.gdx.math.Vector2
import com.ore.infinium.util.ExtendedComponent
import com.ore.infinium.util.defaultCopyFrom
import java.util.*
class ItemComponent : Component(), ExtendedComponent<ItemComponent> {
//number of items this item has. e.g. 35 wood..things
var stackSize: Int = 0
//the max a single item stack can hold
var maxStackSize: Int = 0
var name: String = ""
/**
* indicates the ms point in time that the player dropped the item.
* this way we can avoid picking it up. if we did not, dropping would instantly
* get picked up.
*
* reset it to 0 when consumed (picked up)
*
* server-side only
*/
@Transient
var timeOfDropMs = 0L
companion object {
/**
* ms time necessary between an item was dropped and when it can
* be picked up
*/
const val droppedItemCoolOffMs = 1500L
}
/**
* the size of the item before the drop
* we reduce the size of all dropped items in the world,
* temporarily. if they get picked up, we'd like to restore
* this back to normal, but since we modify the original
* size, we have no idea what it is.
*
*
* This is serialized over the network, unfortunately it is
* for each item. we may want a better method. if this becomes a
* problem network/bandwidth wise
* (todo)
*/
var sizeBeforeDrop = Vector2()
//todo may want to think about ownership. probably a separate field than playerIdWhoDropped
//something like playerUidWhoOwns
/**
* The id of the player (not entity id!!) who dropped the item in the world
*
* Right now it is the connection player id. but this wouldn't make sense if we want
* ownership to exist beyond connections i guess.
*
* Unused if the item is not in a dropped state, or if a player didn't drop it but eg another
* entity/item dropped it.
*
* Utilized for record keeping of ownership
*/
var playerIdWhoDropped: Int? = null
var state = State.InWorldState
/**
* If this item resides in an inventory of some kind, the dragSourceIndex of where it is at will be stored here
*/
var inventoryIndex: Int = -1
/**
* flag to indicate the item was *just* dropped this frame and has not yet
* had velocity integrated yet.
*
* Only set by the server when an item is dropped.
* When it receives the drop request from the client,
* server will simulate the item getting dropped and tell the clients.
*/
@Transient var justDropped: Boolean = false
enum class ItemProperties {
Placeable,
Consumable,
//potions and such FIXME UNUSED maybe unneeded too?
Usable
}
enum class State {
InWorldState,
InInventoryState,
DroppedInWorld
}
/**
* determines what is required to satisfy placement attempts
* for this item. if blocks must be solid on certain sides.
*/
var placementAdjacencyHints = EnumSet.noneOf(PlacementAdjacencyHints::class.java)!!
enum class PlacementAdjacencyHints {
TopSolid,
BottomSolid,
LeftSolid,
RightSolid
}
override fun canCombineWith(other: ItemComponent) =
this.name == other.name &&
this.maxStackSize == other.maxStackSize
override fun copyFrom(other: ItemComponent) {
this.defaultCopyFrom(other)
justDropped = false
}
}
| mit | 378a53e11d7a418bec81121b8b5137fb | 32.262411 | 115 | 0.683582 | 4.488038 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/implements/EmptyImplementsInspection.kt | 1 | 1495 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.implements
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.IMPLEMENTS
import com.demonwav.mcdev.util.findAnnotations
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.RemoveAnnotationQuickFix
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElementVisitor
class EmptyImplementsInspection : MixinInspection() {
override fun getStaticDescription() = "Reports empty @Implements annotations (without an @Interface)"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitAnnotation(annotation: PsiAnnotation) {
if (annotation.qualifiedName != IMPLEMENTS) {
return
}
val interfaces = annotation.findDeclaredAttributeValue(null)?.findAnnotations()
if (interfaces == null || interfaces.isEmpty()) {
holder.registerProblem(
annotation, "@Implements is redundant",
RemoveAnnotationQuickFix(annotation, null)
)
}
}
}
}
| mit | e282f2c8d07c071083c382ff0449f7f6 | 32.977273 | 105 | 0.713043 | 5.17301 | false | false | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/extenstions/PsiElementExt.kt | 3 | 1882 | /*
* 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.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.extenstions
import com.intellij.psi.PsiElement
import java.util.*
/**
* @param classOnly limit ancestors to this class only
* @param limit upper limit to prevent huge unstub. [com.intellij.psi.PsiFile] is good choice
*/
fun <T : PsiElement> PsiElement.getAncestors(limit: PsiElement = this.containingFile, classOnly: Class<out T>): List<T> {
var currentElement = this
val result = ArrayList<T>()
while (currentElement != limit) {
currentElement = currentElement.parent
if (classOnly.isInstance(currentElement)) {
@Suppress("UNCHECKED_CAST") // Checked one line above
result.add(currentElement as T)
}
}
return result
} | apache-2.0 | 1d4a06eb2a9fbc6146a80febddb19525 | 35.211538 | 121 | 0.734325 | 4.091304 | false | false | false | false |
google/intellij-community | platform/diff-impl/src/com/intellij/diff/util/FileEditorBase.kt | 6 | 1579 | // 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.diff.util
import com.intellij.codeHighlighting.BackgroundEditorHighlighter
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorState
import com.intellij.openapi.fileEditor.FileEditorStateLevel
import com.intellij.openapi.util.CheckedDisposable
import com.intellij.openapi.util.UserDataHolderBase
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
abstract class FileEditorBase : UserDataHolderBase(), FileEditor, CheckedDisposable {
private var isDisposed = false
override fun isDisposed(): Boolean = isDisposed
protected val propertyChangeSupport = PropertyChangeSupport(this)
override fun dispose() {
isDisposed = true
}
override fun isValid(): Boolean = true
fun firePropertyChange(propName: String, oldValue: Boolean, newValue: Boolean) {
propertyChangeSupport.firePropertyChange(propName, oldValue, newValue)
}
override fun addPropertyChangeListener(listener: PropertyChangeListener) {
propertyChangeSupport.addPropertyChangeListener(listener)
}
override fun removePropertyChangeListener(listener: PropertyChangeListener) {
propertyChangeSupport.removePropertyChangeListener(listener)
}
//
// Unused
//
override fun getState(level: FileEditorStateLevel): FileEditorState = FileEditorState.INSTANCE
override fun setState(state: FileEditorState) {}
override fun isModified(): Boolean = false
}
| apache-2.0 | 1985a382c3f2b4e3b74f94919b016b3a | 34.088889 | 120 | 0.809373 | 5.177049 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/SuspendFunctionOnCoroutineScopeInspection.kt | 1 | 11856 | // 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.inspections.coroutines
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.UnusedReceiverParameterInspection
import org.jetbrains.kotlin.idea.intentions.ConvertReceiverToParameterIntention
import org.jetbrains.kotlin.idea.intentions.MoveMemberToCompanionObjectIntention
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
class SuspendFunctionOnCoroutineScopeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return namedFunctionVisitor(fun(function: KtNamedFunction) {
if (!function.hasModifier(KtTokens.SUSPEND_KEYWORD)) return
if (!function.hasBody()) return
val context = function.analyzeWithContent()
val descriptor = context[BindingContext.FUNCTION, function] ?: return
val (extensionOfCoroutineScope, memberOfCoroutineScope) = with(descriptor) {
extensionReceiverParameter.ofCoroutineScopeType() to dispatchReceiverParameter.ofCoroutineScopeType()
}
if (!extensionOfCoroutineScope && !memberOfCoroutineScope) return
fun DeclarationDescriptor.isReceiverOfAnalyzedFunction(): Boolean {
if (extensionOfCoroutineScope && this == descriptor) return true
if (memberOfCoroutineScope && this == descriptor.containingDeclaration) return true
return false
}
fun checkSuspiciousReceiver(receiver: ReceiverValue, problemExpression: KtExpression) {
when (receiver) {
is ImplicitReceiver -> if (!receiver.declarationDescriptor.isReceiverOfAnalyzedFunction()) return
is ExpressionReceiver -> {
val receiverThisExpression = receiver.expression as? KtThisExpression ?: return
if (receiverThisExpression.getTargetLabel() != null) {
val instanceReference = receiverThisExpression.instanceReference
if (context[BindingContext.REFERENCE_TARGET, instanceReference]?.isReceiverOfAnalyzedFunction() != true) return
}
}
}
val fixes = mutableListOf<LocalQuickFix>()
val reportElement = (problemExpression as? KtCallExpression)?.calleeExpression ?: problemExpression
holder.registerProblem(
reportElement,
MESSAGE,
GENERIC_ERROR_OR_WARNING,
WrapWithCoroutineScopeFix(removeReceiver = false, wrapCallOnly = true)
)
fixes += WrapWithCoroutineScopeFix(removeReceiver = extensionOfCoroutineScope, wrapCallOnly = false)
if (extensionOfCoroutineScope) {
fixes += IntentionWrapper(ConvertReceiverToParameterIntention())
}
if (memberOfCoroutineScope) {
val containingDeclaration = function.containingClassOrObject
if (containingDeclaration is KtClass && !containingDeclaration.isInterface() && function.hasBody()) {
fixes += IntentionWrapper(MoveMemberToCompanionObjectIntention())
}
}
holder.registerProblem(
with(function) { receiverTypeReference ?: nameIdentifier ?: funKeyword ?: this },
MESSAGE,
GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
function.forEachDescendantOfType(fun(callExpression: KtCallExpression) {
val resolvedCall = callExpression.getResolvedCall(context) ?: return
val extensionReceiverParameter = resolvedCall.resultingDescriptor.extensionReceiverParameter ?: return
if (!extensionReceiverParameter.type.isCoroutineScope()) return
val extensionReceiver = resolvedCall.extensionReceiver ?: return
checkSuspiciousReceiver(extensionReceiver, callExpression)
})
function.forEachDescendantOfType(fun(nameReferenceExpression: KtNameReferenceExpression) {
if (nameReferenceExpression.getReferencedName() != COROUTINE_CONTEXT) return
val resolvedCall = nameReferenceExpression.getResolvedCall(context) ?: return
if (resolvedCall.resultingDescriptor.fqNameSafe.asString() == "$COROUTINE_SCOPE.$COROUTINE_CONTEXT") {
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return
checkSuspiciousReceiver(dispatchReceiver, nameReferenceExpression)
}
})
})
}
private class WrapWithCoroutineScopeFix(
private val removeReceiver: Boolean,
private val wrapCallOnly: Boolean
) : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("wrap.with.coroutine.scope.fix.family.name")
override fun getName(): String =
when {
removeReceiver && !wrapCallOnly -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text3")
wrapCallOnly -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text2")
else -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text")
}
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val problemElement = descriptor.psiElement ?: return
val function = problemElement.getNonStrictParentOfType<KtNamedFunction>() ?: return
val functionDescriptor = function.resolveToDescriptorIfAny()
if (!FileModificationService.getInstance().preparePsiElementForWrite(function)) return
val bodyExpression = function.bodyExpression
fun getExpressionToWrapCall(): KtExpression? {
var result = problemElement as? KtExpression ?: return null
while (result.parent is KtQualifiedExpression || result.parent is KtCallExpression) {
result = result.parent as KtExpression
}
return result
}
var expressionToWrap = when {
wrapCallOnly -> getExpressionToWrapCall()
else -> bodyExpression
} ?: return
if (functionDescriptor?.extensionReceiverParameter.ofCoroutineScopeType()) {
val context = function.analyzeWithContent()
expressionToWrap.forEachDescendantOfType<KtDotQualifiedExpression> {
val receiverExpression = it.receiverExpression as? KtThisExpression
val selectorExpression = it.selectorExpression
if (receiverExpression?.getTargetLabel() != null && selectorExpression != null) {
if (context[BindingContext.REFERENCE_TARGET, receiverExpression.instanceReference] == functionDescriptor) {
runWriteAction {
if (it === expressionToWrap) {
expressionToWrap = it.replaced(selectorExpression)
} else {
it.replace(selectorExpression)
}
}
}
}
}
}
val psiFactory = KtPsiFactory(project)
val blockExpression = function.bodyBlockExpression
project.executeWriteCommand(name, this) {
val result = when {
expressionToWrap != bodyExpression -> expressionToWrap.replaced(
psiFactory.createExpressionByPattern("$COROUTINE_SCOPE_WRAPPER { $0 }", expressionToWrap)
)
blockExpression == null -> bodyExpression.replaced(
psiFactory.createExpressionByPattern("$COROUTINE_SCOPE_WRAPPER { $0 }", bodyExpression)
)
else -> {
val bodyText = buildString {
for (statement in blockExpression.statements) {
append(statement.text)
append("\n")
}
}
blockExpression.replaced(
psiFactory.createBlock("$COROUTINE_SCOPE_WRAPPER { $bodyText }")
)
}
}
ShortenReferences.DEFAULT.process(result.reformatted() as KtElement)
}
val receiverTypeReference = function.receiverTypeReference
if (removeReceiver && !wrapCallOnly && receiverTypeReference != null) {
UnusedReceiverParameterInspection.RemoveReceiverFix.apply(receiverTypeReference, project)
}
}
}
companion object {
private const val COROUTINE_SCOPE = "kotlinx.coroutines.CoroutineScope"
private const val COROUTINE_SCOPE_WRAPPER = "kotlinx.coroutines.coroutineScope"
private const val COROUTINE_CONTEXT = "coroutineContext"
private val MESSAGE get() = KotlinBundle.message("ambiguous.coroutinecontext.due.to.coroutinescope.receiver.of.suspend.function")
private fun KotlinType.isCoroutineScope(): Boolean =
constructor.declarationDescriptor?.fqNameSafe?.asString() == COROUTINE_SCOPE
private fun ReceiverParameterDescriptor?.ofCoroutineScopeType(): Boolean {
if (this == null) return false
if (type.isCoroutineScope()) return true
return type.constructor.supertypes.reversed().any { it.isCoroutineScope() }
}
}
} | apache-2.0 | c757555f9d1b6b816fcef1a5089b2f40 | 53.141553 | 158 | 0.65081 | 6.236718 | false | false | false | false |
JetBrains/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ReplaceBySourceAsTree.kt | 1 | 40692 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.impl
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.ReplaceBySourceAsTree.OperationsApplier
import it.unimi.dsi.fastutil.Hash
import it.unimi.dsi.fastutil.longs.Long2ObjectMap
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap
import org.jetbrains.annotations.TestOnly
import java.util.*
import kotlin.collections.ArrayList
/**
* # Replace By Source ~~as tree~~
*
* Replace By Source, or RBS for short.
*
* "As tree" is not a correct fact. It was previously processed as tree, before we committed to multiple parents.
* So, this is still a directed graph.
*
* During the RBS, we collect a set of operations. After the set is collected, we apply them on a target storage.
* Theoretically, it's possible to create a dry run, if needed.
* Operations are supposed to be isolated and complete. That means that target storage doesn't become in inconsistent state at
* any moment of the RBS.
*
* This RBS implementation doesn't have expected exception and should always succeed.
* If this RBS doesn't have sense from the abstract point of view (for example, during the RBS we transfer some entity,
* but we can't find a parent for this entity in the target store), we still get into some consistent state. As for the example,
* this entity won't be transferred into the target storage.
*
*
* # Implementation details
*
* The operations are collected in separate data structures: For adding, replacing and removing.
* Relabel operation is also known as "Replace".
* Add operations should be applied in order, while for other operations the order is not determined.
*
* During the RBS we maintain a separate state for each of processed entity to avoid processing the same entity twice.
* Two separate states are presented: for target and ReplaceWith storages.
*
* # Debugging
*
* You can use [OperationsApplier.dumpOperations] for listing the operations on the storage.
*
* # Future improvements
*
* - Make type graphs. Separate graphs into independent parts (how is it called correctly?)
* - Work on separate graph parts as on independent items
*/
internal class ReplaceBySourceAsTree : ReplaceBySourceOperation {
private lateinit var targetStorage: MutableEntityStorageImpl
private lateinit var replaceWithStorage: AbstractEntityStorage
private lateinit var entityFilter: (EntitySource) -> Boolean
internal val replaceOperations = ArrayList<RelabelElement>()
internal val removeOperations = ArrayList<RemoveElement>()
internal val addOperations = ArrayList<AddElement>()
internal val targetState = Long2ObjectOpenHashMap<ReplaceState>()
internal val replaceWithState = Long2ObjectOpenHashMap<ReplaceWithState>()
@set:TestOnly
internal var shuffleEntities: Long = -1L
private val replaceWithProcessingCache = HashMap<Pair<EntityId?, Int>, Pair<DataCache, MutableList<ChildEntityId>>>()
override fun replace(
targetStorage: MutableEntityStorageImpl,
replaceWithStorage: AbstractEntityStorage,
entityFilter: (EntitySource) -> Boolean,
) {
this.targetStorage = targetStorage
this.replaceWithStorage = replaceWithStorage
this.entityFilter = entityFilter
// Process entities from the target storage
val targetEntitiesToReplace = targetStorage.entitiesBySource(entityFilter)
val targetEntities = targetEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList()
if (shuffleEntities != -1L && targetEntities.size > 1) {
targetEntities.shuffle(Random(shuffleEntities))
}
for (targetEntityToReplace in targetEntities) {
TargetProcessor().processEntity(targetEntityToReplace)
}
// Process entities from the replaceWith storage
val replaceWithEntitiesToReplace = replaceWithStorage.entitiesBySource(entityFilter)
val replaceWithEntities = replaceWithEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList()
if (shuffleEntities != -1L && replaceWithEntities.size > 1) {
replaceWithEntities.shuffle(Random(shuffleEntities))
}
for (replaceWithEntityToReplace in replaceWithEntities) {
ReplaceWithProcessor().processEntity(replaceWithEntityToReplace)
}
// This method can be used for debugging
// OperationsApplier().dumpOperations()
// Apply collected operations on the target storage
OperationsApplier().apply()
}
// This class is just a wrapper to combine functions logically
private inner class OperationsApplier {
fun apply() {
val replaceToTarget = HashMap<EntityId, EntityId>()
for (addOperation in addOperations) {
val parents = addOperation.parents?.mapTo(HashSet()) {
when (it) {
is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId)
is ParentsRef.TargetRef -> it.targetEntityId
}
}
addElement(parents, addOperation.replaceWithSource, replaceToTarget)
}
for (operation in replaceOperations) {
val targetEntity = targetStorage.entityDataByIdOrDie(operation.targetEntityId).createEntity(targetStorage)
val replaceWithEntity = replaceWithStorage.entityDataByIdOrDie(operation.replaceWithEntityId).createEntity(replaceWithStorage)
val parents = operation.parents?.mapTo(HashSet()) {
val targetEntityId = when (it) {
is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId)
is ParentsRef.TargetRef -> it.targetEntityId
}
targetStorage.entityDataByIdOrDie(targetEntityId).createEntity(targetStorage)
}
targetStorage.modifyEntity(WorkspaceEntity.Builder::class.java, targetEntity) {
(this as ModifiableWorkspaceEntityBase<*, *>).relabel(replaceWithEntity, parents)
}
targetStorage.indexes.updateExternalMappingForEntityId(operation.replaceWithEntityId, operation.targetEntityId, replaceWithStorage.indexes)
}
for (removeOperation in removeOperations) {
targetStorage.removeEntityByEntityId(removeOperation.targetEntityId)
}
}
private fun addElement(parents: Set<EntityId>?, replaceWithDataSource: EntityId, replaceToTarget: HashMap<EntityId, EntityId>) {
val targetParents = mutableListOf<WorkspaceEntity>()
parents?.forEach { parent ->
targetParents += targetStorage.entityDataByIdOrDie(parent).createEntity(targetStorage)
}
val modifiableEntity = replaceWithStorage.entityDataByIdOrDie(replaceWithDataSource).createDetachedEntity(targetParents)
modifiableEntity as ModifiableWorkspaceEntityBase<out WorkspaceEntity, out WorkspaceEntityData<*>>
// We actually bind parents in [createDetachedEntity], but we can't do it for external entities (that are defined in a separate module)
// Here we bind them again, so I guess we can remove "parents binding" from [createDetachedEntity], but let's do it twice for now.
// Actually, I hope to get rid of [createDetachedEntity] at some moment.
targetParents.groupBy { it::class }.forEach { (_, ents) ->
modifiableEntity.linkExternalEntity(ents.first().getEntityInterface().kotlin, false, ents)
}
targetStorage.addEntity(modifiableEntity)
targetStorage.indexes.updateExternalMappingForEntityId(replaceWithDataSource, modifiableEntity.id, replaceWithStorage.indexes)
replaceToTarget[replaceWithDataSource] = modifiableEntity.id
}
/**
* First print the operations, then print the information about entities
*/
fun dumpOperations(): String {
val targetEntities: MutableSet<EntityId> = mutableSetOf()
val replaceWithEntities: MutableSet<EntityId> = mutableSetOf()
return buildString {
appendLine("---- New entities -------")
for (addOperation in addOperations) {
appendLine(infoOf(addOperation.replaceWithSource, replaceWithStorage, true))
replaceWithEntities += addOperation.replaceWithSource
if (addOperation.parents == null) {
appendLine("No parent entities")
}
else {
appendLine("Parents:")
addOperation.parents.forEach { parent ->
when (parent) {
is ParentsRef.AddedElement -> {
appendLine(" - ${infoOf(parent.replaceWithEntityId, replaceWithStorage, true)} <--- New Added Entity")
replaceWithEntities += parent.replaceWithEntityId
}
is ParentsRef.TargetRef -> {
appendLine(" - ${infoOf(parent.targetEntityId, targetStorage, true)} <--- Existing Entity")
targetEntities += parent.targetEntityId
}
}
}
}
appendLine()
}
appendLine("---- No More New Entities -------")
appendLine("---- Removes -------")
removeOperations.map { it.targetEntityId }.forEach { entityId ->
appendLine(infoOf(entityId, targetStorage, true))
targetEntities += entityId
}
appendLine("---- No More Removes -------")
appendLine()
appendLine("---- Replaces -------")
replaceOperations.forEach { operation ->
appendLine(
infoOf(operation.targetEntityId, targetStorage, true) + " -> " + infoOf(operation.replaceWithEntityId, replaceWithStorage,
true) + " | " + "Count of parents: ${operation.parents?.size}")
targetEntities += operation.targetEntityId
replaceWithEntities += operation.replaceWithEntityId
}
appendLine("---- No More Replaces -------")
appendLine()
appendLine("---- Entities -------")
appendLine()
appendLine("---- Target Storage -------")
targetEntities.forEach {
appendLine(infoOf(it, targetStorage, false))
appendLine()
}
appendLine()
appendLine("---- Replace With Storage -------")
replaceWithEntities.forEach {
appendLine(infoOf(it, replaceWithStorage, false))
appendLine()
}
}
}
private fun infoOf(entityId: EntityId, store: AbstractEntityStorage, short: Boolean): String {
val entityData = store.entityDataByIdOrDie(entityId)
val entity = entityData.createEntity(store)
return if (entity is WorkspaceEntityWithSymbolicId) entity.symbolicId.toString() else if (short) "$entity" else "$entity | $entityData"
}
}
// This class is just a wrapper to combine functions logically
private inner class ReplaceWithProcessor {
fun processEntity(replaceWithEntity: WorkspaceEntity) {
replaceWithEntity as WorkspaceEntityBase
if (replaceWithState[replaceWithEntity.id] != null) return
processEntity(TrackToParents(replaceWithEntity.id, replaceWithStorage))
}
private fun processEntity(replaceWithTrack: TrackToParents): ParentsRef? {
val replaceWithEntityId = replaceWithTrack.entity
val replaceWithEntityState = replaceWithState[replaceWithEntityId]
when (replaceWithEntityState) {
ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithEntityId)
is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId)
ReplaceWithState.NoChangeTraceLost -> return null
is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId)
null -> Unit
}
val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithEntityId)
val replaceWithEntity = replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase
if (replaceWithTrack.parents.isEmpty()) {
return findAndReplaceRootEntity(replaceWithEntity)
}
else {
if (replaceWithEntity is WorkspaceEntityWithSymbolicId) {
val targetEntity = targetStorage.resolve(replaceWithEntity.symbolicId)
val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) }
return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation)
}
else {
val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) }
if (parentsAssociation.isNotEmpty()) {
val targetEntityData = parentsAssociation.filterIsInstance<ParentsRef.TargetRef>().firstNotNullOfOrNull { parent ->
findEntityInTargetStore(replaceWithEntityData, parent.targetEntityId, replaceWithEntityId.clazz)
}
val targetEntity = targetEntityData?.createEntity(targetStorage) as? WorkspaceEntityBase
return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation)
}
else {
replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost)
return null
}
}
}
}
private fun findAndReplaceRootEntity(replaceWithEntity: WorkspaceEntityBase): ParentsRef? {
val replaceWithEntityId = replaceWithEntity.id
val currentState = replaceWithState[replaceWithEntityId]
// This was just checked before this call
assert(currentState == null)
val targetEntity = findRootEntityInStorage(replaceWithEntity, targetStorage, replaceWithStorage, targetState)
val parents = null
return processExactEntity(targetEntity, replaceWithEntity, parents)
}
private fun processExactEntity(targetEntity: WorkspaceEntity?,
replaceWithEntity: WorkspaceEntityBase,
parents: Set<ParentsRef>?): ParentsRef? {
val replaceWithEntityId = replaceWithEntity.id
if (targetEntity == null) {
if (entityFilter(replaceWithEntity.entitySource)) {
addSubtree(parents, replaceWithEntityId)
return ParentsRef.AddedElement(replaceWithEntityId)
}
else {
replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost)
return null
}
}
else {
val targetEntityId = (targetEntity as WorkspaceEntityBase).id
val targetCurrentState = targetState[targetEntityId]
when (targetCurrentState) {
is ReplaceState.NoChange -> return ParentsRef.TargetRef(targetEntityId)
is ReplaceState.Relabel -> return ParentsRef.TargetRef(targetEntityId)
ReplaceState.Remove -> return null
null -> Unit
}
when {
entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> {
if (replaceWithEntity.entitySource !is DummyParentEntitySource) {
replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, parents)
} else {
doNothingOn(targetEntityId, replaceWithEntityId)
}
return ParentsRef.TargetRef(targetEntityId)
}
entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> {
removeWorkspaceData(targetEntity.id, replaceWithEntity.id)
return null
}
!entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> {
if (targetEntity is WorkspaceEntityWithSymbolicId) {
if (replaceWithEntity.entitySource !is DummyParentEntitySource) {
replaceWorkspaceData(targetEntityId, replaceWithEntityId, parents)
} else {
doNothingOn(targetEntityId, replaceWithEntityId)
}
return ParentsRef.TargetRef(targetEntityId)
}
else {
addSubtree(parents, replaceWithEntityId)
return ParentsRef.AddedElement(replaceWithEntityId)
}
}
!entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> {
doNothingOn(targetEntity.id, replaceWithEntityId)
return ParentsRef.TargetRef(targetEntityId)
}
else -> error("Unexpected branch")
}
}
}
private fun findAndReplaceRootEntityInTargetStore(replaceWithRootEntity: WorkspaceEntityBase): ParentsRef? {
val replaceRootEntityId = replaceWithRootEntity.id
val replaceWithCurrentState = replaceWithState[replaceRootEntityId]
when (replaceWithCurrentState) {
is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId)
ReplaceWithState.NoChangeTraceLost -> return null
is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId)
ReplaceWithState.ElementMoved -> TODO()
null -> Unit
}
val targetEntity = findRootEntityInStorage(replaceWithRootEntity, targetStorage, replaceWithStorage, targetState)
return processExactEntity(targetEntity, replaceWithRootEntity, null)
}
/**
* This is a very similar thing as [findSameEntity]. But it finds an entity in the target storage (or the entity that will be added)
*/
fun findSameEntityInTargetStore(replaceWithTrack: TrackToParents): ParentsRef? {
// Check if this entity was already processed
val replaceWithCurrentState = replaceWithState[replaceWithTrack.entity]
when (replaceWithCurrentState) {
is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId)
ReplaceWithState.NoChangeTraceLost -> return null
is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId)
ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithTrack.entity)
null -> Unit
}
val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithTrack.entity)
if (replaceWithTrack.parents.isEmpty()) {
val targetRootEntityId = findAndReplaceRootEntityInTargetStore(
replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase)
return targetRootEntityId
}
else {
val parentsAssociation = replaceWithTrack.parents.associateWith { findSameEntityInTargetStore(it) }
val entriesList = parentsAssociation.entries.toList()
val targetParents = mutableSetOf<EntityId>()
var targetEntityData: WorkspaceEntityData<out WorkspaceEntity>? = null
for (i in entriesList.indices) {
val value = entriesList[i].value
if (value is ParentsRef.TargetRef) {
targetEntityData = findEntityInTargetStore(replaceWithEntityData, value.targetEntityId, replaceWithTrack.entity.clazz)
if (targetEntityData != null) {
targetParents += entriesList[i].key.entity
break
}
}
}
if (targetEntityData == null) {
for (entry in entriesList) {
val value = entry.value
if (value is ParentsRef.AddedElement) {
return ParentsRef.AddedElement(replaceWithTrack.entity)
}
}
}
return targetEntityData?.createEntityId()?.let { ParentsRef.TargetRef(it) }
}
}
private fun addSubtree(parents: Set<ParentsRef>?, replaceWithEntityId: EntityId) {
val currentState = replaceWithState[replaceWithEntityId]
when (currentState) {
ReplaceWithState.ElementMoved -> return
is ReplaceWithState.NoChange -> error("Unexpected state")
ReplaceWithState.NoChangeTraceLost -> error("Unexpected state")
is ReplaceWithState.Relabel -> error("Unexpected state")
null -> Unit
}
addElementOperation(parents, replaceWithEntityId)
replaceWithStorage.refs.getChildrenRefsOfParentBy(replaceWithEntityId.asParent()).values.flatten().forEach {
val replaceWithChildEntityData = replaceWithStorage.entityDataByIdOrDie(it.id)
if (!entityFilter(replaceWithChildEntityData.entitySource)) return@forEach
val trackToParents = TrackToParents(it.id, replaceWithStorage)
val sameEntity = findSameEntityInTargetStore(trackToParents)
if (sameEntity is ParentsRef.TargetRef) {
return@forEach
}
val otherParents = trackToParents.parents.mapNotNull { findSameEntityInTargetStore(it) }
addSubtree((otherParents + ParentsRef.AddedElement(replaceWithEntityId)).toSet(), it.id)
}
}
}
// This class is just a wrapper to combine functions logically
private inner class TargetProcessor {
fun processEntity(targetEntityToReplace: WorkspaceEntity) {
targetEntityToReplace as WorkspaceEntityBase
// This method not only finds the same entity in the ReplaceWith storage, but also processes all entities it meets.
// So, for processing an entity, it's enough to call this methos on the entity.
findSameEntity(TrackToParents(targetEntityToReplace.id, targetStorage))
}
/**
* This method searched for the "associated" entity of [targetEntityTrack] in the repalceWith storage
* Here, let's use "associated" termin to define what we're looking for. If the entity have a [SymbolicEntityId],
* this is super simple. "associated" entity is just an entity from the different storage with the same SymbolicId.
*
* Things go complicated if there is no SymbolicId. In this case we build a track to the root entities in the graph, trying
* to find same roots in the replaceWith storage and building a "track" to the entity in the replaceWith storage. This
* traced entity is an "associated" entity for our current entity.
*
* This is a recursive algorithm
* - Get all parents of the entity
* - if there are NO parents:
* - Try to find associated entity in replaceWith storage (by SymbolicId in most cases)
* - if there are parents:
* - Run this algorithm on all parents to find associated parents in the replaceWith storage
* - Based on found parents in replaceWith storage, find an associated entity for our currenly searched entity
*/
private fun findSameEntity(targetEntityTrack: TrackToParents): EntityId? {
// Check if this entity was already processed
val targetEntityState = targetState[targetEntityTrack.entity]
if (targetEntityState != null) {
when (targetEntityState) {
is ReplaceState.NoChange -> return targetEntityState.replaceWithEntityId
is ReplaceState.Relabel -> return targetEntityState.replaceWithEntityId
ReplaceState.Remove -> return null
}
}
val targetEntityData = targetStorage.entityDataByIdOrDie(targetEntityTrack.entity)
if (targetEntityTrack.parents.isEmpty()) {
// If the entity doesn't have parents, it's a root entity for this subtree (subgraph?)
return findAndReplaceRootEntity(targetEntityData)
}
else {
val (targetParents, replaceWithEntity) = processParentsFromReplaceWithStorage(targetEntityTrack, targetEntityData)
return processExactEntity(targetParents, targetEntityData, replaceWithEntity)
}
}
private fun processExactEntity(targetParents: MutableSet<ParentsRef>?,
targetEntityData: WorkspaceEntityData<out WorkspaceEntity>,
replaceWithEntity: WorkspaceEntityBase?): EntityId? {
// Here we check if any of the required parents is missing the our new parents
val requiredParentMissing = if (targetParents != null) {
val targetParentClazzes = targetParents.map {
when (it) {
is ParentsRef.AddedElement -> it.replaceWithEntityId.clazz
is ParentsRef.TargetRef -> it.targetEntityId.clazz
}
}
targetEntityData.getRequiredParents().any { it.toClassId() !in targetParentClazzes }
}
else false
val targetEntity = targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase
if (replaceWithEntity == null || requiredParentMissing) {
// Here we don't have an associated entity in the replaceWith storage. Decide if we remove our entity or just keep it
when (entityFilter(targetEntity.entitySource)) {
true -> {
removeWorkspaceData(targetEntity.id, null)
return null
}
false -> {
doNothingOn(targetEntity.id, null)
return null
}
}
}
else {
when {
entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> {
if (replaceWithEntity.entitySource !is DummyParentEntitySource) {
replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents)
} else {
doNothingOn(targetEntity.id, replaceWithEntity.id)
}
return replaceWithEntity.id
}
entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> {
removeWorkspaceData(targetEntity.id, replaceWithEntity.id)
return null
}
!entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> {
if (replaceWithEntity.entitySource !is DummyParentEntitySource) {
replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents)
} else {
doNothingOn(targetEntity.id, replaceWithEntity.id)
}
return replaceWithEntity.id
}
!entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> {
doNothingOn(targetEntity.id, replaceWithEntity.id)
return replaceWithEntity.id
}
else -> error("Unexpected branch")
}
}
}
/**
* An interesting logic here. We've found associated parents for the target entity.
* Now, among these parents we have to find a child, that will be similar to "our" entity in target storage.
*
* In addition, we're currently missing "new" parents in the replaceWith storage.
* So, the return type is a set of parents (existing and new) and an "associated" entity in the replaceWith storage.
*/
private fun processParentsFromReplaceWithStorage(
targetEntityTrack: TrackToParents,
targetEntityData: WorkspaceEntityData<out WorkspaceEntity>
): Pair<MutableSet<ParentsRef>, WorkspaceEntityBase?> {
// Our future set of parents
val targetParents = mutableSetOf<ParentsRef>()
val targetEntity = targetEntityData.createEntity(targetStorage)
var replaceWithEntity: WorkspaceEntityBase? = null
if (targetEntity is WorkspaceEntityWithSymbolicId) {
replaceWithEntity = replaceWithStorage.resolve(targetEntity.symbolicId) as? WorkspaceEntityBase
}
else {
// Here we're just traversing parents. If we find a parent that does have a child entity that is equal to our entity, stop and save
// this "equaled" entity as our "associated" entity.
// After that we're checking that other parents does have this child among their children. If not, we do not register this parent as
// "new" parent for our entity.
//
// Another approach would be finding the "most common" child among of all parents. But currently we use this approach
// because I think that it's "good enough" and the "most common child" may be not what we're looking for.
// So, here we search for the first equal entity
val parentsAssociation = targetEntityTrack.parents.associateWith { findSameEntity(it) }
val entriesList = parentsAssociation.entries.toList()
var index = 0
for (i in entriesList.indices) {
index = i
val (caching, replaceWithEntityIds) =
replaceWithProcessingCache.getOrPut(entriesList[i].value to targetEntityTrack.entity.clazz) {
val ids = LinkedList(childrenInReplaceWith(entriesList[i].value, targetEntityTrack.entity.clazz))
DataCache(ids.size, EntityDataStrategy()) to ids
}
replaceWithEntity = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage)
?.createEntity(replaceWithStorage) as? WorkspaceEntityBase
if (replaceWithEntity != null) {
assert(replaceWithState[replaceWithEntity.id] == null)
targetParents += ParentsRef.TargetRef(entriesList[i].key.entity)
break
}
}
// Here we know our "associated" entity, so we just check what parents remain with it.
entriesList.drop(index + 1).forEach { tailItem ->
// Should we use cache as in above?
val replaceWithEntityIds = childrenInReplaceWith(tailItem.value, targetEntityTrack.entity.clazz).toMutableList()
val caching = DataCache(replaceWithEntityIds.size, EntityDataStrategy())
var replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage)
while (replaceWithMyEntityData != null && replaceWithEntity!!.id != replaceWithMyEntityData.createEntityId()) {
replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage)
}
if (replaceWithMyEntityData != null) {
targetParents += ParentsRef.TargetRef(tailItem.key.entity)
}
}
}
// And here we get other parent' of the associated entity.
// This is actually a complicated operation because it's not enough just to find parents in replaceWith storage.
// We should also understand if this parent is a new entity or it already exists in the target storage.
if (replaceWithEntity != null) {
val alsoTargetParents = TrackToParents(replaceWithEntity.id, replaceWithStorage).parents
.map { ReplaceWithProcessor().findSameEntityInTargetStore(it) }
targetParents.addAll(alsoTargetParents.filterNotNull())
}
return Pair(targetParents, replaceWithEntity)
}
/**
* Process root entity of the storage
*/
fun findAndReplaceRootEntity(targetEntityData: WorkspaceEntityData<out WorkspaceEntity>): EntityId? {
val targetRootEntityId = targetEntityData.createEntityId()
val currentTargetState = targetState[targetRootEntityId]
assert(currentTargetState == null) { "This state was already checked before this function" }
val replaceWithEntity = findRootEntityInStorage(targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase, replaceWithStorage,
targetStorage, replaceWithState) as? WorkspaceEntityBase
return processExactEntity(null, targetEntityData, replaceWithEntity)
}
}
private class EntityDataStrategy : Hash.Strategy<WorkspaceEntityData<out WorkspaceEntity>> {
override fun equals(a: WorkspaceEntityData<out WorkspaceEntity>?, b: WorkspaceEntityData<out WorkspaceEntity>?): Boolean {
if (a == null || b == null) {
return false
}
return a.equalsByKey(b)
}
override fun hashCode(o: WorkspaceEntityData<out WorkspaceEntity>?): Int {
return o?.hashCodeByKey() ?: 0
}
}
private fun MutableList<ChildEntityId>.removeSomeWithCaching(key: WorkspaceEntityData<out WorkspaceEntity>,
cache: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>,
storage: AbstractEntityStorage): WorkspaceEntityData<out WorkspaceEntity>? {
val foundInCache = cache.removeSome(key)
if (foundInCache != null) return foundInCache
val thisIterator = this.iterator()
while (thisIterator.hasNext()) {
val id = thisIterator.next()
val value = storage.entityDataByIdOrDie(id.id)
if (value.equalsByKey(key)) {
thisIterator.remove()
return value
}
thisIterator.remove()
addValueToMap(cache, value)
}
return null
}
private fun <K, V> Object2ObjectOpenCustomHashMap<K, List<V>>.removeSome(key: K): V? {
val existingValue = this[key] ?: return null
return if (existingValue.size == 1) {
this.remove(key)
existingValue.single()
}
else {
val firstElement = existingValue[0]
this[key] = existingValue.drop(1)
firstElement
}
}
private fun addElementOperation(targetParentEntity: Set<ParentsRef>?, replaceWithEntity: EntityId) {
addOperations += AddElement(targetParentEntity, replaceWithEntity)
replaceWithEntity.addState(ReplaceWithState.ElementMoved)
}
private fun replaceWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId, parents: Set<ParentsRef>?) {
replaceOperations.add(RelabelElement(targetEntityId, replaceWithEntityId, parents))
targetEntityId.addState(ReplaceState.Relabel(replaceWithEntityId, parents))
replaceWithEntityId.addState(ReplaceWithState.Relabel(targetEntityId))
}
private fun removeWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId?) {
removeOperations.add(RemoveElement(targetEntityId))
targetEntityId.addState(ReplaceState.Remove)
replaceWithEntityId?.addState(ReplaceWithState.NoChangeTraceLost)
}
private fun doNothingOn(targetEntityId: EntityId, replaceWithEntityId: EntityId?) {
targetEntityId.addState(ReplaceState.NoChange(replaceWithEntityId))
replaceWithEntityId?.addState(ReplaceWithState.NoChange(targetEntityId))
}
private fun EntityId.addState(state: ReplaceState) {
val currentState = targetState[this]
require(currentState == null) {
"Unexpected existing state for $this: $currentState"
}
targetState[this] = state
}
private fun EntityId.addState(state: ReplaceWithState) {
val currentState = replaceWithState[this]
require(currentState == null)
replaceWithState[this] = state
}
private fun findEntityInTargetStore(replaceWithEntityData: WorkspaceEntityData<out WorkspaceEntity>,
targetParentEntityId: EntityId,
childClazz: Int): WorkspaceEntityData<out WorkspaceEntity>? {
var targetEntityData1: WorkspaceEntityData<out WorkspaceEntity>?
val targetEntityIds = childrenInTarget(targetParentEntityId, childClazz)
val targetChildrenMap = makeEntityDataCollection(targetEntityIds, targetStorage)
targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData)
while (targetEntityData1 != null && targetState[targetEntityData1.createEntityId()] != null) {
targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData)
}
return targetEntityData1
}
private fun makeEntityDataCollection(targetChildEntityIds: List<ChildEntityId>,
storage: AbstractEntityStorage): Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>> {
val targetChildrenMap = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>(
targetChildEntityIds.size,
EntityDataStrategy())
targetChildEntityIds.forEach { id ->
val value = storage.entityDataByIdOrDie(id.id)
addValueToMap(targetChildrenMap, value)
}
return targetChildrenMap
}
private fun addValueToMap(targetChildrenMap: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>,
value: WorkspaceEntityData<out WorkspaceEntity>) {
val existingValue = targetChildrenMap[value]
targetChildrenMap[value] = if (existingValue != null) existingValue + value else listOf(value)
}
private val targetChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>()
private val replaceWithChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>()
private fun childrenInReplaceWith(entityId: EntityId?, childClazz: Int): List<ChildEntityId> {
return childrenInStorage(entityId, childClazz, replaceWithStorage, replaceWithChildrenCache)
}
private fun childrenInTarget(entityId: EntityId?, childClazz: Int): List<ChildEntityId> {
return childrenInStorage(entityId, childClazz, targetStorage, targetChildrenCache)
}
companion object {
private fun childrenInStorage(entityId: EntityId?,
childrenClass: Int,
storage: AbstractEntityStorage,
childrenCache: HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>): List<ChildEntityId> {
val targetEntityIds = if (entityId != null) {
val targetChildren = childrenCache.getOrPut(entityId) { storage.refs.getChildrenRefsOfParentBy(entityId.asParent()) }
val targetFoundChildren = targetChildren.filterKeys {
sameClass(it.childClass, childrenClass, it.connectionType)
}
require(targetFoundChildren.size < 2) { "Got unexpected amount of children" }
if (targetFoundChildren.isEmpty()) {
emptyList()
}
else {
val (_, targetChildEntityIds) = targetFoundChildren.entries.single()
targetChildEntityIds
}
}
else {
emptyList()
}
return targetEntityIds
}
/**
* Search entity from [oppositeStorage] in [goalStorage]
*/
private fun findRootEntityInStorage(rootEntity: WorkspaceEntityBase,
goalStorage: AbstractEntityStorage,
oppositeStorage: AbstractEntityStorage,
goalState: Long2ObjectMap<out Any>): WorkspaceEntity? {
return if (rootEntity is WorkspaceEntityWithSymbolicId) {
val symbolicId = rootEntity.symbolicId
goalStorage.resolve(symbolicId)
}
else {
val oppositeEntityData = oppositeStorage.entityDataByIdOrDie(rootEntity.id)
goalStorage.entities(rootEntity.id.clazz.findWorkspaceEntity())
.filter {
val itId = (it as WorkspaceEntityBase).id
if (goalState[itId] != null) return@filter false
goalStorage.entityDataByIdOrDie(itId).equalsByKey(oppositeEntityData) && goalStorage.refs.getParentRefsOfChild(itId.asChild())
.isEmpty()
}
.firstOrNull()
}
}
}
}
typealias DataCache = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>
internal data class RelabelElement(val targetEntityId: EntityId, val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>?)
internal data class RemoveElement(val targetEntityId: EntityId)
internal data class AddElement(val parents: Set<ParentsRef>?, val replaceWithSource: EntityId)
internal sealed interface ReplaceState {
data class Relabel(val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>? = null) : ReplaceState
data class NoChange(val replaceWithEntityId: EntityId?) : ReplaceState
object Remove : ReplaceState
}
internal sealed interface ReplaceWithState {
object ElementMoved : ReplaceWithState
data class NoChange(val targetEntityId: EntityId) : ReplaceWithState
data class Relabel(val targetEntityId: EntityId) : ReplaceWithState
object NoChangeTraceLost : ReplaceWithState
}
sealed interface ParentsRef {
data class TargetRef(val targetEntityId: EntityId) : ParentsRef
data class AddedElement(val replaceWithEntityId: EntityId) : ParentsRef
}
private class TrackToParents(
val entity: EntityId,
private val storage: AbstractEntityStorage
) {
private var cachedParents: List<TrackToParents>? = null
val parents: List<TrackToParents>
get() {
if (cachedParents == null) {
cachedParents = storage.refs.getParentRefsOfChild(entity.asChild()).values.map { parentEntityId ->
TrackToParents(parentEntityId.id, storage)
}
}
return cachedParents!!
}
}
| apache-2.0 | cd065f83a3cfe7ffde1530e4a14633fe | 45.558352 | 194 | 0.697262 | 5.788336 | false | false | false | false |
jogy/jmoney | src/main/kotlin/name/gyger/jmoney/category/CategoryFactory.kt | 1 | 3727 | package name.gyger.jmoney.category
import org.springframework.stereotype.Component
@Component
class CategoryFactory(private val categoryRepository: CategoryRepository) {
fun createNormalCategories(root: Category) {
createNormalCategory("Taxes", root)
createNormalCategory("Memberships", root)
createNormalCategory("Donations", root)
createNormalCategory("Fees", root)
createNormalCategory("Gifts", root)
val income = createNormalCategory("Income", root)
createNormalCategory("Wages", income)
createNormalCategory("Sidelines", income)
val children = createNormalCategory("Children", root)
createNormalCategory("Doctor", children)
createNormalCategory("Clothing", children)
createNormalCategory("Child care", children)
createNormalCategory("Toys", children)
val housing = createNormalCategory("Living", root)
createNormalCategory("Additional costs", housing)
createNormalCategory("Rent/Mortgage", housing)
createNormalCategory("TV", housing)
val communication = createNormalCategory("Communication", root)
createNormalCategory("Phone", communication)
createNormalCategory("Mobile", communication)
createNormalCategory("Internet", communication)
val insurance = createNormalCategory("Insurance", root)
createNormalCategory("Health insurance", insurance)
createNormalCategory("Household insurance", insurance)
val household = createNormalCategory("Household", root)
createNormalCategory("Food", household)
createNormalCategory("Restaurant", household)
createNormalCategory("Clothing", household)
val transport = createNormalCategory("Traffic", root)
createNormalCategory("Car", transport)
createNormalCategory("Public transport", transport)
val entertainment = createNormalCategory("Entertainment", root)
createNormalCategory("Books", entertainment)
createNormalCategory("Newspapers", entertainment)
createNormalCategory("Magazines", entertainment)
createNormalCategory("Music", entertainment)
createNormalCategory("Movies", entertainment)
createNormalCategory("Games", entertainment)
val leisure = createNormalCategory("Leisure", root)
createNormalCategory("Outgoing", leisure)
createNormalCategory("Cinema", leisure)
createNormalCategory("Sports", leisure)
createNormalCategory("Concerts", leisure)
createNormalCategory("Trips", leisure)
createNormalCategory("Vacation", leisure)
val healthCare = createNormalCategory("Health", root)
createNormalCategory("Doctor", healthCare)
createNormalCategory("Drugstore", healthCare)
createNormalCategory("Dentist", healthCare)
createNormalCategory("Hygiene", healthCare)
}
fun createRootCategory(): Category {
return createCategory(Category.Type.ROOT, "[ROOT]", null)
}
fun createTransferCategory(root: Category): Category {
return createCategory(Category.Type.TRANSFER, "[TRANSFER]", root)
}
fun createSplitCategory(root: Category): Category {
return createCategory(Category.Type.SPLIT, "[SPLIT]", root)
}
private fun createNormalCategory(name: String, parent: Category): Category {
return createCategory(Category.Type.NORMAL, name, parent)
}
private fun createCategory(type: Category.Type, name: String, parent: Category?): Category {
val c = Category()
c.type = type
c.name = name
c.parent = parent
categoryRepository.save(c)
return c
}
}
| mit | fd126d6cd4ed956387b7c0a628cb44e2 | 37.822917 | 96 | 0.696539 | 4.759898 | false | false | false | false |
heitorcolangelo/kappuccino | sample/src/main/java/br/com/concretesolutions/kappuccino/sample/SwipeToDeleteCallback.kt | 1 | 3105 | package br.com.concretesolutions.kappuccino.sample
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
abstract class SwipeToDeleteCallback(context: Context)
: ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START or ItemTouchHelper.END) {
private val deleteIcon = ContextCompat.getDrawable(context, R.drawable.ic_delete)
private val background = ColorDrawable()
private val backgroundColour = ContextCompat.getColor(context, R.color.red)
private val intrinsicWidth = deleteIcon!!.intrinsicWidth
private val intrinsicHeight = deleteIcon!!.intrinsicHeight
private val clearPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) }
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onChildDraw(canvas: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean) {
val itemView = viewHolder.itemView
val itemHeight = itemView.bottom - itemView.top
val isCanceled = dX == 0f && !isCurrentlyActive
if (isCanceled) {
with(itemView) {
clearCanvas(canvas, right + dX, top.toFloat(), right.toFloat(), bottom.toFloat())
}
super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
return
}
// Draw the red delete background
background.color = backgroundColour
background.setBounds(itemView.right + dX.toInt(),
itemView.top,
itemView.right,
itemView.bottom)
background.draw(canvas)
// Calculate position of delete icon
val deleteIconTop = itemView.top + (itemHeight - intrinsicHeight) / 2
val deleteIconMargin = (itemHeight - intrinsicHeight) / 2
val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth
val deleteIconRight = itemView.right - deleteIconMargin
val deleteIconBottom = deleteIconTop + intrinsicHeight
// Draw the delete icon
deleteIcon!!.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
deleteIcon.draw(canvas)
super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
private fun clearCanvas(canvas: Canvas?, left: Float, top: Float, right: Float, bottom: Float) {
canvas?.drawRect(left, top, right, bottom, clearPaint)
}
} | apache-2.0 | 2382b10177a4c0bc16fbb7d62bf1d396 | 42.138889 | 103 | 0.672464 | 5.149254 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_reviews/repository/CourseReviewsRepository.kt | 1 | 1088 | package org.stepik.android.domain.course_reviews.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_reviews.model.CourseReview
interface CourseReviewsRepository {
/**
* Returns [page] of items if exists from [sourceType]
*/
fun getCourseReviewsByCourseId(courseId: Long, page: Int = 1, sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<CourseReview>>
fun getCourseReviewByCourseIdAndUserId(courseId: Long, userId: Long, primarySourceType: DataSourceType = DataSourceType.CACHE): Maybe<CourseReview>
fun getCourseReviewsByUserId(userId: Long, page: Int = 1, sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<CourseReview>>
fun createCourseReview(courseReview: CourseReview): Single<CourseReview>
fun saveCourseReview(courseReview: CourseReview): Single<CourseReview>
fun removeCourseReview(courseReviewId: Long): Completable
} | apache-2.0 | 2fc128bb06ada3ce62b58357e39f3497 | 42.56 | 151 | 0.799632 | 4.689655 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/entities/EntitiesWithSoftLinks.kt | 3 | 8221 | // 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.
@file:Suppress("unused")
package com.intellij.workspaceModel.storage.entities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.storage.impl.references.ManyToOne
import com.intellij.workspaceModel.storage.impl.references.MutableManyToOne
// ------------------------------ Persistent Id ---------------
internal data class NameId(private val name: String) : PersistentEntityId<NamedEntity>() {
override val parentId: PersistentEntityId<*>?
get() = null
override val presentableName: String
get() = name
override fun toString(): String = name
}
internal data class AnotherNameId(private val name: String) : PersistentEntityId<NamedEntity>() {
override val parentId: PersistentEntityId<*>?
get() = null
override val presentableName: String
get() = name
override fun toString(): String = name
}
internal data class ComposedId(internal val name: String, internal val link: NameId) : PersistentEntityId<ComposedIdSoftRefEntity>() {
override val parentId: PersistentEntityId<*>?
get() = null
override val presentableName: String
get() = "$name - ${link.presentableName}"
}
// ------------------------------ Entity With Persistent Id ------------------
internal class NamedEntityData : WorkspaceEntityData.WithCalculablePersistentId<NamedEntity>() {
lateinit var name: String
var additionalProperty: String? = null
override fun createEntity(snapshot: WorkspaceEntityStorage): NamedEntity {
return NamedEntity(name, additionalProperty).also { addMetaData(it, snapshot) }
}
override fun persistentId(): PersistentEntityId<*> = NameId(name)
}
internal class NamedEntity(val name: String, val additionalProperty: String?) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId() = NameId(name)
}
internal class ModifiableNamedEntity : ModifiableWorkspaceEntityBase<NamedEntity>() {
var name: String by EntityDataDelegation()
var additionalProperty: String? by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilderImpl.addNamedEntity(name: String, additionalProperty: String? = null, source: EntitySource = MySource) =
addEntity(ModifiableNamedEntity::class.java, source) {
this.name = name
this.additionalProperty = additionalProperty
}
internal val NamedEntity.children: Sequence<NamedChildEntity>
get() = referrers(NamedChildEntity::parent)
// ------------------------------ Child of entity with persistent id ------------------
internal class NamedChildEntityData : WorkspaceEntityData<NamedChildEntity>() {
lateinit var childProperty: String
override fun createEntity(snapshot: WorkspaceEntityStorage): NamedChildEntity {
return NamedChildEntity(childProperty).also { addMetaData(it, snapshot) }
}
}
internal class NamedChildEntity(
val childProperty: String
) : WorkspaceEntityBase() {
val parent: NamedEntity by ManyToOne.NotNull(NamedEntity::class.java)
}
internal class ModifiableNamedChildEntity : ModifiableWorkspaceEntityBase<NamedChildEntity>() {
var childProperty: String by EntityDataDelegation()
var parent: NamedEntity by MutableManyToOne.NotNull(NamedChildEntity::class.java, NamedEntity::class.java)
}
internal fun WorkspaceEntityStorageBuilder.addNamedChildEntity(parentEntity: NamedEntity,
childProperty: String = "child",
source: EntitySource = MySource) =
addEntity(ModifiableNamedChildEntity::class.java, source) {
this.parent = parentEntity
this.childProperty = childProperty
}
// ------------------------------ Entity with soft link --------------------
internal class WithSoftLinkEntityData : WorkspaceEntityData<WithSoftLinkEntity>(), SoftLinkable {
lateinit var link: PersistentEntityId<*>
override fun createEntity(snapshot: WorkspaceEntityStorage): WithSoftLinkEntity {
return WithSoftLinkEntity(link).also { addMetaData(it, snapshot) }
}
override fun getLinks(): Set<PersistentEntityId<*>> = setOf(link)
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
this.link = newLink
return true
}
}
internal class WithSoftLinkEntity(val link: PersistentEntityId<*>) : WorkspaceEntityBase()
internal class ModifiableWithSoftLinkEntity : ModifiableWorkspaceEntityBase<WithSoftLinkEntity>() {
var link: PersistentEntityId<*> by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilderImpl.addWithSoftLinkEntity(link: PersistentEntityId<*>, source: EntitySource = MySource) =
addEntity(ModifiableWithSoftLinkEntity::class.java, source) {
this.link = link
}
// ------------------------- Entity with persistentId and the list of soft links ------------------
internal class WithListSoftLinksEntityData : SoftLinkable, WorkspaceEntityData.WithCalculablePersistentId<WithListSoftLinksEntity>() {
lateinit var name: String
lateinit var links: MutableList<NameId>
override fun getLinks(): Set<PersistentEntityId<*>> = links.toSet()
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
links.remove(oldLink)
links.add(newLink as NameId)
return true
}
override fun createEntity(snapshot: WorkspaceEntityStorage): WithListSoftLinksEntity {
return WithListSoftLinksEntity(name, links).also { addMetaData(it, snapshot) }
}
override fun persistentId() = AnotherNameId(name)
}
internal class WithListSoftLinksEntity(val name: String, val links: List<NameId>) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId(): AnotherNameId = AnotherNameId(name)
}
internal class ModifiableWithListSoftLinksEntity : ModifiableWorkspaceEntityBase<WithListSoftLinksEntity>() {
var name: String by EntityDataDelegation()
var links: List<NameId> by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilderImpl.addWithListSoftLinksEntity(name: String,
links: List<NameId>,
source: EntitySource = MySource) =
addEntity(ModifiableWithListSoftLinksEntity::class.java, source) {
this.name = name
this.links = links
}
// --------------------------- Entity with composed persistent id via soft reference ------------------
internal class ComposedIdSoftRefEntityData : WorkspaceEntityData.WithCalculablePersistentId<ComposedIdSoftRefEntity>(), SoftLinkable {
lateinit var name: String
lateinit var link: NameId
override fun createEntity(snapshot: WorkspaceEntityStorage): ComposedIdSoftRefEntity {
return ComposedIdSoftRefEntity(name, link).also { addMetaData(it, snapshot) }
}
override fun getLinks(): Set<PersistentEntityId<*>> = setOf(link)
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
if (oldLink != link) return false
this.link = newLink as NameId
return true
}
override fun persistentId() = ComposedId(name, link)
}
internal class ComposedIdSoftRefEntity(val name: String, val link: NameId) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId(): ComposedId = ComposedId(name, link)
}
internal class ModifiableComposedIdSoftRefEntity : ModifiableWorkspaceEntityBase<ComposedIdSoftRefEntity>() {
var name: String by EntityDataDelegation()
var link: NameId by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilderImpl.addComposedIdSoftRefEntity(name: String,
link: NameId,
source: EntitySource = MySource): ComposedIdSoftRefEntity {
return addEntity(ModifiableComposedIdSoftRefEntity::class.java, source) {
this.name = name
this.link = link
}
}
| apache-2.0 | 1e782224e3f46bc89129245c21fbdf5c | 38.714976 | 146 | 0.707213 | 5.880544 | false | false | false | false |
allotria/intellij-community | plugins/ide-features-trainer/src/training/dsl/impl/LessonExecutor.kt | 1 | 13149 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.dsl.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import org.intellij.lang.annotations.Language
import training.dsl.*
import training.learn.ActionsRecorder
import training.learn.course.KLesson
import training.learn.exceptons.NoTextEditor
import training.learn.lesson.LessonManager
import training.statistic.StatisticBase
import training.ui.LearnToolWindowFactory
import training.util.WeakReferenceDelegator
import java.awt.Component
import kotlin.math.max
class LessonExecutor(val lesson: KLesson, val project: Project, initialEditor: Editor?, val predefinedFile: VirtualFile?) : Disposable {
private data class TaskInfo(val content: () -> Unit,
var restoreIndex: Int,
var taskProperties: TaskProperties?,
val taskContent: (TaskContext.() -> Unit)?,
var messagesNumberBeforeStart: Int = 0,
var rehighlightComponent: (() -> Component)? = null,
var userVisibleInfo: PreviousTaskInfo? = null,
val removeAfterDoneMessages: MutableList<Int> = mutableListOf())
var predefinedEditor: Editor? by WeakReferenceDelegator(initialEditor)
private set
private val selectedEditor: Editor?
get() {
val result = if (lesson.lessonType.isSingleEditor) predefinedEditor
else FileEditorManager.getInstance(project).selectedTextEditor?.also {
// We may need predefined editor in the multi-editor lesson in the start of the lesson.
// It seems, there is a platform bug with no selected editor when the needed editor is actually opened.
// But better do not use it later to avoid possible bugs.
predefinedEditor = null
} ?: predefinedEditor // It may be needed in the start of the lesson.
return result?.takeIf { !it.isDisposed }
}
val editor: Editor
get() = selectedEditor ?: throw NoTextEditor()
data class TaskData(var shouldRestoreToTask: (() -> TaskContext.TaskId?)? = null,
var delayMillis: Int = 0)
private val taskActions: MutableList<TaskInfo> = ArrayList()
var foundComponent: Component? = null
var rehighlightComponent: (() -> Component)? = null
private var currentRecorder: ActionsRecorder? = null
private var currentRestoreRecorder: ActionsRecorder? = null
internal var currentTaskIndex = 0
private set
private val parentDisposable: Disposable = LearnToolWindowFactory.learnWindowPerProject[project]?.parentDisposable ?: project
// Is used from ui detection pooled thread
@Volatile
var hasBeenStopped = false
private set
init {
Disposer.register(parentDisposable, this)
}
private fun addTaskAction(taskProperties: TaskProperties? = null, taskContent: (TaskContext.() -> Unit)? = null, content: () -> Unit) {
val previousIndex = max(taskActions.size - 1, 0)
taskActions.add(TaskInfo(content, previousIndex, taskProperties, taskContent))
}
fun getUserVisibleInfo(index: Int): PreviousTaskInfo {
return taskActions[index].userVisibleInfo ?: throw IllegalArgumentException("No information available for task $index")
}
fun waitBeforeContinue(delayMillis: Int) {
addTaskAction {
val action = {
foundComponent = taskActions[currentTaskIndex].userVisibleInfo?.ui
rehighlightComponent = taskActions[currentTaskIndex].rehighlightComponent
processNextTask(currentTaskIndex + 1)
}
Alarm().addRequest(action, delayMillis)
}
}
fun task(taskContent: TaskContext.() -> Unit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val taskProperties = LessonExecutorUtil.taskProperties(taskContent, project)
addTaskAction(taskProperties, taskContent) {
val taskInfo = taskActions[currentTaskIndex]
taskInfo.taskProperties?.messagesNumber?.let {
LessonManager.instance.removeInactiveMessages(it)
taskInfo.taskProperties?.messagesNumber = 0 // Here could be runtime messages
}
processTask(taskContent)
}
}
override fun dispose() {
if (!hasBeenStopped) {
ApplicationManager.getApplication().assertIsDispatchThread()
disposeRecorders()
hasBeenStopped = true
taskActions.clear()
}
}
fun stopLesson() {
Disposer.dispose(this)
}
private fun disposeRecorders() {
currentRecorder?.let { Disposer.dispose(it) }
currentRecorder = null
currentRestoreRecorder?.let { Disposer.dispose(it) }
currentRestoreRecorder = null
}
val virtualFile: VirtualFile
get() = FileDocumentManager.getInstance().getFile(editor.document) ?: error("No Virtual File")
fun startLesson() {
addAllInactiveMessages()
if (lesson.properties.canStartInDumbMode) {
processNextTask(0)
}
else {
DumbService.getInstance(project).runWhenSmart {
if (!hasBeenStopped)
processNextTask(0)
}
}
}
private fun processNextTask(taskIndex: Int) {
// ModalityState.current() or without argument - cannot be used: dialog steps can stop to work.
// Good example: track of rename refactoring
invokeLater(ModalityState.any()) {
disposeRecorders()
currentTaskIndex = taskIndex
processNextTask2()
}
}
private fun processNextTask2() {
LessonManager.instance.clearRestoreMessage()
ApplicationManager.getApplication().assertIsDispatchThread()
if (currentTaskIndex == taskActions.size) {
LessonManager.instance.passLesson(lesson)
disposeRecorders()
return
}
val taskInfo = taskActions[currentTaskIndex]
taskInfo.messagesNumberBeforeStart = LessonManager.instance.messagesNumber()
setUserVisibleInfo()
taskInfo.content()
}
private fun setUserVisibleInfo() {
val taskInfo = taskActions[currentTaskIndex]
// do not reset information from the previous tasks if it is available already
if (taskInfo.userVisibleInfo == null) {
taskInfo.userVisibleInfo = object : PreviousTaskInfo {
override val text: String = selectedEditor?.document?.text ?: ""
override val position: LogicalPosition = selectedEditor?.caretModel?.currentCaret?.logicalPosition ?: LogicalPosition(0, 0)
override val sample: LessonSample = selectedEditor?.let { prepareSampleFromCurrentState(it) } ?: parseLessonSample("")
override val ui: Component? = foundComponent
override val file: VirtualFile? = selectedEditor?.let { FileDocumentManager.getInstance().getFile(it.document) }
}
taskInfo.rehighlightComponent = rehighlightComponent
}
//Clear user visible information for later tasks
for (i in currentTaskIndex + 1 until taskActions.size) {
taskActions[i].userVisibleInfo = null
taskActions[i].rehighlightComponent = null
}
foundComponent = null
rehighlightComponent = null
}
private fun processTask(taskContent: TaskContext.() -> Unit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val recorder = ActionsRecorder(project, selectedEditor?.document, this)
currentRecorder = recorder
val taskCallbackData = TaskData()
val taskContext = TaskContextImpl(this, recorder, currentTaskIndex, taskCallbackData)
taskContext.apply(taskContent)
if (taskContext.steps.isEmpty()) {
processNextTask(currentTaskIndex + 1)
return
}
chainNextTask(taskContext, recorder, taskCallbackData)
processTestActions(taskContext)
}
internal fun applyRestore(taskContext: TaskContextImpl, restoreId: TaskContext.TaskId? = null) {
taskContext.steps.forEach { it.cancel(true) }
val restoreIndex = restoreId?.idx ?: taskActions[taskContext.taskIndex].restoreIndex
val restoreInfo = taskActions[restoreIndex]
restoreInfo.rehighlightComponent?.let { it() }
LessonManager.instance.resetMessagesNumber(restoreInfo.messagesNumberBeforeStart)
StatisticBase.logRestorePerformed(lesson, currentTaskIndex)
processNextTask(restoreIndex)
}
/** @return a callback to clear resources used to track restore */
private fun checkForRestore(taskContext: TaskContextImpl,
taskData: TaskData): () -> Unit {
var clearRestore: () -> Unit = {}
fun restore(restoreId: TaskContext.TaskId) {
clearRestore()
invokeLater(ModalityState.any()) { // restore check must be done after pass conditions (and they will be done during current event processing)
if (canBeRestored(taskContext)) {
applyRestore(taskContext, restoreId)
}
}
}
val shouldRestoreToTask = taskData.shouldRestoreToTask ?: return {}
fun checkFunction(): Boolean {
if (hasBeenStopped) {
// Strange situation
clearRestore()
return false
}
val checkAndRestoreIfNeeded = {
if (canBeRestored(taskContext)) {
val restoreId = shouldRestoreToTask()
if (restoreId != null) {
restore(restoreId)
}
}
}
if (taskData.delayMillis == 0) {
checkAndRestoreIfNeeded()
}
else {
Alarm().addRequest(checkAndRestoreIfNeeded, taskData.delayMillis)
}
return false
}
// Not sure about use-case when we need to check restore at the start of current task
// But it theoretically can be needed in case of several restores of dependent steps
if (checkFunction()) return {}
val restoreRecorder = ActionsRecorder(project, selectedEditor?.document, this)
currentRestoreRecorder = restoreRecorder
val restoreFuture = restoreRecorder.futureCheck { checkFunction() }
clearRestore = {
if (!restoreFuture.isDone) {
restoreFuture.cancel(true)
}
}
return clearRestore
}
private fun chainNextTask(taskContext: TaskContextImpl,
recorder: ActionsRecorder,
taskData: TaskData) {
val clearRestore = checkForRestore(taskContext, taskData)
recorder.tryToCheckCallback()
taskContext.steps.forEach { step ->
step.thenAccept {
ApplicationManager.getApplication().assertIsDispatchThread()
val taskHasBeenDone = isTaskCompleted(taskContext)
if (taskHasBeenDone) {
clearRestore()
LessonManager.instance.passExercise()
val taskInfo = taskActions[currentTaskIndex]
if (foundComponent == null) foundComponent = taskInfo.userVisibleInfo?.ui
if (rehighlightComponent == null) rehighlightComponent = taskInfo.rehighlightComponent
for (index in taskInfo.removeAfterDoneMessages) {
LessonManager.instance.removeMessage(index)
}
taskInfo.taskProperties?.let { it.messagesNumber -= taskInfo.removeAfterDoneMessages.size }
processNextTask(currentTaskIndex + 1)
}
}
}
}
private fun isTaskCompleted(taskContext: TaskContextImpl) = taskContext.steps.all { it.isDone && it.get() }
internal val taskCount: Int
get() = taskActions.size
private fun canBeRestored(taskContext: TaskContextImpl): Boolean {
return !hasBeenStopped && taskContext.steps.any { !it.isCancelled && !it.isCompletedExceptionally && (!it.isDone || !it.get()) }
}
private fun processTestActions(taskContext: TaskContextImpl) {
if (TaskTestContext.inTestMode && taskContext.testActions.isNotEmpty()) {
LessonManager.instance.testActionsExecutor.execute {
taskContext.testActions.forEach { it.run() }
}
}
}
fun text(@Language("HTML") text: String, removeAfterDone: Boolean = false) {
val taskInfo = taskActions[currentTaskIndex]
if (removeAfterDone) taskInfo.removeAfterDoneMessages.add(LessonManager.instance.messagesNumber())
// Here could be runtime messages
taskInfo.taskProperties?.let {
it.messagesNumber++
}
var hasDetection = false
for (i in currentTaskIndex until taskActions.size) {
if (taskInfo.taskProperties?.hasDetection == true) {
hasDetection = true
break
}
}
LessonManager.instance.addMessage(text, !hasDetection)
}
private fun addAllInactiveMessages() {
val tasksWithContent = taskActions.mapNotNull { it.taskContent }
val messages = tasksWithContent.map { LessonExecutorUtil.textMessages(it, project) }.flatten()
LessonManager.instance.addInactiveMessages(messages)
}
} | apache-2.0 | 1c817d9f93c1bebd493920af6757d3ba | 36.571429 | 148 | 0.705453 | 4.798905 | false | false | false | false |
ptkNktq/AndroidNotificationNotifier | AndroidApp/ui/src/main/java/me/nya_n/notificationnotifier/ui/screen/top/TopFragment.kt | 1 | 7511 | package me.nya_n.notificationnotifier.ui.screen.top
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuProvider
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import me.nya_n.notificationnotifier.model.Backup
import me.nya_n.notificationnotifier.model.Fab
import me.nya_n.notificationnotifier.model.InstalledApp
import me.nya_n.notificationnotifier.model.Message
import me.nya_n.notificationnotifier.ui.R
import me.nya_n.notificationnotifier.ui.adapters.AppAdapter
import me.nya_n.notificationnotifier.ui.databinding.FragmentTopBinding
import me.nya_n.notificationnotifier.ui.dialogs.PackageVisibilityDialog
import me.nya_n.notificationnotifier.ui.screen.MainViewModel
import me.nya_n.notificationnotifier.ui.screen.SharedViewModel
import me.nya_n.notificationnotifier.ui.util.Snackbar
import me.nya_n.notificationnotifier.ui.util.addMenuProvider
import me.nya_n.notificationnotifier.ui.util.autoCleared
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class TopFragment : Fragment() {
private var binding: FragmentTopBinding by autoCleared()
private val viewModel: TopViewModel by viewModel()
private val sharedViewModel: SharedViewModel by sharedViewModel()
private val activityViewModel: MainViewModel by sharedViewModel()
private val filter = object : AppAdapter.Filter {
private val targets = ArrayList<InstalledApp>()
override fun filter(items: List<InstalledApp>): List<InstalledApp> {
return items.filter { app ->
targets.any { t -> t.packageName == app.packageName }
}
}
fun targetChanged(elements: List<InstalledApp>) {
targets.clear()
targets.addAll(elements)
}
}
private val exportDataResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == AppCompatActivity.RESULT_CANCELED) return@registerForActivityResult
val uri = it.data?.data
if (uri != null) {
viewModel.exportData(requireContext(), uri)
} else {
handleMessage(Message.Error(R.string.export_failed))
}
}
private val importDataResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == AppCompatActivity.RESULT_CANCELED) return@registerForActivityResult
val uri = it.data?.data
if (uri != null) {
viewModel.importData(requireContext(), uri)
} else {
handleMessage(Message.Error(R.string.import_failed))
}
}
private val menuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu, menu)
}
override fun onMenuItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.export_data -> {
exportDataResult.launch(
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/json"
putExtra(Intent.EXTRA_TITLE, Backup.FILE_NAME)
}
)
true
}
R.id.import_data -> {
importDataResult.launch(
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/json"
}
)
true
}
R.id.license -> {
findNavController().navigate(R.id.action_MainFragment_to_LicenseFragment)
true
}
else -> false
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate<FragmentTopBinding>(
inflater,
R.layout.fragment_top,
container,
false
).also {
it.lifecycleOwner = viewLifecycleOwner
it.viewModel = viewModel
it.sharedViewModel = sharedViewModel
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addMenuProvider(menuProvider)
initViews()
observes()
}
override fun onResume() {
super.onResume()
activityViewModel.changeFabState((Fab(true) {
findNavController().navigate(R.id.action_MainFragment_to_SelectionFragment)
}))
}
private fun initViews() {
val adapter = AppAdapter(requireContext().packageManager, filter) { app ->
findNavController().navigate(
TopFragmentDirections.actionMainFragmentToDetailFragment(app)
)
}
binding.list.apply {
val divider = DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
addItemDecoration(divider)
layoutManager = LinearLayoutManager(requireContext())
this.adapter = adapter
}
binding.refresh.setOnRefreshListener {
sharedViewModel.loadApps()
}
}
private fun observes() {
viewModel.message.observe(viewLifecycleOwner) {
val message = it.getContentIfNotHandled() ?: return@observe
handleMessage(message)
}
sharedViewModel.targets.observe(viewLifecycleOwner) {
filter.targetChanged(it)
val adapter = binding.list.adapter as AppAdapter
adapter.targetChanged()
}
sharedViewModel.list.observe(viewLifecycleOwner) {
binding.refresh.isRefreshing = false
(binding.list.adapter as AppAdapter).apply {
clear()
addAll(it)
}
}
sharedViewModel.checkPackageVisibilityEvent.observe(viewLifecycleOwner) {
it.getContentIfNotHandled() ?: return@observe
binding.refresh.isRefreshing = false
PackageVisibilityDialog.showOnlyOnce(childFragmentManager)
childFragmentManager.setFragmentResultListener(
PackageVisibilityDialog.TAG,
viewLifecycleOwner
) { _, result ->
val isGranted = result.getBoolean(PackageVisibilityDialog.KEY_IS_GRANTED)
if (isGranted) {
sharedViewModel.packageVisibilityGranted()
sharedViewModel.loadApps()
binding.refresh.isRefreshing = true
}
}
}
}
private fun handleMessage(message: Message) {
Snackbar.create(binding.root, message).show()
}
} | mit | 2575e7f9e9538061f6237ab2ef7f3771 | 37.523077 | 100 | 0.625483 | 5.486486 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/jps-plugin/testSrc/org/jetbrains/jps/incremental/groovy/GroovyRtPathsTest.kt | 1 | 2875 | // 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.jps.incremental.groovy
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.directoryContent
import org.junit.Assert
import org.junit.Test
import java.io.File
class GroovyRtPathsTest {
@Test
fun runningFromSources() {
val out = directoryContent {
dir("intellij.groovy.constants.rt") {}
dir("intellij.groovy.jps") {}
dir("intellij.groovy.rt") {}
}.generateInTempDir()
val roots = GroovyBuilder.getGroovyRtRoots(File(out, "intellij.groovy.jps"))
assertSameFiles(roots, File(out, "intellij.groovy.rt"), File(out, "intellij.groovy.constants.rt"))
}
@Test
fun pluginDistribution() {
val lib = directoryContent {
file("groovy-jps-plugin.jar")
file("groovy-rt-constants.jar")
file("groovy_rt.jar")
}.generateInTempDir()
val roots = GroovyBuilder.getGroovyRtRoots(File(lib, "groovy-jps-plugin.jar"))
assertSameFiles(roots, File(lib, "groovy_rt.jar"), File(lib, "groovy-rt-constants.jar"))
}
@Test
fun buildScriptDependencies() {
val lib = directoryContent {
file("groovy-constants-rt-193.239.jar")
file("groovy-rt-193.239.jar")
file("groovy-jps-193.239.jar")
}.generateInTempDir()
val roots = GroovyBuilder.getGroovyRtRoots(File(lib, "groovy-jps-193.239.jar"))
assertSameFiles(roots, File(lib, "groovy-rt-193.239.jar"), File(lib, "groovy-constants-rt-193.239.jar"))
}
@Test
fun mavenArtifactsInRepository() {
val repo = directoryContent {
dir("com") {
dir("jetbrains") {
dir("intellij") {
dir("groovy") {
dir("groovy-constants-rt") {
dir("193.239") { file("groovy-constants-rt-193.239.jar") }
}
dir("groovy-jps") {
dir("193.239") { file("groovy-jps-193.239.jar") }
}
dir("groovy-rt") {
dir("193.239") { file("groovy-rt-193.239.jar") }
}
}
}
}
}
}.generateInTempDir()
val roots = GroovyBuilder.getGroovyRtRoots(File(repo, "com/jetbrains/intellij/groovy/groovy-jps/193.239/groovy-jps-193.239.jar"))
assertSameFiles(roots, File(repo, "com/jetbrains/intellij/groovy/groovy-rt/193.239/groovy-rt-193.239.jar"),
File(repo, "com/jetbrains/intellij/groovy/groovy-constants-rt/193.239/groovy-constants-rt-193.239.jar"))
}
private fun assertSameFiles(paths: List<String>, vararg file: File) {
val actualPaths = paths.mapTo(HashSet()) { FileUtil.toSystemIndependentName(it) }
val expectedPaths = file.mapTo(HashSet()) { FileUtil.toSystemIndependentName(it.absolutePath) }
Assert.assertEquals(expectedPaths, actualPaths)
}
}
| apache-2.0 | a13a0121f5cf5050113851e1d843af60 | 37.333333 | 140 | 0.648 | 3.676471 | false | true | false | false |
JuliusKunze/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt | 1 | 5542 | /*
* Copyright 2010-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 kotlinx.cinterop
private const val MAX_ARGUMENT_SIZE = 8
typealias FfiTypeKind = Int
// Also declared in Interop.cpp
const val FFI_TYPE_KIND_VOID: FfiTypeKind = 0
const val FFI_TYPE_KIND_SINT8: FfiTypeKind = 1
const val FFI_TYPE_KIND_SINT16: FfiTypeKind = 2
const val FFI_TYPE_KIND_SINT32: FfiTypeKind = 3
const val FFI_TYPE_KIND_SINT64: FfiTypeKind = 4
const val FFI_TYPE_KIND_FLOAT: FfiTypeKind = 5
const val FFI_TYPE_KIND_DOUBLE: FfiTypeKind = 6
const val FFI_TYPE_KIND_POINTER: FfiTypeKind = 7
private tailrec fun convertArgument(
argument: Any?, isVariadic: Boolean, location: COpaquePointer,
additionalPlacement: AutofreeScope
): FfiTypeKind = when (argument) {
is CValuesRef<*>? -> {
location.reinterpret<CPointerVar<*>>()[0] = argument?.getPointer(additionalPlacement)
FFI_TYPE_KIND_POINTER
}
is String -> {
location.reinterpret<CPointerVar<*>>()[0] = argument.cstr.getPointer(additionalPlacement)
FFI_TYPE_KIND_POINTER
}
is Int -> {
location.reinterpret<IntVar>()[0] = argument
FFI_TYPE_KIND_SINT32
}
is Long -> {
location.reinterpret<LongVar>()[0] = argument
FFI_TYPE_KIND_SINT64
}
is Boolean -> convertArgument(argument.toByte(), isVariadic, location, additionalPlacement)
is Byte -> if (isVariadic) {
convertArgument(argument.toInt(), isVariadic, location, additionalPlacement)
} else {
location.reinterpret<ByteVar>()[0] = argument
FFI_TYPE_KIND_SINT8
}
is Short -> if (isVariadic) {
convertArgument(argument.toInt(), isVariadic, location, additionalPlacement)
} else {
location.reinterpret<ShortVar>()[0] = argument
FFI_TYPE_KIND_SINT16
}
is Double -> {
location.reinterpret<DoubleVar>()[0] = argument
FFI_TYPE_KIND_DOUBLE
}
is Float -> if (isVariadic) {
convertArgument(argument.toDouble(), isVariadic, location, additionalPlacement)
} else {
location.reinterpret<FloatVar>()[0] = argument
FFI_TYPE_KIND_FLOAT
}
is CEnum -> convertArgument(argument.value, isVariadic, location, additionalPlacement)
is ObjCPointerHolder -> {
location.reinterpret<COpaquePointerVar>()[0] = interpretCPointer(argument.rawPtr)
FFI_TYPE_KIND_POINTER
}
else -> throw Error("unsupported argument: $argument")
}
inline fun <reified T : CVariable> NativePlacement.allocFfiReturnValueBuffer(type: CVariable.Type): T {
var size = type.size
var align = type.align
// libffi requires return value buffer to be no smaller than system register size;
// TODO: system register size is not exactly the same as pointer size.
if (size < pointerSize) {
size = pointerSize.toLong()
}
if (align < pointerSize) {
align = pointerSize
}
return this.alloc(size, align).reinterpret<T>()
}
fun callWithVarargs(codePtr: NativePtr, returnValuePtr: NativePtr, returnTypeKind: FfiTypeKind,
fixedArguments: Array<out Any?>, variadicArguments: Array<out Any?>?,
argumentsPlacement: AutofreeScope) {
val totalArgumentsNumber = fixedArguments.size + if (variadicArguments == null) 0 else variadicArguments.size
// All supported arguments take at most 8 bytes each:
val argumentsStorage = argumentsPlacement.allocArray<LongVar>(totalArgumentsNumber)
val arguments = argumentsPlacement.allocArray<CPointerVar<*>>(totalArgumentsNumber)
val types = argumentsPlacement.allocArray<COpaquePointerVar>(totalArgumentsNumber)
var index = 0
inline fun addArgument(argument: Any?, isVariadic: Boolean) {
val storage = (argumentsStorage + index)!!
val typeKind = convertArgument(argument, isVariadic = isVariadic,
location = storage, additionalPlacement = argumentsPlacement)
types[index] = typeKind.toLong().toCPointer()
arguments[index] = storage
++index
}
for (argument in fixedArguments) {
addArgument(argument, isVariadic = false)
}
val variadicArgumentsNumber: Int
if (variadicArguments != null) {
for (argument in variadicArguments) {
addArgument(argument, isVariadic = true)
}
variadicArgumentsNumber = variadicArguments.size
} else {
variadicArgumentsNumber = -1
}
assert (index == totalArgumentsNumber)
callFunctionPointer(codePtr, returnValuePtr, returnTypeKind, arguments.rawValue, types.rawValue,
totalArgumentsNumber, variadicArgumentsNumber)
}
@SymbolName("Kotlin_Interop_callFunctionPointer")
private external fun callFunctionPointer(
codePtr: NativePtr,
returnValuePtr: NativePtr,
returnTypeKind: FfiTypeKind,
arguments: NativePtr,
argumentTypeKinds: NativePtr,
totalArgumentsNumber: Int,
variadicArgumentsNumber: Int
)
| apache-2.0 | d28dbffe2b31ad6f7c94b37eb78e5a36 | 32.185629 | 113 | 0.688741 | 4.276235 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/boxingOptimization/unsafeRemoving.kt | 3 | 667 | // WITH_RUNTIME
import kotlin.test.assertEquals
fun returningBoxed() : Int? = 1
fun acceptingBoxed(x : Int?) : Int ? = x
class A(var x : Int? = null)
fun box() : String {
assertEquals(1, returningBoxed())
assertEquals(1, acceptingBoxed(1))
val a = A()
a.x = 1
assertEquals(1, a.x)
val b = Array<Int?>(1, { null })
b[0] = 1
assertEquals(1, b[0])
val x: Int? = 1
assertEquals(1, x!!.hashCode())
val y: Int? = 1000
val z: Int? = 1000
val res = y === z
val c1: Any = if (1 == 1) 0 else "abc"
val c2: Any = if (1 != 1) 0 else "abc"
assertEquals(0, c1)
assertEquals("abc", c2)
return "OK"
}
| apache-2.0 | c938425e3f113a71f98cac0e122d3505 | 18.057143 | 42 | 0.550225 | 2.9 | false | false | false | false |
smmribeiro/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/auth/AccountManagerBase.kt | 8 | 4867 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.auth
import com.intellij.credentialStore.*
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.Disposer
import org.jetbrains.annotations.VisibleForTesting
import java.util.concurrent.CopyOnWriteArrayList
/**
* Base class for account management application service
* Accounts are stored in [accountsRepository]
* Credentials are serialized and stored in [passwordSafe]
*
* @see [AccountsListener]
*/
abstract class AccountManagerBase<A : Account, Cred>(private val serviceName: String)
: AccountManager<A, Cred>, Disposable {
protected open val passwordSafe
get() = PasswordSafe.instance
private val persistentAccounts
get() = accountsRepository()
protected abstract fun accountsRepository(): AccountsRepository<A>
private val listeners = CopyOnWriteArrayList<AccountsListener<A>>()
private val messageBusConnection by lazy { messageBusConnection() }
@VisibleForTesting
protected open fun messageBusConnection() = ApplicationManager.getApplication().messageBus.connect(this)
override val accounts: Set<A>
get() = persistentAccounts.accounts
init {
messageBusConnection.subscribe(PasswordSafeSettings.TOPIC, object : PasswordSafeSettingsListener {
override fun credentialStoreCleared() = persistentAccounts.accounts.forEach { account ->
listeners.forEach { it.onAccountCredentialsChanged(account) }
}
})
}
override fun updateAccounts(accountsWithCredentials: Map<A, Cred?>) {
val currentSet = persistentAccounts.accounts
val removed = currentSet - accountsWithCredentials.keys
for (account in removed) {
passwordSafe.set(account.credentialAttributes(), null)
}
for ((account, credentials) in accountsWithCredentials) {
if (credentials != null) {
passwordSafe.set(account.credentialAttributes(), account.credentials(credentials))
if (currentSet.contains(account)) listeners.forEach { it.onAccountCredentialsChanged(account) }
}
}
val added = accountsWithCredentials.keys - currentSet
if (added.isNotEmpty() || removed.isNotEmpty()) {
persistentAccounts.accounts = accountsWithCredentials.keys
listeners.forEach { it.onAccountListChanged(currentSet, accountsWithCredentials.keys) }
LOG.debug("Account list changed to: ${persistentAccounts.accounts}")
}
}
override fun updateAccount(account: A, credentials: Cred) {
val currentSet = persistentAccounts.accounts
val newAccount = !currentSet.contains(account)
if (!newAccount) {
// remove and add an account to update auxiliary fields
persistentAccounts.accounts = (currentSet - account) + account
}
else {
persistentAccounts.accounts = currentSet + account
LOG.debug("Added new account: $account")
}
passwordSafe.set(account.credentialAttributes(), account.credentials(credentials))
LOG.debug((if (credentials == null) "Cleared" else "Updated") + " credentials for account: $account")
if (!newAccount) {
listeners.forEach { it.onAccountCredentialsChanged(account) }
}
else {
listeners.forEach { it.onAccountListChanged(currentSet, persistentAccounts.accounts) }
}
}
override fun removeAccount(account: A) {
val currentSet = persistentAccounts.accounts
val newSet = currentSet - account
if (newSet.size != currentSet.size) {
persistentAccounts.accounts = newSet
passwordSafe.set(account.credentialAttributes(), null)
LOG.debug("Removed account: $account")
listeners.forEach { it.onAccountListChanged(currentSet, newSet) }
}
}
override fun findCredentials(account: A): Cred? =
passwordSafe.get(account.credentialAttributes())?.getPasswordAsString()?.let(::deserializeCredentials)
private fun A.credentialAttributes() = CredentialAttributes(generateServiceName(serviceName, id))
private fun A.credentials(credentials: Cred?): Credentials? = credentials?.let { Credentials(id, serializeCredentials(it)) }
protected abstract fun serializeCredentials(credentials: Cred): String
protected abstract fun deserializeCredentials(credentials: String): Cred
override fun addListener(disposable: Disposable, listener: AccountsListener<A>) {
listeners.add(listener)
Disposer.register(disposable) {
listeners.remove(listener)
}
}
@VisibleForTesting
fun addListener(listener: AccountsListener<A>) {
listeners.add(listener)
}
override fun dispose() {}
companion object {
private val LOG
get() = thisLogger()
}
} | apache-2.0 | 3ce49e1cae28931a515b8121191420e7 | 36.736434 | 140 | 0.744607 | 4.679808 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/CheckoutRiskMessageFragmentViewModel.kt | 1 | 1684 | package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.libs.Environment
import com.kickstarter.libs.FragmentViewModel
import com.kickstarter.libs.utils.UrlUtils
import com.kickstarter.ui.fragments.CheckoutRiskMessageFragment
import rx.Observable
import rx.subjects.PublishSubject
interface CheckoutRiskMessageFragmentViewModel {
interface Inputs {
fun onLearnMoreAboutAccountabilityLinkClicked()
}
interface Outputs {
fun openLearnMoreAboutAccountabilityLink(): Observable<String>
}
class ViewModel(@NonNull val environment: Environment) :
FragmentViewModel<CheckoutRiskMessageFragment>(environment), Inputs, Outputs {
private val onLearnMoreAboutAccountabilityLinkClicked = PublishSubject.create<Void>()
private val openLearnMoreAboutAccountabilityLink = PublishSubject.create<String>()
val inputs: Inputs = this
val outputs: Outputs = this
init {
this.onLearnMoreAboutAccountabilityLinkClicked
.compose(bindToLifecycle())
.subscribe {
this.openLearnMoreAboutAccountabilityLink.onNext(
UrlUtils
.appendPath(environment.webEndpoint(), TRUST)
)
}
}
override fun onLearnMoreAboutAccountabilityLinkClicked() = this
.onLearnMoreAboutAccountabilityLinkClicked.onNext(null)
override fun openLearnMoreAboutAccountabilityLink(): Observable<String> =
this.openLearnMoreAboutAccountabilityLink
}
companion object {
const val TRUST = "trust"
}
}
| apache-2.0 | e4588d3bc296356710fe0c53cd005058 | 34.829787 | 93 | 0.695368 | 6.427481 | false | false | false | false |
viartemev/requestmapper | src/test/kotlin/com/viartemev/requestmapper/model/PathSpek.kt | 1 | 9932 | package com.viartemev.requestmapper.model
import com.viartemev.requestmapper.model.Path.Companion.isSubpathOf
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeTrue
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object PathSpek : Spek({
describe("Path") {
context("toFullPath on instance which contains empty string") {
it("should return empty string") {
Path("").toFullPath() shouldBeEqualTo ""
}
}
context("toFullPath on instance which contains string without slashes") {
it("should return the original string") {
val path = "string"
Path(path).toFullPath() shouldBeEqualTo path
}
}
context("toFullPath on instance which contains string with slashes") {
it("should return the original string") {
val path = "/api/id"
Path(path).toFullPath() shouldBeEqualTo path
}
}
context("addPathVariablesTypes on instance which contains empty string") {
it("should return the original string") {
val path = ""
Path(path).addPathVariablesTypes(mapOf()).toFullPath() shouldBeEqualTo path
}
}
context("addPathVariablesTypes on instance which contains string without slashes") {
it("should return the original string") {
val path = "api"
Path(path).addPathVariablesTypes(mapOf()).toFullPath() shouldBeEqualTo path
}
}
context("addPathVariablesTypes on instance which contains string without curly brackets") {
it("should return the original string") {
val path = "/api/id"
Path(path).addPathVariablesTypes(mapOf()).toFullPath() shouldBeEqualTo path
}
}
context("addPathVariablesTypes on instance which contains string with curly brackets with empty parameters map") {
it("should return the original string") {
Path("/api/{id}").addPathVariablesTypes(mapOf()).toFullPath() shouldBeEqualTo "/api/{Object:id}"
}
}
context("addPathVariablesTypes on instance which contains string with curly brackets with not empty parameters map") {
it("should return the original string") {
Path("/api/{id}").addPathVariablesTypes(mapOf("id" to "Long")).toFullPath() shouldBeEqualTo "/api/{Long:id}"
}
}
context("addPathVariablesTypes on instance which contains string with regex") {
it("should return the original string") {
Path("/api/{id:.+}").addPathVariablesTypes(mapOf("id" to "Long")).toFullPath() shouldBeEqualTo "/api/{Long:id:.+}"
}
}
context("isSubpathOf case 1") {
it("should return true") {
isSubpathOf(Path("/api"), (Path("/api"))).shouldBeTrue()
}
}
context("isSubpathOf case 2") {
it("should return false") {
isSubpathOf(Path("/api"), (Path("/api1"))).shouldBeFalse()
}
}
context("isSubpathOf case 3") {
it("should return true") {
isSubpathOf(Path("/api/v1"), Path("/api/v1")).shouldBeTrue()
}
}
context("isSubpathOf case 4") {
it("should return false") {
isSubpathOf(Path("/api/v1"), Path("/api/v2")).shouldBeFalse()
}
}
context("isSubpathOf case 5") {
it("should return true") {
isSubpathOf(Path("/api/v1/items"), Path("/api/v1")).shouldBeTrue()
}
}
context("isSubpathOf case 6") {
it("should return true") {
isSubpathOf(Path("/api/v1/items"), Path("/api/v1/items")).shouldBeTrue()
}
}
context("isSubpathOf case 7") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{Long:itemId}"), Path("/api/v1/items/123")).shouldBeTrue()
}
}
context("isSubpathOf case 8") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{Long:itemId}"), Path("/api/v1/items/asdasd")).shouldBeFalse()
}
}
context("isSubpathOf case 9") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}"), Path("/api/v1/items/asdasd")).shouldBeTrue()
}
}
context("isSubpathOf case 10") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}"), Path("/api/v1/items/123")).shouldBeTrue()
}
}
context("isSubpathOf case 11") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/product"), Path("/api/v1/items/123/product")).shouldBeTrue()
}
}
context("isSubpathOf case 12") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/product/{Long:productId}"), Path("/api/v1/items/123/product/123")).shouldBeTrue()
}
}
context("isSubpathOf case 13") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/product/{Long:productId}"), Path("/api/v1/items/123/product/asdasd")).shouldBeFalse()
}
}
context("isSubpathOf case 14") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/api/v1/items/123/123")).shouldBeTrue()
}
}
context("isSubpathOf case 15") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/api/v1/items/123/asdasd")).shouldBeFalse()
}
}
context("isSubpathOf case 16") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/asdaasd/123")).shouldBeFalse()
}
}
context("isSubpathOf case 17") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/items/asdaasd/123")).shouldBeTrue()
}
}
context("isSubpathOf case 18") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/123")).shouldBeFalse()
}
}
context("isSubpathOf case 19") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}"), Path("/items/123")).shouldBeTrue()
}
}
context("isSubpathOf case 20") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/products/{Long:productId}"), Path("/products/123")).shouldBeTrue()
}
}
context("isSubpathOf case 21") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/products/{Long:productId}"), Path("/123/products")).shouldBeTrue()
}
}
context("isSubpathOf case 22") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/products/{Long:productId}"), Path("/123/products/1231")).shouldBeTrue()
}
}
context("isSubpathOf case 23") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("/123/price")).shouldBeTrue()
}
}
context("isSubpathOf case 24") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("itemId/123/price")).shouldBeTrue()
}
}
context("isSubpathOf case 25") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("localhost:8080/api/v1")).shouldBeTrue()
}
}
context("isSubpathOf case 26") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("/api/")).shouldBeTrue()
}
}
context("isSubpathOf case 27") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("/ap")).shouldBeTrue()
}
}
context("isSubpathOf case 28") {
it("should return false") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{Long:productId}/price"), Path("/price/")).shouldBeFalse()
}
}
context("isSubpathOf case 29") {
it("should return true") {
isSubpathOf(Path("/api/v1/items/{String:itemId}/{SpecialType:productId}/price"), Path("/api/v1/items/itemId/special-type")).shouldBeTrue()
}
}
context("isSubpathOf case 30") {
it("should return true") {
isSubpathOf(Path("/{String:item}"), Path("/ap")).shouldBeTrue()
}
}
context("isSubpathOf case 31") {
it("should return true") {
isSubpathOf(Path("/{String:item}/{String:product}"), Path("/item/product")).shouldBeTrue()
}
}
context("isSubpathOf case 32") {
it("should return true") {
isSubpathOf(Path("/api/v1"), Path("localhost:8080/routing-path/api/v1")).shouldBeTrue()
}
}
}
})
| mit | 8c2a15fe91327104e5c61cbed5adc25e | 43.142222 | 154 | 0.546315 | 4.400532 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/PackageSearchOperation.kt | 1 | 3387 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
internal sealed class PackageSearchOperation<T>(
open val model: T,
open val projectModule: ProjectModule
) {
sealed class Package(
override val model: UnifiedDependency,
override val projectModule: ProjectModule
) : PackageSearchOperation<UnifiedDependency>(model, projectModule) {
data class Install(
override val model: UnifiedDependency,
override val projectModule: ProjectModule,
val newVersion: PackageVersion,
val newScope: PackageScope
) : Package(model, projectModule) {
override fun toString() =
"Package.Install(model='${model.displayName}', projectModule='${projectModule.getFullName()}', " +
"version='$newVersion', scope='$newScope')"
}
data class Remove(
override val model: UnifiedDependency,
override val projectModule: ProjectModule,
val currentVersion: PackageVersion,
val currentScope: PackageScope
) : Package(model, projectModule) {
override fun toString() =
"Package.Remove(model='${model.displayName}', projectModule='${projectModule.getFullName()}', " +
"currentVersion='$currentVersion', scope='$currentScope')"
}
data class ChangeInstalled(
override val model: UnifiedDependency,
override val projectModule: ProjectModule,
val currentVersion: PackageVersion,
val currentScope: PackageScope,
val newVersion: PackageVersion,
val newScope: PackageScope
) : Package(model, projectModule) {
override fun toString() =
"Package.Change(model='${model.displayName}', projectModule='${projectModule.getFullName()}', " +
"currentVersion='$currentVersion', currentScope='$currentScope', " +
"newVersion='$newVersion', newScope='$newScope')"
}
}
sealed class Repository(
override val model: UnifiedDependencyRepository,
override val projectModule: ProjectModule
) : PackageSearchOperation<UnifiedDependencyRepository>(model, projectModule) {
data class Install(
override val model: UnifiedDependencyRepository,
override val projectModule: ProjectModule
) : Repository(model, projectModule) {
override fun toString() = "Repository.Install(model='${model.displayName}', projectModule='${projectModule.getFullName()}')"
}
data class Remove(
override val model: UnifiedDependencyRepository,
override val projectModule: ProjectModule
) : Repository(model, projectModule) {
override fun toString() = "Repository.Remove(model='${model.displayName}', projectModule='${projectModule.getFullName()}')"
}
}
}
| apache-2.0 | f877fa7adc98d8c5c2a682b2c0bdcf45 | 41.3375 | 136 | 0.663124 | 6.048214 | false | false | false | false |
zdary/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/SetChangesGroupingAction.kt | 6 | 1448 | // 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 com.intellij.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport
abstract class SetChangesGroupingAction : ToggleAction(), DumbAware {
init {
isEnabledInModalContext = true
}
abstract val groupingKey: @NlsSafe String
override fun update(e: AnActionEvent): Unit = super.update(e).also {
e.presentation.isEnabledAndVisible = getGroupingSupport(e)?.isAvailable(groupingKey) ?: false
}
override fun isSelected(e: AnActionEvent): Boolean =
getGroupingSupport(e)?.let { it.isAvailable(groupingKey) && it[groupingKey] } ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
getGroupingSupport(e)!![groupingKey] = state
}
protected fun getGroupingSupport(e: AnActionEvent): ChangesGroupingSupport? = e.getData(ChangesGroupingSupport.KEY)
}
class SetDirectoryChangesGroupingAction : SetChangesGroupingAction() {
override val groupingKey: String get() = "directory" // NON-NLS
}
class SetModuleChangesGroupingAction : SetChangesGroupingAction() {
override val groupingKey: String get() = "module" // NON-NLS
} | apache-2.0 | 68833321b6fea6d5c0ff2293c72e7be7 | 39.25 | 140 | 0.781077 | 4.441718 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/implicitReceiversUtils.kt | 2 | 5285 | // 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.util
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.DslMarkerUtils
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import java.util.*
import kotlin.collections.LinkedHashSet
fun LexicalScope.getImplicitReceiversWithInstance(excludeShadowedByDslMarkers: Boolean = false): Collection<ReceiverParameterDescriptor> =
getImplicitReceiversWithInstanceToExpression(excludeShadowedByDslMarkers).keys
interface ReceiverExpressionFactory {
val isImmediate: Boolean
val expressionText: String
fun createExpression(psiFactory: KtPsiFactory, shortThis: Boolean = true): KtExpression
}
fun LexicalScope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType: KotlinType): ReceiverExpressionFactory? =
getImplicitReceiversWithInstanceToExpression().entries.firstOrNull { (receiverDescriptor, _) ->
receiverDescriptor.type.isSubtypeOf(receiverType)
}?.value
fun LexicalScope.getImplicitReceiversWithInstanceToExpression(
excludeShadowedByDslMarkers: Boolean = false
): Map<ReceiverParameterDescriptor, ReceiverExpressionFactory?> {
val allReceivers = getImplicitReceiversHierarchy()
// we use a set to workaround a bug with receiver for companion object present twice in the result of getImplicitReceiversHierarchy()
val receivers = LinkedHashSet(
if (excludeShadowedByDslMarkers) {
allReceivers - allReceivers.shadowedByDslMarkers()
} else {
allReceivers
}
)
val outerDeclarationsWithInstance = LinkedHashSet<DeclarationDescriptor>()
var current: DeclarationDescriptor? = ownerDescriptor
while (current != null) {
if (current is PropertyAccessorDescriptor) {
current = current.correspondingProperty
}
outerDeclarationsWithInstance.add(current)
val classDescriptor = current as? ClassDescriptor
if (classDescriptor != null && !classDescriptor.isInner && !DescriptorUtils.isLocal(classDescriptor)) break
current = current.containingDeclaration
}
val result = LinkedHashMap<ReceiverParameterDescriptor, ReceiverExpressionFactory?>()
for ((index, receiver) in receivers.withIndex()) {
val owner = receiver.containingDeclaration
if (owner is ScriptDescriptor) {
result[receiver] = null
outerDeclarationsWithInstance.addAll(owner.implicitReceivers)
continue
}
val (expressionText, isImmediateThis) = if (owner in outerDeclarationsWithInstance) {
val thisWithLabel = thisQualifierName(receiver)?.let { "this@${it.render()}" }
if (index == 0)
(thisWithLabel ?: "this") to true
else
thisWithLabel to false
} else if (owner is ClassDescriptor && owner.kind.isSingleton) {
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(owner) to false
} else {
continue
}
val factory = if (expressionText != null)
object : ReceiverExpressionFactory {
override val isImmediate = isImmediateThis
override val expressionText: String get() = expressionText
override fun createExpression(psiFactory: KtPsiFactory, shortThis: Boolean): KtExpression {
return psiFactory.createExpression(if (shortThis && isImmediateThis) "this" else expressionText)
}
}
else
null
result[receiver] = factory
}
return result
}
private fun thisQualifierName(receiver: ReceiverParameterDescriptor): Name? {
val descriptor = receiver.containingDeclaration
val name = descriptor.name
if (!name.isSpecial) return name
val functionLiteral = DescriptorToSourceUtils.descriptorToDeclaration(descriptor) as? KtFunctionLiteral
return functionLiteral?.findLabelAndCall()?.first
}
private fun List<ReceiverParameterDescriptor>.shadowedByDslMarkers(): Set<ReceiverParameterDescriptor> {
val typesByDslScopes = mutableMapOf<FqName, MutableList<ReceiverParameterDescriptor>>()
for (receiver in this) {
val dslMarkers = DslMarkerUtils.extractDslMarkerFqNames(receiver.value).all()
for (marker in dslMarkers) {
typesByDslScopes.getOrPut(marker) { mutableListOf() } += receiver
}
}
// for each DSL marker, all receivers except the closest one are shadowed by it; that is why we drop it
return typesByDslScopes.values.flatMapTo(mutableSetOf()) { it.drop(1) }
} | apache-2.0 | 98b496c20fc1a2c2b8a2d36e407cf357 | 43.79661 | 158 | 0.733586 | 5.295591 | false | false | false | false |
siosio/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/status/Status.kt | 2 | 5064 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.status
import com.intellij.openapi.vcs.FileStatus
import org.jetbrains.idea.svn.SvnFileStatus
import org.jetbrains.idea.svn.api.BaseNodeDescription
import org.jetbrains.idea.svn.api.NodeKind
import org.jetbrains.idea.svn.api.Revision
import org.jetbrains.idea.svn.api.Url
import org.jetbrains.idea.svn.checkin.CommitInfo
import org.jetbrains.idea.svn.info.Info
import org.jetbrains.idea.svn.lock.Lock
import org.jetbrains.idea.svn.status.StatusType.*
import java.io.File
import java.util.function.Supplier
class Status private constructor(builder: Builder) : BaseNodeDescription(builder.nodeKind) {
private val infoProvider = builder.infoProvider
val info by lazy { if (itemStatus != STATUS_NONE) infoProvider.get() else null }
val url = builder.url
get() = field ?: info?.url
private val fileExists = builder.fileExists
override val nodeKind get() = if (fileExists) super.nodeKind else info?.nodeKind ?: super.nodeKind
val revision: Revision = builder.revision
get() {
return if (field.isValid || `is`(STATUS_NONE, STATUS_UNVERSIONED, STATUS_ADDED)) field else info?.revision ?: field
}
val copyFromUrl get() = if (isCopied) info?.copyFromUrl else null
val treeConflict get() = if (isTreeConflicted) info?.treeConflict else null
val repositoryRootUrl get() = info?.repositoryRootUrl
val file = builder.file
val commitInfo: CommitInfo = builder.commitInfo?.build() ?: CommitInfo.EMPTY
val itemStatus = builder.itemStatus
val propertyStatus = builder.propertyStatus
val remoteItemStatus = builder.remoteItemStatus
val remotePropertyStatus = builder.remotePropertyStatus
val isWorkingCopyLocked = builder.isWorkingCopyLocked
val isCopied = builder.isCopied
val isSwitched = builder.isSwitched
val remoteLock = builder.remoteLock?.build()
val localLock = builder.localLock?.build()
val changeListName = builder.changeListName
val isTreeConflicted = builder.isTreeConflicted
fun `is`(vararg types: StatusType) = itemStatus in types
fun isProperty(vararg types: StatusType) = propertyStatus in types
class Builder(var file: File) {
var infoProvider = Supplier<Info?> { null }
var url: Url? = null
var fileExists = false
var nodeKind = NodeKind.UNKNOWN
var revision = Revision.UNDEFINED
var commitInfo: CommitInfo.Builder? = null
var itemStatus = STATUS_NONE
var propertyStatus = STATUS_NONE
var remoteItemStatus: StatusType? = null
var remotePropertyStatus: StatusType? = null
var isWorkingCopyLocked = false
var isCopied = false
var isSwitched = false
var remoteLock: Lock.Builder? = null
var localLock: Lock.Builder? = null
var changeListName: String? = null
var isTreeConflicted = false
fun build() = Status(this)
}
companion object {
@JvmStatic
fun convertStatus(status: Status) = convertStatus(status.itemStatus, status.propertyStatus, status.isSwitched, status.isCopied)
@JvmStatic
fun convertStatus(itemStatus: StatusType?, propertyStatus: StatusType?, isSwitched: Boolean, isCopied: Boolean): FileStatus =
when {
itemStatus == null -> FileStatus.UNKNOWN
STATUS_UNVERSIONED == itemStatus -> FileStatus.UNKNOWN
STATUS_MISSING == itemStatus -> FileStatus.DELETED_FROM_FS
STATUS_EXTERNAL == itemStatus -> SvnFileStatus.EXTERNAL
STATUS_OBSTRUCTED == itemStatus -> SvnFileStatus.OBSTRUCTED
STATUS_IGNORED == itemStatus -> FileStatus.IGNORED
STATUS_ADDED == itemStatus -> FileStatus.ADDED
STATUS_DELETED == itemStatus -> FileStatus.DELETED
STATUS_REPLACED == itemStatus -> SvnFileStatus.REPLACED
STATUS_CONFLICTED == itemStatus || STATUS_CONFLICTED == propertyStatus -> {
if (STATUS_CONFLICTED == itemStatus && STATUS_CONFLICTED == propertyStatus) FileStatus.MERGED_WITH_BOTH_CONFLICTS
else if (STATUS_CONFLICTED == itemStatus) FileStatus.MERGED_WITH_CONFLICTS
else FileStatus.MERGED_WITH_PROPERTY_CONFLICTS
}
STATUS_MODIFIED == itemStatus || STATUS_MODIFIED == propertyStatus -> FileStatus.MODIFIED
isSwitched -> FileStatus.SWITCHED
isCopied -> FileStatus.ADDED
else -> FileStatus.NOT_CHANGED
}
@JvmStatic
fun convertPropertyStatus(status: StatusType?): FileStatus = when (status) {
null -> FileStatus.UNKNOWN
STATUS_UNVERSIONED -> FileStatus.UNKNOWN
STATUS_MISSING -> FileStatus.DELETED_FROM_FS
STATUS_EXTERNAL -> SvnFileStatus.EXTERNAL
STATUS_OBSTRUCTED -> SvnFileStatus.OBSTRUCTED
STATUS_IGNORED -> FileStatus.IGNORED
STATUS_ADDED -> FileStatus.ADDED
STATUS_DELETED -> FileStatus.DELETED
STATUS_REPLACED -> SvnFileStatus.REPLACED
STATUS_CONFLICTED -> FileStatus.MERGED_WITH_PROPERTY_CONFLICTS
STATUS_MODIFIED -> FileStatus.MODIFIED
else -> FileStatus.NOT_CHANGED
}
}
}
| apache-2.0 | f988f825f6ccec37912929cfaae37aad | 41.2 | 140 | 0.73124 | 4.434326 | false | false | false | false |
JetBrains/xodus | vfs/src/main/kotlin/jetbrains/exodus/vfs/ClusterKey.kt | 1 | 1493 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.vfs
import jetbrains.exodus.ArrayByteIterable
import jetbrains.exodus.ByteIterable
import jetbrains.exodus.bindings.LongBinding
import jetbrains.exodus.util.LightOutputStream
internal class ClusterKey(iterable: ByteIterable) {
val descriptor: Long
val clusterNumber: Long
init {
val iterator = iterable.iterator()
descriptor = LongBinding.readCompressed(iterator)
clusterNumber = LongBinding.readCompressed(iterator)
}
companion object {
@JvmStatic
fun toByteIterable(fd: Long, clusterNumber: Long): ArrayByteIterable {
val output = LightOutputStream(8)
val bytes = IntArray(8)
LongBinding.writeCompressed(output, fd, bytes)
LongBinding.writeCompressed(output, clusterNumber, bytes)
return output.asArrayByteIterable()
}
}
}
| apache-2.0 | 0b0ca6cf7b0abc7f3c58a31db60afcb3 | 32.177778 | 78 | 0.716008 | 4.510574 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt | 4 | 18392 | // 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.completion.smart
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.idea.caches.resolve.util.resolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.collectSyntheticStaticMembersAndConstructors
import org.jetbrains.kotlin.idea.completion.*
import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionCompositeDeclarativeInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionInsertHandler
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper
import org.jetbrains.kotlin.idea.core.Tail
import org.jetbrains.kotlin.idea.core.multipleFuzzyTypes
import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.resolveTopLevelClass
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.util.constructors
import org.jetbrains.kotlin.util.kind
import org.jetbrains.kotlin.utils.addIfNotNull
class TypeInstantiationItems(
val resolutionFacade: ResolutionFacade,
val bindingContext: BindingContext,
val visibilityFilter: (DeclarationDescriptor) -> Boolean,
val toFromOriginalFileMapper: ToFromOriginalFileMapper,
val inheritorSearchScope: GlobalSearchScope,
val lookupElementFactory: LookupElementFactory,
val forOrdinaryCompletion: Boolean,
val indicesHelper: KotlinIndicesHelper
) {
fun addTo(
items: MutableCollection<LookupElement>,
inheritanceSearchers: MutableCollection<InheritanceItemsSearcher>,
expectedInfos: Collection<ExpectedInfo>
) {
val expectedInfosGrouped = LinkedHashMap<FuzzyType, MutableList<ExpectedInfo>>()
for (expectedInfo in expectedInfos) {
for (fuzzyType in expectedInfo.multipleFuzzyTypes) {
expectedInfosGrouped.getOrPut(fuzzyType.makeNotNullable()) { ArrayList() }.add(expectedInfo)
}
}
for ((type, infos) in expectedInfosGrouped) {
val tail = mergeTails(infos.map { it.tail })
addTo(items, inheritanceSearchers, type, tail)
}
}
private fun addTo(
items: MutableCollection<LookupElement>,
inheritanceSearchers: MutableCollection<InheritanceItemsSearcher>,
fuzzyType: FuzzyType,
tail: Tail?
) {
if (fuzzyType.type.isFunctionType) return // do not show "object: ..." for function types
val classifier = fuzzyType.type.constructor.declarationDescriptor as? ClassifierDescriptorWithTypeParameters ?: return
val classDescriptor = when (classifier) {
is ClassDescriptor -> classifier
is TypeAliasDescriptor -> classifier.classDescriptor
else -> null
}
addSamConstructorItem(items, classifier, classDescriptor, tail)
items.addIfNotNull(createTypeInstantiationItem(fuzzyType, classDescriptor, tail))
indicesHelper.resolveTypeAliasesUsingIndex(fuzzyType.type, classifier.name.asString()).forEach {
addSamConstructorItem(items, it, classDescriptor, tail)
val typeAliasFuzzyType = it.defaultType.toFuzzyType(fuzzyType.freeParameters)
items.addIfNotNull(createTypeInstantiationItem(typeAliasFuzzyType, classDescriptor, tail))
}
if (classDescriptor != null && !forOrdinaryCompletion && !KotlinBuiltIns.isAny(classDescriptor)) { // do not search inheritors of Any
val typeArgs = fuzzyType.type.arguments
inheritanceSearchers.addInheritorSearcher(classDescriptor, classDescriptor, typeArgs, fuzzyType.freeParameters, tail)
val javaClassId = JavaToKotlinClassMap.mapKotlinToJava(DescriptorUtils.getFqName(classifier))
if (javaClassId != null) {
val javaAnalog =
resolutionFacade.moduleDescriptor.resolveTopLevelClass(javaClassId.asSingleFqName(), NoLookupLocation.FROM_IDE)
if (javaAnalog != null) {
inheritanceSearchers.addInheritorSearcher(javaAnalog, classDescriptor, typeArgs, fuzzyType.freeParameters, tail)
}
}
}
}
private fun MutableCollection<InheritanceItemsSearcher>.addInheritorSearcher(
descriptor: ClassDescriptor,
kotlinClassDescriptor: ClassDescriptor,
typeArgs: List<TypeProjection>,
freeParameters: Collection<TypeParameterDescriptor>,
tail: Tail?
) {
val _declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(resolutionFacade.project, descriptor) ?: return
val declaration = if (_declaration is KtDeclaration)
toFromOriginalFileMapper.toOriginalFile(_declaration) ?: return
else
_declaration
val psiClass: PsiClass = when (declaration) {
is PsiClass -> declaration
is KtClassOrObject -> declaration.toLightClass() ?: return
else -> return
}
add(InheritanceSearcher(psiClass, kotlinClassDescriptor, typeArgs, freeParameters, tail))
}
private fun createTypeInstantiationItem(fuzzyType: FuzzyType, classDescriptor: ClassDescriptor?, tail: Tail?): LookupElement? {
val classifier = fuzzyType.type.constructor.declarationDescriptor as? ClassifierDescriptorWithTypeParameters ?: return null
var lookupElement = lookupElementFactory.createLookupElement(classifier, useReceiverTypes = false)
if (DescriptorUtils.isNonCompanionObject(classifier)) {
return lookupElement.addTail(tail)
}
// not all inner classes can be instantiated and we handle them via constructors returned by ReferenceVariantsHelper
if (classifier.isInner) return null
val isAbstract = classDescriptor?.modality == Modality.ABSTRACT
if (forOrdinaryCompletion && isAbstract) return null
val allConstructors = classifier.constructors
val visibleConstructors = allConstructors.filter {
if (isAbstract)
visibilityFilter(it) || it.visibility == DescriptorVisibilities.PROTECTED
else
visibilityFilter(it)
}
if (allConstructors.isNotEmpty() && visibleConstructors.isEmpty()) return null
var lookupString = lookupElement.lookupString
var allLookupStrings = setOf(lookupString)
var itemText = lookupString
var signatureText: String? = null
val typeText = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classifier)
val insertHandler: InsertHandler<LookupElement>
if (isAbstract) {
val typeArgs = fuzzyType.type.arguments
// drop "in" and "out" from type arguments - they cannot be used in constructor call
val typeArgsToUse = typeArgs.map { TypeProjectionImpl(Variance.INVARIANT, it.type) }
val allTypeArgsKnown =
fuzzyType.freeParameters.isEmpty() || typeArgs.none { it.type.areTypeParametersUsedInside(fuzzyType.freeParameters) }
itemText += if (allTypeArgsKnown) {
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderTypeArguments(typeArgsToUse)
} else {
"<...>"
}
val constructorParenthesis = if (classifier.kind != ClassKind.INTERFACE) "()" else ""
itemText += constructorParenthesis
itemText = "object : $itemText{...}"
lookupString = "object"
allLookupStrings = setOf(lookupString, lookupElement.lookupString)
insertHandler = InsertHandler<LookupElement> { context, _ ->
val startOffset = context.startOffset
val settings = context.file.kotlinCustomSettings
val spaceBefore = if (settings.SPACE_BEFORE_EXTEND_COLON) " " else ""
val spaceAfter = if (settings.SPACE_AFTER_EXTEND_COLON) " " else ""
val text1 = "object$spaceBefore:$spaceAfter$typeText"
val text2 = "$constructorParenthesis {}"
val text = if (allTypeArgsKnown)
text1 + IdeDescriptorRenderers.SOURCE_CODE.renderTypeArguments(typeArgsToUse) + text2
else
"$text1<>$text2"
context.document.replaceString(startOffset, context.tailOffset, text)
if (allTypeArgsKnown) {
context.editor.caretModel.moveToOffset(startOffset + text.length - 1)
shortenReferences(context, startOffset, startOffset + text.length)
ImplementMembersHandler().invoke(context.project, context.editor, context.file, true)
} else {
context.editor.caretModel.moveToOffset(startOffset + text1.length + 1) // put caret into "<>"
shortenReferences(context, startOffset, startOffset + text.length)
}
}
lookupElement = lookupElement.suppressAutoInsertion()
lookupElement = lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.ANONYMOUS_OBJECT)
} else {
//TODO: when constructor has one parameter of lambda type with more than one parameter, generate special additional item
signatureText = when (visibleConstructors.size) {
0 -> "()"
1 -> {
val constructor = visibleConstructors.single()
val substitutor = TypeSubstitutor.create(fuzzyType.presentationType())
val substitutedConstructor = constructor.substitute(substitutor)
?: constructor // render original signature if failed to substitute
BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderFunctionParameters(substitutedConstructor)
}
else -> "(...)"
}
val baseInsertHandler = when (visibleConstructors.size) {
0 -> KotlinFunctionInsertHandler.Normal(
CallType.DEFAULT,
inputTypeArguments = false,
inputValueArguments = false,
argumentsOnly = true
)
1 -> lookupElementFactory.insertHandlerProvider.insertHandler(visibleConstructors.single(), argumentsOnly = true)
else -> KotlinFunctionInsertHandler.Normal(
CallType.DEFAULT,
inputTypeArguments = false,
inputValueArguments = true,
argumentsOnly = true
)
}
insertHandler = InsertHandler { context, item ->
context.document.replaceString(context.startOffset, context.tailOffset, typeText)
context.tailOffset = context.startOffset + typeText.length
baseInsertHandler.handleInsert(context, item)
shortenReferences(context, context.startOffset, context.tailOffset)
}
run {
val (inputValueArgs, isLambda) = when (baseInsertHandler) {
is KotlinFunctionInsertHandler.Normal -> baseInsertHandler.inputValueArguments to (baseInsertHandler.lambdaInfo != null)
is KotlinFunctionCompositeDeclarativeInsertHandler -> baseInsertHandler.inputValueArguments to baseInsertHandler.isLambda
else -> false to false
}
if (inputValueArgs) {
lookupElement = lookupElement.keepOldArgumentListOnTab()
}
if (isLambda) {
lookupElement.putUserData(KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE, Unit)
}
}
lookupElement = lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.INSTANTIATION)
}
class InstantiationLookupElement : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() = lookupString
override fun getAllLookupStrings() = allLookupStrings
override fun renderElement(presentation: LookupElementPresentation) {
delegate.renderElement(presentation)
presentation.itemText = itemText
presentation.clearTail()
signatureText?.let {
presentation.appendTailText(it, false)
}
presentation.appendTailText(" (" + DescriptorUtils.getFqName(classifier.containingDeclaration) + ")", true)
}
override fun getDelegateInsertHandler() = insertHandler
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is InstantiationLookupElement) return false
if (getLookupString() != other.lookupString) return false
val presentation1 = LookupElementPresentation()
val presentation2 = LookupElementPresentation()
renderElement(presentation1)
other.renderElement(presentation2)
return presentation1.itemText == presentation2.itemText && presentation1.tailText == presentation2.tailText
}
override fun hashCode() = lookupString.hashCode()
}
return InstantiationLookupElement().addTail(tail)
}
private fun KotlinType.areTypeParametersUsedInside(freeParameters: Collection<TypeParameterDescriptor>): Boolean {
return FuzzyType(this, freeParameters).freeParameters.isNotEmpty()
}
private fun addSamConstructorItem(
collection: MutableCollection<LookupElement>,
classifier: ClassifierDescriptorWithTypeParameters,
classDescriptor: ClassDescriptor?,
tail: Tail?
) {
if (classDescriptor?.kind == ClassKind.INTERFACE) {
val samConstructor = run {
val scope = when (val container = classifier.containingDeclaration) {
is PackageFragmentDescriptor -> container.getMemberScope()
is ClassDescriptor -> container.unsubstitutedMemberScope
else -> return
}
scope.collectSyntheticStaticMembersAndConstructors(
resolutionFacade,
DescriptorKindFilter.FUNCTIONS
) { classifier.name == it }
.filterIsInstance<SamConstructorDescriptor>()
.singleOrNull() ?: return
}
lookupElementFactory
.createStandardLookupElementsForDescriptor(samConstructor, useReceiverTypes = false)
.mapTo(collection) { it.assignSmartCompletionPriority(SmartCompletionItemPriority.INSTANTIATION).addTail(tail) }
}
}
private inner class InheritanceSearcher(
private val psiClass: PsiClass,
classDescriptor: ClassDescriptor,
typeArgs: List<TypeProjection>,
private val freeParameters: Collection<TypeParameterDescriptor>,
private val tail: Tail?
) : InheritanceItemsSearcher {
private val baseHasTypeArgs = classDescriptor.declaredTypeParameters.isNotEmpty()
private val expectedType = KotlinTypeFactory.simpleNotNullType(TypeAttributes.Empty, classDescriptor, typeArgs)
private val expectedFuzzyType = expectedType.toFuzzyType(freeParameters)
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
val parameters = ClassInheritorsSearch.SearchParameters(psiClass, inheritorSearchScope, true, true, false, nameFilter)
for (inheritor in ClassInheritorsSearch.search(parameters)) {
val descriptor = inheritor.resolveToDescriptor(
resolutionFacade
) { toFromOriginalFileMapper.toSyntheticFile(it) } ?: continue
if (!visibilityFilter(descriptor)) continue
var inheritorFuzzyType = descriptor.defaultType.toFuzzyType(descriptor.typeConstructor.parameters)
val hasTypeArgs = descriptor.declaredTypeParameters.isNotEmpty()
if (hasTypeArgs || baseHasTypeArgs) {
val substitutor = inheritorFuzzyType.checkIsSubtypeOf(expectedFuzzyType) ?: continue
if (!substitutor.isEmpty) {
val inheritorTypeSubstituted = substitutor.substitute(inheritorFuzzyType.type, Variance.INVARIANT)!!
inheritorFuzzyType = inheritorTypeSubstituted.toFuzzyType(freeParameters + inheritorFuzzyType.freeParameters)
}
}
val lookupElement = createTypeInstantiationItem(inheritorFuzzyType, descriptor, tail) ?: continue
consumer(lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.INHERITOR_INSTANTIATION))
}
}
}
}
| apache-2.0 | 7ffabe7ddd784bdd30b937d74cdf3660 | 48.708108 | 158 | 0.677577 | 5.96175 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/LibraryModificationTracker.kt | 1 | 4290 | // 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.caches.project
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCopyEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
class LibraryModificationTracker(project: Project) : SimpleModificationTracker() {
companion object {
@JvmStatic
fun getInstance(project: Project): LibraryModificationTracker = project.service()
}
init {
val disposable = KotlinPluginDisposable.getInstance(project)
val connection = project.messageBus.connect(disposable)
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
events.filter(::isRelevantEvent).let { createEvents ->
if (createEvents.isNotEmpty()) {
ApplicationManager.getApplication().invokeLater({
processBulk(createEvents) {
projectFileIndex.isInLibraryClasses(it) || isLibraryArchiveRoot(
it
)
}
}, project.disposed)
}
}
}
override fun before(events: List<VFileEvent>) {
processBulk(events) {
projectFileIndex.isInLibraryClasses(it)
}
}
})
connection.subscribe(DumbService.DUMB_MODE, object : DumbService.DumbModeListener {
override fun enteredDumbMode() {
incModificationCount()
}
override fun exitDumbMode() {
incModificationCount()
}
})
connection.subscribe(FileTypeManager.TOPIC, object : FileTypeListener {
override fun beforeFileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
override fun fileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
})
}
private val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
private inline fun processBulk(events: List<VFileEvent>, check: (VirtualFile) -> Boolean) {
events.forEach { event ->
if (event.isValid) {
val file = event.file
if (file != null && check(file)) {
incModificationCount()
return
}
}
}
}
// if library points to a jar, the jar does not pass isInLibraryClasses check, so we have to perform additional check for this case
private fun isLibraryArchiveRoot(virtualFile: VirtualFile): Boolean {
if (!FileTypeRegistry.getInstance().isFileOfType(virtualFile, ArchiveFileType.INSTANCE)) return false
val archiveRoot = JarFileSystem.getInstance().getRootByLocal(virtualFile) ?: return false
return projectFileIndex.isInLibraryClasses(archiveRoot)
}
}
private fun isRelevantEvent(vFileEvent: VFileEvent) =
vFileEvent is VFileCreateEvent || vFileEvent is VFileMoveEvent || vFileEvent is VFileCopyEvent
| apache-2.0 | 1bc28c21a070fbb30bb5dd959abf94dc | 41.058824 | 158 | 0.667366 | 5.485934 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuspendCallLineMarkerProvider.kt | 3 | 7530 | // 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.highlighter
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.descriptors.accessors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.highlighter.markers.LineMarkerInfos
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContext.*
import org.jetbrains.kotlin.resolve.calls.checkers.isBuiltInCoroutineContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class KotlinSuspendCallLineMarkerProvider : LineMarkerProvider {
private class SuspendCallMarkerInfo(callElement: PsiElement, message: String) : LineMarkerInfo<PsiElement>(
callElement,
callElement.textRange,
KotlinIcons.SUSPEND_CALL,
{ message },
null,
GutterIconRenderer.Alignment.RIGHT,
{ message }
) {
override fun createGutterRenderer(): GutterIconRenderer {
return object : LineMarkerGutterIconRenderer<PsiElement>(this) {
override fun getClickAction(): AnAction? = null
}
}
}
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null
override fun collectSlowLineMarkers(elements: MutableList<out PsiElement>, result: LineMarkerInfos) {
val markedLineNumbers = HashSet<Int>()
for (element in elements) {
ProgressManager.checkCanceled()
if (element !is KtExpression) continue
val containingFile = element.containingFile
if (containingFile !is KtFile || containingFile is KtCodeFragment) continue
val lineNumber = element.getLineNumber()
if (lineNumber in markedLineNumbers) continue
val kind = getSuspendCallKind(element, element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: continue
val anchor = kind.anchor ?: continue
markedLineNumbers += lineNumber
result += SuspendCallMarkerInfo(getElementForLineMark(anchor), kind.description)
}
}
}
sealed class SuspendCallKind<T : KtExpression>(val element: T) {
class Iteration(element: KtForExpression) : SuspendCallKind<KtForExpression>(element) {
override val anchor get() = element.loopRange
override val description get() = KotlinBundle.message("highlighter.message.suspending.iteration")
}
class FunctionCall(element: KtCallExpression) : SuspendCallKind<KtCallExpression>(element) {
override val anchor get() = element.calleeExpression
override val description get() = KotlinBundle.message("highlighter.message.suspend.function.call")
}
class PropertyDelegateCall(element: KtProperty) : SuspendCallKind<KtProperty>(element) {
override val anchor get() = element.delegate?.node?.findChildByType(KtTokens.BY_KEYWORD) as? PsiElement ?: element.delegate
override val description get() = KotlinBundle.message("highlighter.message.suspend.function.call")
}
class NameCall(element: KtSimpleNameExpression) : SuspendCallKind<KtSimpleNameExpression>(element) {
override val anchor get() = element
override val description get() = KotlinBundle.message("highlighter.message.suspend.function.call")
}
abstract val anchor: PsiElement?
abstract val description: String
}
fun getSuspendCallKind(expression: KtExpression, bindingContext: BindingContext): SuspendCallKind<*>? {
fun isSuspend(descriptor: CallableDescriptor): Boolean = when (descriptor) {
is FunctionDescriptor -> descriptor.isSuspend
is PropertyDescriptor -> descriptor.accessors.any { it.isSuspend } || descriptor.isBuiltInCoroutineContext()
else -> false
}
fun isSuspend(resolvedCall: ResolvedCall<*>): Boolean {
if (resolvedCall is VariableAsFunctionResolvedCall) {
return isSuspend(resolvedCall.variableCall.resultingDescriptor) || isSuspend(resolvedCall.functionCall.resultingDescriptor)
}
return isSuspend(resolvedCall.resultingDescriptor)
}
when {
expression is KtForExpression -> {
val loopRange = expression.loopRange
val iteratorResolvedCall = bindingContext[LOOP_RANGE_ITERATOR_RESOLVED_CALL, loopRange]
val hasNextResolvedCall = bindingContext[LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, loopRange]
val nextResolvedCall = bindingContext[LOOP_RANGE_NEXT_RESOLVED_CALL, loopRange]
val isSuspend = listOf(iteratorResolvedCall, hasNextResolvedCall, nextResolvedCall)
.any { it?.resultingDescriptor?.isSuspend == true }
if (isSuspend) {
return SuspendCallKind.Iteration(expression)
}
}
expression is KtProperty && expression.hasDelegateExpression() -> {
val variableDescriptor = bindingContext[DECLARATION_TO_DESCRIPTOR, expression] as? VariableDescriptorWithAccessors
val accessors = variableDescriptor?.accessors ?: emptyList()
val isSuspend = accessors.any { accessor ->
val delegatedFunctionDescriptor = bindingContext[DELEGATED_PROPERTY_RESOLVED_CALL, accessor]?.resultingDescriptor
delegatedFunctionDescriptor?.isSuspend == true
}
if (isSuspend) {
return SuspendCallKind.PropertyDelegateCall(expression)
}
}
expression is KtCallExpression -> {
val resolvedCall = expression.getResolvedCall(bindingContext)
if (resolvedCall != null && isSuspend(resolvedCall)) {
return SuspendCallKind.FunctionCall(expression)
}
}
expression is KtOperationReferenceExpression -> {
val resolvedCall = expression.getResolvedCall(bindingContext)
if (resolvedCall != null && isSuspend(resolvedCall)) {
return SuspendCallKind.NameCall(expression)
}
}
expression is KtNameReferenceExpression -> {
val resolvedCall = expression.getResolvedCall(bindingContext)
// Function calls should be handled by KtCallExpression branch
if (resolvedCall != null && resolvedCall.resultingDescriptor !is FunctionDescriptor && isSuspend(resolvedCall)) {
return SuspendCallKind.NameCall(expression)
}
}
}
return null
}
| apache-2.0 | 76457cfc5299d08f7f2875780f83dce8 | 44.914634 | 158 | 0.72085 | 5.5902 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/sdk/HaskellSdkConfigurableForm.kt | 1 | 2458 | package org.jetbrains.haskell.sdk
import javax.swing.*
import java.awt.GridBagLayout
import org.jetbrains.haskell.util.*
import java.awt.GridBagConstraints
import java.awt.Insets
import com.intellij.ui.DocumentAdapter
import javax.swing.event.DocumentEvent
import com.intellij.openapi.ui.TextFieldWithBrowseButton
class HaskellSdkConfigurableForm {
var isModified: Boolean = false
private val ghciPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton()
private val ghcpkgPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton()
private val cabalPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton()
fun getContentPanel(): JComponent {
val panel = JPanel(GridBagLayout())
val listener : DocumentAdapter = object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent?) {
isModified = true
}
}
ghciPathField.textField.document.addDocumentListener(listener)
ghcpkgPathField.textField.document.addDocumentListener(listener)
cabalPathField.textField.document.addDocumentListener(listener)
addLine(panel, 0, "ghci", ghciPathField)
addLine(panel, 1, "ghc-pkg", ghcpkgPathField)
addLine(panel, 2, "cabal", cabalPathField)
return panel
}
private fun addLine(panel: JPanel, y: Int, label: String, textField: TextFieldWithBrowseButton) {
val base = gridBagConstraints {
insets = Insets(2, 0, 2, 3)
gridy = y
}
panel.add(JLabel(label), base.setConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0
})
panel.add(textField, base.setConstraints {
gridx = 1
fill = GridBagConstraints.HORIZONTAL
weightx = 1.0
})
panel.add(Box.createHorizontalStrut(1), base.setConstraints {
gridx = 2
weightx = 0.1
})
}
fun getCabalPath(): String {
return cabalPathField.text
}
fun getGhciPath(): String {
return ghciPathField.text
}
fun getGhcpkgPath(): String {
return ghcpkgPathField.text
}
fun init(ghciPath : String,
ghcpkgPath : String,
cabalPath : String): Unit {
ghciPathField.text = ghciPath
ghcpkgPathField.text = ghcpkgPath
cabalPathField.text = cabalPath
}
}
| apache-2.0 | 84cb4e4e849b54d00d01d407c81991f6 | 26.617978 | 101 | 0.650936 | 4.782101 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/HeartRateVariabilityDifferentialIndexRecord.kt | 3 | 2161 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures user's heart rate variability (HRV) measured as the difference between the widths of the
* histogram of differences between adjacent heart beats measured at selected heights.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class HeartRateVariabilityDifferentialIndexRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/** Heart rate variability in milliseconds. Required field. */
public val heartRateVariabilityMillis: Double,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HeartRateVariabilityDifferentialIndexRecord) return false
if (heartRateVariabilityMillis != other.heartRateVariabilityMillis) return false
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = 0
result = 31 * result + heartRateVariabilityMillis.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
}
| apache-2.0 | d77c4fdc5e31a4d696428170e935b7f8 | 36.912281 | 100 | 0.719112 | 4.56871 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentTest.kt | 3 | 12796 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import android.app.Instrumentation
import android.os.Bundle
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.annotation.RequiresApi
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.test.R
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.waitForExecution
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
/**
* Miscellaneous tests for fragments that aren't big enough to belong to their own classes.
*/
@RunWith(AndroidJUnit4::class)
class FragmentTest {
@Suppress("DEPRECATION")
var activityRule = androidx.test.rule.ActivityTestRule(FragmentTestActivity::class.java)
// Detect leaks BEFORE and AFTER activity is destroyed
@get:Rule
val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess())
.around(activityRule)
private lateinit var instrumentation: Instrumentation
@Before
fun setup() {
instrumentation = InstrumentationRegistry.getInstrumentation()
}
@SmallTest
@UiThreadTest
@Test
fun testRequireView() {
val activity = activityRule.activity
val fragment1 = StrictViewFragment()
activity.supportFragmentManager.beginTransaction().add(R.id.content, fragment1).commitNow()
assertThat(fragment1.requireView()).isNotNull()
}
@SmallTest
@UiThreadTest
@Test(expected = IllegalStateException::class)
fun testRequireViewWithoutView() {
val activity = activityRule.activity
val fragment1 = StrictFragment()
activity.supportFragmentManager.beginTransaction().add(fragment1, "fragment").commitNow()
fragment1.requireView()
}
@SmallTest
@UiThreadTest
@Test
fun testOnCreateOrder() {
val activity = activityRule.activity
val fragment1 = OrderFragment()
val fragment2 = OrderFragment()
activity.supportFragmentManager.beginTransaction()
.add(R.id.content, fragment1)
.add(R.id.content, fragment2)
.commitNow()
assertThat(fragment1.createOrder).isEqualTo(0)
assertThat(fragment2.createOrder).isEqualTo(1)
}
@LargeTest
@Test
@SdkSuppress(minSdkVersion = 16) // waitForHalfFadeIn requires API 16
fun testChildFragmentManagerGone() {
val activity = activityRule.activity
val fragmentA = FragmentA()
val fragmentB = FragmentB()
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.add(R.id.content, fragmentA)
.commitNow()
}
instrumentation.waitForIdleSync()
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.long_fade_in, R.anim.long_fade_out,
R.anim.long_fade_in, R.anim.long_fade_out
)
.replace(R.id.content, fragmentB)
.addToBackStack(null)
.commit()
}
// Wait for the middle of the animation
waitForHalfFadeIn(fragmentB)
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.long_fade_in, R.anim.long_fade_out,
R.anim.long_fade_in, R.anim.long_fade_out
)
.replace(R.id.content, fragmentA)
.addToBackStack(null)
.commit()
}
// Wait for the middle of the animation
waitForHalfFadeIn(fragmentA)
activityRule.popBackStackImmediate()
// Wait for the middle of the animation
waitForHalfFadeIn(fragmentB)
activityRule.popBackStackImmediate()
}
@LargeTest
@Test
@SdkSuppress(minSdkVersion = 16) // waitForHalfFadeIn requires API 16
fun testRemoveUnrelatedDuringAnimation() {
val activity = activityRule.activity
val unrelatedFragment = StrictFragment()
val fragmentA = FragmentA()
val fragmentB = FragmentB()
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.add(unrelatedFragment, "unrelated")
.commitNow()
activity.supportFragmentManager.beginTransaction()
.add(R.id.content, fragmentA)
.commitNow()
}
instrumentation.waitForIdleSync()
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.long_fade_in, R.anim.long_fade_out,
R.anim.long_fade_in, R.anim.long_fade_out
)
.replace(R.id.content, fragmentB)
.addToBackStack(null)
.commit()
}
// Wait for the middle of the animation
waitForHalfFadeIn(fragmentB)
assertThat(unrelatedFragment.calledOnResume).isTrue()
activityRule.runOnUiThread {
activity.supportFragmentManager.beginTransaction()
.remove(unrelatedFragment)
.commit()
}
instrumentation.waitForIdleSync()
assertThat(unrelatedFragment.calledOnDestroy).isTrue()
}
@SmallTest
@Test
fun testChildFragmentManagerNotAttached() {
val fragment = Fragment()
try {
fragment.childFragmentManager
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment has not been attached yet.")
}
}
@RequiresApi(16) // ViewTreeObserver.OnDrawListener was added in API 16
private fun waitForHalfFadeIn(fragment: Fragment) {
if (fragment.view == null) {
activityRule.waitForExecution()
}
val view = fragment.requireView()
val animation = view.animation
if (animation == null || animation.hasEnded()) {
// animation has already completed
return
}
val startTime = animation.startTime
if (view.drawingTime > animation.startTime) {
return // We've already done at least one frame
}
val latch = CountDownLatch(1)
val viewTreeObserver = view.viewTreeObserver
val listener = object : ViewTreeObserver.OnDrawListener {
override fun onDraw() {
if (animation.hasEnded() || view.drawingTime > startTime) {
val onDrawListener = this
latch.countDown()
view.post { viewTreeObserver.removeOnDrawListener(onDrawListener) }
}
}
}
viewTreeObserver.addOnDrawListener(listener)
latch.await(5, TimeUnit.SECONDS)
}
@MediumTest
@UiThreadTest
@Test
fun testViewOrder() {
val activity = activityRule.activity
val fragmentA = FragmentA()
val fragmentB = FragmentB()
val fragmentC = FragmentC()
activity.supportFragmentManager
.beginTransaction()
.add(R.id.content, fragmentA)
.add(R.id.content, fragmentB)
.add(R.id.content, fragmentC)
.commitNow()
val content = activity.findViewById(R.id.content) as ViewGroup
assertChildren(content, fragmentA, fragmentB, fragmentC)
}
@SmallTest
@UiThreadTest
@Test
fun testRequireParentFragment() {
val activity = activityRule.activity
val parentFragment = StrictFragment()
activity.supportFragmentManager.beginTransaction().add(parentFragment, "parent").commitNow()
val childFragmentManager = parentFragment.childFragmentManager
val childFragment = StrictFragment()
childFragmentManager.beginTransaction().add(childFragment, "child").commitNow()
assertThat(childFragment.requireParentFragment()).isSameInstanceAs(parentFragment)
}
@Suppress("DEPRECATION") // needed for requireFragmentManager()
@SmallTest
@Test
fun requireMethodsThrowsWhenNotAttached() {
val fragment = Fragment()
try {
fragment.requireContext()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment not attached to a context.")
}
try {
fragment.requireActivity()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment not attached to an activity.")
}
try {
fragment.requireHost()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment not attached to a host.")
}
try {
fragment.requireParentFragment()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment is not attached to any Fragment or host")
}
try {
fragment.requireView()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains(
"Fragment $fragment did not return a View from onCreateView() or this was " +
"called before onCreateView()."
)
}
try {
fragment.requireFragmentManager()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment not associated with a fragment manager.")
}
try {
fragment.parentFragmentManager
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment not associated with a fragment manager.")
}
}
@SmallTest
@Test
fun requireArguments() {
val fragment = Fragment()
try {
fragment.requireArguments()
fail()
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Fragment $fragment does not have any arguments.")
}
val arguments = Bundle()
fragment.arguments = arguments
assertWithMessage("requireArguments should return the arguments")
.that(fragment.requireArguments())
.isSameInstanceAs(arguments)
}
class OrderFragment : Fragment() {
var createOrder = -1
override fun onCreate(savedInstanceState: Bundle?) {
createOrder = order.getAndIncrement()
super.onCreate(savedInstanceState)
}
companion object {
private val order = AtomicInteger()
}
}
class FragmentA : Fragment(R.layout.fragment_a)
class FragmentB : Fragment(R.layout.fragment_b)
class FragmentC : Fragment(R.layout.fragment_c)
}
| apache-2.0 | 744ca5572de30e21239742011fb0d5f6 | 33.031915 | 100 | 0.626524 | 5.302942 | false | true | false | false |
GunoH/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncEvents.kt | 2 | 2277 | package com.intellij.settingsSync
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.EventDispatcher
import java.util.*
internal class SettingsSyncEvents : Disposable {
private val settingsChangeDispatcher = EventDispatcher.create(SettingsChangeListener::class.java)
private val enabledStateChangeDispatcher = EventDispatcher.create(SettingsSyncEnabledStateListener::class.java)
private val categoriesChangeDispatcher = EventDispatcher.create(SettingsSyncCategoriesChangeListener::class.java)
fun addSettingsChangedListener(settingsChangeListener: SettingsChangeListener) {
settingsChangeDispatcher.addListener(settingsChangeListener)
}
fun removeSettingsChangedListener(settingsChangeListener: SettingsChangeListener) {
settingsChangeDispatcher.removeListener(settingsChangeListener)
}
fun fireSettingsChanged(event: SyncSettingsEvent) {
settingsChangeDispatcher.multicaster.settingChanged(event)
}
fun addCategoriesChangeListener(categoriesChangeListener: SettingsSyncCategoriesChangeListener) {
categoriesChangeDispatcher.addListener(categoriesChangeListener)
}
fun removeCategoriesChangeListener(categoriesChangeListener: SettingsSyncCategoriesChangeListener) {
categoriesChangeDispatcher.removeListener(categoriesChangeListener)
}
fun fireCategoriesChanged() {
categoriesChangeDispatcher.multicaster.categoriesStateChanged()
}
fun addEnabledStateChangeListener(listener: SettingsSyncEnabledStateListener, parentDisposable: Disposable? = null) {
if (parentDisposable != null) enabledStateChangeDispatcher.addListener(listener, parentDisposable)
else enabledStateChangeDispatcher.addListener(listener, this)
}
fun fireEnabledStateChanged(syncEnabled: Boolean) {
enabledStateChangeDispatcher.multicaster.enabledStateChanged(syncEnabled)
}
companion object {
fun getInstance(): SettingsSyncEvents = ApplicationManager.getApplication().getService(SettingsSyncEvents::class.java)
}
override fun dispose() {
settingsChangeDispatcher.listeners.clear()
enabledStateChangeDispatcher.listeners.clear()
}
}
interface SettingsSyncCategoriesChangeListener : EventListener {
fun categoriesStateChanged()
} | apache-2.0 | 6a60b2a98819625b87f21ddd6a5dfcfe | 37.610169 | 122 | 0.835749 | 5.764557 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/PluginDeclarationProviderFactory.kt | 4 | 7456 | // 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.stubindex.resolve
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.idea.caches.PerModulePackageCacheService
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.caches.project.projectSourceModules
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.lazy.data.KtClassLikeInfo
import org.jetbrains.kotlin.resolve.lazy.declarations.*
import org.jetbrains.kotlin.storage.StorageManager
class PluginDeclarationProviderFactory(
private val project: Project,
private val indexedFilesScope: GlobalSearchScope,
private val storageManager: StorageManager,
private val nonIndexedFiles: Collection<KtFile>,
private val moduleInfo: ModuleInfo
) : AbstractDeclarationProviderFactory(storageManager) {
private val fileBasedDeclarationProviderFactory = FileBasedDeclarationProviderFactory(storageManager, nonIndexedFiles)
override fun getClassMemberDeclarationProvider(classLikeInfo: KtClassLikeInfo): ClassMemberDeclarationProvider {
return PsiBasedClassMemberDeclarationProvider(storageManager, classLikeInfo)
}
override fun createPackageMemberDeclarationProvider(name: FqName): PackageMemberDeclarationProvider? {
val fileBasedProvider = fileBasedDeclarationProviderFactory.getPackageMemberDeclarationProvider(name)
val stubBasedProvider = getStubBasedPackageMemberDeclarationProvider(name)
return when {
fileBasedProvider == null && stubBasedProvider == null -> null
fileBasedProvider == null -> stubBasedProvider
stubBasedProvider == null -> fileBasedProvider
else -> CombinedPackageMemberDeclarationProvider(listOf(stubBasedProvider, fileBasedProvider))
}
}
override fun packageExists(fqName: FqName) =
fileBasedDeclarationProviderFactory.packageExists(fqName) || stubBasedPackageExists(fqName)
private fun stubBasedPackageExists(name: FqName): Boolean {
// We're only looking for source-based declarations
return (moduleInfo as? IdeaModuleInfo)?.projectSourceModules()
?.any { PerModulePackageCacheService.getInstance(project).packageExists(name, it) }
?: false
}
private fun getStubBasedPackageMemberDeclarationProvider(name: FqName): PackageMemberDeclarationProvider? {
if (!stubBasedPackageExists(name)) return null
return StubBasedPackageMemberDeclarationProvider(name, project, indexedFilesScope)
}
private fun diagnoseMissingPackageFragmentPartialPackageIndexCorruption(message: String): Nothing {
throw IllegalStateException("KotlinPartialPackageNamesIndex seems corrupted.\n$message")
}
private fun diagnoseMissingPackageFragmentPerModulePackageCacheMiss(message: String): Nothing {
PerModulePackageCacheService.getInstance(project).onTooComplexChange() // Postpone cache rebuild
throw IllegalStateException("PerModulePackageCache miss.\n$message")
}
private fun diagnoseMissingPackageFragmentUnknownReason(message: String): Nothing {
throw IllegalStateException(message)
}
override fun diagnoseMissingPackageFragment(fqName: FqName, file: KtFile?) {
val moduleSourceInfo = moduleInfo as? ModuleSourceInfo
val packageExists = KotlinPackageIndexUtils.packageExists(fqName, indexedFilesScope)
val spiPackageExists = KotlinPackageIndexUtils.packageExists(fqName, project)
val oldPackageExists = oldPackageExists(fqName)
val cachedPackageExists =
moduleSourceInfo?.let { project.service<PerModulePackageCacheService>().packageExists(fqName, it) }
val moduleModificationCount = moduleSourceInfo?.createModificationTracker()?.modificationCount
val common = """
packageExists = $packageExists, cachedPackageExists = $cachedPackageExists,
oldPackageExists = $oldPackageExists,
SPI.packageExists = $spiPackageExists,
OOCB count = ${KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker.modificationCount}
moduleModificationCount = $moduleModificationCount
""".trimIndent()
val message = if (file != null) {
val virtualFile = file.virtualFile
val inScope = virtualFile in indexedFilesScope
val packageFqName = file.packageFqName
"""
|Cannot find package fragment '$fqName' for file ${file.name}, file package = '$packageFqName':
|vFile: $virtualFile,
|nonIndexedFiles = $nonIndexedFiles, isNonIndexed = ${file in nonIndexedFiles},
|scope = $indexedFilesScope, isInScope = $inScope,
|$common,
|packageFqNameByTree = '${file.packageFqNameByTree}', packageDirectiveText = '${file.packageDirective?.text}'
""".trimMargin()
} else {
"""
|Cannot find package fragment '$fqName' for unspecified file:
|nonIndexedFiles = $nonIndexedFiles,
|scope = $indexedFilesScope,
|$common
""".trimMargin()
}
val scopeNotEmptyAndContainsFile =
!GlobalSearchScope.isEmptyScope(indexedFilesScope) && (file == null || file.virtualFile in indexedFilesScope)
when {
scopeNotEmptyAndContainsFile
&& !packageExists && !oldPackageExists -> diagnoseMissingPackageFragmentPartialPackageIndexCorruption(message)
scopeNotEmptyAndContainsFile
&& packageExists && cachedPackageExists == false -> diagnoseMissingPackageFragmentPerModulePackageCacheMiss(message)
else -> diagnoseMissingPackageFragmentUnknownReason(message)
}
}
// trying to diagnose org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException in completion
private val onCreationDebugInfo = debugInfo()
fun debugToString(): String {
return arrayOf("PluginDeclarationProviderFactory", "On failure:", debugInfo(), "On creation:", onCreationDebugInfo,
"moduleInfo:$moduleInfo.name", "moduleInfo dependencies: ${moduleInfo.dependencies()}").joinToString("\n")
}
private fun oldPackageExists(packageFqName: FqName): Boolean =
KotlinPackageIndexUtils.packageExists(packageFqName, indexedFilesScope)
private fun debugInfo(): String {
if (nonIndexedFiles.isEmpty()) return "-no synthetic files-\n"
return buildString {
nonIndexedFiles.forEach {
append(it.name)
append(" isPhysical=${it.isPhysical}")
append(" modStamp=${it.modificationStamp}")
appendLine()
}
}
}
}
| apache-2.0 | 37d30289b9f510b50389a8d5466205f6 | 49.378378 | 158 | 0.722371 | 5.446311 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/repl/src/org/jetbrains/kotlin/console/CommandHistory.kt | 4 | 1028 | // 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.console
import com.intellij.openapi.util.TextRange
class CommandHistory {
class Entry(
val entryText: String,
val rangeInHistoryDocument: TextRange
)
private val entries = arrayListOf<Entry>()
var processedEntriesCount: Int = 0
private set
val listeners = arrayListOf<HistoryUpdateListener>()
operator fun get(i: Int) = entries[i]
fun addEntry(entry: Entry) {
entries.add(entry)
listeners.forEach { it.onNewEntry(entry) }
}
fun lastUnprocessedEntry(): Entry? = if (processedEntriesCount < size) {
get(processedEntriesCount)
} else {
null
}
fun entryProcessed() {
processedEntriesCount++
}
val size: Int get() = entries.size
}
interface HistoryUpdateListener {
fun onNewEntry(entry: CommandHistory.Entry)
} | apache-2.0 | ab6011c236b22b6ef362be8710adf099 | 24.097561 | 158 | 0.679961 | 4.26556 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/KotlinNameSuggestionProvider.kt | 7 | 3725 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.codeInsight
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiVariable
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.SuggestedNameInfo
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.statistics.JavaStatisticsManager
import com.intellij.refactoring.rename.NameSuggestionProvider
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.core.AbstractKotlinNameSuggester
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
abstract class KotlinNameSuggestionProvider<Validator : (String) -> Boolean> : NameSuggestionProvider {
abstract val nameSuggester: AbstractKotlinNameSuggester
enum class ValidatorTarget {
PROPERTY,
PARAMETER,
VARIABLE,
FUNCTION,
CLASS
}
override fun getSuggestedNames(element: PsiElement, nameSuggestionContext: PsiElement?, result: MutableSet<String>): SuggestedNameInfo? {
if (element is KtCallableDeclaration) {
val context = nameSuggestionContext ?: element.parent
val target = getValidatorTarget(element)
val validator = createNameValidator(context, element, target, listOf(element))
val names = SmartList<String>().apply {
val name = element.name
if (!name.isNullOrBlank()) {
this += nameSuggester.getCamelNames(name, validator, name.first().isLowerCase())
}
this += getReturnTypeNames(element, validator)
}
result += names
if (element is KtProperty && element.isLocal) {
for (ref in ReferencesSearch.search(element, LocalSearchScope(element.parent))) {
val refExpr = ref.element as? KtSimpleNameExpression ?: continue
val argument = refExpr.parent as? KtValueArgument ?: continue
result += getNameForArgument(argument) ?: continue
}
}
return object : SuggestedNameInfo(names.toTypedArray()) {
override fun nameChosen(name: String?) {
val psiVariable = element.toLightElements().firstIsInstanceOrNull<PsiVariable>() ?: return
JavaStatisticsManager.incVariableNameUseCount(
name,
JavaCodeStyleManager.getInstance(element.project).getVariableKind(psiVariable),
psiVariable.name,
psiVariable.type
)
}
}
}
return null
}
private fun getValidatorTarget(element: PsiElement): ValidatorTarget {
return when (element) {
is KtProperty -> if (element.isLocal) ValidatorTarget.VARIABLE else ValidatorTarget.PROPERTY
is KtParameter -> ValidatorTarget.PARAMETER
is KtFunction -> ValidatorTarget.FUNCTION
else -> ValidatorTarget.CLASS
}
}
protected abstract fun createNameValidator(
container: PsiElement,
anchor: PsiElement?,
target: ValidatorTarget,
excludedDeclarations: List<KtDeclaration>
): Validator
protected abstract fun getReturnTypeNames(callable: KtCallableDeclaration, validator: Validator): List<String>
protected abstract fun getNameForArgument(argument: KtValueArgument): String?
} | apache-2.0 | dc22021c6fd5044118ec0dbe27769bac | 42.325581 | 141 | 0.668993 | 5.593093 | false | false | false | false |
idea4bsd/idea4bsd | plugins/git4idea/tests/git4idea/rebase/GitMultiRepoRebaseTest.kt | 5 | 9353 | /*
* 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 git4idea.rebase
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vcs.Executor
import com.intellij.openapi.vcs.Executor.mkdir
import com.intellij.openapi.vcs.Executor.touch
import git4idea.branch.GitBranchUiHandler
import git4idea.branch.GitBranchWorker
import git4idea.branch.GitRebaseParams
import git4idea.repo.GitRepository
import git4idea.test.GitExecutor.git
import git4idea.test.GitTestUtil.cleanupForAssertion
import git4idea.test.UNKNOWN_ERROR_TEXT
import org.mockito.Mockito
import kotlin.properties.Delegates
class GitMultiRepoRebaseTest : GitRebaseBaseTest() {
private var myUltimate: GitRepository by Delegates.notNull()
private var myCommunity: GitRepository by Delegates.notNull()
private var myContrib: GitRepository by Delegates.notNull()
private var myAllRepositories: List<GitRepository> by Delegates.notNull()
override fun setUp() {
super.setUp()
Executor.cd(myProjectRoot)
val community = mkdir("community")
val contrib = mkdir("contrib")
myUltimate = createRepository(myProjectPath)
myCommunity = createRepository(community.path)
myContrib = createRepository(contrib.path)
myAllRepositories = listOf(myUltimate, myCommunity, myContrib)
Executor.cd(myProjectRoot)
touch(".gitignore", "community\ncontrib")
git("add .gitignore")
git("commit -m gitignore")
}
fun `test all successful`() {
myUltimate.`place feature above master`()
myCommunity.`diverge feature and master`()
myContrib.`place feature on master`()
rebase("master")
assertSuccessfulRebaseNotification("Rebased feature on master")
assertAllRebased()
assertNoRebaseInProgress(myAllRepositories)
}
fun `test abort from critical error during rebasing 2nd root, before any commits were applied`() {
val localChange = LocalChange(myUltimate, "new.txt", "Some content")
`fail with critical error while rebasing 2nd root`(localChange)
assertErrorNotification("Rebase Failed",
"""
community: $UNKNOWN_ERROR_TEXT <br/>
You can <a>retry</a> or <a>abort</a> rebase.
$LOCAL_CHANGES_WARNING
""")
myUltimate.`assert feature rebased on master`()
myCommunity.`assert feature not rebased on master`()
myContrib.`assert feature not rebased on master`()
assertNoRebaseInProgress(myAllRepositories)
myUltimate.assertNoLocalChanges()
var confirmation: String? = null
myDialogManager.onMessage {
confirmation = it
Messages.YES;
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want to rollback the successful rebase in project?"),
cleanupForAssertion(confirmation!!));
assertNoRebaseInProgress(myAllRepositories)
myAllRepositories.forEach { it.`assert feature not rebased on master`() }
localChange.verify()
}
fun `test abort from critical error while rebasing 2nd root, after some commits were applied`() {
val localChange = LocalChange(myUltimate, "new.txt", "Some content")
`fail with critical error while rebasing 2nd root after some commits are applied`(localChange)
myVcsNotifier.lastNotification
var confirmation: String? = null
myDialogManager.onMessage {
confirmation = it
Messages.YES;
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want just to abort rebase in community, or also rollback the successful rebase in project?"),
cleanupForAssertion(confirmation!!));
assertNoRebaseInProgress(myAllRepositories)
myAllRepositories.forEach { it.`assert feature not rebased on master`() }
localChange.verify()
}
fun `test conflicts in multiple repositories are resolved separately`() {
myUltimate.`prepare simple conflict`()
myCommunity.`prepare simple conflict`()
myContrib.`diverge feature and master`()
var facedConflictInUltimate = false
var facedConflictInCommunity = false
myVcsHelper.onMerge({
assertFalse(facedConflictInCommunity && facedConflictInUltimate)
if (myUltimate.hasConflict("c.txt")) {
assertFalse(facedConflictInUltimate)
facedConflictInUltimate = true
assertNoRebaseInProgress(myCommunity)
resolveConflicts(myUltimate)
}
else if (myCommunity.hasConflict("c.txt")) {
assertFalse(facedConflictInCommunity)
facedConflictInCommunity = true
assertNoRebaseInProgress(myUltimate)
resolveConflicts(myCommunity)
}
})
rebase("master")
assertTrue(facedConflictInUltimate)
assertTrue(facedConflictInCommunity)
myAllRepositories.forEach {
it.`assert feature rebased on master`()
assertNoRebaseInProgress(it)
it.assertNoLocalChanges()
}
}
fun `test retry doesn't touch successful repositories`() {
`fail with critical error while rebasing 2nd root`()
GitRebaseUtils.continueRebase(myProject)
assertSuccessfulRebaseNotification("Rebased feature on master")
assertAllRebased()
assertNoRebaseInProgress(myAllRepositories)
}
public fun `test continue rebase shouldn't attempt to stash`() {
myUltimate.`diverge feature and master`()
myCommunity.`prepare simple conflict`()
myContrib.`diverge feature and master`()
`do nothing on merge`()
rebase("master")
GitRebaseUtils.continueRebase(myProject)
`assert conflict not resolved notification`()
assertNotRebased("feature", "master", myCommunity)
}
public fun `test continue rebase with unresolved conflicts should show merge dialog`() {
myUltimate.`diverge feature and master`()
myCommunity.`prepare simple conflict`()
myContrib.`diverge feature and master`()
`do nothing on merge`()
rebase("master")
var mergeDialogShown = false
myVcsHelper.onMerge {
mergeDialogShown = true
resolveConflicts(myCommunity)
}
GitRebaseUtils.continueRebase(myProject)
assertTrue("Merge dialog was not shown", mergeDialogShown)
assertAllRebased()
}
fun `test rollback if checkout with rebase fails on 2nd root`() {
myAllRepositories.forEach {
it.`diverge feature and master`()
git(it, "checkout master")
}
myGit.setShouldRebaseFail { it == myCommunity }
val uiHandler = Mockito.mock(GitBranchUiHandler::class.java)
Mockito.`when`(uiHandler.progressIndicator).thenReturn(EmptyProgressIndicator())
try {
GitBranchWorker(myProject, myGit, uiHandler).rebaseOnCurrent(myAllRepositories, "feature")
}
finally {
myGit.setShouldRebaseFail { false }
}
var confirmation: String? = null
myDialogManager.onMessage {
confirmation = it
Messages.YES;
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want to rollback the successful rebase in project?"),
cleanupForAssertion(confirmation!!));
assertNoRebaseInProgress(myAllRepositories)
myAllRepositories.forEach {
it.`assert feature not rebased on master`()
assertEquals("Incorrect current branch", "master", it.currentBranchName) }
}
private fun `fail with critical error while rebasing 2nd root`(localChange: LocalChange? = null) {
myAllRepositories.forEach { it.`diverge feature and master`() }
localChange?.generate()
myGit.setShouldRebaseFail { it == myCommunity }
try {
rebase("master")
}
finally {
myGit.setShouldRebaseFail { false }
}
}
private fun `fail with critical error while rebasing 2nd root after some commits are applied`(localChange: LocalChange? = null) {
myUltimate.`diverge feature and master`()
myCommunity.`make rebase fail on 2nd commit`()
myContrib.`diverge feature and master`()
localChange?.generate()
try {
rebase("master")
}
finally {
myGit.setShouldRebaseFail { false }
}
}
private fun rebase(onto: String) {
GitTestingRebaseProcess(myProject, GitRebaseParams(onto), myAllRepositories).rebase()
}
private fun abortOngoingRebase() {
GitRebaseUtils.abort(myProject, EmptyProgressIndicator())
}
private fun assertAllRebased() {
assertRebased(myUltimate, "feature", "master")
assertRebased(myCommunity, "feature", "master")
assertRebased(myContrib, "feature", "master")
}
}
| apache-2.0 | 1c362c5a2c225d8bf897f50800c20158 | 32.523297 | 138 | 0.720624 | 4.878978 | false | true | false | false |
idea4bsd/idea4bsd | plugins/settings-repository/src/git/GitRepositoryManager.kt | 3 | 10620 | /*
* 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.settingsRepository.git
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.SmartList
import com.intellij.util.io.*
import com.intellij.util.text.nullize
import org.eclipse.jgit.api.AddCommand
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.api.errors.UnmergedPathsException
import org.eclipse.jgit.errors.TransportException
import org.eclipse.jgit.ignore.IgnoreNode
import org.eclipse.jgit.lib.ConfigConstants
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.RepositoryState
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.transport.*
import org.jetbrains.settingsRepository.*
import org.jetbrains.settingsRepository.RepositoryManager.Updater
import java.io.IOException
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Path
import kotlin.concurrent.write
class GitRepositoryManager(private val credentialsStore: Lazy<IcsCredentialsStore>, dir: Path) : BaseRepositoryManager(dir) {
val repository: Repository
get() {
var r = _repository
if (r == null) {
r = FileRepositoryBuilder().setWorkTree(dir.toFile()).build()
_repository = r
if (ApplicationManager.getApplication()?.isUnitTestMode != true) {
ShutDownTracker.getInstance().registerShutdownTask { _repository?.close() }
}
}
return r!!
}
// we must recreate repository if dir changed because repository stores old state and cannot be reinitialized (so, old instance cannot be reused and we must instantiate new one)
var _repository: Repository? = null
val credentialsProvider: CredentialsProvider by lazy {
JGitCredentialsProvider(credentialsStore, repository)
}
private var ignoreRules: IgnoreNode? = null
override fun createRepositoryIfNeed(): Boolean {
ignoreRules = null
if (isRepositoryExists()) {
return false
}
repository.create()
repository.disableAutoCrLf()
return true
}
override fun deleteRepository() {
ignoreRules = null
super.deleteRepository()
val r = _repository
if (r != null) {
_repository = null
r.close()
}
}
override fun getUpstream(): String? {
return repository.config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL).nullize()
}
override fun setUpstream(url: String?, branch: String?) {
repository.setUpstream(url, branch ?: Constants.MASTER)
}
override fun isRepositoryExists(): Boolean {
val repo = _repository
if (repo == null) {
return dir.exists() && FileRepositoryBuilder().setWorkTree(dir.toFile()).setup().objectDirectory.exists()
}
else {
return repo.objectDatabase.exists()
}
}
override fun hasUpstream() = getUpstream() != null
override fun addToIndex(file: Path, path: String, content: ByteArray, size: Int) {
repository.edit(AddLoadedFile(path, content, size, file.lastModified().toMillis()))
}
override fun deleteFromIndex(path: String, isFile: Boolean) {
repository.deletePath(path, isFile, false)
}
override fun commit(indicator: ProgressIndicator?, syncType: SyncType?, fixStateIfCannotCommit: Boolean): Boolean {
lock.write {
try {
// will be reset if OVERWRITE_LOCAL, so, we should not fix state in this case
return commitIfCan(indicator, if (!fixStateIfCannotCommit || syncType == SyncType.OVERWRITE_LOCAL) repository.repositoryState else repository.fixAndGetState())
}
catch (e: UnmergedPathsException) {
if (syncType == SyncType.OVERWRITE_LOCAL) {
LOG.warn("Unmerged detected, ignored because sync type is OVERWRITE_LOCAL", e)
return false
}
else {
indicator?.checkCanceled()
LOG.warn("Unmerged detected, will be attempted to resolve", e)
resolveUnmergedConflicts(repository)
indicator?.checkCanceled()
return commitIfCan(indicator, repository.fixAndGetState())
}
}
catch (e: NoHeadException) {
LOG.warn("Cannot commit - no HEAD", e)
return false
}
}
}
private fun commitIfCan(indicator: ProgressIndicator?, state: RepositoryState): Boolean {
if (state.canCommit()) {
return commit(repository, indicator)
}
else {
LOG.warn("Cannot commit, repository in state ${state.description}")
return false
}
}
override fun getAheadCommitsCount() = repository.getAheadCommitsCount()
override fun commit(paths: List<String>) {
}
override fun push(indicator: ProgressIndicator?) {
LOG.debug("Push")
val refSpecs = SmartList(RemoteConfig(repository.config, Constants.DEFAULT_REMOTE_NAME).pushRefSpecs)
if (refSpecs.isEmpty()) {
val head = repository.findRef(Constants.HEAD)
if (head != null && head.isSymbolic) {
refSpecs.add(RefSpec(head.leaf.name))
}
}
val monitor = indicator.asProgressMonitor()
for (transport in Transport.openAll(repository, Constants.DEFAULT_REMOTE_NAME, Transport.Operation.PUSH)) {
for (attempt in 0..1) {
transport.credentialsProvider = credentialsProvider
try {
val result = transport.push(monitor, transport.findRemoteRefUpdatesFor(refSpecs))
if (LOG.isDebugEnabled) {
printMessages(result)
for (refUpdate in result.remoteUpdates) {
LOG.debug(refUpdate.toString())
}
}
break
}
catch (e: TransportException) {
if (e.status == TransportException.Status.NOT_PERMITTED) {
if (attempt == 0) {
credentialsProvider.reset(transport.uri)
}
else {
throw AuthenticationException(e)
}
}
else {
wrapIfNeedAndReThrow(e)
}
}
finally {
transport.close()
}
}
}
}
override fun fetch(indicator: ProgressIndicator?): Updater {
val pullTask = Pull(this, indicator ?: EmptyProgressIndicator())
val refToMerge = pullTask.fetch()
return object : Updater {
override var definitelySkipPush = false
// KT-8632
override fun merge(): UpdateResult? = lock.write {
val committed = commit(pullTask.indicator)
if (refToMerge == null) {
definitelySkipPush = !committed && getAheadCommitsCount() == 0
return null
}
return pullTask.pull(prefetchedRefToMerge = refToMerge)
}
}
}
override fun pull(indicator: ProgressIndicator?) = Pull(this, indicator).pull()
override fun resetToTheirs(indicator: ProgressIndicator) = Reset(this, indicator).reset(true)
override fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?) = Reset(this, indicator).reset(false, localRepositoryInitializer)
override fun canCommit() = repository.repositoryState.canCommit()
fun renameDirectory(pairs: Map<String, String?>, commitMessage: String): Boolean {
var addCommand: AddCommand? = null
val toDelete = SmartList<DeleteDirectory>()
for ((oldPath, newPath) in pairs) {
val old = dir.resolve(oldPath)
if (!old.exists()) {
continue
}
LOG.info("Rename $oldPath to $newPath")
old.directoryStreamIfExists {
val new = if (newPath == null) dir else dir.resolve(newPath)
for (file in it) {
LOG.catchAndLog {
if (file.isHidden()) {
file.delete()
}
else {
try {
file.move(new.resolve(file.fileName))
}
catch (ignored: FileAlreadyExistsException) {
return@catchAndLog
}
if (addCommand == null) {
addCommand = AddCommand(repository)
}
addCommand!!.addFilepattern(if (newPath == null) file.fileName.toString() else "$newPath/${file.fileName}")
}
}
}
toDelete.add(DeleteDirectory(oldPath))
}
LOG.catchAndLog {
old.delete()
}
}
if (toDelete.isEmpty() && addCommand == null) {
return false
}
repository.edit(toDelete)
if (addCommand != null) {
addCommand!!.call()
}
repository.commit(with(IdeaCommitMessageFormatter()) { StringBuilder().appendCommitOwnerInfo(true) }.append(commitMessage).toString())
return true
}
private fun getIgnoreRules(): IgnoreNode? {
var node = ignoreRules
if (node == null) {
val file = dir.resolve(Constants.DOT_GIT_IGNORE)
if (file.exists()) {
node = IgnoreNode()
file.inputStream().use { node!!.parse(it) }
ignoreRules = node
}
}
return node
}
override fun isPathIgnored(path: String): Boolean {
// add first slash as WorkingTreeIterator does "The ignore code wants path to start with a '/' if possible."
return getIgnoreRules()?.isIgnored("/$path", false) == IgnoreNode.MatchResult.IGNORED
}
}
fun printMessages(fetchResult: OperationResult) {
if (LOG.isDebugEnabled) {
val messages = fetchResult.messages
if (!StringUtil.isEmptyOrSpaces(messages)) {
LOG.debug(messages)
}
}
}
class GitRepositoryService : RepositoryService {
override fun isValidRepository(file: Path): Boolean {
if (file.resolve(Constants.DOT_GIT).exists()) {
return true
}
// existing bare repository
try {
FileRepositoryBuilder().setGitDir(file.toFile()).setMustExist(true).build()
}
catch (e: IOException) {
return false
}
return true
}
} | apache-2.0 | 68d641b61e3364b95bf17c109e33d49c | 31.184848 | 179 | 0.666667 | 4.494287 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingUtil.kt | 2 | 4480 | // 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.highlighter
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.caches.project.NotUnderContentRootModuleInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.util.isInDumbMode
import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.isRunningInCidrIde
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtFile
import kotlin.script.experimental.api.ScriptDiagnostic
object KotlinHighlightingUtil {
fun shouldHighlight(psiElement: PsiElement): Boolean {
val ktFile = psiElement.containingFile as? KtFile ?: return false
return shouldHighlightFile(ktFile)
}
fun shouldHighlightFile(ktFile: KtFile): Boolean {
if (ktFile is KtCodeFragment && ktFile.context != null) {
return true
}
if (ktFile.isCompiled) return false
if (OutsidersPsiFileSupportWrapper.isOutsiderFile(ktFile.virtualFile)) {
val origin = OutsidersPsiFileSupportUtils.getOutsiderFileOrigin(ktFile.project, ktFile.virtualFile) ?: return false
val psiFileOrigin = PsiManager.getInstance(ktFile.project).findFile(origin) ?: return false
return shouldHighlight(psiFileOrigin)
}
val shouldCheckScript = ktFile.shouldCheckScript()
if (shouldCheckScript == true) {
return shouldHighlightScript(ktFile)
}
return if (shouldCheckScript != null) ProjectRootsUtil.isInProjectOrLibraryContent(ktFile) && ktFile.getModuleInfo() !is NotUnderContentRootModuleInfo
else ProjectRootsUtil.isInContent(
element = ktFile,
includeProjectSource = true,
includeLibrarySource = true,
includeLibraryClasses = true,
includeScriptDependencies = true,
includeScriptsOutsideSourceRoots = true,
)
}
fun shouldHighlightErrors(ktFile: KtFile): Boolean {
if (ktFile.isCompiled) {
return false
}
if (ktFile is KtCodeFragment && ktFile.context != null) {
return true
}
val canCheckScript = ktFile.shouldCheckScript()
if (canCheckScript == true) {
return shouldHighlightScript(ktFile)
}
return ProjectRootsUtil.isInProjectSource(ktFile, includeScriptsOutsideSourceRoots = canCheckScript == null)
}
private fun KtFile.shouldCheckScript(): Boolean? = runReadAction {
when {
// to avoid SNRE from stub (KTIJ-7633)
project.isInDumbMode() -> null
isScript() -> true
else -> false
}
}
@Suppress("DEPRECATION")
private fun shouldHighlightScript(ktFile: KtFile): Boolean {
if (isRunningInCidrIde) return false // There is no Java support in CIDR. So do not highlight errors in KTS if running in CIDR.
if (!ScriptConfigurationManager.getInstance(ktFile.project).hasConfiguration(ktFile)) return false
if (IdeScriptReportSink.getReports(ktFile).any { it.severity == ScriptDiagnostic.Severity.FATAL }) {
return false
}
if (!ScriptDefinitionsManager.getInstance(ktFile.project).isReady()) return false
return ProjectRootsUtil.isInProjectSource(ktFile, includeScriptsOutsideSourceRoots = true)
}
fun hasCustomPropertyDeclaration(descriptor: PropertyDescriptor): Boolean {
var hasCustomPropertyDeclaration = false
if (!hasExtensionReceiverParameter(descriptor)) {
if (descriptor.getter?.isDefault == false || descriptor.setter?.isDefault == false)
hasCustomPropertyDeclaration = true
}
return hasCustomPropertyDeclaration
}
fun hasExtensionReceiverParameter(descriptor: PropertyDescriptor): Boolean {
return descriptor.extensionReceiverParameter != null
}
} | apache-2.0 | b1b3225fa051adaefabd5856daa96e9a | 40.878505 | 158 | 0.71183 | 5.16129 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/operations/FreakingJavaFXApplication.kt | 1 | 2433 | package alraune.operations
import javafx.application.Application
import javafx.application.Platform
import javafx.geometry.Insets
import javafx.scene.Scene
import javafx.scene.control.Label
import javafx.scene.control.Menu
import javafx.scene.control.MenuBar
import javafx.scene.control.SplitPane
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.stage.Stage
import javafx.stage.WindowEvent
import vgrechka.*
import kotlin.system.exitProcess
class FreakingJavaFXApplication : Application() {
companion object {
var the by once<FreakingJavaFXApplication>()
private var launched = false
private var onGUIThread by once<() -> Unit>()
fun launch(onGUIThread: () -> Unit) {
check(!launched)
launched = true
this.onGUIThread = onGUIThread
Application.launch(FreakingJavaFXApplication::class.java)
}
}
var primaryStage by once<Stage>()
override fun start(primaryStage: Stage) {
the = this
JFXPile.installUncaughtExceptionHandler_errorAlert()
this.primaryStage = primaryStage
Platform.setImplicitExit(false)
onGUIThread()
}
}
class FreakingWindow {
val stage = Stage()
var doMessAround: (() -> Unit)? = null
var mainSplitPane by once<SplitPane>()
var statusLabel by once<Label>()
fun assemble() {
val vbox = VBox()
vbox.children += MenuBar().also {o->
o.menus += Menu("_Tools").also {o->
doMessAround?.let {o.addItem("_Mess Around", it)}
o.addItem("Throw Something") {throw Exception("Something")}
}
}
mainSplitPane = SplitPane()
VBox.setVgrow(mainSplitPane, Priority.ALWAYS)
mainSplitPane.setDividerPosition(0, 0.4)
vbox.children += mainSplitPane
statusLabel = Label()
statusLabel.padding = Insets(5.0)
vbox.children += statusLabel
stage.scene = Scene(vbox).also {
// it.stylesheets.add(FreakingCommander::class.simpleName + ".css")
}
}
fun onClose_exitProcess() {
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN) {e->
exitProcess(0)
}
}
fun titleAndSize(title: String, width: Int, height: Int) {
stage.title = title
stage.width = width.toDouble()
stage.height = height.toDouble()
}
}
| apache-2.0 | b182e18aa38ba8b29595a1b35c2b6ee5 | 26.033333 | 79 | 0.642006 | 4.407609 | false | false | false | false |
JetBrains/kotlin-native | Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmTypes.kt | 1 | 8391 | /*
* Copyright 2010-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 kotlinx.cinterop
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.full.companionObjectInstance
typealias NativePtr = Long
internal typealias NonNullNativePtr = NativePtr
@PublishedApi internal fun NonNullNativePtr.toNativePtr() = this
internal fun NativePtr.toNonNull(): NonNullNativePtr = this
public val nativeNullPtr: NativePtr = 0L
// TODO: the functions below should eventually be intrinsified
@Suppress("DEPRECATION")
private val typeOfCache = ConcurrentHashMap<Class<*>, CVariable.Type>()
@Deprecated("Use sizeOf<T>() or alignOf<T>() instead.")
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
inline fun <reified T : CVariable> typeOf() =
@Suppress("DEPRECATION")
typeOfCache.computeIfAbsent(T::class.java) { T::class.companionObjectInstance as CVariable.Type }
/**
* Returns interpretation of entity with given pointer, or `null` if it is null.
*
* @param T must not be abstract
*/
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
inline fun <reified T : NativePointed> interpretNullablePointed(ptr: NativePtr): T? {
if (ptr == nativeNullPtr) {
return null
} else {
val result = nativeMemUtils.allocateInstance<T>()
result.rawPtr = ptr
return result
}
}
/**
* Creates a [CPointer] from the raw pointer of [NativePtr].
*
* @return a [CPointer] representation, or `null` if the [rawValue] represents native `nullptr`.
*/
fun <T : CPointed> interpretCPointer(rawValue: NativePtr) =
if (rawValue == nativeNullPtr) {
null
} else {
CPointer<T>(rawValue)
}
internal fun CPointer<*>.cPointerToString() = "CPointer(raw=0x%x)".format(rawValue)
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CLength(val value: Int)
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class CNaturalStruct(vararg val fieldNames: String)
fun <R> staticCFunction(function: () -> R): CPointer<CFunction<() -> R>> =
staticCFunctionImpl(function)
fun <P1, R> staticCFunction(function: (P1) -> R): CPointer<CFunction<(P1) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, R> staticCFunction(function: (P1, P2) -> R): CPointer<CFunction<(P1, P2) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, R> staticCFunction(function: (P1, P2, P3) -> R): CPointer<CFunction<(P1, P2, P3) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, R> staticCFunction(function: (P1, P2, P3, P4) -> R): CPointer<CFunction<(P1, P2, P3, P4) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, R> staticCFunction(function: (P1, P2, P3, P4, P5) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>> =
staticCFunctionImpl(function)
fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> staticCFunction(function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>> =
staticCFunctionImpl(function)
| apache-2.0 | 6d1020eee23edfb5241c9355c50ff645 | 56.868966 | 373 | 0.634966 | 2.339281 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/persistence/ManagedEntity.kt | 1 | 3110 | package com.onyx.persistence
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
import com.onyx.descriptor.EntityDescriptor
import com.onyx.persistence.context.SchemaContext
import com.onyx.extension.common.catchAll
import com.onyx.extension.get
import com.onyx.extension.set
import com.onyx.persistence.context.Contexts
/**
* All managed entities should extend this class
* Base class is needed for proper serialization
*
* @author Tim Osborn
* @see com.onyx.persistence.IManagedEntity
*
* @since 1.0.0
*/
abstract class ManagedEntity : IManagedEntity, BufferStreamable {
@Transient private var descriptor: EntityDescriptor? = null
@Transient internal var ignoreListeners = false
/**
* Get the corresponding descriptor for this entity given its context
*
* @param context Owning schema context
* @since 2.0.0
*/
@Suppress("MemberVisibilityCanPrivate")
protected fun getDescriptor(context: SchemaContext):EntityDescriptor {
if (descriptor == null) {
descriptor = context.getDescriptorForEntity(this, "")
}
return descriptor!!
}
override fun write(buffer: BufferStream) {
val descriptor = getDescriptor(Contexts.first())
descriptor.reflectionFields.forEach { (name, _) ->
buffer.putOther(this.get(descriptor = descriptor, name = name))
}
}
override fun read(buffer: BufferStream) {
val descriptor = getDescriptor(Contexts.first())
descriptor.reflectionFields.forEach { (name, _) ->
this.set(descriptor = descriptor, name = name, value = buffer.other)
}
}
override fun write(buffer: BufferStream, context: SchemaContext?) {
val systemEntity = context!!.getSystemEntityByName(this.javaClass.name)
buffer.putInt(systemEntity!!.primaryKey)
systemEntity.attributes.forEach {
catchAll {
buffer.putObject(this.get(context = context, name = it.name))
}
}
}
override fun read(buffer: BufferStream, context: SchemaContext?) {
val serializerId = buffer.int
val systemEntity = context!!.getSystemEntityById(serializerId)
val descriptor = context.getDescriptorForEntity(this, "")
systemEntity!!.attributes.forEach {
catchAll {
this.set(context = context, name = it.name, value = buffer.value, descriptor = descriptor)
}
}
}
/**
* This method maps the keys from a structure to the attributes of the entity
* @param mapObj Map to convert from
*/
fun fromMap(mapObj: Map<String, Any>, context: SchemaContext) {
val descriptor = getDescriptor(context)
descriptor.attributes.values.forEach {
catchAll {
if (mapObj.containsKey(it.name)) {
val attributeValueWithinMap = mapObj[it.name]
this.set(context = context, descriptor = descriptor, name = it.name, value = attributeValueWithinMap)
}
}
}
}
}
| agpl-3.0 | 843fd0c390f23c101b94a3b20dfb4011 | 32.44086 | 121 | 0.65209 | 4.683735 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticVariableRenamer.kt | 2 | 7489 | // 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.refactoring.rename
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiVariable
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.rename.naming.AutomaticRenamer
import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.unquote
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class AutomaticVariableRenamer(
klass: PsiNamedElement, // PsiClass or JetClass
newClassName: String,
usages: Collection<UsageInfo>
) : AutomaticRenamer() {
private val toUnpluralize = ArrayList<KtNamedDeclaration>()
init {
val oldClassName = klass.name!!.unquote()
val newClassNameUnquoted = newClassName.unquote()
for (usage in usages) {
val usageElement = usage.element ?: continue
val parameterOrVariable = PsiTreeUtil.getParentOfType(
usageElement,
KtVariableDeclaration::class.java,
KtParameter::class.java
) as KtCallableDeclaration? ?: continue
val variableName = parameterOrVariable.name ?: continue
if (variableName.equals(newClassNameUnquoted, ignoreCase = true)) continue
if (!StringUtil.containsIgnoreCase(variableName, oldClassName)) continue
val descriptor = parameterOrVariable.resolveToDescriptorIfAny() ?: continue
val type = (descriptor as VariableDescriptor).type
if (type.isCollectionLikeOf(klass)) {
toUnpluralize.add(parameterOrVariable)
}
myElements.add(parameterOrVariable)
}
suggestAllNames(oldClassName, newClassNameUnquoted)
}
override fun getDialogTitle() = JavaRefactoringBundle.message("rename.variables.title")
override fun getDialogDescription() = JavaRefactoringBundle.message("title.rename.variables.with.the.following.names.to")
override fun entityName() = JavaRefactoringBundle.message("entity.name.variable")
override fun nameToCanonicalName(name: String, element: PsiNamedElement): String {
if (element !is KtNamedDeclaration) return name
val codeStyleManager = JavaCodeStyleManager.getInstance(element.project)
val kind = variableKind(codeStyleManager, element)
val propertyName = if (kind != null) {
codeStyleManager.variableNameToPropertyName(name, kind)
} else name
if (element in toUnpluralize) {
val singular = StringUtil.unpluralize(propertyName)
if (singular != null) return singular
toUnpluralize.remove(element)
}
return propertyName
}
override fun canonicalNameToName(canonicalName: String, element: PsiNamedElement): String {
if (element !is KtNamedDeclaration) return canonicalName
val codeStyleManager = JavaCodeStyleManager.getInstance(element.project)
val kind = variableKind(codeStyleManager, element)
val varName = if (kind != null) {
codeStyleManager.propertyNameToVariableName(canonicalName, kind)
} else canonicalName
return if (element in toUnpluralize)
StringUtil.pluralize(varName)
else
varName
}
private fun variableKind(
codeStyleManager: JavaCodeStyleManager,
ktElement: KtNamedDeclaration
): VariableKind? {
if (ktElement is KtProperty && ktElement.isTopLevel && !ktElement.hasModifier(KtTokens.CONST_KEYWORD)) {
return null
}
if (ktElement.containingClassOrObject is KtObjectDeclaration) {
return null
}
val psiVariable = ktElement.toLightElements().firstIsInstanceOrNull<PsiVariable>()
return if (psiVariable != null) codeStyleManager.getVariableKind(psiVariable) else null
}
companion object {
val LOG = Logger.getInstance(AutomaticVariableRenamer::class.java)
}
}
private fun KotlinType.isCollectionLikeOf(classPsiElement: PsiNamedElement): Boolean {
val klass = this.constructor.declarationDescriptor as? ClassDescriptor ?: return false
if (KotlinBuiltIns.isArray(this) || DescriptorUtils.isSubclass(klass, klass.builtIns.collection)) {
val typeArgument = this.arguments.singleOrNull()?.type ?: return false
val typePsiElement = ((typeArgument.constructor.declarationDescriptor as? ClassDescriptor)?.source as? PsiSourceElement)?.psi
return classPsiElement == typePsiElement || typeArgument.isCollectionLikeOf(classPsiElement)
}
return false
}
open class AutomaticVariableRenamerFactory : AutomaticRenamerFactory {
override fun isApplicable(element: PsiElement) = element is KtClass || element is KtTypeAlias
override fun createRenamer(element: PsiElement, newName: String, usages: Collection<UsageInfo>) =
AutomaticVariableRenamer(element as PsiNamedElement, newName, usages)
override fun isEnabled() = KotlinRefactoringSettings.instance.renameVariables
override fun setEnabled(enabled: Boolean) {
KotlinRefactoringSettings.instance.renameVariables = enabled
}
override fun getOptionName(): String? = JavaRefactoringBundle.message("rename.variables")
}
class AutomaticVariableRenamerFactoryForJavaClass : AutomaticVariableRenamerFactory() {
override fun isApplicable(element: PsiElement) = element is PsiClass
override fun getOptionName(): String? = null
}
class AutomaticVariableInJavaRenamerFactory : AutomaticRenamerFactory {
override fun isApplicable(element: PsiElement) = element is KtClass && element.toLightClass() != null
override fun createRenamer(element: PsiElement, newName: String, usages: Collection<UsageInfo>) =
// Using java variable renamer for java usages
com.intellij.refactoring.rename.naming.AutomaticVariableRenamer((element as KtClass).toLightClass()!!, newName, usages)
override fun isEnabled() = KotlinRefactoringSettings.instance.renameVariables
override fun setEnabled(enabled: Boolean) {
KotlinRefactoringSettings.instance.renameVariables = enabled
}
override fun getOptionName() = null
} | apache-2.0 | 6364aeed9c1154852d35da7d0efd7bba | 42.294798 | 158 | 0.746428 | 5.222455 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/groovyPatterns.kt | 13 | 2539 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.patterns
import com.intellij.openapi.util.Key
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PsiMethodPattern
import com.intellij.psi.PsiMethod
import com.intellij.util.ProcessingContext
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder.checkKind
val closureCallKey: Key<GrCall> = Key.create<GrCall>("groovy.pattern.closure.call")
inline fun <reified T : GroovyPsiElement> groovyElement(): GroovyElementPattern.Capture<T> {
return GroovyElementPattern.Capture(T::class.java)
}
inline fun <reified T : GrExpression> groovyExpression(): GroovyExpressionPattern.Capture<T> {
return GroovyExpressionPattern.Capture(T::class.java)
}
fun groovyList(): GroovyExpressionPattern.Capture<GrListOrMap> {
return groovyExpression<GrListOrMap>().with(object : PatternCondition<GrListOrMap>("isList") {
override fun accepts(t: GrListOrMap, context: ProcessingContext?) = !t.isMap
})
}
fun psiMethod(containingClass: String, vararg names: String): PsiMethodPattern {
val methodPattern = GroovyPatterns.psiMethod()
val withName = if (names.isEmpty()) methodPattern else methodPattern.withName(*names)
return withName.definedInClass(containingClass)
}
fun PsiMethodPattern.withKind(kind: Any): PsiMethodPattern {
return with(object : PatternCondition<PsiMethod>("withKind") {
override fun accepts(t: PsiMethod, context: ProcessingContext?): Boolean = checkKind(t, kind)
})
}
fun groovyClosure(): GroovyClosurePattern = GroovyClosurePattern()
val groovyAnnotationArgumentValue: GroovyElementPattern.Capture<GrAnnotationMemberValue> = groovyElement()
val groovyAnnotationArgument: GroovyAnnotationArgumentPattern.Capture = GroovyAnnotationArgumentPattern.Capture()
val groovyAnnotationArgumentList: GroovyElementPattern.Capture<GrAnnotationArgumentList> = groovyElement()
| apache-2.0 | ebd1ec8237d819d5f3d9d077db5a8353 | 50.816327 | 140 | 0.822371 | 4.377586 | false | false | false | false |
smmribeiro/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ParameterNullityInference.kt | 3 | 9756 | // 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 com.intellij.codeInspection.dataFlow.inference
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaTokenType
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType.*
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.tree.TokenSet
import java.util.*
internal fun inferNotNullParameters(tree: LighterAST, parameterNames: List<String?>, statements: List<LighterASTNode>): BitSet {
val canBeNulls = parameterNames.filterNotNullTo(HashSet())
if (canBeNulls.isEmpty()) return BitSet()
val notNulls = HashSet<String>()
val queue = ArrayDeque(statements)
while (queue.isNotEmpty() && canBeNulls.isNotEmpty()) {
val element = queue.removeFirst()
val type = element.tokenType
when (type) {
CONDITIONAL_EXPRESSION, EXPRESSION_STATEMENT -> JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
RETURN_STATEMENT -> {
queue.clear()
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
FOR_STATEMENT -> {
val condition = JavaLightTreeUtil.findExpressionChild(tree, element)
queue.clear()
if (condition != null) {
queue.addFirst(condition)
LightTreeUtil.firstChildOfType(tree, element, ElementType.JAVA_STATEMENT_BIT_SET)?.let(queue::addFirst)
}
else {
// no condition == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
WHILE_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
if (expression?.tokenType == LITERAL_EXPRESSION &&
LightTreeUtil.firstChildOfType(tree, expression, JavaTokenType.TRUE_KEYWORD) != null) {
// while(true) == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
} else {
dereference(tree, expression, canBeNulls, notNulls, queue)
}
}
SWITCH_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
val hasExplicitNullCheck = findCaseLabelElementList(tree, element)
.flatMap { node -> LightTreeUtil.getChildrenOfType(tree, node, LITERAL_EXPRESSION) }
.any { node -> JavaLightTreeUtil.isNullLiteralExpression(tree, node) }
if (hasExplicitNullCheck) {
ignore(tree, expression, canBeNulls)
}
else {
dereference(tree, expression, canBeNulls, notNulls, queue)
}
}
FOREACH_STATEMENT, IF_STATEMENT, THROW_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, expression, canBeNulls, notNulls, queue)
}
BINARY_EXPRESSION, POLYADIC_EXPRESSION -> {
if (LightTreeUtil.firstChildOfType(tree, element, TokenSet.create(JavaTokenType.ANDAND, JavaTokenType.OROR)) != null) {
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
EMPTY_STATEMENT, ASSERT_STATEMENT, DO_WHILE_STATEMENT, DECLARATION_STATEMENT, BLOCK_STATEMENT -> {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
SYNCHRONIZED_STATEMENT -> {
val sync = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, sync, canBeNulls, notNulls, queue)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
}
FIELD, PARAMETER, LOCAL_VARIABLE -> {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, element))
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
EXPRESSION_LIST -> {
val children = JavaLightTreeUtil.getExpressionChildren(tree, element)
// When parameter is passed to another method, that method may have "null -> fail" contract,
// so without knowing this we cannot continue inference for the parameter
children.forEach { ignore(tree, it, canBeNulls) }
children.asReversed().forEach(queue::addFirst)
}
ASSIGNMENT_EXPRESSION -> {
val lvalue = JavaLightTreeUtil.findExpressionChild(tree, element)
ignore(tree, lvalue, canBeNulls)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
ARRAY_ACCESS_EXPRESSION -> JavaLightTreeUtil.getExpressionChildren(tree, element).forEach {
dereference(tree, it, canBeNulls, notNulls, queue)
}
METHOD_REF_EXPRESSION, REFERENCE_EXPRESSION -> {
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, qualifier, canBeNulls, notNulls, queue)
}
CLASS, METHOD, LAMBDA_EXPRESSION -> {
// Ignore classes, methods and lambda expression bodies as it's not known whether they will be instantiated/executed.
// For anonymous classes argument list, field initializers and instance initialization sections are checked.
}
TRY_STATEMENT -> {
queue.clear()
val canCatchNpe = LightTreeUtil.getChildrenOfType(tree, element, CATCH_SECTION)
.asSequence()
.map { LightTreeUtil.firstChildOfType(tree, it, PARAMETER) }
.filterNotNull()
.map { parameter -> LightTreeUtil.firstChildOfType(tree, parameter, TYPE) }
.any { canCatchNpe(tree, it) }
if (!canCatchNpe) {
LightTreeUtil.getChildrenOfType(tree, element, RESOURCE_LIST).forEach(queue::addFirst)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
// stop analysis after first try as we are not sure how execution goes further:
// whether or not it visit catch blocks, etc.
}
}
else -> {
if (ElementType.JAVA_STATEMENT_BIT_SET.contains(type)) {
// Unknown/unprocessed statement: just stop processing the rest of the method
queue.clear()
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
}
}
val notNullParameters = BitSet()
parameterNames.forEachIndexed { index, s -> if (notNulls.contains(s)) notNullParameters.set(index) }
return notNullParameters
}
private val NPE_CATCHERS = setOf("Throwable", "Exception", "RuntimeException", "NullPointerException",
CommonClassNames.JAVA_LANG_THROWABLE, CommonClassNames.JAVA_LANG_EXCEPTION,
CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, CommonClassNames.JAVA_LANG_NULL_POINTER_EXCEPTION)
fun canCatchNpe(tree: LighterAST, type: LighterASTNode?): Boolean {
if (type == null) return false
val codeRef = LightTreeUtil.firstChildOfType(tree, type, JAVA_CODE_REFERENCE)
val name = JavaLightTreeUtil.getNameIdentifierText(tree, codeRef)
if (name == null) {
// Multicatch
return LightTreeUtil.getChildrenOfType(tree, type, TYPE).any { canCatchNpe(tree, it) }
}
return NPE_CATCHERS.contains(name)
}
private fun ignore(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>) {
val stripped = JavaLightTreeUtil.skipParenthesesDown(tree, expression)
if (stripped != null &&
stripped.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, stripped) == null) {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, stripped))
}
}
private fun dereference(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>,
notNulls: HashSet<String>,
queue: ArrayDeque<LighterASTNode>) {
val stripped = JavaLightTreeUtil.skipParenthesesDown(tree, expression)
if (stripped == null) return
if (stripped.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, stripped) == null) {
JavaLightTreeUtil.getNameIdentifierText(tree, stripped)?.takeIf(canBeNulls::remove)?.let(notNulls::add)
}
else {
queue.addFirst(stripped)
}
}
/**
* Returns list of parameter names. A null in returned list means that either parameter name
* is absent in the source or it's a primitive type (thus nullity inference does not apply).
*/
internal fun getParameterNames(tree: LighterAST, method: LighterASTNode): List<String?> {
val parameterList = LightTreeUtil.firstChildOfType(tree, method, PARAMETER_LIST) ?: return emptyList()
val parameters = LightTreeUtil.getChildrenOfType(tree, parameterList, PARAMETER)
return parameters.map {
if (LightTreeUtil.firstChildOfType(tree, it, ElementType.PRIMITIVE_TYPE_BIT_SET) != null) null
else JavaLightTreeUtil.getNameIdentifierText(tree, it)
}
}
private fun findCaseLabelElementList(tree: LighterAST, switchNode: LighterASTNode): List<LighterASTNode> {
val codeBlock = LightTreeUtil.firstChildOfType(tree, switchNode, CODE_BLOCK) ?: return emptyList()
val rules = LightTreeUtil.getChildrenOfType(tree, codeBlock, SWITCH_LABELED_RULE)
return rules.mapNotNull { node -> LightTreeUtil.firstChildOfType(tree, node, CASE_LABEL_ELEMENT_LIST) }
}
| apache-2.0 | b951b057e197fbd24b346ced33e71e6b | 47.537313 | 140 | 0.693419 | 4.820158 | false | false | false | false |
android/storage-samples | SafDemos/app/src/main/java/com/android/samples/safdemos/MainFragment.kt | 1 | 2966 | /*
* Copyright (C) 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.android.samples.safdemos
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.android.samples.safdemos.databinding.FragmentMainBinding
import com.android.samples.safdemos.databinding.ListItemDemoBinding
class MainFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentMainBinding.inflate(layoutInflater)
val demoItems = arrayOf(
// TODO: Add other SAF demos
Demo(
getString(R.string.image_picker_demo_title),
getString(R.string.image_picker_demo_text),
R.drawable.ic_image_black_24dp,
R.id.action_mainFragment_to_imagePickerFragment
)
)
val adapter = DemoAdapter(demoItems) { clickedDemo ->
findNavController().navigate(clickedDemo.action)
}
binding.demosList.adapter = adapter
return binding.root
}
}
data class Demo(
val title: String,
val text: String,
@DrawableRes val icon: Int,
@IdRes val action: Int
)
private class DemoViewHolder(val binding: ListItemDemoBinding) :
RecyclerView.ViewHolder(binding.root)
private class DemoAdapter(
private val demos: Array<Demo>,
private val itemClickListener: (Demo) -> Unit
) : RecyclerView.Adapter<DemoViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
LayoutInflater.from(parent.context).let { layoutInflater ->
DemoViewHolder(ListItemDemoBinding.inflate(layoutInflater, parent, false))
}
override fun getItemCount() = demos.size
override fun onBindViewHolder(holder: DemoViewHolder, position: Int) {
val demo = demos[position]
holder.binding.demoIcon.setImageResource(demo.icon)
holder.binding.demoTitle.text = demo.title
holder.binding.demoText.text = demo.text
holder.binding.root.setOnClickListener { itemClickListener(demos[position]) }
}
} | apache-2.0 | 3d7fb512d6c00f9409265e5683bc688f | 33.905882 | 86 | 0.712744 | 4.500759 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/util/ActionBarState.kt | 1 | 4701 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.util
import android.os.Bundle
import android.support.annotation.DrawableRes
/**
* Created by sinyuk on 2018/3/6.
*
*/
data class ActionBarUi
@JvmOverloads constructor(var title: String? = null,
var subTitle: String? = null,
@DrawableRes var startButtonDrawable: Int?,
var startButtonType: Int = ActionButton.Avatar,
var endButtonType: Int = ActionButton.Rice,
@DrawableRes var endButtonDrawable: Int?,
var displayedChildIndex: Int = 0) {
companion object {
const val TITLE = "title"
const val DISPLAYED_CHILD_INDEX = "displayedChildIndex"
const val SUBTITLE = "subTitle"
const val START_BUTTON_DRAWABLE = "startButtonDrawable"
const val START_BUTTON_TYPE = "startButtonType"
const val END_BUTTON_DRAWABLE = "endButtonDrawable"
const val END_BUTTON_TYPE = "endButtonType"
}
fun update(payLoads: PayLoads): Boolean {
if (payLoads.get().isEmpty) return false
if (payLoads.get().containsKey(TITLE)) title = payLoads.get().getString(TITLE)
if (payLoads.get().containsKey(DISPLAYED_CHILD_INDEX)) displayedChildIndex = payLoads.get().getInt(DISPLAYED_CHILD_INDEX)
if (payLoads.get().containsKey(SUBTITLE)) subTitle = payLoads.get().getString(SUBTITLE)
if (payLoads.get().containsKey(START_BUTTON_DRAWABLE)) startButtonDrawable = payLoads.get().getInt(START_BUTTON_DRAWABLE)
if (payLoads.get().containsKey(START_BUTTON_TYPE)) startButtonType = payLoads.get().getInt(START_BUTTON_TYPE)
if (payLoads.get().containsKey(END_BUTTON_DRAWABLE)) endButtonDrawable = payLoads.get().getInt(END_BUTTON_DRAWABLE)
if (payLoads.get().containsKey(END_BUTTON_TYPE)) endButtonType = payLoads.get().getInt(END_BUTTON_TYPE)
return true
}
override fun hashCode(): Int {
return super.hashCode()
}
override fun equals(other: Any?): Boolean {
if (other is ActionBarUi) {
if (other.displayedChildIndex == displayedChildIndex &&
other.title == title &&
other.subTitle == subTitle &&
other.startButtonDrawable == startButtonDrawable &&
other.startButtonType == startButtonType &&
other.endButtonDrawable == endButtonDrawable &&
other.endButtonType == endButtonType) {
return true
}
}
return false
}
class PayLoads constructor(private val bundle: Bundle = Bundle()) {
fun title(title: String?): PayLoads {
bundle.putString(TITLE, title)
return this@PayLoads
}
fun subTitle(subTitle: String?): PayLoads {
bundle.putString(SUBTITLE, subTitle)
return this@PayLoads
}
fun displayedChildIndex(displayedChildIndex: Int): PayLoads {
bundle.putInt(DISPLAYED_CHILD_INDEX, displayedChildIndex)
return this@PayLoads
}
fun startButtonDrawable(@DrawableRes drawable: Int): PayLoads {
bundle.putInt(START_BUTTON_DRAWABLE, drawable)
return this@PayLoads
}
fun endButtonDrawable(@DrawableRes drawable: Int): PayLoads {
bundle.putInt(END_BUTTON_DRAWABLE, drawable)
return this@PayLoads
}
fun startButtonType(type: Int): PayLoads {
bundle.putInt(START_BUTTON_TYPE, type)
return this@PayLoads
}
fun endButtonType(type: Int): PayLoads {
bundle.putInt(END_BUTTON_TYPE, type)
return this@PayLoads
}
fun get(): Bundle = bundle
}
}
object ActionButton {
const val Avatar = 1
const val Back = 2
const val Rice = 3
const val SearchClose = 4
const val AddFriend = 5
const val Settings = 6
const val Send = 7
}
| mit | ecf84c9ef4d8503d7bfd8e5ed80448c4 | 32.578571 | 129 | 0.619868 | 4.472883 | false | false | false | false |
jaredrummler/AndroidDeviceNames | generator/src/main/kotlin/com/jaredrummler/androiddevicenames/DatabaseGenerator.kt | 1 | 2832 | /*
* Copyright (C) 2017 Jared Rummler
*
* 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.jaredrummler.androiddevicenames
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.sql.DriverManager
import java.sql.SQLException
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
class DatabaseGenerator(
private val devices: List<Device>,
private val databasePath: String = "database/android-devices.db",
private val zipPath: String = "database/android-devices.zip"
) {
fun generate() {
val url = "jdbc:sqlite:$databasePath"
try {
File(databasePath).parentFile?.mkdirs()
DriverManager.getConnection(url)?.let { conn ->
conn.createStatement().execute(SQL_DROP)
conn.createStatement().execute(SQL_CREATE)
val statement = conn.prepareStatement(SQL_INSERT)
devices.forEach { device ->
statement.setString(1, device.marketName)
statement.setString(2, device.codename)
statement.setString(3, device.model)
statement.addBatch()
}
statement.executeBatch()
conn.close()
}
ZipOutputStream(BufferedOutputStream(FileOutputStream(zipPath))).use { out ->
FileInputStream(databasePath).use { fi ->
BufferedInputStream(fi).use { origin ->
val entry = ZipEntry(databasePath)
out.putNextEntry(entry)
origin.copyTo(out, 1024)
}
}
}
} catch (e: SQLException) {
e.printStackTrace()
}
}
companion object {
private const val SQL_INSERT =
"INSERT INTO devices (name, codename, model) VALUES (?, ?, ?)"
private const val SQL_DROP = "DROP TABLE IF EXISTS devices;"
private const val SQL_CREATE = "CREATE TABLE devices (\n" +
"_id INTEGER PRIMARY KEY,\n" +
"name TEXT,\n" +
"codename TEXT,\n" +
"model TEXT\n" +
");"
}
} | apache-2.0 | 11a6d35ce15e2a96b82a6772a52738de | 34.4125 | 89 | 0.601695 | 4.783784 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/di/AppModule.kt | 1 | 5512 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.di
import android.app.Application
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import android.util.Log
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.*
import com.sinyuk.fanfou.App
import com.sinyuk.fanfou.domain.*
import com.sinyuk.fanfou.domain.api.Endpoint
import com.sinyuk.fanfou.domain.api.Oauth1SigningInterceptor
import com.sinyuk.fanfou.domain.api.RestAPI
import com.sinyuk.fanfou.domain.db.LocalDatabase
import com.sinyuk.fanfou.domain.util.LiveDataCallAdapterFactory
import com.sinyuk.fanfou.util.Oauth1SigningInterceptor
import com.sinyuk.myutils.system.ToastUtils
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Named
import javax.inject.Singleton
/**
* Created by sinyuk on 2017/11/28.
*
*/
@Module(includes = [(ViewModelModule::class)])
class AppModule constructor(private val app: App) {
@Suppress("unused")
@Provides
@Singleton
fun provideApplication(): Application = app
@Suppress("unused")
@Provides
@Singleton
@Named(DATABASE_IN_DISK)
fun provideDatabase(): LocalDatabase = LocalDatabase.getInstance(app)
@Suppress("unused")
@Provides
@Singleton
@Named(DATABASE_IN_MEMORY)
fun provideMemoryDatabase(): LocalDatabase = LocalDatabase.getInMemory(app)
@Suppress("unused")
@Provides
@Singleton
@Named(TYPE_GLOBAL)
fun provideGlobalPrefs(): SharedPreferences = app.getSharedPreferences(TYPE_GLOBAL, MODE_PRIVATE)
@Suppress("unused")
@Provides
@Singleton
fun provideToastUtils(): ToastUtils = ToastUtils(app)
@Suppress("unused")
@Provides
@Singleton
fun provideGson(): Gson {
return GsonBuilder()
// Blank fields are included as null instead of being omitted.
.serializeNulls()
.registerTypeAdapter(Date::class.java, JsonDeserializer<Date> { json, _, _ ->
if (json == null) {
Date()
} else {
formatter.timeZone = TimeZone.getDefault()
formatter.parse(json.asString)
}
})
.registerTypeAdapter(Date::class.java, JsonSerializer<Date> { src, _, _ ->
formatter.timeZone = TimeZone.getTimeZone("UTC+8")
JsonPrimitive(formatter.format(src))
})
.create()
}
@Suppress("unused")
@Provides
@Singleton
fun provideEndpoint() = Endpoint("http://api.fanfou.com/")
@Suppress("unused")
@Provides
@Singleton
fun provideAuthenticator(@Named(TYPE_GLOBAL) p: SharedPreferences) =
Oauth1SigningInterceptor(p.getString(ACCESS_TOKEN, null), p.getString(ACCESS_SECRET, null))
@Suppress("unused")
@Provides
@Singleton
fun provideOkHttp(interceptor: Oauth1SigningInterceptor): OkHttpClient {
@Suppress("UNUSED_VARIABLE")
val max = (1024 * 1024 * 100).toLong()
val timeout: Long = 30
return OkHttpClient.Builder()
.addNetworkInterceptor(interceptor)
.connectTimeout(timeout, TimeUnit.SECONDS)
.writeTimeout(timeout, TimeUnit.SECONDS)
.readTimeout(timeout, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.also {
val logging = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
Log.d("FANFOU", it)
})
if (BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY
it.addInterceptor(logging).addNetworkInterceptor(StethoInterceptor())
} else {
logging.level = HttpLoggingInterceptor.Level.HEADERS
it.addInterceptor(logging)
}
}.build()
}
@Suppress("unused")
@Provides
@Singleton
fun provideRestAPI(gson: Gson, endpoint: Endpoint, okHttpClient: OkHttpClient): RestAPI {
return Retrofit.Builder()
.baseUrl(endpoint.baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(LiveDataCallAdapterFactory())
.client(okHttpClient)
.build()
.create(RestAPI::class.java)
}
companion object {
val formatter = SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH)
}
} | mit | df0126407c1f32cc0d3d5e475ec6adc9 | 31.429412 | 103 | 0.640058 | 4.743546 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.