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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlintest/kotlintest | kotest-core/src/commonMain/kotlin/io/kotest/core/test/TestCase.kt | 1 | 2561 | package io.kotest.core.test
import io.kotest.core.*
import io.kotest.core.factory.TestFactoryId
import io.kotest.core.spec.Spec
/**
* A [TestCase] describes an actual block of code that will be tested.
* It contains a reference back to the [Spec] instance in which it
* is being executed.
*
* It also captures a closure of the body of the test case.
* This is a function which is invoked with a [TestContext].
* The context is used so that the test function can, at runtime,
* register nested tests with the test engine. This allows
* nested tests to be executed lazily as required, rather
* than when the [Spec] instance is created.
*
* A test can be nested inside other tests if the [Spec] supports it.
*
* For example, in the FunSpec we only allow top level tests.
*
* test("this is a test") { }
*
* And in WordSpec we allow two levels of tests.
*
* "a string" should {
* "return the length" {
* }
* }
*
*/
data class TestCase(
// the description contains the names of all parents, plus the name of this test case
val description: Description,
// the spec that contains this testcase
val spec: Spec,
// a closure of the test function
val test: suspend TestContext.() -> Unit,
val source: SourceRef,
val type: TestType,
// config used when running the test, such as number of
// invocations, threads, etc
val config: TestCaseConfig = TestCaseConfig(),
// an optional factory id which is used to indicate which factory (if any) generated this test case.
val factoryId: TestFactoryId? = null,
// assertion mode can be set to control errors/warnings in a test
// if null, defaults will be applied
val assertionMode: AssertionMode? = null
) {
val name = description.name
fun isTopLevel(): Boolean = description.isTopLevel()
// for compatibility with earlier plugins
fun getLine(): Int = source.lineNumber
companion object {
fun test(description: Description, spec: Spec, test: suspend TestContext.() -> Unit): TestCase =
TestCase(
description,
spec,
test,
sourceRef(),
TestType.Test,
TestCaseConfig(),
null,
null
)
fun container(description: Description, spec: Spec, test: suspend TestContext.() -> Unit): TestCase =
TestCase(
description,
spec,
test,
sourceRef(),
TestType.Container,
TestCaseConfig(),
null,
null
)
}
}
| apache-2.0 | 5fb0d31800fd644c17b582aaded96890 | 29.129412 | 107 | 0.643889 | 4.430796 | false | true | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/map/cache/GeoPackageFeatureTableCacheOverlay.kt | 1 | 14922 | package mil.nga.giat.mage.map.cache
import android.content.Context
import android.util.Log
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.TileOverlay
import mil.nga.geopackage.GeoPackageFactory
import mil.nga.geopackage.attributes.AttributesRow
import mil.nga.geopackage.db.GeoPackageDataType
import mil.nga.geopackage.extension.related.ExtendedRelation
import mil.nga.geopackage.extension.related.RelatedTablesExtension
import mil.nga.geopackage.extension.related.RelationType
import mil.nga.geopackage.extension.schema.columns.DataColumnsDao
import mil.nga.geopackage.geom.GeoPackageGeometryData
import mil.nga.geopackage.map.MapUtils
import mil.nga.geopackage.map.geom.GoogleMapShape
import mil.nga.geopackage.map.geom.GoogleMapShapeConverter
import mil.nga.geopackage.map.tiles.overlay.FeatureOverlayQuery
import mil.nga.giat.mage.R
import mil.nga.giat.mage.map.GeoPackageAttribute
import mil.nga.giat.mage.map.GeoPackageFeatureMapState
import mil.nga.giat.mage.map.GeoPackageMediaProperty
import mil.nga.giat.mage.map.GeoPackageProperty
import mil.nga.giat.mage.utils.DateFormatFactory
import mil.nga.sf.Geometry
import mil.nga.sf.GeometryType
import mil.nga.sf.Point
import mil.nga.sf.proj.GeometryTransform
import java.util.*
/**
* Constructor
*
* @param name GeoPackage table name
* @param geoPackage GeoPackage name
* @param cacheName Cache name
* @param count count
* @param minZoom min zoom level
* @param isIndexed Indexed flag, true when the feature table is indexed
* @param geometryType geometry type
*/
class GeoPackageFeatureTableCacheOverlay(
name: String?, geoPackage: String?, cacheName: String?, count: Int, minZoom: Int,
val isIndexed: Boolean,
val geometryType: GeometryType,
) : GeoPackageTableCacheOverlay(
name,
geoPackage,
cacheName,
CacheOverlayType.GEOPACKAGE_FEATURE_TABLE,
count,
minZoom,
MAX_ZOOM
) {
/**
* Mapping between feature ids and shapes
*/
private val shapes: MutableMap<Long, GoogleMapShape> = HashMap()
/**
* Tile Overlay
*/
var tileOverlay: TileOverlay? = null
/**
* Used to query the backing feature table
*/
lateinit var featureOverlayQuery: FeatureOverlayQuery
/**
* Linked tile table cache overlays
*/
private val linkedTiles: MutableList<GeoPackageTileTableCacheOverlay> = ArrayList()
override fun removeFromMap() {
shapes.values.forEach { it.remove() }
shapes.clear()
tileOverlay?.remove()
tileOverlay = null
linkedTiles.forEach { it.removeFromMap() }
}
override fun getIconImageResourceId(): Int {
return R.drawable.ic_place_preference_24dp
}
override fun getInfo(): String {
var minZoom = minZoom
var maxZoom = maxZoom
linkedTiles.forEach { tileTable ->
minZoom = minZoom.coerceAtMost(tileTable.minZoom)
maxZoom = maxZoom.coerceAtLeast(tileTable.maxZoom)
}
return "features: $count, zoom: $minZoom - $maxZoom"
}
override fun onMapClick(latLng: LatLng, mapView: MapView, map: GoogleMap): String? {
return featureOverlayQuery.buildMapClickMessage(latLng, mapView, map)
}
/**
* Add a shape
*
* @param id
* @param shape
*/
private fun addShape(id: Long, shape: GoogleMapShape) {
shapes[id] = shape
}
/**
* Remove a shape
*
* @param id
* @return
*/
private fun removeShape(id: Long): GoogleMapShape? {
return shapes.remove(id)
}
/**
* Add a shape to the map
*
* @param id
* @param shape
* @return added map shape
*/
fun addShapeToMap(id: Long, shape: GoogleMapShape?, map: GoogleMap?): GoogleMapShape {
val mapShape = GoogleMapShapeConverter.addShapeToMap(map, shape)
addShape(id, mapShape)
return mapShape
}
/**
* Remove a shape from the map
*
* @param id
* @return
*/
fun removeShapeFromMap(id: Long): GoogleMapShape? {
val shape = removeShape(id)
shape?.remove()
return shape
}
/**
* Add a linked tile table cache overlay
*
* @param tileTable tile table cache overlay
*/
fun addLinkedTileTable(tileTable: GeoPackageTileTableCacheOverlay) {
linkedTiles.add(tileTable)
}
/**
* Get the linked tile table cache overlays
*
* @return linked tile table cache overlays
*/
val linkedTileTables: List<GeoPackageTileTableCacheOverlay>
get() = linkedTiles
override fun getFeaturesNearClick(
latLng: LatLng,
mapView: MapView,
map: GoogleMap,
context: Context
): List<GeoPackageFeatureMapState> {
val features: MutableList<GeoPackageFeatureMapState> = ArrayList()
val zoom = MapUtils.getCurrentZoom(map).toDouble()
// Build a bounding box to represent the click location
val boundingBox = MapUtils.buildClickBoundingBox(
latLng,
mapView,
map,
featureOverlayQuery.screenClickPercentage
)
val styles = featureOverlayQuery.featureTiles.featureTableStyles
// Verify the features are indexed and we are getting information
val maxFeaturesInfo = context.resources.getBoolean(R.bool.map_feature_overlay_max_features_info)
val featuresInfo = context.resources.getBoolean(R.bool.map_feature_overlay_features_info)
if (isIndexed && (maxFeaturesInfo || featuresInfo)) {
if (featureOverlayQuery.isOnAtCurrentZoom(zoom, latLng)) {
val tileFeatureCount = featureOverlayQuery.tileFeatureCount(latLng, zoom)
if (featureOverlayQuery.isMoreThanMaxFeatures(tileFeatureCount)) {
features.add(GeoPackageFeatureMapState(
id = 0L,
geoPackage = geoPackage,
table = name,
title = "GeoPackage",
primary = "$name $tileFeatureCount Features",
secondary = "$tileFeatureCount features, zoom in for more detail"
))
} else if (featuresInfo) {
try {
// Query for the features near the click
val geoPackage = GeoPackageFactory.getManager(context).open(geoPackage)
val relatedTablesExtension = RelatedTablesExtension(geoPackage)
val relationsDao = relatedTablesExtension.extendedRelationsDao
val mediaTables: MutableList<ExtendedRelation> = ArrayList()
val attributeTables: MutableList<ExtendedRelation> = ArrayList()
if (relationsDao.isTableExists) {
mediaTables.addAll(relationsDao.getBaseTableRelations(name)
.filter { relation ->
relation.relationType == RelationType.MEDIA
}
)
attributeTables.addAll(relationsDao.getBaseTableRelations(name)
.filter { relation ->
relation.relationType == RelationType.ATTRIBUTES ||
relation.relationType == RelationType.SIMPLE_ATTRIBUTES
}
)
}
val results = featureOverlayQuery.queryFeatures(boundingBox)
for (featureRow in results) {
val attributeRows: MutableList<AttributesRow> = ArrayList()
val featureId = featureRow.id
for (relation in attributeTables) {
val relatedAttributes = relatedTablesExtension.getMappingsForBase(
relation.mappingTableName,
featureId
)
val attributesDao = geoPackage.getAttributesDao(relation.relatedTableName)
for (relatedAttribute in relatedAttributes) {
val row = attributesDao.queryForIdRow(relatedAttribute)
if (row != null) {
attributeRows.add(row)
}
}
}
val dataColumnsDao = DataColumnsDao.create(geoPackage)
val properties: MutableList<GeoPackageProperty> = ArrayList()
var geometry: Geometry? = Point(latLng.longitude, latLng.latitude)
val geometryColumn = featureRow.geometryColumnIndex
for (i in 0 until featureRow.columnCount()) {
val value = featureRow.getValue(i)
var columnName = featureRow.getColumnName(i)
if (dataColumnsDao.isTable) {
val dataColumn =
dataColumnsDao.getDataColumn(featureRow.table.tableName, columnName)
if (dataColumn != null) {
columnName = dataColumn.name
}
}
if (i == geometryColumn) {
val geometryData = value as GeoPackageGeometryData
var centroid = geometryData.geometry.centroid
val transform = GeometryTransform.create(
featureOverlayQuery.featureTiles.featureDao.projection, 4326L
)
centroid = transform.transform(centroid)
geometry = centroid
}
if (value != null && featureRow.columns.getColumn(i).dataType != GeoPackageDataType.BLOB) {
properties.add(GeoPackageProperty(columnName, value))
}
}
val attributes: MutableList<GeoPackageAttribute> = ArrayList()
for (row in attributeRows) {
val attributeProperties: MutableList<GeoPackageProperty> = ArrayList()
val attributeId = row.id
for (relation in mediaTables) {
val relatedMedia = relatedTablesExtension.getMappingsForBase(
relation.mappingTableName,
attributeId
)
val mediaDao = relatedTablesExtension.getMediaDao(relation.relatedTableName)
val mediaRows = mediaDao.getRows(relatedMedia)
for (mediaRow in mediaRows) {
var name = "Media"
var columnIndex = mediaRow.columns.getColumnIndex("title", false)
if (columnIndex == null) {
columnIndex = mediaRow.columns.getColumnIndex("name", false)
}
if (columnIndex != null) {
name = mediaRow.getValue(columnIndex).toString()
}
val typeIndex = mediaRow.columns.getColumnIndex("content_type", false)
if (typeIndex != null) {
val contentType = mediaRow.getValue(typeIndex).toString()
attributeProperties.add(GeoPackageMediaProperty(name, mediaRow.data, mediaDao.tableName, mediaRow.id, contentType))
}
}
}
for (i in 0 until row.columnCount()) {
val value = row.getValue(i)
var columnName = row.getColumnName(i)
if (dataColumnsDao.isTable) {
val dataColumn = dataColumnsDao.getDataColumn(row.table.tableName, columnName)
if (dataColumn != null) {
columnName = dataColumn.name
}
}
if (value != null && row.columns.getColumn(i).dataType != GeoPackageDataType.BLOB) {
attributeProperties.add(GeoPackageProperty(columnName, value))
}
}
attributes.add(GeoPackageAttribute(attributeProperties))
}
val featureStyle = styles?.getFeatureStyle(featureRow)
val style = featureStyle?.style
val icon = if (featureStyle?.hasIcon() == true) {
featureStyle.icon.dataBitmap
} else null
val title: String? = getDate(properties, context)
val primary = getValue(
listOf("name", "title", "primaryfield"),
properties
) ?: "GeoPackage Feature"
val secondary = getValue(
listOf("subtitle", "secondaryfield", "variantfield"),
properties
) ?: name
features.add(GeoPackageFeatureMapState(
id = featureId,
geoPackage = this.geoPackage,
table = name,
title = title,
primary = primary,
secondary = secondary,
geometry = geometry,
image = icon,
properties = properties,
attributes = attributes
))
}
} catch (e: Exception) {
Log.e("featureOverlayQuery", "error", e)
}
}
}
}
return features
}
private fun getDate(properties: List<GeoPackageProperty>, context: Context): String? {
val dateFormat = DateFormatFactory.format(
"yyyy-MM-dd HH:mm zz",
Locale.getDefault(),
context
)
val keys = listOf("date", "timestamp")
val property = properties.find { property ->
keys.contains(property.key.lowercase())
}
return (property?.value as? Date)?.let { date ->
dateFormat.format(date)
}
}
private fun getValue(keys: List<String>, properties: List<GeoPackageProperty>): String? {
val property = properties.find { property ->
keys.contains(property.key.lowercase())
}
return property?.value as? String
}
companion object {
/**
* Max zoom for features
*/
const val MAX_ZOOM = 21
}
} | apache-2.0 | 974970c7aa22249b013424e08df69800 | 36.779747 | 148 | 0.559509 | 5.201115 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/tileentity/electric/TileAirLock.kt | 2 | 6087 | package tileentity.electric
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.block.BlockAirBubble
import com.cout970.magneticraft.block.BlockAirLock
import com.cout970.magneticraft.config.Config
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitElectricity
import com.cout970.magneticraft.tileentity.TileBase
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
import net.minecraft.block.Block
import net.minecraft.init.Blocks
/**
* Created by cout970 on 18/08/2016.
*/
@TileRegister("airlock")
class TileAirLock : TileBase() {
val node = ElectricNode({ worldObj }, { pos }, capacity = 2.0)
val traitElectricity = TraitElectricity(this, listOf(node))
override val traits: List<ITileTrait> = listOf(traitElectricity)
val range = 10
val length = 9 * 9
override fun update() {
super.update()
if (worldObj.isServer && shouldTick(40)) {
Config.airlockBubbleCost = 2.0
if (node.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE) {
val array = Array(range * 2 + 1, { Array(range * 2 + 1, { Array<Block?>(range * 2 + 1, { null }) }) })
//fin water
for (j in -range..range) {
for (k in -range..range) {
for (i in -range..range) {
val pos = pos.add(i, j, k)
var block = worldObj.getBlockState(pos).block
if (i * i + j * j + k * k <= length) {
if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) {
block = BlockAirBubble
}
}
if (block != Blocks.AIR) {
array[i + range][j + range][k + range] = block
}
}
}
}
//remove unnecessary blocks
for (j in -range..range) {
for (k in -range..range) {
for (i in -range..range) {
if (i * i + j * j + k * k <= length) {
val x = i + range
val y = j + range
val z = k + range
if (array[x][y][z] == BlockAirBubble) {
if (array[x - 1][y][z] != Blocks.WATER && array[x - 1][y][z] != Blocks.FLOWING_WATER &&
array[x + 1][y][z] != Blocks.WATER && array[x + 1][y][z] != Blocks.FLOWING_WATER &&
array[x][y - 1][z] != Blocks.WATER && array[x][y - 1][z] != Blocks.FLOWING_WATER &&
array[x][y + 1][z] != Blocks.WATER && array[x][y + 1][z] != Blocks.FLOWING_WATER &&
array[x][y][z - 1] != Blocks.WATER && array[x][y][z - 1] != Blocks.FLOWING_WATER &&
array[x][y][z + 1] != Blocks.WATER && array[x][y][z + 1] != Blocks.FLOWING_WATER) {
array[x][y][z] = Blocks.AIR
}
}
}
}
}
}
//apply changes
for (j in -range..range) {
for (k in -range..range) {
for (i in -range..range) {
if (i * i + j * j + k * k <= length) {
val x = i + range
val y = j + range
val z = k + range
if (array[x][y][z] == BlockAirBubble) {
if (node.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE) {
worldObj.setBlockState(pos.add(i, j, k), BlockAirBubble.defaultState.withProperty(BlockAirBubble.PROPERTY_DECAY, false))
node.applyPower(-Config.airlockBubbleCost, false)
} else {
if (worldObj.getBlockState(pos.add(i, j, k)).block == BlockAirBubble) {
node.applyPower(-Config.airlockBubbleCost, false)
}
}
}
}
}
}
}
if (node.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE) {
for (j_ in -range..range) {
for (k in -range..range) {
for (i in -range..range) {
val j = -j_
if (i * i + j * j + k * k <= length) {
val x = i + range
val y = j + range
val z = k + range
if (array[x][y][z] == Blocks.AIR) {
if (node.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE) {
worldObj.setBlockToAir(pos.add(i, j, k))
node.applyPower(-Config.airlockAirCost, false)
}
}
}
}
}
}
}
} else {
BlockAirLock.startBubbleDecay(worldObj, pos, range, length)
}
}
}
} | gpl-2.0 | f3d24c4f8a3263c4cb721c898daf7780 | 49.31405 | 160 | 0.393297 | 4.827121 | false | false | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/service/IntentEndpoint.kt | 1 | 3564 | package jp.blanktar.ruumusic.service
import android.content.Context
import android.content.Intent
import android.os.Build
import jp.blanktar.ruumusic.util.EqualizerInfo
import jp.blanktar.ruumusic.util.PlayingStatus
import jp.blanktar.ruumusic.util.RepeatModeType
import jp.blanktar.ruumusic.widget.MusicNameWidget
import jp.blanktar.ruumusic.widget.PlayPauseWidget
import jp.blanktar.ruumusic.widget.SkipNextWidget
import jp.blanktar.ruumusic.widget.SkipPrevWidget
import jp.blanktar.ruumusic.widget.UnifiedWidget
class IntentEndpoint(val context: Context, private val controller: RuuService.Controller) : Endpoint {
override val supported = true
override fun close() {}
override fun onStatusUpdated(status: PlayingStatus) {
context.sendBroadcast(status.toIntent())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.sendBroadcast(status.toIntent(Intent(context, MusicNameWidget::class.java)))
context.sendBroadcast(status.toIntent(Intent(context, PlayPauseWidget::class.java)))
context.sendBroadcast(status.toIntent(Intent(context, SkipNextWidget::class.java)))
context.sendBroadcast(status.toIntent(Intent(context, SkipPrevWidget::class.java)))
context.sendBroadcast(status.toIntent(Intent(context, UnifiedWidget::class.java)))
}
}
override fun onEqualizerInfo(info: EqualizerInfo) {
context.sendBroadcast(info.toIntent())
}
override fun onFailedPlay(status: PlayingStatus) {
context.sendBroadcast(status.toIntent().setAction(RuuService.ACTION_FAILED_PLAY))
}
override fun onError(message: String, status: PlayingStatus) {}
override fun onEndOfList(isFirst: Boolean, status: PlayingStatus) {}
fun onIntent(intent: Intent){
when (intent.action) {
RuuService.ACTION_PLAY -> {
val path = intent.getStringExtra("path")
if (path == null) {
controller.play()
} else {
controller.play(path)
}
}
RuuService.ACTION_PLAY_RECURSIVE -> {
controller.playRecursive(intent.getStringExtra("path"))
}
RuuService.ACTION_PLAY_SEARCH -> {
controller.playSearch(intent.getStringExtra("path"), intent.getStringExtra("query"))
}
RuuService.ACTION_PAUSE -> {
controller.pause()
}
RuuService.ACTION_PAUSE_TRANSIENT -> {
controller.pauseTransient()
}
RuuService.ACTION_PLAY_PAUSE -> {
controller.playPause()
}
RuuService.ACTION_SEEK -> {
controller.seek(intent.getIntExtra("newtime", -1).toLong())
}
RuuService.ACTION_REPEAT -> {
intent.getStringExtra("mode")?.let {
controller.setRepeatMode(RepeatModeType.valueOf(it))
}
}
RuuService.ACTION_SHUFFLE -> {
controller.setShuffleMode(intent.getBooleanExtra("mode", false))
}
RuuService.ACTION_NEXT -> {
controller.next()
}
RuuService.ACTION_PREV -> {
controller.prev()
}
RuuService.ACTION_PING -> {
controller.sendStatus()
}
RuuService.ACTION_REQUEST_EQUALIZER_INFO -> {
controller.sendEqualizerInfo()
}
}
}
}
| mit | 687ef32eabd4521827b86f50fb0841f3 | 36.515789 | 102 | 0.612233 | 4.432836 | false | false | false | false |
intrigus/chemie | android/src/main/kotlin/de/intrigus/chem/fragments/AboutFragment.kt | 1 | 3025 | /*Copyright 2015 Simon Gerst
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.intrigus.chem.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.TextView
import de.intrigus.chem.ChemieActivity
import de.intrigus.chem.R
class AboutFragment : Fragment() {
lateinit private var showLicenses: Button
lateinit private var licenseText: TextView
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view = inflater!!.inflate(R.layout.about_app, container, false)
(activity as ChemieActivity).setupToolbar(view!!.findViewById(R.id.toolbar) as Toolbar)
(activity as ChemieActivity).supportActionBar.title = "About"
(view.findViewById(R.id.about_app_text)as TextView).movementMethod = LinkMovementMethod.getInstance()
licenseText = view.findViewById(R.id.licenses) as TextView
(view.findViewById(R.id.show_licenses)as Button).setOnClickListener { view ->
if (licenseText.isShown) {
licenseText.slideUp({ licenseText.visibility = View.GONE })
} else {
licenseText.visibility = View.VISIBLE
licenseText.movementMethod = LinkMovementMethod.getInstance() // Only has an effect on visible views
licenseText.slideDown()
}
}
return view
}
fun TextView.slideDown() {
val a = AnimationUtils.loadAnimation(activity, R.anim.slide_down)
a.reset()
licenseText.clearAnimation()
licenseText.startAnimation(a)
}
fun TextView.slideUp(action: () -> Unit) {
val a = AnimationUtils.loadAnimation(activity, R.anim.slide_up)
a.reset()
a.setAnimationListener(object : AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
action.invoke()
}
})
licenseText.clearAnimation()
licenseText.startAnimation(a)
}
} | apache-2.0 | f6c5163ca9d98bf6e1f47f33717f22e1 | 35.457831 | 117 | 0.706777 | 4.562594 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/shared/src/main/java/com/supercilex/robotscouter/shared/TeamMediaCreator.kt | 1 | 9564 | package com.supercilex.robotscouter.shared
import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.Gravity
import androidx.annotation.StringRes
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.supercilex.robotscouter.core.CrashLogger
import com.supercilex.robotscouter.core.RobotScouter
import com.supercilex.robotscouter.core.data.TEAM_KEY
import com.supercilex.robotscouter.core.data.mimeType
import com.supercilex.robotscouter.core.data.safeCreateNewFile
import com.supercilex.robotscouter.core.data.shouldAskToUploadMediaToTba
import com.supercilex.robotscouter.core.data.shouldUploadMediaToTba
import com.supercilex.robotscouter.core.data.teams
import com.supercilex.robotscouter.core.isInTestMode
import com.supercilex.robotscouter.core.longToast
import com.supercilex.robotscouter.core.model.Team
import com.supercilex.robotscouter.core.providerAuthority
import com.supercilex.robotscouter.core.ui.OnActivityResult
import com.supercilex.robotscouter.core.ui.StateHolder
import com.supercilex.robotscouter.core.ui.hasPerms
import com.supercilex.robotscouter.core.ui.hasPermsOnActivityResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import java.io.File
class TeamMediaCreator(private val savedState: SavedStateHandle) : ViewModel(), OnActivityResult {
private val _state = StateHolder(State())
val state: LiveData<State> get() = _state.liveData
private val _viewActions = Channel<ViewAction>(Channel.CONFLATED)
val viewActions: Flow<ViewAction> = flow { for (e in _viewActions) emit(e) }
private var photoFile: File? = savedState.get(PHOTO_FILE_KEY)
set(value) {
field = value
savedState.set(PHOTO_FILE_KEY, value)
}
private var shouldUpload: Boolean? = savedState.get(PHOTO_SHOULD_UPLOAD)
set(value) {
field = value
savedState.set(PHOTO_SHOULD_UPLOAD, value)
}
fun reset() {
photoFile = null
shouldUpload = null
_state.update { State() }
}
fun capture() {
if (!hasPerms(perms)) {
_viewActions.offer(ViewAction.RequestPermissions(
perms.toList(), R.string.media_write_storage_rationale))
return
}
if (isInTestMode) {
capture(false)
return
}
if (shouldAskToUploadMediaToTba) {
_viewActions.offer(ViewAction.ShowTbaUploadDialog)
} else {
capture(shouldUploadMediaToTba)
}
}
fun capture(shouldUploadMediaToTba: Boolean) {
shouldUpload = shouldUploadMediaToTba
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(RobotScouter.packageManager) == null) {
longToast(R.string.error_unknown)
return
}
viewModelScope.launch {
val file = createImageFile() ?: return@launch
photoFile = file
val photoUri = FileProvider.getUriForFile(RobotScouter, providerAuthority, file)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
val choosePictureIntent = Intent(Intent.ACTION_GET_CONTENT)
choosePictureIntent.type = "image/*"
choosePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
val chooser = Intent.createChooser(
choosePictureIntent, RobotScouter.getString(R.string.media_picker_title))
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(takePictureIntent))
if (Build.VERSION.SDK_INT < 21) {
val infos = RobotScouter.packageManager
.queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in infos) {
val packageName = resolveInfo.activityInfo.packageName
RobotScouter.grantUriPermission(
packageName,
photoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
}
_viewActions.offer(ViewAction.StartIntentForResult(chooser, TAKE_PHOTO_RC))
if (shouldUpload == true) {
longToast(RobotScouter.getText(R.string.media_upload_reminder).trim())
.setGravity(Gravity.CENTER, 0, 0)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (hasPermsOnActivityResult(perms, requestCode)) {
capture()
return
}
if (requestCode != TAKE_PHOTO_RC) return
val photoFile = checkNotNull(photoFile)
if (resultCode == Activity.RESULT_OK) {
viewModelScope.launch {
val getContentUri = data?.data
if (getContentUri != null) {
handleRemoteUri(getContentUri, photoFile)
return@launch
}
handleInternalUri(photoFile)
}
} else {
GlobalScope.launch(Dispatchers.IO) { photoFile.delete() }
}
}
private suspend fun createImageFile(): File? = Dispatchers.IO {
val teamId = savedState.get<Team>(TEAM_KEY)?.id
val teamName = teams.find { it.id == teamId }?.toString()
val fileName = "${teamName}_${System.currentTimeMillis()}.jpg"
try {
if (Build.VERSION.SDK_INT >= 29) {
File(RobotScouter.filesDir, "Pictures/$fileName")
} else {
@Suppress("DEPRECATION")
val mediaDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
File(mediaDir, "Robot Scouter/$fileName")
}.safeCreateNewFile()
} catch (e: Exception) {
CrashLogger.onFailure(e)
longToast(e.toString())
null
}
}
private suspend fun handleRemoteUri(uri: Uri, photoFile: File) {
copyUriToFile(uri, photoFile)
handleInternalUri(photoFile, false)
}
private suspend fun handleInternalUri(photoFile: File, notifyWorld: Boolean = true) {
if (notifyWorld) {
insertFileIntoMediaStore(photoFile)
}
_state.update { copy(image = State.Image(photoFile.toUri(), checkNotNull(shouldUpload))) }
}
private suspend fun insertFileIntoMediaStore(photoFile: File) = Dispatchers.IO {
val imageDetails = ContentValues().apply {
put(MediaStore.MediaColumns.MIME_TYPE, photoFile.mimeType())
put(MediaStore.MediaColumns.TITLE, photoFile.name)
put(MediaStore.MediaColumns.DISPLAY_NAME, photoFile.nameWithoutExtension)
put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis())
if (Build.VERSION.SDK_INT >= 29) {
put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/Robot Scouter")
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
}
val resolver = RobotScouter.contentResolver
val photoUri = checkNotNull(resolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageDetails))
if (Build.VERSION.SDK_INT >= 29) {
checkNotNull(resolver.openOutputStream(photoUri)).use { output ->
photoFile.inputStream().use { input ->
input.copyTo(output)
}
}
resolver.update(photoUri, ContentValues().apply {
put(MediaStore.MediaColumns.IS_PENDING, 0)
}, null, null)
}
}
private suspend fun copyUriToFile(uri: Uri, photoFile: File) = Dispatchers.IO {
val stream = checkNotNull(RobotScouter.contentResolver.openInputStream(uri))
stream.use { input ->
photoFile.outputStream().use { output ->
input.copyTo(output)
}
}
}
data class State(
val image: Image? = null
) {
data class Image(val media: Uri, val shouldUploadMediaToTba: Boolean)
}
sealed class ViewAction {
data class RequestPermissions(
val perms: List<String>,
@StringRes val rationaleId: Int
) : ViewAction()
data class StartIntentForResult(val intent: Intent, val rc: Int) : ViewAction()
object ShowTbaUploadDialog : ViewAction()
}
private companion object {
const val TAKE_PHOTO_RC = 334
const val PHOTO_FILE_KEY = "photo_file_key"
const val PHOTO_SHOULD_UPLOAD = "photo_should_upload"
val perms = if (Build.VERSION.SDK_INT >= 29) {
arrayOf(Manifest.permission.CAMERA)
} else {
arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
}
| gpl-3.0 | 8e0e742f7aa0a117e36f4e85fa8446cc | 36.359375 | 107 | 0.643664 | 4.772455 | false | false | false | false |
Zhuinden/simple-stack | samples/community-samples/simple-stack-example-kotlin-community-sample/src/main/java/com/community/simplestackkotlindaggerexample/screens/userdetail/UserDetailFragment.kt | 1 | 1082 | package com.community.simplestackkotlindaggerexample.screens.userdetail
import android.os.Bundle
import android.view.View
import com.community.simplestackkotlindaggerexample.R
import com.community.simplestackkotlindaggerexample.data.database.User
import com.community.simplestackkotlindaggerexample.databinding.FragmentUserDetailBinding
import com.zhuinden.simplestackextensions.fragments.KeyedFragment
class UserDetailFragment : KeyedFragment(R.layout.fragment_user_detail) {
private lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
user = getKey<UserDetailKey>().user
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val user = user
val binding = FragmentUserDetailBinding.bind(view)
binding.textUsername.text = user.userName
binding.userPhoneNumber.text = "${user.userPhoneNumber} (${user.userPhoneNumberType})"
binding.userEmail.text = user.userEmail
}
}
| apache-2.0 | 9912f63d41e0bc407a22844cdb674ebd | 36.310345 | 94 | 0.775416 | 4.830357 | false | false | false | false |
semonte/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/AddRequiredModuleTest.kt | 1 | 2210 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.daemon.quickFix
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.*
/**
* @author Pavel.Dolgov
*/
class AddRequiredModuleTest : LightJava9ModulesCodeInsightFixtureTestCase() {
val messageM2 = QuickFixBundle.message("module.info.add.requires.name", "M2")!!
override fun setUp() {
super.setUp()
addFile("module-info.java", "module M2 { exports pkgA; }", M2)
addFile("pkgA/A.java", "package pkgA; public class A {}", M2)
}
fun testAddRequiresToModuleInfo() {
addFile("module-info.java", "module MAIN {}", MAIN)
val editedFile = addFile("pkgB/B.java", "package pkgB; " +
"import <caret>pkgA.A; " +
"public class B { A a; }", MAIN)
myFixture.configureFromExistingVirtualFile(editedFile)
val action = myFixture.findSingleIntention(messageM2)
assertNotNull(action)
myFixture.launchAction(action)
myFixture.checkHighlighting() // error is gone
myFixture.checkResult("module-info.java", "module MAIN {\n requires M2;\n}", false)
}
fun testNoIdeaModuleDependency() {
addFile("module-info.java", "module M3 {}", M3)
val editedFile = addFile("pkgB/B.java", "package pkgB; " +
"import <caret>pkgA.A; " +
"public class B { A a; }", M3)
myFixture.configureFromExistingVirtualFile(editedFile)
val actions = myFixture.filterAvailableIntentions(messageM2)
assertEmpty(actions)
}
} | apache-2.0 | e2153354988cbc5ded8bcd51719677c3 | 36.474576 | 95 | 0.722624 | 4.047619 | false | true | false | false |
tinypass/piano-sdk-for-android | sample/src/main/java/io/piano/sample/SimpleDependenciesProvider.kt | 1 | 921 | package io.piano.sample
import android.content.Context
import com.squareup.moshi.Moshi
import io.piano.android.id.PianoIdJsonAdapterFactory
class SimpleDependenciesProvider private constructor(context: Context) {
val appContext: Context = context.applicationContext
val moshi: Moshi = Moshi.Builder().add(PianoIdJsonAdapterFactory()).build()
val prefsStorage: PrefsStorage = PrefsStorage(appContext, moshi)
companion object {
@JvmStatic
private var instance: SimpleDependenciesProvider? = null
@JvmStatic
fun getInstance(context: Context): SimpleDependenciesProvider {
if (instance == null) {
synchronized(SimpleDependenciesProvider::class.java) {
if (instance == null)
instance = SimpleDependenciesProvider(context)
}
}
return instance!!
}
}
}
| apache-2.0 | ab556f3b6e992d20b3e2828c5483e933 | 33.111111 | 79 | 0.65798 | 5.417647 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/kotlin/KSClassifierReferenceImpl.kt | 1 | 2266 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.kotlin
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.findParentOfType
import com.google.devtools.ksp.symbol.KSClassifierReference
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.KSTypeArgument
import com.google.devtools.ksp.symbol.Location
import com.google.devtools.ksp.symbol.Origin
import com.google.devtools.ksp.symbol.impl.toLocation
import org.jetbrains.kotlin.psi.*
class KSClassifierReferenceImpl private constructor(val ktUserType: KtUserType) : KSClassifierReference {
companion object : KSObjectCache<KtUserType, KSClassifierReferenceImpl>() {
fun getCached(ktUserType: KtUserType) = cache.getOrPut(ktUserType) { KSClassifierReferenceImpl(ktUserType) }
}
override val origin = Origin.KOTLIN
override val location: Location by lazy {
ktUserType.toLocation()
}
override val parent: KSNode? by lazy {
ktUserType.findParentOfType<KtTypeReference>()?.let { KSTypeReferenceImpl.getCached(it) }
}
override val typeArguments: List<KSTypeArgument> by lazy {
ktUserType.typeArguments.map { KSTypeArgumentKtImpl.getCached(it) }
}
override fun referencedName(): String {
return ktUserType.referencedName ?: ""
}
override val qualifier: KSClassifierReference? by lazy {
if (ktUserType.qualifier == null) {
null
} else {
KSClassifierReferenceImpl.getCached(ktUserType.qualifier!!)
}
}
override fun toString() = referencedName()
}
| apache-2.0 | dedeeef9af802a0420bb193fbf4a3cf4 | 35.548387 | 116 | 0.741836 | 4.425781 | false | false | false | false |
michael-johansen/workshop-jb | src/i_introduction/_8_Extension_Functions/ExtensionFunctions.kt | 5 | 1032 | package i_introduction._8_Extension_Functions.StringExtensions
import util.TODO
fun String.lastChar() = this.charAt(this.length() - 1)
//'this' can be omitted
fun String.lastChar1() = charAt(length() - 1)
fun use() {
// Try IntelliJ's Ctrl+Space "default completion" after the dot: lastChar() will be visible in
// the completion window and can be easily found
"abc".lastChar()
}
// 'lastChar' compiles to a static function in the class StringExtensionsPackage
// and can be used in Java with a String as its first argument (see JavaCode8.useExtension)
fun todoTask8() = TODO(
"""
Task 8.
Implement the extension functions Int.r(), Pair<Int, Int>.r()
to support the following manner of creating rational numbers:
1.r(), Pair(1, 2).r()
""",
references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) })
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = todoTask8()
fun Pair<Int, Int>.r(): RationalNumber = todoTask8()
| mit | d331c40651342c62a1efbe0212003c0a | 29.352941 | 98 | 0.680233 | 3.752727 | false | false | false | false |
jtransc/jtransc | jtransc-utils/src/com/jtransc/lang/Dynamic.kt | 1 | 9829 | package com.jtransc.lang
import com.jtransc.error.InvalidOperationException
import com.jtransc.error.noImpl
import com.jtransc.util.toDoubleOrNull2
import java.lang.reflect.Array
import java.lang.reflect.Modifier
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.*
object Dynamic {
@Suppress("UNCHECKED_CAST")
fun <T> createEmptyClass(clazz: Class<T>): T {
if (clazz == java.util.List::class.java) return listOf<Any?>() as T
if (clazz == java.util.Map::class.java) return mapOf<Any?, Any?>() as T
if (clazz == java.lang.Iterable::class.java) return listOf<Any?>() as T
val constructor = clazz.constructors.first()
val args = constructor.parameterTypes.map {
dynamicCast(null, it)
}
return constructor.newInstance(*args.toTypedArray()) as T
}
fun <T : Any> setField(instance: T, name: String, value: Any?) {
val field = instance.javaClass.declaredFields.find { it.name == name }
//val field = instance.javaClass.getField(name)
field?.isAccessible = true
field?.set(instance, value)
}
fun <T : Any> getField(instance: T?, name: String): Any? {
if (instance == null) return null
val getter = instance.javaClass.getMethod("get${name.capitalize()}")
if (getter != null) {
getter.isAccessible = true
return getter.invoke(instance)
} else {
val field = instance.javaClass.declaredFields.find { it.name == name }
//val field = instance.javaClass.getField(name)
field?.isAccessible = true
return field?.get(instance)
}
}
fun toNumber(it: Any?): Double {
return when (it) {
null -> 0.0
is Number -> it.toDouble()
else -> {
it.toString().toDoubleOrNull2() ?: 0.0
}
}
}
fun toInt(it: Any?): Int {
return toNumber(it).toInt()
}
fun toBool(it: Any?): Boolean {
return when (it) {
null -> false
is Boolean -> it
is String -> it.isNotEmpty() && it != "0" && it != "false"
else -> toInt(it) != 0
}
}
fun toIterable(it: Any?): Iterable<*> {
return when (it) {
null -> listOf<Any?>()
is Iterable<*> -> it
is CharSequence -> it.toList()
else -> listOf<Any?>()
}
}
fun toMap(it: Any?): Map<*, *> {
return when (it) {
null -> mapOf<Any?, Any?>()
is Iterable<*> -> it.withIndex().map { it.index to it.value }.toMap()
is Map<*, *> -> it
else -> {
val out = hashMapOf<String, Any?>()
for (field in it.javaClass.fields.filter { !Modifier.isStatic(it.modifiers) }) {
field.isAccessible = true
out[field.name] = field.get(it)
}
//for (method in it.javaClass.methods.filter { it.name.startsWith("get") && it.parameterCount == 0 }) {
// out[method.name] = method.invoke(it)
//}
out
}
}
}
@Suppress("UNCHECKED_CAST")
fun toComparable(it: Any?): Comparable<Any?> {
return when (it) {
null -> 0 as Comparable<Any?>
is Comparable<*> -> it as Comparable<Any?>
else -> it.toString() as Comparable<Any?>
}
}
fun compare(l: Any?, r: Any?): Int {
val lc = toComparable(l)
val rc = toComparable(r)
if (lc.javaClass.isAssignableFrom(rc.javaClass)) {
return lc.compareTo(rc)
} else {
return -1
}
}
fun accessAny(instance: Any?, key:Any?): Any? {
return when (instance) {
null -> null
is Map<*, *> -> instance[key]
is Iterable<*> -> instance.toList()[toInt(key)]
else -> getField(instance, key.toString())
}
}
@Suppress("UNCHECKED_CAST")
fun setAny(instance: Any?, key:Any?, value: Any?): Any? {
return when (instance) {
null -> null
is MutableMap<*, *> -> (instance as MutableMap<Any?, Any?>).set(key, value)
is MutableList<*> -> (instance as MutableList<Any?>)[toInt(key)] = value
else -> setField(instance, key.toString(), value)
}
}
fun hasField(javaClass: Class<Any>, name: String): Boolean {
return javaClass.declaredFields.any { it.name == name }
}
fun getFieldType(javaClass: Class<Any>, name: String): Class<*> {
return javaClass.getField(name).type
}
inline fun <reified T : Any> dynamicCast(value: Any?): T? = dynamicCast(value, T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T : Any>dynamicCast(value: Any?, target: Class<T>, genericType: Type? = null): T? {
if (value != null && target.isAssignableFrom(value.javaClass)) {
return if (genericType != null && genericType is ParameterizedType) {
val typeArgs = genericType.actualTypeArguments
when(value) {
is List<*> -> value.map { dynamicCast(it, typeArgs[0] as Class<Any>) }
else -> value
} as T
} else {
value as T
}
}
val str = if (value != null) "$value" else "0"
if (target.isPrimitive) {
when (target) {
java.lang.Boolean.TYPE -> return (str == "true" || str == "1") as T
java.lang.Byte.TYPE -> return str.parseInt().toByte() as T
java.lang.Character.TYPE -> return str.parseInt().toChar() as T
java.lang.Short.TYPE -> return str.parseInt().toShort() as T
java.lang.Long.TYPE -> return str.parseLong() as T
java.lang.Float.TYPE -> return str.toFloat() as T
java.lang.Double.TYPE -> return str.parseDouble() as T
java.lang.Integer.TYPE -> return str.parseInt() as T
else -> throw InvalidOperationException("Unhandled primitive '${target.name}'")
}
}
if (target.isAssignableFrom(java.lang.Boolean::class.java)) return (str == "true" || str == "1") as T
if (target.isAssignableFrom(java.lang.Byte::class.java)) return str.parseInt().toByte() as T
if (target.isAssignableFrom(java.lang.Character::class.java)) return str.parseInt().toChar() as T
if (target.isAssignableFrom(java.lang.Short::class.java)) return str.parseShort() as T
if (target.isAssignableFrom(java.lang.Integer::class.java)) return str.parseInt() as T
if (target.isAssignableFrom(java.lang.Long::class.java)) return str.parseLong() as T
if (target.isAssignableFrom(java.lang.Float::class.java)) return str.toFloat() as T
if (target.isAssignableFrom(java.lang.Double::class.java)) return str.toDouble() as T
if (target.isAssignableFrom(java.lang.String::class.java)) return (if (value == null) "" else str) as T
if (target.isEnum) return if (value != null) java.lang.Enum.valueOf<AnyEnum>(target as Class<AnyEnum>, str) as T else target.enumConstants.first()
if (value is List<*>) return value.toList() as T
if (value is Map<*, *>) {
val map = value as Map<Any?, *>
val resultClass = target as Class<Any>
val result = Dynamic.createEmptyClass(resultClass)
for (field in result.javaClass.declaredFields) {
if (field.name in map) {
val v = map[field.name]
field.isAccessible = true
field.set(result, dynamicCast(v, field.type, field.genericType))
}
}
return result as T
}
if (value == null) return createEmptyClass(target)
throw InvalidOperationException("Can't convert '$value' to '$target'")
}
private enum class AnyEnum {}
fun String?.parseBool(): Boolean? = when (this) {
"true", "yes", "1" -> true
"false", "no", "0" -> false
else -> null
}
fun String?.parseInt(): Int = this?.parseDouble()?.toInt() ?: 0
fun String?.parseShort(): Short = this?.parseDouble()?.toInt()?.toShort() ?: 0
fun String?.parseLong(): Long = try {
this?.toLong()
} catch (e: Throwable) {
this?.parseDouble()?.toLong()
} ?: 0L
fun String?.parseDouble(): Double {
if (this == null) return 0.0
try {
return this.toDouble()
} catch (e: Throwable) {
return 0.0
}
}
fun <T : Any> fromTyped(value: T?): Any? {
return when (value) {
null -> null
true -> true
false -> false
is Number -> value.toDouble()
is String -> value
is Map<*, *> -> value
is Iterable<*> -> value
else -> {
val clazz = value.javaClass
val out = hashMapOf<Any?, Any?>()
for (field in clazz.declaredFields) {
if (field.name.startsWith('$')) continue
field.isAccessible = true
out[field.name] = fromTyped(field.get(value))
}
out
}
}
}
fun unop(r: Any?, op: String): Any? {
return when (op) {
"+" -> r
"-" -> -toNumber(r)
"~" -> toInt(r).inv()
"!" -> !toBool(r)
else -> noImpl("Not implemented unary operator $op")
}
}
//fun toFixNumber(value: Double): Any = if (value == value.toInt().toDouble()) value.toInt() else value
fun toString(value: Any?): String {
when (value) {
is Double -> {
if (value == value.toInt().toDouble()) {
return value.toInt().toString()
}
}
}
return value.toString()
}
fun binop(l: Any?, r: Any?, op: String): Any? {
return when (op) {
"+" -> {
when (l) {
is String -> l.toString() + r.toBetterString()
is Iterable<*> -> toIterable(l) + toIterable(r)
else -> toNumber(l) + toNumber(r)
}
}
"-" -> toNumber(l) - toNumber(r)
"*" -> toNumber(l) * toNumber(r)
"/" -> toNumber(l) / toNumber(r)
"%" -> toNumber(l) % toNumber(r)
"**" -> Math.pow(toNumber(l), toNumber(r))
"&" -> toInt(l) and toInt(r)
"or" -> toInt(l) or toInt(r)
"^" -> toInt(l) xor toInt(r)
"&&" -> toBool(l) && toBool(r)
"||" -> toBool(l) || toBool(r)
"==" -> Objects.equals(l, r)
"!=" -> !Objects.equals(l, r)
"<" -> compare(l, r) < 0
"<=" -> compare(l, r) <= 0
">" -> compare(l, r) > 0
">=" -> compare(l, r) >= 0
else -> noImpl("Not implemented binary operator $op")
}
}
fun callAny(obj: Any?, key: Any?, args: List<Any?>): Any? {
if (obj == null) return null
if (key == null) return null
val method = obj.javaClass.methods.first { it.name == key }
method.isAccessible = true
val result = method.invoke(obj, *args.toTypedArray())
return result
}
fun callAny(callable: Any?, args: List<Any?>): Any? {
return callAny(callable, "invoke", args)
}
fun length(subject: Any?): Int {
if (subject == null) return 0
if (subject.javaClass.isArray) return Array.getLength(subject)
if (subject is List<*>) return subject.size
return subject.toString().length
}
}
| apache-2.0 | d02e55fb4da3ad7cab017134eade953d | 29.619938 | 148 | 0.629667 | 3.123292 | false | false | false | false |
jpmoreto/play-with-robots | android/testsApp/src/test/java/jpm/lib/TestKDTreeDBase.kt | 1 | 2725 | package jpm.lib
/**
* Created by jm on 18/03/17.
*/
import javafx.application.Platform
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.canvas.Canvas
import javafx.scene.canvas.GraphicsContext
import javafx.scene.paint.Color
import javafx.stage.Stage
import jpm.lib.maps.*
import jpm.lib.math.*
import java.util.*
interface TestKDTreeDBase {
val iterations:Int
val deltaX:Int
val deltaY:Int
val rndX:Int
val rndY:Int
val dimMin: Double
val initialDim: Int
val centerPointD: DoubleVector2D
fun startDraw(primaryStage: Stage) {
primaryStage.title = "Drawing Operations Test"
val root = Group()
val canvas = Canvas(1350.0, 702.0)
val gc = canvas.graphicsContext2D
root.children.add(canvas)
primaryStage.scene = Scene(root)
primaryStage.show()
drawShapes(gc)
}
private fun drawShapes(gc: GraphicsContext) {
object : Thread() {
override fun run() {
Platform.runLater({ drawShapesKDTreeD(gc) })
}
}.start()
}
fun drawShapesKDTreeD(gc: GraphicsContext)
fun setGcColor(gc: GraphicsContext, fill: Color, stroke: Color, lineWidth: Double) {
gc.fill = fill
gc.stroke = stroke
gc.lineWidth = lineWidth
}
fun drawKDTreeD(gc: GraphicsContext, tree: KDTreeD.Node, threshold: Double) {
tree.visitAll { t ->
if (t.isLeaf && t.occupied() > threshold) {
val dim = t.getDimVector()
gc.fillRect(t.center.x - dim.x, t.center.y - dim.y, 2 * dim.x, 2 * dim.y)
}
}
}
fun <T : Tree<T, DoubleVector2D, Double>> setOccupiedD(tree: Tree<T, DoubleVector2D, Double>, xRnd: Random, yRnd: Random) {
for (i in 1..iterations) {
val p = DoubleVector2D((deltaX + xRnd.nextInt(rndX)).toDouble(), (deltaY + yRnd.nextInt(rndY)).toDouble())
tree.setOccupied(p)
}
}
fun <T : Tree<T, DoubleVector2D, Double>> setOccupiedDBound(tree: Tree<T, DoubleVector2D, Double>) {
var x = deltaX
while(x <= deltaX + rndX) {
val ptop = DoubleVector2D(x.toDouble(), deltaY.toDouble())
tree.setOccupied(ptop)
val pbot = DoubleVector2D(x.toDouble(), deltaY.toDouble() + rndY)
tree.setOccupied(pbot)
x += 1
}
var y = deltaX
while(y <= deltaY + rndY) {
val ptop = DoubleVector2D(deltaX.toDouble(), y.toDouble())
tree.setOccupied(ptop)
val pbot = DoubleVector2D(deltaX.toDouble() + rndX, y.toDouble())
tree.setOccupied(pbot)
y += 1
}
}
} | mit | 450d3725a9070db89586daa86045823b | 27.103093 | 127 | 0.595229 | 3.707483 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/render/nodes/BatchBasedRenderNode.kt | 1 | 1253 | package com.binarymonks.jj.core.render.nodes
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.properties.PropOverride
import com.binarymonks.jj.core.render.ShaderSpec
import com.binarymonks.jj.core.specs.render.RenderGraphType
abstract class BatchBasedRenderNode(
priority: Int,
color: PropOverride<Color>,
renderGraphType: RenderGraphType,
name: String?,
shaderSpec: ShaderSpec?
) : RenderNode(
priority,
color,
renderGraphType,
name,
shaderSpec) {
internal var batchColor: Color? = null
override fun setShaderAndColor() {
if (shaderSpec != null) {
val shader = JJ.render.getShaderPipe(shaderSpec!!.shaderPipe)
JJ.B.renderWorld.polyBatch.shader = shader
shaderSpec!!.bind(shader)
}
batchColor = JJ.B.renderWorld.polyBatch.color
JJ.B.renderWorld.polyBatch.color = color.get()
}
override fun restoreShaderAndColor() {
if (shaderSpec != null) {
JJ.B.renderWorld.polyBatch.shader = null
}
JJ.B.renderWorld.polyBatch.color = batchColor
}
} | apache-2.0 | a7ce7dbe668f00d598340bfd6e2e3b07 | 28.162791 | 73 | 0.667997 | 4.135314 | false | false | false | false |
juan-tonina/es6-intentions-intelliJ | src/ConvertFromArrow.kt | 1 | 3743 | import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
class ConvertFromArrow : AnAction("Convert from arrow function") {
override fun actionPerformed(event: AnActionEvent) {
val project = event.getData(PlatformDataKeys.PROJECT)
val caret = event.getData(PlatformDataKeys.CARET)
val editor = event.getData(PlatformDataKeys.EDITOR)
var document: Document? = null
if (editor != null) {
document = editor.document
}
var psiFile: PsiFile? = null
if (project != null && document != null) {
psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document)
}
var psiElement: PsiElement? = null
if (psiFile != null && caret != null) {
psiElement = psiFile.findElementAt(caret.offset)
}
// I'm SURE that there is a better way of doing this... but again, I'm usually wrong
while (psiElement != null && !(psiElement.node != null &&
psiElement.node.elementType.toString() == "JS:FUNCTION_EXPRESSION" &&
!psiElement.text.startsWith("function"))) {
psiElement = psiElement.parent
}
if (psiElement != null) {
var text = psiElement.text
if (!text.endsWith("}")) {
text = text.replaceFirst("=>".toRegex(), "{ return")
text += ";}"
} else {
text = text.replaceFirst("=>".toRegex(), "")
}
if (text.startsWith("(")) {
text = "function" + text
} else {
// This should be "functionExpression.ParamList.param.length"
val textLength = psiElement.firstChild.firstChild.textLength
text = "function (" + text.substring(0, textLength) + ")" + text.substring(textLength)
}
text = "a = " + text
val fileFromText = PsiFileFactory.getInstance(project!!).createFileFromText(text, psiFile!!)
val finalPsiElement = psiElement
var runnable: Runnable? = null
if (fileFromText != null) {
runnable = Runnable { finalPsiElement.replace(fileFromText.lastChild.lastChild.lastChild) }
}
if (runnable != null) {
WriteCommandAction.runWriteCommandAction(project, runnable)
}
}
}
/**
* This is mostly duplicated, but let's pretend it is not
*
* @param e some action event from which we get the project, data context and file language
*/
override fun update(e: AnActionEvent?) {
super.update(e)
val project = e!!.getData(PlatformDataKeys.PROJECT)
val file = PlatformDataKeys.VIRTUAL_FILE.getData(e.dataContext)
if (file != null) {
val visible: Boolean = try {
project != null && (file.fileType as LanguageFileType).language.id == "JavaScript"
} catch (e: Exception) {
false
}
// Visibility
e.presentation.isVisible = visible
// Enable or disable
e.presentation.isEnabled = visible
} else {
e.presentation.isVisible = false
e.presentation.isEnabled = false
}
}
}// Set the menu item name.
| mit | 5b0b5abe66ce08c727d089754a7066e7 | 35.696078 | 107 | 0.597115 | 5.051282 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/CollisionGroups.kt | 1 | 2386 | package com.binarymonks.jj.core.physics
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.Array
import kotlin.experimental.or
/**
* This is needed to check Collision groups of your game objects. This will determine what collides with what.
*/
class CollisionGroups {
private var groups: ObjectMap<String, CollisionGroup> = ObjectMap()
/**
* Add a collision group
*/
fun addGroup(group: CollisionGroup) {
groups.put(group.name, group)
}
fun getCollisionData(name: String): CollisionData {
if (groups.containsKey(name)) {
return groups.get(name).collisionData
}
throw Exception("No Collision group for $name")
}
/**
* A helper for building your collision groups.
* You can create a maximum of 15 distinct groups.
*/
fun buildGroups(init: GroupBuilder.() -> Unit): GroupBuilder {
val groupBuilder = GroupBuilder()
groupBuilder.init()
groupBuilder.build().forEach {
addGroup(it)
}
return groupBuilder
}
}
class Group(var name: String) {
var colliderGroupNames: Array<String> = Array()
fun collidesWith(vararg groupNames: String) {
groupNames.forEach {
colliderGroupNames.add(it)
}
}
}
class GroupBuilder {
private var groups: Array<Group> = Array()
fun group(name: String): Group {
if (groups.size == 15) throw Exception("Sorry, you can only create 15 collision groups")
val group = Group(name)
groups.add(group)
return group
}
fun build(): Array<CollisionGroup> {
val builtGroups: Array<CollisionGroup> = Array()
val categoryLookup: ObjectMap<String, Short> = ObjectMap()
for (i in 0..groups.size - 1) {
val cat:Short = Math.pow(2.toDouble(), i.toDouble()).toShort()
categoryLookup.put(groups.get(i).name, cat)
}
for (i in 0..groups.size - 1) {
val group = groups.get(i)
val category: Short = categoryLookup[group.name]
var mask: Short = 0
for (colliderName in group.colliderGroupNames) {
mask = mask or categoryLookup[colliderName]
}
builtGroups.add(CollisionGroup(group.name, CollisionData(category, mask)))
}
return builtGroups
}
}
| apache-2.0 | 66bf09177004fd6df54627ec6514109c | 27.404762 | 110 | 0.616932 | 4.200704 | false | false | false | false |
material-components/material-components-android-codelabs | kotlin/shrine/app/src/main/java/com/google/codelabs/mdc/kotlin/shrine/staggeredgridlayout/StaggeredProductCardRecyclerViewAdapter.kt | 1 | 1776 | package com.google.codelabs.mdc.kotlin.shrine.staggeredgridlayout
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.codelabs.mdc.kotlin.shrine.R
import com.google.codelabs.mdc.kotlin.shrine.network.ImageRequester
import com.google.codelabs.mdc.kotlin.shrine.network.ProductEntry
/**
* Adapter used to show an asymmetric grid of products, with 2 items in the first column, and 1
* item in the second column, and so on.
*/
class StaggeredProductCardRecyclerViewAdapter(private val productList: List<ProductEntry>?) : RecyclerView.Adapter<StaggeredProductCardViewHolder>() {
override fun getItemViewType(position: Int): Int {
return position % 3
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StaggeredProductCardViewHolder {
var layoutId = R.layout.shr_staggered_product_card_first
if (viewType == 1) {
layoutId = R.layout.shr_staggered_product_card_second
} else if (viewType == 2) {
layoutId = R.layout.shr_staggered_product_card_third
}
val layoutView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
return StaggeredProductCardViewHolder(layoutView)
}
override fun onBindViewHolder(holder: StaggeredProductCardViewHolder, position: Int) {
if (productList != null && position < productList.size) {
val product = productList[position]
holder.productTitle.text = product.title
holder.productPrice.text = product.price
ImageRequester.setImageFromUrl(holder.productImage, product.url)
}
}
override fun getItemCount(): Int {
return productList?.size ?: 0
}
}
| apache-2.0 | e8dcdb1482795f105e7d9c13fb157df0 | 38.466667 | 150 | 0.718468 | 4.530612 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/data/handler/ClassDetailHandler.kt | 1 | 2414 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.data.handler
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import co.timetableapp.data.query.Filters
import co.timetableapp.data.query.Query
import co.timetableapp.data.schema.ClassDetailsSchema
import co.timetableapp.model.ClassDetail
import java.util.*
class ClassDetailHandler(context: Context) : DataHandler<ClassDetail>(context) {
override val tableName = ClassDetailsSchema.TABLE_NAME
override val itemIdCol = ClassDetailsSchema._ID
override fun createFromCursor(cursor: Cursor) = ClassDetail.from(cursor)
override fun createFromId(id: Int) = ClassDetail.create(context, id)
override fun propertiesAsContentValues(item: ClassDetail): ContentValues {
val values = ContentValues()
with(values) {
put(ClassDetailsSchema._ID, item.id)
put(ClassDetailsSchema.COL_CLASS_ID, item.classId)
put(ClassDetailsSchema.COL_ROOM, item.room)
put(ClassDetailsSchema.COL_BUILDING, item.building)
put(ClassDetailsSchema.COL_TEACHER, item.teacher)
}
return values
}
override fun deleteItemWithReferences(itemId: Int) {
super.deleteItemWithReferences(itemId)
ClassTimeHandler.getClassTimesForDetail(context, itemId).forEach {
ClassTimeHandler(context).deleteItemWithReferences(it.id)
}
}
companion object {
@JvmStatic
fun getClassDetailsForClass(context: Context, classId: Int): ArrayList<ClassDetail> {
val query = Query.Builder()
.addFilter(Filters.equal(ClassDetailsSchema.COL_CLASS_ID, classId.toString()))
.build()
return ClassDetailHandler(context).getAllItems(query)
}
}
}
| apache-2.0 | e86517aff1102957f7d7f13a806fe6e4 | 34.5 | 98 | 0.71251 | 4.381125 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-registry/streamops-registry-confluent/src/test/kotlin/com/octaldata/registry/confluent/ConfluentRegistryClientTest.kt | 1 | 3026 | @file:Suppress("BlockingMethodInNonBlockingContext", "RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
package com.octaldata.registry.confluent
import KafkaContainer
import SchemaRegistryContainer
import ZookeeperContainer
import com.octaldata.domain.schemas.SchemaSubject
import com.octaldata.domain.schemas.SchemaType
import com.octaldata.domain.schemas.SchemaVersion
import io.confluent.kafka.schemaregistry.avro.AvroSchema
import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient
import io.kotest.core.spec.style.FunSpec
import io.kotest.inspectors.forOne
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import org.testcontainers.containers.Network
class ConfluentRegistryClientTest : FunSpec({
val network = Network.newNetwork()
val zk = ZookeeperContainer().withNetwork(network).apply { start() }
val k = KafkaContainer(zk.internalUrl).withNetwork(network).apply { start() }
val s = SchemaRegistryContainer(zk.internalUrl).withNetwork(network).apply { start() }
afterSpec {
zk.stop()
k.stop()
s.stop()
}
test("reading schema metadata") {
val client = ConfluentRegistryClient(s.url)
val confluentClient = CachedSchemaRegistryClient(s.url, 10000)
confluentClient.register(
"regions",
AvroSchema(javaClass.getResourceAsStream("/region.json").reader().readText())
)
confluentClient.register(
"chats",
AvroSchema(javaClass.getResourceAsStream("/chat.json").reader().readText())
)
val meta = client.latestSchemas().getOrThrow()
meta.shouldHaveSize(2)
meta.forOne {
it.version shouldBe SchemaVersion("1")
it.type shouldBe SchemaType("AVRO")
it.subject shouldBe SchemaSubject("chats")
}
meta.forOne {
it.version shouldBe SchemaVersion("1")
it.type shouldBe SchemaType("AVRO")
it.subject shouldBe SchemaSubject("regions")
}
}
test("retrieving specific version of schema") {
val client = ConfluentRegistryClient(s.url)
val confluentClient = CachedSchemaRegistryClient(s.url, 10000)
confluentClient.register(
"a",
AvroSchema("""{"type":"record","name":"a","namespace":"com.bar.foo","fields":[{"name":"a","type":"string"}]}""")
)
confluentClient.register(
"a",
AvroSchema("""{"type":"record","name":"a","namespace":"com.bar.foo","fields":[{"name":"a","type":"string"},{"name":"b","type":"string","default":"foo"}]}""")
)
client.schema(SchemaSubject("a"), SchemaVersion("1")).getOrThrow().schema shouldBe
"""{"type":"record","name":"a","namespace":"com.bar.foo","fields":[{"name":"a","type":"string"}]}"""
client.schema(SchemaSubject("a"), SchemaVersion("2")).getOrThrow().schema shouldBe
"""{"type":"record","name":"a","namespace":"com.bar.foo","fields":[{"name":"a","type":"string"},{"name":"b","type":"string","default":"foo"}]}"""
}
})
| apache-2.0 | 1ae69a4c8757857f39ca55f17cdc7d5f | 36.825 | 166 | 0.676801 | 4.191136 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/OverpassQueryCreator.kt | 1 | 6800 | package de.westnordost.streetcomplete.data.elementfilter
import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.*
import de.westnordost.streetcomplete.data.elementfilter.filters.ElementFilter
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import java.util.EnumSet
/** Create an overpass query from the given element filter expression */
class OverpassQueryCreator(
elementTypes: EnumSet<ElementsTypeFilter>,
private val expr: BooleanExpression<ElementFilter, Element>?)
{
private val elementTypes = elementTypes.toOqlNames()
private var setIdCounter: Int = 1
private val dataSets: MutableMap<BooleanExpression<ElementFilter, Element>, Int> = mutableMapOf()
fun create(): String {
if (elementTypes.size == 1) {
val elementType = elementTypes.first()
if (expr == null) {
return "$elementType;\n"
}
return expr.toOverpassString(elementType, null)
} else {
if (expr == null) {
return "(" + elementTypes.joinToString(" ") { "$it; " } + ");\n"
}
val result = StringBuilder()
val resultSetId = expr.assignResultSetId()
for (elementType in elementTypes) {
result.append(expr.toOverpassString(elementType, resultSetId))
}
val unionChildren = elementTypes.joinToString(" ") { getSetId(it, resultSetId) + ";" }
result.append("($unionChildren);\n")
return result.toString()
}
}
private fun EnumSet<ElementsTypeFilter>.toOqlNames(): List<String> = when {
containsAll(listOf(NODES, WAYS, RELATIONS)) -> listOf("nwr")
containsAll(listOf(NODES, WAYS)) -> listOf("nw")
containsAll(listOf(WAYS, RELATIONS)) -> listOf("wr")
else -> map { when (it!!) {
NODES -> "node"
WAYS -> "way"
RELATIONS -> "rel"
} }
}
private fun BooleanExpression<ElementFilter, Element>.toOverpassString(elementType: String, resultSetId: Int?): String {
return when (this) {
is Leaf -> AllTagFilters(value).toOverpassString(elementType, null, resultSetId)
is AnyOf -> toOverpassString(elementType, null, resultSetId)
is AllOf -> toOverpassString(elementType, null, resultSetId)
else -> throw IllegalStateException("Unexpected expression")
}
}
private fun AllOf<ElementFilter, Element>.childrenWithLeavesMerged(): List<BooleanExpression<ElementFilter, Element>> {
val consecutiveLeaves = mutableListOf<ElementFilter>()
val mergedChildren = mutableListOf<BooleanExpression<ElementFilter, Element>>()
for (child in children) {
when (child) {
is Leaf -> consecutiveLeaves.add(child.value)
is AnyOf -> {
if (consecutiveLeaves.isNotEmpty()) {
mergedChildren.add(AllTagFilters(consecutiveLeaves.toList()))
consecutiveLeaves.clear()
}
mergedChildren.add(child)
}
else -> throw IllegalStateException("Expected only Leaf and AnyOf children")
}
}
if (consecutiveLeaves.isNotEmpty()) {
mergedChildren.add(AllTagFilters(consecutiveLeaves.toList()))
}
return mergedChildren
}
private fun AllOf<ElementFilter, Element>.toOverpassString(elementType: String, inputSetId: Int?, resultSetId: Int?): String {
val result = StringBuilder()
val workingSet by lazy { assignResultSetId() }
val childrenMerged = childrenWithLeavesMerged()
childrenMerged.forEachIndexed { i, child ->
val isFirst = i == 0
val isLast = i == childrenMerged.lastIndex
val stmtInputSetId = if (isFirst) inputSetId else workingSet
val stmtResultSetId = if (isLast) resultSetId else workingSet
if (child is AnyOf) result.append(child.toOverpassString(elementType, stmtInputSetId, stmtResultSetId))
else if (child is AllTagFilters) result.append(child.toOverpassString(elementType, stmtInputSetId, stmtResultSetId))
}
return result.toString()
}
private fun AnyOf<ElementFilter, Element>.toOverpassString(elementType: String, inputSetId: Int?, resultSetId: Int?): String {
val childrenResultSetIds = mutableListOf<Int>()
val result = StringBuilder()
// first print every nested statement
for (child in children) {
val workingSetId = child.assignResultSetId()
result.append(when (child) {
is Leaf ->
AllTagFilters(child.value).toOverpassString(elementType, inputSetId, workingSetId)
is AllOf ->
child.toOverpassString(elementType, inputSetId, workingSetId)
else ->
throw IllegalStateException("Expected only Leaf and AllOf children")
})
childrenResultSetIds.add(workingSetId)
}
// then union all direct children
val unionChildren = childrenResultSetIds.joinToString(" ") { getSetId(elementType, it)+";" }
val resultStmt = resultSetId?.let { " -> " + getSetId(elementType,it) }.orEmpty()
result.append("($unionChildren)$resultStmt;\n")
return result.toString()
}
private fun AllTagFilters.toOverpassString(elementType: String, inputSetId: Int?, resultSetId: Int?): String {
val elementFilter = elementType + inputSetId?.let { getSetId(elementType,it) }.orEmpty()
val tagFilters = values.joinToString("") { it.toOverpassQLString() }
val resultStmt = resultSetId?.let { " -> " + getSetId(elementType,it) }.orEmpty()
return "$elementFilter$tagFilters$resultStmt;\n"
}
private fun getSetId(elementType: String, id: Int): String {
val prefix = when (elementType) {
"node" -> "n"
"way" -> "w"
"rel" -> "r"
"nwr", "nw", "wr" -> "e"
else -> throw IllegalArgumentException("Expected element to be any of 'node', 'way', 'rel', 'nw', 'wr' or 'nwr'")
}
return ".$prefix$id"
}
private fun BooleanExpression<ElementFilter, Element>.assignResultSetId(): Int {
return dataSets.getOrPut(this) { setIdCounter++ }
}
private class AllTagFilters(val values: List<ElementFilter>) : BooleanExpression<ElementFilter, Element>() {
constructor(value: ElementFilter) : this(listOf(value))
override fun matches(obj: Element?) = values.all { it.matches(obj) }
override fun toString() = values.joinToString(" and ")
}
}
| gpl-3.0 | c6ef83da6cc27844b5b43ba4a81eb585 | 44.637584 | 130 | 0.6225 | 4.768583 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/widget/ScoreGraphView.kt | 1 | 5695 | package com.boardgamegeek.ui.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.Style
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.boardgamegeek.R
import com.boardgamegeek.extensions.significantDigits
import java.text.DecimalFormat
import kotlin.math.ceil
class ScoreGraphView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val scorePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val scoreRadius: Float
private val smallTickHeight: Float
private val largeTickHeight: Float
private val lowScoreColor: Int
private val averageScoreColor: Int
private val averageWinScoreColor: Int
private val highScoreColor: Int
var lowScore: Double = 0.toDouble()
var averageScore: Double = 0.toDouble()
var averageWinScore: Double = 0.toDouble()
var highScore: Double = 0.toDouble()
private var hasPersonalScores: Boolean = false
var personalLowScore: Double = 0.toDouble()
set(value) {
field = value
hasPersonalScores = true
}
var personalAverageScore: Double = 0.toDouble()
set(value) {
field = value
hasPersonalScores = true
}
var personalAverageWinScore: Double = 0.toDouble()
set(value) {
field = value
hasPersonalScores = true
}
var personalHighScore: Double = 0.toDouble()
set(value) {
field = value
hasPersonalScores = true
}
init {
barPaint.color = Color.BLACK
barPaint.strokeWidth = 1f
scorePaint.strokeWidth = SCORE_STROKE_WIDTH.toFloat()
textPaint.color = ContextCompat.getColor(getContext(), R.color.secondary_text)
textPaint.textSize = 8f * getContext().resources.displayMetrics.scaledDensity
scoreRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, context.resources.displayMetrics)
smallTickHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2f, context.resources.displayMetrics)
largeTickHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, context.resources.displayMetrics)
lowScoreColor = ContextCompat.getColor(getContext(), R.color.score_low)
averageScoreColor = ContextCompat.getColor(getContext(), R.color.score_average)
averageWinScoreColor = ContextCompat.getColor(getContext(), R.color.score_average_win)
highScoreColor = ContextCompat.getColor(getContext(), R.color.score_high)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val y = (height / 2).toFloat()
val left = scoreRadius + SCORE_STROKE_WIDTH
val right = width.toFloat() - scoreRadius - SCORE_STROKE_WIDTH.toFloat()
canvas.drawLine(left, y, right, y, barPaint)
// ticks
val scoreSpread = highScore - lowScore
val tickSpacing = when {
scoreSpread <= 20 -> 1
scoreSpread <= 50 -> 5
scoreSpread <= 200 -> 10
scoreSpread <= 500 -> 20
else -> (ceil(scoreSpread / 100) * 10).toInt().significantDigits(2)
}
var tickScore = ceil(lowScore / tickSpacing) * tickSpacing
while (tickScore <= highScore) {
val x = ((tickScore - lowScore) / scoreSpread * (right - left) + left).toFloat()
val tickHeight: Float
if (tickScore % (5 * tickSpacing) == 0.0) {
tickHeight = largeTickHeight
val label = SCORE_FORMAT.format(tickScore)
val labelWidth = textPaint.measureText(label)
val labelLeft = (x - labelWidth / 2).coerceIn(0f, width - labelWidth)
canvas.drawText(label, labelLeft, height.toFloat(), textPaint)
} else {
tickHeight = smallTickHeight
}
canvas.drawLine(x, y - tickHeight, x, y + tickHeight, barPaint)
tickScore += tickSpacing.toDouble()
}
// score dots
scorePaint.style = if (hasPersonalScores) Style.STROKE else Style.FILL
drawScore(canvas, y, left, right, lowScore, lowScoreColor)
drawScore(canvas, y, left, right, highScore, highScoreColor)
drawScore(canvas, y, left, right, averageScore, averageScoreColor)
drawScore(canvas, y, left, right, averageWinScore, averageWinScoreColor)
if (hasPersonalScores) {
scorePaint.style = Style.FILL
drawScore(canvas, y, left, right, personalLowScore, lowScoreColor)
drawScore(canvas, y, left, right, personalHighScore, highScoreColor)
drawScore(canvas, y, left, right, personalAverageScore, averageScoreColor)
drawScore(canvas, y, left, right, personalAverageWinScore, averageWinScoreColor)
}
}
private fun drawScore(canvas: Canvas, y: Float, left: Float, right: Float, score: Double, @ColorInt color: Int) {
scorePaint.color = color
val x = ((score - lowScore) / (highScore - lowScore) * (right - left) + left).toFloat()
canvas.drawCircle(x, y, scoreRadius, scorePaint)
}
companion object {
private val SCORE_FORMAT = DecimalFormat("0")
private const val SCORE_STROKE_WIDTH = 2
}
}
| gpl-3.0 | 513fca9ca8b0f736ddec8fbc6bedca9b | 37.47973 | 118 | 0.657594 | 4.350649 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/extensions/Dialog.kt | 1 | 3657 | package com.boardgamegeek.extensions
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.text.util.Linkify
import android.widget.TextView
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.boardgamegeek.R
import java.util.*
fun FragmentActivity.showAndSurvive(dialog: DialogFragment, tag: String = "dialog") {
showAndSurvive(dialog, supportFragmentManager, tag)
}
fun Fragment.showAndSurvive(dialog: DialogFragment, tag: String = "dialog") {
showAndSurvive(dialog, parentFragmentManager, tag)
}
private fun showAndSurvive(dialog: DialogFragment, fragmentManager: FragmentManager, tag: String = "dialog") {
fragmentManager.beginTransaction().apply {
fragmentManager.findFragmentByTag(tag)?.let {
remove(it)
}
addToBackStack(null)
dialog.show(this, tag)
}
}
fun Context.createConfirmationDialog(
messageId: Int,
@StringRes positiveButtonTextId: Int,
okListener: DialogInterface.OnClickListener?,
): Dialog {
val builder = createThemedBuilder()
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(positiveButtonTextId, okListener)
if (messageId > 0) builder.setMessage(messageId)
return builder.create()
}
fun Activity.createDiscardDialog(
@StringRes objectResId: Int,
@StringRes positiveButtonResId: Int = R.string.keep_editing,
isNew: Boolean,
finishActivity: Boolean = true,
discardListener: () -> Unit = {}): Dialog {
val messageFormat = getString(if (isNew)
R.string.discard_new_message
else
R.string.discard_changes_message)
return createThemedBuilder()
.setMessage(String.format(messageFormat, getString(objectResId).lowercase(Locale.getDefault())))
.setPositiveButton(positiveButtonResId, null)
.setNegativeButton(R.string.discard) { _, _ ->
discardListener()
if (finishActivity) {
setResult(Activity.RESULT_CANCELED)
finish()
}
}
.setCancelable(true)
.create()
}
fun Context.createThemedBuilder(): AlertDialog.Builder {
return AlertDialog.Builder(this, R.style.Theme_bgglight_Dialog_Alert)
}
fun Context.showClickableAlertDialog(@StringRes titleResId: Int, @StringRes messageResId: Int, vararg formatArgs: Any) {
val spannableMessage = SpannableString(getString(messageResId, *formatArgs))
showClickableAlertDialog(spannableMessage, titleResId)
}
fun Context.showClickableAlertDialogPlural(@StringRes titleResId: Int, @PluralsRes messageResId: Int, quantity: Int, vararg formatArgs: Any) {
val spannableMessage = SpannableString(resources.getQuantityString(messageResId, quantity, *formatArgs))
showClickableAlertDialog(spannableMessage, titleResId)
}
private fun Context.showClickableAlertDialog(spannableMessage: SpannableString, titleResId: Int) {
Linkify.addLinks(spannableMessage, Linkify.WEB_URLS)
val dialog = AlertDialog.Builder(this)
.setTitle(titleResId)
.setMessage(spannableMessage)
.show()
dialog.findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance()
}
| gpl-3.0 | 43638fb85e66a14154eed467d03c0fac | 36.701031 | 142 | 0.733935 | 4.64676 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/GeekListItemActivity.kt | 1 | 4491 | package com.boardgamegeek.ui
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.boardgamegeek.R
import com.boardgamegeek.entities.GeekListEntity
import com.boardgamegeek.entities.GeekListItemEntity
import com.boardgamegeek.extensions.link
import com.boardgamegeek.extensions.startActivity
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.GameActivity.Companion.start
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class GeekListItemActivity : HeroTabActivity() {
private var geekListId = 0
private var geekListTitle = ""
private var order = 0
private var geekListItemEntity = GeekListItemEntity()
private val adapter: GeekListItemPagerAdapter by lazy {
GeekListItemPagerAdapter(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
geekListTitle = intent.getStringExtra(KEY_TITLE).orEmpty()
geekListId = intent.getIntExtra(KEY_ID, BggContract.INVALID_ID)
order = intent.getIntExtra(KEY_ORDER, 0)
geekListItemEntity = intent.getParcelableExtra(KEY_ITEM) ?: GeekListItemEntity()
initializeViewPager()
safelySetTitle(geekListItemEntity.objectName)
if (savedInstanceState == null && geekListItemEntity.objectId != BggContract.INVALID_ID) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "GeekListItem")
param(FirebaseAnalytics.Param.ITEM_ID, geekListItemEntity.objectId.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, geekListItemEntity.objectName)
}
}
loadToolbarImage(geekListItemEntity.imageId)
}
override val optionsMenuId = R.menu.view
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
if (geekListId != BggContract.INVALID_ID) {
GeekListActivity.startUp(this, geekListId, geekListTitle)
finish()
}
else onBackPressed()
true
}
R.id.menu_view -> {
if (geekListItemEntity.isBoardGame) {
if (geekListItemEntity.objectId == BggContract.INVALID_ID || geekListItemEntity.objectName.isBlank()) false else {
start(this, geekListItemEntity.objectId, geekListItemEntity.objectName)
true
}
}
else {
if (geekListItemEntity.objectUrl.isBlank()) false else {
link(geekListItemEntity.objectUrl)
true
}
}
}
else -> super.onOptionsItemSelected(item)
}
}
override fun createAdapter() = adapter
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> getString(R.string.title_description)
1 -> getString(R.string.title_comments)
else -> ""
}
}
inner class GeekListItemPagerAdapter(activity: FragmentActivity) :
FragmentStateAdapter(activity) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> GeekListItemFragment.newInstance(order, geekListTitle, geekListItemEntity)
1 -> GeekListItemCommentsFragment.newInstance(geekListItemEntity.comments)
else -> ErrorFragment()
}
}
override fun getItemCount() = 2
}
companion object {
private const val KEY_ID = "GEEK_LIST_ID"
private const val KEY_ORDER = "GEEK_LIST_ORDER"
private const val KEY_TITLE = "GEEK_LIST_TITLE"
private const val KEY_ITEM = "GEEK_LIST_ITEM"
fun start(context: Context, geekList: GeekListEntity, item: GeekListItemEntity, order: Int) {
context.startActivity<GeekListItemActivity>(
KEY_ID to geekList.id,
KEY_TITLE to geekList.title,
KEY_ORDER to order,
KEY_ITEM to item,
)
}
}
}
| gpl-3.0 | 924832f8b5c9e60b9cac57621bbb8793 | 37.384615 | 134 | 0.638165 | 4.803209 | false | false | false | false |
JotraN/shows-to-watch-android | app/src/main/java/io/josephtran/showstowatch/show_search/ShowSearchAdapter.kt | 1 | 1966 | package io.josephtran.showstowatch.show_search
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import io.josephtran.showstowatch.R
import io.josephtran.showstowatch.api.TVDBShow
import io.josephtran.showstowatch.api.TVDB_IMG_URL
import java.util.*
class ShowSearchAdapter(val context: Context, val listener: ShowSearchAdapterListener)
: RecyclerView.Adapter<ShowSearchAdapter.ViewHolder>() {
private val tvdbShows = ArrayList<TVDBShow>()
interface ShowSearchAdapterListener {
fun onClick(tvdbShow: TVDBShow)
}
inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
val titleTv =
itemView!!.findViewById(R.id.stw_title_text) as TextView
val bannerIv =
itemView!!.findViewById(R.id.stw_banner_image) as ImageView
init {
itemView!!.setOnClickListener { listener.onClick(tvdbShows[adapterPosition]) }
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ShowSearchAdapter.ViewHolder {
val v = LayoutInflater.from(parent!!.context)
.inflate(R.layout.show_item, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return tvdbShows.size
}
override fun onBindViewHolder(holder: ShowSearchAdapter.ViewHolder?, position: Int) {
if (holder != null) {
val show = tvdbShows[position]
holder.titleTv.text = show.title
Picasso.with(context)
.load(TVDB_IMG_URL + show.banner)
.into(holder.bannerIv)
}
}
fun addAll(tvdbShows: List<TVDBShow>) {
this.tvdbShows.addAll(tvdbShows)
notifyDataSetChanged()
}
}
| mit | a575caad56164851ea73662c1e88e3cb | 31.766667 | 102 | 0.684639 | 4.20985 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/show/EpisodeFragment.kt | 1 | 14066 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.show
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import butterknife.BindView
import butterknife.OnClick
import net.simonvt.cathode.R
import net.simonvt.cathode.api.enumeration.ItemType
import net.simonvt.cathode.api.util.TraktUtils
import net.simonvt.cathode.common.ui.fragment.RefreshableAppBarFragment
import net.simonvt.cathode.common.ui.instantiate
import net.simonvt.cathode.common.util.DateStringUtils
import net.simonvt.cathode.common.util.Ids
import net.simonvt.cathode.common.util.Intents
import net.simonvt.cathode.common.util.guava.Preconditions
import net.simonvt.cathode.common.widget.CircularProgressIndicator
import net.simonvt.cathode.entity.Comment
import net.simonvt.cathode.entity.Episode
import net.simonvt.cathode.images.ImageType
import net.simonvt.cathode.images.ImageUri
import net.simonvt.cathode.provider.util.DataHelper
import net.simonvt.cathode.settings.TraktLinkSettings
import net.simonvt.cathode.sync.scheduler.EpisodeTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.NavigationListener
import net.simonvt.cathode.ui.comments.LinearCommentsAdapter
import net.simonvt.cathode.ui.dialog.CheckInDialog
import net.simonvt.cathode.ui.dialog.CheckInDialog.Type
import net.simonvt.cathode.ui.dialog.RatingDialog
import net.simonvt.cathode.ui.history.AddToHistoryDialog
import net.simonvt.cathode.ui.history.RemoveFromHistoryDialog
import net.simonvt.cathode.ui.lists.ListsDialog
import net.simonvt.cathode.widget.CheckInDrawable
import javax.inject.Inject
class EpisodeFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val episodeScheduler: EpisodeTaskScheduler
) : RefreshableAppBarFragment() {
@BindView(R.id.title)
@JvmField
var title: TextView? = null
@BindView(R.id.overview)
@JvmField
var overview: TextView? = null
@BindView(R.id.episodeNumber)
@JvmField
var episodeNumber: TextView? = null
@BindView(R.id.firstAired)
@JvmField
var firstAired: TextView? = null
@BindView(R.id.rating)
@JvmField
var rating: CircularProgressIndicator? = null
@BindView(R.id.checkmarks)
@JvmField
var checkmarks: View? = null
@BindView(R.id.isWatched)
@JvmField
var watchedView: View? = null
@BindView(R.id.inCollection)
@JvmField
var inCollectionView: View? = null
@BindView(R.id.inWatchlist)
@JvmField
var inWatchlistView: View? = null
@BindView(R.id.commentsParent)
@JvmField
var commentsParent: View? = null
@BindView(R.id.commentsHeader)
@JvmField
var commentsHeader: View? = null
@BindView(R.id.commentsContainer)
@JvmField
var commentsContainer: LinearLayout? = null
@BindView(R.id.viewOnTrakt)
@JvmField
var viewOnTrakt: TextView? = null
private lateinit var viewModel: EpisodeViewModel
private var userComments: List<Comment>? = null
private var comments: List<Comment>? = null
var episodeId: Long = 0
private set
private var episode: Episode? = null
private var episodeTitle: String? = null
private var showTitle: String? = null
private var showId = -1L
private var season = -1
private var seasonId = -1L
private var currentRating: Int = 0
private var loaded: Boolean = false
private var watched: Boolean = false
private var collected: Boolean = false
private var inWatchlist: Boolean = false
private var watching: Boolean = false
private var checkedIn: Boolean = false
lateinit var navigationListener: NavigationListener
private var checkInDrawable: CheckInDrawable? = null
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
val args = arguments
episodeId = args!!.getLong(ARG_EPISODEID)
showTitle = args.getString(ARG_SHOW_TITLE)
setTitle(showTitle)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(EpisodeViewModel::class.java)
viewModel.setEpisodeId(episodeId)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.episode.observe(this, Observer { episode -> updateEpisodeViews(episode) })
viewModel.userComments.observe(this, Observer { userComments ->
[email protected] = userComments
updateComments()
})
viewModel.comments.observe(this, Observer { comments ->
[email protected] = comments
updateComments()
})
}
override fun onHomeClicked() {
if (showId >= 0L && seasonId >= 0L) {
navigationListener.upFromEpisode(showId, showTitle, seasonId)
} else {
navigationListener.onHomeClicked()
}
}
public override fun createView(
inflater: LayoutInflater,
container: ViewGroup?,
inState: Bundle?
): View {
return inflater.inflate(R.layout.fragment_episode, container, false)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
val linkDrawable = VectorDrawableCompat.create(resources, R.drawable.ic_link_black_24dp, null)
viewOnTrakt!!.setCompoundDrawablesWithIntrinsicBounds(linkDrawable, null, null, null)
if (TraktLinkSettings.isLinked(requireContext())) {
rating!!.setOnClickListener {
requireFragmentManager().instantiate(
RatingDialog::class.java,
RatingDialog.getArgs(RatingDialog.Type.EPISODE, episodeId, currentRating)
).show(requireFragmentManager(), DIALOG_RATING)
}
}
}
override fun onRefresh() {
viewModel.refresh()
}
@OnClick(R.id.commentsHeader)
fun onShowComments() {
navigationListener.onDisplayComments(ItemType.EPISODE, episodeId)
}
override fun createMenu(toolbar: Toolbar) {
if (loaded) {
val menu = toolbar.menu
if (TraktLinkSettings.isLinked(requireContext())) {
if (checkInDrawable == null) {
checkInDrawable = CheckInDrawable(toolbar.context)
checkInDrawable!!.setWatching(watching || checkedIn)
checkInDrawable!!.setId(episodeId)
}
val checkInItem: MenuItem
if (watching || checkedIn) {
checkInItem = menu.add(0, R.id.action_checkin, 1, R.string.action_checkin_cancel)
} else {
checkInItem = menu.add(0, R.id.action_checkin, 1, R.string.action_checkin)
}
checkInItem.setIcon(checkInDrawable).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
checkInItem.isEnabled = !watching
}
menu.add(0, R.id.action_history_add, 3, R.string.action_history_add)
if (watched) {
menu.add(0, R.id.action_history_remove, 4, R.string.action_history_remove)
} else {
if (inWatchlist) {
menu.add(0, R.id.action_watchlist_remove, 5, R.string.action_watchlist_remove)
} else {
menu.add(0, R.id.action_watchlist_add, 6, R.string.action_watchlist_add)
}
}
menu.add(0, R.id.action_history_add_older, 7, R.string.action_history_add_older)
if (collected) {
menu.add(0, R.id.action_collection_remove, 8, R.string.action_collection_remove)
} else {
menu.add(0, R.id.action_collection_add, 9, R.string.action_collection_add)
}
menu.add(0, R.id.action_list_add, 10, R.string.action_list_add)
}
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_history_add -> {
requireFragmentManager().instantiate(
AddToHistoryDialog::class.java,
AddToHistoryDialog.getArgs(AddToHistoryDialog.Type.EPISODE, episodeId, episodeTitle)
).show(requireFragmentManager(), AddToHistoryDialog.TAG)
return true
}
R.id.action_history_remove -> {
if (TraktLinkSettings.isLinked(requireContext())) {
requireFragmentManager().instantiate(
RemoveFromHistoryDialog::class.java,
RemoveFromHistoryDialog.getArgs(
RemoveFromHistoryDialog.Type.EPISODE,
episodeId,
episodeTitle,
showTitle
)
).show(requireFragmentManager(), RemoveFromHistoryDialog.TAG)
} else {
episodeScheduler.removeFromHistory(episodeId)
}
return true
}
R.id.action_history_add_older -> {
requireFragmentManager().instantiate(
AddToHistoryDialog::class.java,
AddToHistoryDialog.getArgs(AddToHistoryDialog.Type.EPISODE_OLDER, episodeId, episodeTitle)
).show(requireFragmentManager(), AddToHistoryDialog.TAG)
return true
}
R.id.action_checkin -> {
if (!watching) {
if (checkedIn) {
episodeScheduler.cancelCheckin()
if (checkInDrawable != null) {
checkInDrawable!!.setWatching(false)
}
} else {
if (!CheckInDialog.showDialogIfNecessary(
requireActivity(), Type.SHOW, episodeTitle,
episodeId
)
) {
episodeScheduler.checkin(episodeId, null, false, false, false)
checkInDrawable!!.setWatching(true)
}
}
}
return true
}
R.id.action_checkin_cancel -> {
episodeScheduler.cancelCheckin()
return true
}
R.id.action_collection_add -> {
episodeScheduler.setIsInCollection(episodeId, true)
return true
}
R.id.action_collection_remove -> {
episodeScheduler.setIsInCollection(episodeId, false)
return true
}
R.id.action_watchlist_add -> {
episodeScheduler.setIsInWatchlist(episodeId, true)
return true
}
R.id.action_watchlist_remove -> {
episodeScheduler.setIsInWatchlist(episodeId, false)
return true
}
R.id.action_list_add -> {
requireFragmentManager().instantiate(
ListsDialog::class.java,
ListsDialog.getArgs(ItemType.EPISODE, episodeId)
).show(requireFragmentManager(), DIALOG_LISTS_ADD)
return true
}
else -> return super.onMenuItemClick(item)
}
}
private fun updateEpisodeViews(episode: Episode) {
this.episode = episode
loaded = true
showId = episode.showId
seasonId = episode.seasonId
showTitle = episode.showTitle
watched = episode.watched
collected = episode.inCollection
inWatchlist = episode.inWatchlist
watching = episode.watching
checkedIn = episode.checkedIn
season = episode.season
episodeTitle = DataHelper.getEpisodeTitle(
requireContext(), episode.title, season,
episode.episode, episode.watched
)
title!!.text = episodeTitle
episodeNumber!!.text = getString(
R.string.season_x_episode, season,
episode.episode
)
overview!!.text = episode.overview
val screenshotUri = ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, episodeId)
setBackdrop(screenshotUri, true)
firstAired!!.text =
DateStringUtils.getAirdateInterval(requireContext(), episode.firstAired, true)
if (checkInDrawable != null) {
checkInDrawable!!.setWatching(watching || checkedIn)
}
val hasCheckmark = watched || collected || inWatchlist
checkmarks!!.visibility = if (hasCheckmark) View.VISIBLE else View.GONE
watchedView!!.visibility = if (watched) View.VISIBLE else View.GONE
inCollectionView!!.visibility = if (collected) View.VISIBLE else View.GONE
inWatchlistView!!.visibility = if (inWatchlist) View.VISIBLE else View.GONE
currentRating = episode.userRating
val ratingAll = episode.rating
rating!!.setValue(ratingAll)
viewOnTrakt!!.setOnClickListener {
Intents.openUrl(
requireContext(),
TraktUtils.getTraktEpisodeUrl(episode.traktId)
)
}
invalidateMenu()
}
private fun updateComments() {
LinearCommentsAdapter.updateComments(
requireContext(),
commentsContainer!!,
userComments,
comments
)
commentsParent!!.visibility = View.VISIBLE
}
companion object {
private const val TAG = "net.simonvt.cathode.ui.show.EpisodeFragment"
private const val ARG_EPISODEID = "net.simonvt.cathode.ui.show.EpisodeFragment.episodeId"
private const val ARG_SHOW_TITLE = "net.simonvt.cathode.ui.show.EpisodeFragment.showTitle"
private const val DIALOG_RATING = "net.simonvt.cathode.ui.show.EpisodeFragment.ratingDialog"
private const val DIALOG_LISTS_ADD =
"net.simonvt.cathode.ui.show.EpisodeFragment.listsAddDialog"
@JvmStatic
fun getTag(episodeId: Long): String {
return TAG + "/" + episodeId + "/" + Ids.newId()
}
@JvmStatic
fun getArgs(episodeId: Long, showTitle: String?): Bundle {
Preconditions.checkArgument(episodeId >= 0, "episodeId must be >= 0, was $episodeId")
val args = Bundle()
args.putLong(ARG_EPISODEID, episodeId)
args.putString(ARG_SHOW_TITLE, showTitle)
return args
}
}
}
| apache-2.0 | 8a2a4d042286d34a8d5c01a99ee84715 | 30.538117 | 100 | 0.700341 | 4.294962 | false | false | false | false |
FHannes/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GuiTestLocalLauncher.kt | 2 | 8368 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.launcher
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.impl.GuiTestStarter
import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder
import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder.Companion.isWin
import com.intellij.testGuiFramework.launcher.ide.Ide
import com.intellij.testGuiFramework.launcher.ide.IdeType
import com.intellij.util.containers.HashSet
import junit.framework.Assert.fail
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.URL
import java.nio.file.Paths
import java.util.jar.JarInputStream
import java.util.stream.Collectors
/**
* @author Sergey Karashevich
*/
object GuiTestLocalLauncher {
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher")
var process: Process? = null
fun killProcessIfPossible() {
try {
if (process?.isAlive ?: false) process!!.destroyForcibly()
}
catch (e: KotlinNullPointerException) {
LOG.error("Seems that process has already destroyed, right after condition")
}
}
fun runIdeLocally(ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) {
//todo: check that we are going to run test locally
val args = createArgs(ide, port)
return startIde(ide, args)
}
fun runIdeByPath(path: String, ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) {
//todo: check that we are going to run test locally
val args = createArgs(path, port)
return startIde(ide, args)
}
private fun startIde(ide: Ide, args: List<String>) {
LOG.info("Running $ide locally")
val runnable: () -> Unit = {
val ideaStartTest = ProcessBuilder().inheritIO().command(args)
process = ideaStartTest.start()
val wait = process!!.waitFor()
if (process!!.exitValue() != 1) println("${ide.ideType} started successfully")
else {
System.err.println("Process execution error:")
System.err.println(BufferedReader(InputStreamReader(process!!.errorStream)).lines().collect(Collectors.joining("\n")))
fail("Starting ${ide.ideType} failed.")
}
}
val ideaTestThread = Thread(runnable, "IdeaTestThread")
ideaTestThread.start()
}
private fun createArgs(ide: Ide, port: Int = 0): List<String> {
var resultingArgs = listOf<String>()
.plus(getCurrentJavaExec())
.plus(getDefaultVmOptions(ide))
.plus("-classpath")
.plus(getOsSpecificClasspath(ide.ideType.mainModule))
.plus("com.intellij.idea.Main")
.plus(GuiTestStarter.COMMAND_NAME)
if (port != 0) resultingArgs = resultingArgs.plus("port=$port")
LOG.info("Running with args: ${resultingArgs.joinToString(" ")}")
return resultingArgs
}
private fun createArgs(path: String, port: Int = 0): List<String> {
var resultingArgs = listOf<String>()
.plus("open")
.plus(path) //path to exec
.plus("--args")
.plus(GuiTestStarter.COMMAND_NAME)
.plus("-Didea.additional.classpath=/Users/jetbrains/IdeaProjects/idea-ultimate/out/classes/test/testGuiFramework/")
if (port != 0) resultingArgs = resultingArgs.plus("port=$port")
LOG.info("Running with args: ${resultingArgs.joinToString(" ")}")
return resultingArgs
}
private fun getDefaultVmOptions(ide: Ide,
configPath: String = "./config",
systemPath: String = "./system",
bootClasspath: String = "./out/classes/production/boot",
encoding: String = "UTF-8",
isInternal: Boolean = true,
useMenuScreenBar: Boolean = true,
debugPort: Int = 5009,
suspendDebug: String = "n"): List<String> =
listOf<String>()
.plus("-ea")
.plus("-Xbootclasspath/p:$bootClasspath")
.plus("-Dsun.awt.disablegrab=true")
.plus("-Dsun.io.useCanonCaches=false")
.plus("-Djava.net.preferIPv4Stack=true")
.plus("-Dapple.laf.useScreenMenuBar=${useMenuScreenBar.toString()}")
.plus("-Didea.is.internal=${isInternal.toString()}")
.plus("-Didea.config.path=$configPath")
.plus("-Didea.system.path=$systemPath")
.plus("-Dfile.encoding=$encoding")
.plus("-Didea.platform.prefix=${ide.ideType.platformPrefix}")
.plus("-Xdebug")
.plus(
"-Xrunjdwp:transport=dt_socket,server=y,suspend=$suspendDebug,address=$debugPort") //todo: add System.getProperty(...) to customize debug port
private fun getCurrentJavaExec(): String {
val homePath = System.getProperty("java.home")
val jreDir = File(homePath)
val homeDir = File(jreDir.parent)
val binDir = File(homeDir, "bin")
val javaName: String = if (System.getProperty("os.name").toLowerCase().contains("win")) "java.exe" else "java"
return File(binDir, javaName).path
}
private fun getOsSpecificClasspath(moduleName: String): String = ClassPathBuilder.buildOsSpecific(
getFullClasspath(moduleName).map { it.path })
/**
* return union of classpaths for current test (get from classloader) and classpaths of main and testGuiFramework modules*
*/
private fun getFullClasspath(moduleName: String): List<File> {
val classpath = getExtendedClasspath(moduleName)
classpath.addAll(getTestClasspath())
return classpath.toList()
}
private fun getTestClasspath(): List<File> {
val classLoader = this.javaClass.classLoader
val urlClassLoaderClass = classLoader.javaClass
val getUrlsMethod = urlClassLoaderClass.getMethod("getUrls")
@Suppress("UNCHECKED_CAST")
var urls = getUrlsMethod.invoke(classLoader) as List<URL>
if (isWin()) {
val classPathUrl = urls.find { it.toString().contains(Regex("classpath[\\d]*.jar")) }
val jarStream = JarInputStream(File(classPathUrl!!.path).inputStream())
val mf = jarStream.manifest
urls = mf.mainAttributes.getValue("Class-Path").split(" ").map { URL(it) }
}
return urls.map { Paths.get(it.toURI()).toFile() }
}
/**
* return union of classpaths for @moduleName and testGuiFramework modules
*/
private fun getExtendedClasspath(moduleName: String): MutableSet<File> {
val modules = getModulesList()
val resultSet = HashSet<File>()
val module = modules.module(moduleName)
assert(module != null)
resultSet.addAll(module!!.getClasspath())
val testGuiFrameworkModule = modules.module("testGuiFramework")
assert(testGuiFrameworkModule != null)
resultSet.addAll(testGuiFrameworkModule!!.getClasspath())
return resultSet
}
private fun List<JpsModule>.module(moduleName: String): JpsModule? =
this.filter { it.name == moduleName }.firstOrNull()
private fun JpsModule.getClasspath(): MutableCollection<File> =
JpsJavaExtensionService.dependencies(this).productionOnly().runtimeOnly().recursively().classes().roots
private fun getModulesList(): MutableList<JpsModule> {
val home = PathManager.getHomePath()
val model = JpsElementFactory.getInstance().createModel()
val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global)
JpsProjectLoader.loadProject(model.project, pathVariables, home)
return model.project.modules
}
}
| apache-2.0 | c3b192da1819772f6b31296e0b4e4f69 | 39.230769 | 150 | 0.695148 | 4.501345 | false | true | false | false |
FHannes/intellij-community | java/execution/impl/src/com/intellij/execution/ui/DefaultJreSelector.kt | 2 | 4169 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.ui
import com.intellij.application.options.ModulesComboBox
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.util.JavaParametersUtil
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.ui.EditorTextFieldWithBrowseButton
/**
* @author nik
*/
abstract class DefaultJreSelector {
companion object {
@JvmStatic
fun projectSdk(project: Project): DefaultJreSelector = ProjectSdkSelector(project)
@JvmStatic
fun fromModuleDependencies(moduleComboBox: ModulesComboBox, productionOnly: Boolean): DefaultJreSelector
= SdkFromModuleDependencies(moduleComboBox, {productionOnly})
@JvmStatic
fun fromSourceRootsDependencies(moduleComboBox: ModulesComboBox, classSelector: EditorTextFieldWithBrowseButton): DefaultJreSelector
= SdkFromSourceRootDependencies(moduleComboBox, classSelector)
}
abstract fun getNameAndDescription(): Pair<String?, String>
open fun addChangeListener(listener: Runnable) {
}
fun getDescriptionString(): String {
val (name, description) = getNameAndDescription()
return " (${name ?: "<no JRE>"} - $description)"
}
class ProjectSdkSelector(val project: Project): DefaultJreSelector() {
override fun getNameAndDescription() = Pair.create(ProjectRootManager.getInstance(project).projectSdkName, "project SDK")
}
open class SdkFromModuleDependencies(val moduleComboBox: ModulesComboBox, val productionOnly: () -> Boolean): DefaultJreSelector() {
override fun getNameAndDescription(): Pair<String?, String> {
val module = moduleComboBox.selectedModule ?: return Pair.create(null, "module not specified")
val productionOnly = productionOnly()
val jdkToRun = JavaParameters.getJdkToRunModule(module, productionOnly)
val moduleJdk = ModuleRootManager.getInstance(module).sdk
if (moduleJdk == null || jdkToRun == null) {
return Pair.create(null, "module not specified")
}
if (moduleJdk.homeDirectory == jdkToRun.homeDirectory) {
return Pair.create(moduleJdk.name, "SDK of '${module.name}' module")
}
return Pair.create(jdkToRun.name, "newest SDK from '${module.name}' module${if (productionOnly) "" else " test"} dependencies")
}
override fun addChangeListener(listener: Runnable) {
moduleComboBox.addActionListener { listener.run() }
}
}
class SdkFromSourceRootDependencies(moduleComboBox: ModulesComboBox, val classSelector: EditorTextFieldWithBrowseButton)
: SdkFromModuleDependencies(moduleComboBox, { isClassInProductionSources(moduleComboBox, classSelector) }) {
override fun addChangeListener(listener: Runnable) {
super.addChangeListener(listener)
classSelector.childComponent.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent?) {
listener.run()
}
})
}
}
}
private fun isClassInProductionSources(moduleSelector: ModulesComboBox, classSelector: EditorTextFieldWithBrowseButton): Boolean {
val module = moduleSelector.selectedModule ?: return false
return JavaParametersUtil.isClassInProductionSources(classSelector.text, module) ?: false
}
| apache-2.0 | b706e30305a467ff03ed0b39d34bf459 | 39.475728 | 136 | 0.762773 | 4.716063 | false | false | false | false |
EMResearch/EMB | jdk_8_maven/cs/graphql/graphql-ncs/src/main/kotlin/org/graphqlncs/type/Remainder.kt | 1 | 1038 | package org.graphqlncs.type
import org.springframework.stereotype.Component
@Component
class Remainder {
fun exe(a: Int, b: Int): Int {
var r = 0 - 1
var cy = 0
var ny = 0
if (a == 0) ; else if (b == 0) ; else if (a > 0) if (b > 0) while (a - ny >= b) {
ny = ny + b
r = a - ny
cy = cy + 1
} else // b<0
//while((a+ny)>=Math.abs(b))
while (a + ny >= if (b >= 0) b else -b) {
ny = ny + b
r = a + ny
cy = cy - 1
} else // a<0
if (b > 0) //while(Math.abs(a+ny)>=b)
while ((if (a + ny >= 0) a + ny else -(a + ny)) >= b) {
ny = ny + b
r = a + ny
cy = cy - 1
} else while (b >= a - ny) {
ny = ny + b
//r=Math.abs(a-ny);
r = if (a - ny >= 0) a - ny else -(a - ny)
cy = cy + 1
}
return r
}
} | apache-2.0 | 9c474cde30cc128f01be5b44e2c25b56 | 28.685714 | 89 | 0.333333 | 3.135952 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/DebugLogActivity.kt | 1 | 5688 | /*****************************************************************************
* DebugLogActivity.java
*
* Copyright © 2013-2015 VLC authors and VideoLAN
* Copyright © 2013 Edward Wang
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import androidx.fragment.app.FragmentActivity
import com.google.android.material.snackbar.Snackbar
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.vlc.DebugLogService
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.util.Permissions
class DebugLogActivity : FragmentActivity(), DebugLogService.Client.Callback {
private lateinit var client: DebugLogService.Client
private lateinit var startButton: Button
private lateinit var stopButton: Button
private lateinit var copyButton: Button
private lateinit var clearButton: Button
private lateinit var saveButton: Button
private lateinit var logView: ListView
private var logList: MutableList<String> = ArrayList()
private lateinit var logAdapter: ArrayAdapter<String>
private val startClickListener = View.OnClickListener {
startButton.isEnabled = false
stopButton.isEnabled = false
client.start()
}
private val stopClickListener = View.OnClickListener {
startButton.isEnabled = false
stopButton.isEnabled = false
client.stop()
}
private val clearClickListener = View.OnClickListener {
if (::client.isInitialized) client.clear()
logList.clear()
if (::logAdapter.isInitialized) logAdapter.notifyDataSetChanged()
setOptionsButtonsEnabled(false)
}
private val saveClickListener = View.OnClickListener {
if (AndroidUtil.isOOrLater && !Permissions.canWriteStorage())
Permissions.askWriteStoragePermission(this@DebugLogActivity, false, Runnable { client.save() })
else
client.save()
}
private val copyClickListener = View.OnClickListener { v ->
val buffer = StringBuffer()
for (line in logList)
buffer.append(line).append("\n")
val clipboard = applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
clipboard.text = buffer
UiTools.snacker(v.rootView, R.string.copied_to_clipboard)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.debug_log)
startButton = findViewById(R.id.start_log)
stopButton = findViewById(R.id.stop_log)
logView = findViewById(R.id.log_list)
copyButton = findViewById(R.id.copy_to_clipboard)
clearButton = findViewById(R.id.clear_log)
saveButton = findViewById(R.id.save_to_file)
client = DebugLogService.Client(this, this)
startButton.isEnabled = false
stopButton.isEnabled = false
setOptionsButtonsEnabled(false)
startButton.setOnClickListener(startClickListener)
stopButton.setOnClickListener(stopClickListener)
clearButton.setOnClickListener(clearClickListener)
saveButton.setOnClickListener(saveClickListener)
copyButton.setOnClickListener(copyClickListener)
}
override fun onDestroy() {
client.release()
super.onDestroy()
}
private fun setOptionsButtonsEnabled(enabled: Boolean) {
clearButton.isEnabled = enabled
copyButton.isEnabled = enabled
saveButton.isEnabled = enabled
}
override fun onStarted(logList: List<String>) {
startButton.isEnabled = false
stopButton.isEnabled = true
if (logList.isNotEmpty())
setOptionsButtonsEnabled(true)
this.logList = ArrayList(logList)
logAdapter = ArrayAdapter(this, R.layout.debug_log_item, this.logList)
logView.adapter = logAdapter
logView.transcriptMode = ListView.TRANSCRIPT_MODE_NORMAL
if (this.logList.size > 0)
logView.setSelection(this.logList.size - 1)
}
override fun onStopped() {
startButton.isEnabled = true
stopButton.isEnabled = false
}
override fun onLog(msg: String) {
logList.add(msg)
if (::logAdapter.isInitialized) logAdapter.notifyDataSetChanged()
setOptionsButtonsEnabled(true)
}
override fun onSaved(success: Boolean, path: String) {
if (success) {
Snackbar.make(logView, String.format(
getString(R.string.dump_logcat_success),
path), Snackbar.LENGTH_LONG).show()
} else {
UiTools.snacker(window.decorView.findViewById(android.R.id.content), R.string.dump_logcat_failure)
}
}
companion object {
const val TAG = "VLC/DebugLogActivity"
}
}
| gpl-2.0 | 594b954a545b3eb45815feb25ef1b8b6 | 34.987342 | 119 | 0.690995 | 4.742285 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/androidTest/org/videolan/vlc/database/BrowserFavDaoTest.kt | 1 | 5123 | /*******************************************************************************
* BrowserFavDaoTest.kt
* ****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
******************************************************************************/
package org.videolan.vlc.database
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.junit.Test
import org.junit.runner.RunWith
import org.videolan.vlc.util.getValue
import org.videolan.vlc.util.TestUtil
@RunWith(AndroidJUnit4::class)
class BrowserFavDaoTest: DbTest() {
@Test fun insertTwoNetworkAndOneLocal_GetAllShouldReturnThreeFav() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFav = TestUtil.createLocalFavs(1)[0]
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
db.browserFavDao().insert(fakeLocalFav)
/*===========================================================*/
val browsersFavs = getValue(db.browserFavDao().getAll())
assertThat(browsersFavs.size, `is`(3))
assertThat(browsersFavs, hasItem(fakeNetworkFavs[0]))
assertThat(browsersFavs, hasItem(fakeNetworkFavs[1]))
assertThat(browsersFavs, hasItem(fakeLocalFav))
}
@Test fun insertTwoNetworkAndOneLocal_GetNetworkFavsShouldReturnTwoFav() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFavs = TestUtil.createLocalFavs(1)[0]
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
db.browserFavDao().insert(fakeLocalFavs)
/*===========================================================*/
val networkFavs = getValue(db.browserFavDao().getAllNetwrokFavs())
assertThat(networkFavs.size, equalTo(2))
assertThat(networkFavs, hasItem(fakeNetworkFavs[0]))
assertThat(networkFavs, hasItem(fakeNetworkFavs[1]))
}
@Test fun insertTwoNetworkAndTwoLocal_GetLocalFavsShouldReturnTwoFav() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFavs = TestUtil.createLocalFavs(2)
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
fakeLocalFavs.forEach { db.browserFavDao().insert(it)}
/*===========================================================*/
val localFavs = getValue(db.browserFavDao().getAllLocalFavs())
assertThat(localFavs.size, `is`(2))
assertThat(localFavs, hasItem(localFavs[0]))
assertThat(localFavs, hasItem(localFavs[1]))
}
@Test fun insertTwoNetworkAndTwoLocal_GetFavByUriShouldReturnOneFav() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFavs = TestUtil.createLocalFavs(2)
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
fakeLocalFavs.forEach { db.browserFavDao().insert(it)}
/*===========================================================*/
val fav = db.browserFavDao().get(fakeNetworkFavs[0].uri)
assertThat(fav.size, `is`(1))
assertThat(fav[0], `is`(fakeNetworkFavs[0]))
}
@Test fun insertTwoNetworkAndTwoLocal_DeleteOne() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFavs = TestUtil.createLocalFavs(2)
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
fakeLocalFavs.forEach { db.browserFavDao().insert(it)}
/*===========================================================*/
db.browserFavDao().delete(fakeNetworkFavs[0].uri)
val favs = getValue(db.browserFavDao().getAll())
assertThat(favs.size, `is`(3))
assertThat(favs, not(hasItem(fakeNetworkFavs[0])))
}
@Test fun insertTwoNetworkAndTwoLocal_DeleteAll() {
val fakeNetworkFavs = TestUtil.createNetworkFavs(2)
val fakeLocalFavs = TestUtil.createLocalFavs(2)
fakeNetworkFavs.forEach { db.browserFavDao().insert(it) }
fakeLocalFavs.forEach { db.browserFavDao().insert(it)}
/*===========================================================*/
fakeLocalFavs.forEach { db.browserFavDao().delete(it.uri) }
fakeNetworkFavs.forEach { db.browserFavDao().delete(it.uri) }
val favs = getValue(db.browserFavDao().getAll())
assertThat(favs.size, `is`(0))
}
} | gpl-2.0 | 131e43154356f667b4507c02a50755f6 | 37.810606 | 80 | 0.617142 | 4.377778 | false | true | false | false |
jereksel/LibreSubstratum | sublib/reader/src/main/kotlin/com/jereksel/libresubstratumlib/ThemeReader.kt | 1 | 3246 | package com.jereksel.libresubstratumlib
import java.io.File
import java.util.zip.ZipFile
class ThemeReader {
fun readThemePack(location: File): ThemePack {
val overlaysLocation = File(location, "overlays")
if (!overlaysLocation.exists()) {
throw IllegalArgumentException("Overlays directory doesn't exists: $overlaysLocation")
}
val themedPackages = overlaysLocation
.listFiles()
.filter { it.isDirectory }
.map { readTheme(it) }
return ThemePack(themedPackages, readType3Data(overlaysLocation))
}
fun readTheme(location: File) = Theme(location.name, readType1Data(location), readType2Data(location))
fun readType1Data(location: File): List<Type1Data> {
val typeMap = mutableMapOf<String, MutableList<Type1Extension>>()
location.listFiles()
.filter { it.name.startsWith("type1") }
.forEach {
//TODO: Refactor this
val type = "${it.name[5]}"
if (it.name.length == 6) {
typeMap.getOrPut(type, { mutableListOf() }).add(Type1Extension(it.readText(), true))
} else {
val name = it.name.substring(7).removeSuffix(".xml")
typeMap.getOrPut(type, { mutableListOf() }).add(Type1Extension(name, false))
}
}
return typeMap.map { Type1Data(it.value, it.key) }.sortedBy { it.suffix }
}
fun readType2Data(dir: File): Type2Data? {
val type2File = File(dir, "type2")
if (!type2File.exists()) {
return null
}
val firstType = Type2Extension(type2File.readText().trim(), true)
val rest = dir.listFiles()
.filter { it.isDirectory }
.filter { it.name.startsWith("type2") }
.map { it.name.removePrefix("type2_") }
.map { Type2Extension(it, false) }
.sortedBy { it.name }
.toTypedArray()
return Type2Data(listOf(firstType, *rest))
}
fun readType3Data(location: File): Type3Data? {
val dir = location.listFiles()[0]
val type3File = File(dir, "type3")
if (!type3File.exists()) {
return null
}
val firstType = Type3Extension(type3File.readText().trim(), true)
val rest = dir.listFiles()
.filter { it.isDirectory }
.filter { it.name.startsWith("type3") }
.map { it.name.removePrefix("type3_") }
.map { Type3Extension(it, false) }
.sortedBy { it.name }
.toTypedArray()
return Type3Data(listOf(firstType, *rest))
}
fun checkIfEncrypted(apk: File): Boolean {
return ZipFile(apk).use { zipFile ->
val enc = zipFile.entries().asSequence().firstOrNull { it.name.endsWith(".enc") }?.name
if (enc == null) {
//No encrypted file
false
} else {
val nonEnc = enc.removeSuffix(".enc")
zipFile.getEntry(nonEnc) == null
}
}
}
} | mit | 31007488dd8751205f3ad4e3153a84a2 | 31.148515 | 108 | 0.536352 | 4.428377 | false | false | false | false |
arturbosch/detekt | detekt-generator/src/main/kotlin/io/gitlab/arturbosch/detekt/generator/printer/RuleSetPagePrinter.kt | 1 | 4329 | package io.gitlab.arturbosch.detekt.generator.printer
import io.gitlab.arturbosch.detekt.generator.collection.Active
import io.gitlab.arturbosch.detekt.generator.collection.Rule
import io.gitlab.arturbosch.detekt.generator.collection.RuleSetPage
import io.gitlab.arturbosch.detekt.generator.out.MarkdownContent
import io.gitlab.arturbosch.detekt.generator.out.bold
import io.gitlab.arturbosch.detekt.generator.out.code
import io.gitlab.arturbosch.detekt.generator.out.codeBlock
import io.gitlab.arturbosch.detekt.generator.out.crossOut
import io.gitlab.arturbosch.detekt.generator.out.description
import io.gitlab.arturbosch.detekt.generator.out.h3
import io.gitlab.arturbosch.detekt.generator.out.h4
import io.gitlab.arturbosch.detekt.generator.out.item
import io.gitlab.arturbosch.detekt.generator.out.list
import io.gitlab.arturbosch.detekt.generator.out.markdown
import io.gitlab.arturbosch.detekt.generator.out.paragraph
object RuleSetPagePrinter : DocumentationPrinter<RuleSetPage> {
override fun print(item: RuleSetPage): String {
return markdown {
if (item.ruleSet.description.isNotEmpty()) {
paragraph { item.ruleSet.description }
} else {
paragraph { "TODO: Specify description" }
}
item.rules.forEach {
markdown { printRule(it) }
}
}
}
private fun printRule(rule: Rule): String {
return markdown {
h3 { rule.name }
if (rule.description.isNotEmpty()) {
paragraph { rule.description }
} else {
paragraph { "TODO: Specify description" }
}
paragraph {
"${bold { "Active by default" }}: ${if (rule.defaultActivationStatus.active) "Yes" else "No"}" +
((rule.defaultActivationStatus as? Active)?.let { " - Since v${it.since}" }.orEmpty())
}
if (rule.requiresTypeResolution) {
paragraph {
bold { "Requires Type Resolution" }
}
}
if (rule.debt.isNotEmpty()) {
paragraph {
"${bold { "Debt" }}: ${rule.debt}"
}
}
if (!rule.aliases.isNullOrEmpty()) {
paragraph {
"${bold { "Aliases" }}: ${rule.aliases}"
}
}
if (rule.configuration.isNotEmpty()) {
h4 { "Configuration options:" }
list {
rule.configuration.forEach {
val defaultValues = formatDefaultValues(it.defaultValue)
val defaultAndroidValues = it.defaultAndroidValue?.let(RuleSetPagePrinter::formatDefaultValues)
val defaultString = if (defaultAndroidValues != null) {
"(default: ${code { defaultValues }}) (android default: ${code { defaultAndroidValues }})"
} else {
"(default: ${code { defaultValues }})"
}
if (it.isDeprecated()) {
item {
crossOut { code { it.name } } + " " + defaultString
}
description { "${bold { "Deprecated" }}: ${it.deprecated}" }
} else {
item {
code { it.name } + " " + defaultString
}
}
description { it.description }
}
}
}
printRuleCodeExamples(rule)
}
}
private fun formatDefaultValues(rawString: String) = rawString.lines().joinToString {
it.trim().removePrefix("- ")
}
private fun MarkdownContent.printRuleCodeExamples(rule: Rule) {
if (rule.nonCompliantCodeExample.isNotEmpty()) {
h4 { "Noncompliant Code:" }
paragraph { codeBlock { rule.nonCompliantCodeExample } }
}
if (rule.compliantCodeExample.isNotEmpty()) {
h4 { "Compliant Code:" }
paragraph { codeBlock { rule.compliantCodeExample } }
}
}
}
| apache-2.0 | 9ac04b5252b0934de37eab2bbcc185db | 37.651786 | 119 | 0.537538 | 5.045455 | false | false | false | false |
wiltonlazary/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/RegressionsReporter.kt | 1 | 7253 | /*
* Copyright 2010-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/LICENSE.txt file.
*/
package org.jetbrains.kotlin
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory
import org.jetbrains.report.json.*
import java.io.FileInputStream
import java.io.IOException
import java.io.File
import java.util.concurrent.TimeUnit
import java.net.HttpURLConnection
import java.net.URL
import java.util.Base64
import java.util.Properties
/**
* Task to produce regressions report and send it to slack. Requires a report with current benchmarks result
* and path to analyzer tool
*
* @property currentBenchmarksReportFile path to file with becnhmarks result
* @property analyzer path to analyzer tool
* @property htmlReport name of result html report
* @property defaultBranch name of default branch
* @property summaryFile name of file with short summary
* @property bundleBuild property to show if current build is full or not
*/
open class RegressionsReporter : DefaultTask() {
val slackUsers = mapOf(
"olonho" to "nikolay.igotti",
"nikolay.igotti" to "nikolay.igotti",
"ilya.matveev" to "ilya.matveev",
"ilmat192" to "ilya.matveev",
"vasily.v.levchenko" to "minamoto",
"vasily.levchenko" to "minamoto",
"alexander.gorshenev" to "alexander.gorshenev",
"igor.chevdar" to "igor.chevdar",
"pavel.punegov" to "Pavel Punegov",
"dmitriy.dolovov" to "dmitriy.dolovov",
"svyatoslav.scherbina" to "svyatoslav.scherbina",
"sbogolepov" to "sergey.bogolepov",
"Alexey.Zubakov" to "Alexey.Zubakov",
"kirill.shmakov" to "kirill.shmakov",
"elena.lepilkina" to "elena.lepilkina")
@Input
lateinit var currentBenchmarksReportFile: String
@Input
lateinit var analyzer: String
@Input
lateinit var htmlReport: String
@Input
lateinit var defaultBranch: String
@Input
lateinit var summaryFile: String
@Input
var bundleBuild: Boolean = false
private fun tabUrl(buildId: String, buildTypeId: String, tab: String) =
"$teamCityUrl/viewLog.html?buildId=$buildId&buildTypeId=$buildTypeId&tab=$tab"
private fun testReportUrl(buildId: String, buildTypeId: String) =
tabUrl(buildId, buildTypeId, "testsInfo")
private fun previousBuildLocator(buildTypeId: String, branchName: String) =
"buildType:id:$buildTypeId,branch:name:$branchName,status:SUCCESS,state:finished,count:1"
private fun changesListUrl(buildLocator: String) =
"$teamCityUrl/app/rest/changes/?locator=build:$buildLocator"
private fun getCommits(buildLocator: String, user: String, password: String): CommitsList {
val changes = try {
sendGetRequest(changesListUrl(buildLocator), user, password)
} catch (t: Throwable) {
error("Try to get commits! TeamCity is unreachable!")
}
return CommitsList(JsonTreeParser.parse(changes))
}
@TaskAction
fun run() {
// Get TeamCity properties.
val teamcityConfig = System.getenv("TEAMCITY_BUILD_PROPERTIES_FILE") ?:
error("Can't load teamcity config!")
val buildProperties = Properties()
buildProperties.load(FileInputStream(teamcityConfig))
val buildId = buildProperties.getProperty("teamcity.build.id")
val buildTypeId = buildProperties.getProperty("teamcity.buildType.id")
val buildNumber = buildProperties.getProperty("build.number")
val user = buildProperties.getProperty("teamcity.auth.userId")
val password = buildProperties.getProperty("teamcity.auth.password")
// Get branch.
val currentBuild = getBuild("id:$buildId", user, password)
val branch = getBuildProperty(currentBuild,"branchName")
val testReportUrl = testReportUrl(buildId, buildTypeId)
// Get previous build on branch.
val builds = getBuild(previousBuildLocator(buildTypeId,branch), user, password)
// Get changes description.
val changesList = getCommits("id:$buildId", user, password)
val changesInfo = "*Changes* in branch *$branch:*\n" + buildString {
changesList.commits.forEach {
append(" - Change ${it.revision} by ${it.developer} (details: ${it.webUrlWithDescription})\n")
}
}
// File name on Artifactory is the same as current.
val artifactoryFileName = currentBenchmarksReportFile.substringAfterLast("/")
// Get compare to build.
val compareToBuild = getBuild(previousBuildLocator(buildTypeId, defaultBranch), user, password)
val compareToBuildLink = getBuildProperty(compareToBuild,"webUrl")
val compareToBuildNumber = getBuildProperty(compareToBuild,"number")
val target = System.getProperty("os.name").replace("\\s".toRegex(), "")
// Generate comparison report.
val output = arrayOf("$analyzer", "-r", "html", "$currentBenchmarksReportFile", "artifactory:$compareToBuildNumber:$target:$artifactoryFileName", "-o", "$htmlReport")
.runCommand()
if (output.contains("Uncaught exception")) {
error("Error during comparasion of $currentBenchmarksReportFile and " +
"artifactory:$compareToBuildNumber:$target:$artifactoryFileName with $analyzer! " +
"Please check files existance and their correctness.")
}
arrayOf("$analyzer", "-r", "statistics", "$currentBenchmarksReportFile", "artifactory:$compareToBuildNumber:$target:$artifactoryFileName", "-o", "$summaryFile")
.runCommand()
val reportLink = "https://kotlin-native-perf-summary.labs.jb.gg/?target=$target&build=$buildNumber"
val detailedReportLink = "https://kotlin-native-performance.labs.jb.gg/?" +
"report=artifactory:$buildNumber:$target:$artifactoryFileName&" +
"compareTo=artifactory:$compareToBuildNumber:$target:$artifactoryFileName"
val title = "\n*Performance report for target $target (build $buildNumber)* - $reportLink\n" +
"*Detailed info - * $detailedReportLink"
val header = "$title\n$changesInfo\n\nCompare to build $compareToBuildNumber: $compareToBuildLink\n\n"
val footer = "*Benchmarks statistics:* $testReportUrl"
val message = "$header\n$footer\n"
// Send to channel or user directly.
val session = SlackSessionFactory.createWebSocketSlackSession(buildProperties.getProperty("konan-reporter-token"))
session.connect()
if (branch == defaultBranch) {
if (bundleBuild) {
val channel = session.findChannelByName(buildProperties.getProperty("konan-channel-name"))
session.sendMessage(channel, message)
}
}
session.disconnect()
}
} | apache-2.0 | 28e4d3a06c101f72b532bc1c4324e17c | 40.930636 | 174 | 0.676548 | 4.274013 | false | false | false | false |
soywiz/korge | @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Curve.kt | 1 | 7051 | package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter
/**
* Represents a curve in a Spriter SCML file.
* An instance of this class is responsible for tweening given data.
* The most important method of this class is [.tween].
* Curves can be changed with sub curves [Curve.subCurve].
* @author Trixt0r
*/
class Curve
/**
* Creates a new curve with the given type and sub cuve.
* @param type the curve type
* *
* @param subCurve the sub curve. Can be `null`
*/
constructor(
type: Type = Curve.Type.Linear,
/**
* The sub curve of this curve, which can be `null`.
*/
var subCurve: Curve? = null
) {
/**
* Represents a curve type in a Spriter SCML file.
* @author Trixt0r
*/
enum class Type {
Instant, Linear, Quadratic, Cubic, Quartic, Quintic, Bezier
}
/**
* Returns the type of this curve.
* @return the curve type
*/
/**
* Sets the type of this curve.
* *
* @throws SpriterException if the type is `null`
*/
var type: Type? = null
set(type) {
if (type == null) throw SpriterException("The type of a curve cannot be null!")
field = type
}
/**
* The constraints of a curve which will affect a curve of the types different from [Type.Linear] and [Type.Instant].
*/
val constraints = Constraints(0f, 0f, 0f, 0f)
init {
this.type = type
}
private var lastCubicSolution = 0f
/**
* Returns a new value based on the given values.
* Tweens the weight with the set sub curve.
* @param a the start value
* *
* @param b the end value
* *
* @param t the weight which lies between 0.0 and 1.0
* *
* @return tweened value
*/
fun tween(a: Float, b: Float, t: Float): Float {
var tt = t
tt = tweenSub(0f, 1f, tt)
when (this.type) {
Type.Instant -> return a
Type.Linear -> return Interpolator.linear(a, b, tt)
Type.Quadratic -> return Interpolator.quadratic(a, Interpolator.linear(a, b, constraints.c1), b, tt)
Type.Cubic -> return Interpolator.cubic(
a,
Interpolator.linear(a, b, constraints.c1),
Interpolator.linear(a, b, constraints.c2),
b,
tt
)
Type.Quartic -> return Interpolator.quartic(
a,
Interpolator.linear(a, b, constraints.c1),
Interpolator.linear(a, b, constraints.c2),
Interpolator.linear(a, b, constraints.c3),
b,
tt
)
Type.Quintic -> return Interpolator.quintic(
a,
Interpolator.linear(a, b, constraints.c1),
Interpolator.linear(a, b, constraints.c2),
Interpolator.linear(a, b, constraints.c3),
Interpolator.linear(a, b, constraints.c4),
b,
tt
)
Type.Bezier -> {
var cubicSolution = Calculator.solveCubic(
3f * (constraints.c1 - constraints.c3) + 1f,
3f * (constraints.c3 - 2f * constraints.c1),
3f * constraints.c1,
-tt
)
if (cubicSolution == Calculator.NO_SOLUTION)
cubicSolution = lastCubicSolution
else
lastCubicSolution = cubicSolution
return Interpolator.linear(
a,
b,
Interpolator.bezier(cubicSolution, 0f, constraints.c2, constraints.c4, 1f)
)
}
else -> return Interpolator.linear(a, b, tt)
}
}
/**
* Interpolates the given two points with the given weight and saves the result in the target point.
* @param a the start point
* *
* @param b the end point
* *
* @param t the weight which lies between 0.0 and 1.0
* *
* @param target the target point to save the result in
*/
fun tweenPoint(a: Point, b: Point, t: Float, target: Point) {
target.set(this.tween(a.x, b.x, t), this.tween(a.y, b.y, t))
}
private fun tweenSub(a: Float, b: Float, t: Float): Float =
if (this.subCurve != null) subCurve!!.tween(a, b, t) else t
/**
* Returns a tweened angle based on the given angles, weight and the spin.
* @param a the start angle
* *
* @param b the end angle
* *
* @param t the weight which lies between 0.0 and 1.0
* *
* @param spin the spin, which is either 0, 1 or -1
* *
* @return tweened angle
*/
fun tweenAngle(a: Float, b: Float, t: Float, spin: Int): Float {
var bb = b
if (spin > 0) {
if (bb - a < 0)
bb += 360f
} else if (spin < 0) {
if (bb - a > 0)
bb -= 360f
} else
return a
return tween(a, bb, t)
}
/**
* @see {@link .tween
*/
fun tweenAngle(a: Float, b: Float, t: Float): Float {
var tt = t
tt = tweenSub(0f, 1f, tt)
when (this.type) {
Type.Instant -> return a
Type.Linear -> return Interpolator.linearAngle(a, b, tt)
Type.Quadratic -> return Interpolator.quadraticAngle(
a,
Interpolator.linearAngle(a, b, constraints.c1),
b,
tt
)
Type.Cubic -> return Interpolator.cubicAngle(
a,
Interpolator.linearAngle(a, b, constraints.c1),
Interpolator.linearAngle(a, b, constraints.c2),
b,
tt
)
Type.Quartic -> return Interpolator.quarticAngle(
a,
Interpolator.linearAngle(a, b, constraints.c1),
Interpolator.linearAngle(a, b, constraints.c2),
Interpolator.linearAngle(a, b, constraints.c3),
b,
tt
)
Type.Quintic -> return Interpolator.quinticAngle(
a,
Interpolator.linearAngle(a, b, constraints.c1),
Interpolator.linearAngle(a, b, constraints.c2),
Interpolator.linearAngle(a, b, constraints.c3),
Interpolator.linearAngle(a, b, constraints.c4),
b,
tt
)
Type.Bezier -> {
var cubicSolution = Calculator.solveCubic(
3f * (constraints.c1 - constraints.c3) + 1f,
3f * (constraints.c3 - 2f * constraints.c1),
3f * constraints.c1,
-tt
)
if (cubicSolution == Calculator.NO_SOLUTION)
cubicSolution = lastCubicSolution
else
lastCubicSolution = cubicSolution
return Interpolator.linearAngle(
a,
b,
Interpolator.bezier(cubicSolution, 0f, constraints.c2, constraints.c4, 1f)
)
}
else -> return Interpolator.linearAngle(a, b, tt)
}
}
override fun toString(): String {
return "" + this::class + "|[" + this.type + ":" + constraints + ", subCurve: " + subCurve + "]"
}
/**
* Represents constraints for a curve.
* Constraints are important for curves which have a order higher than 1.
* @author Trixt0r
*/
class Constraints(c1: Float, c2: Float, c3: Float, c4: Float) {
var c1: Float = 0.toFloat()
var c2: Float = 0.toFloat()
var c3: Float = 0.toFloat()
var c4: Float = 0.toFloat()
init {
this[c1, c2, c3] = c4
}
operator fun set(c1: Float, c2: Float, c3: Float, c4: Float) {
this.c1 = c1
this.c2 = c2
this.c3 = c3
this.c4 = c4
}
override fun toString(): String {
return "" + this::class + "| [c1:" + c1 + ", c2:" + c2 + ", c3:" + c3 + ", c4:" + c4 + "]"
}
}
companion object {
/**
* Returns a curve type based on the given curve name.
* @param name the name of the curve
* *
* @return the curve type. [Type.Linear] is returned as a default type.
*/
fun getType(name: String): Type = when (name) {
"instant" -> Type.Instant
"quadratic" -> Type.Quadratic
"cubic" -> Type.Cubic
"quartic" -> Type.Quartic
"quintic" -> Type.Quintic
"bezier" -> Type.Bezier
else -> Type.Linear
}
}
}
| apache-2.0 | bd9a596739db407275f24643bb9e6be9 | 24.733577 | 118 | 0.631116 | 3.011961 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/Library3D.kt | 1 | 6290 | package com.soywiz.korge3d
import com.soywiz.kds.*
import com.soywiz.korge3d.animation.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.color.*
import com.soywiz.korim.format.*
import com.soywiz.korio.file.std.*
import com.soywiz.korma.geom.*
@Korge3DExperimental
data class Library3D(
val cameraDefs: FastStringMap<CameraDef> = FastStringMap(),
val lightDefs: FastStringMap<LightDef> = FastStringMap(),
val materialDefs: FastStringMap<MaterialDef> = FastStringMap(),
val effectDefs: FastStringMap<EffectDef> = FastStringMap(),
val imageDefs: FastStringMap<ImageDef> = FastStringMap(),
val geometryDefs: FastStringMap<GeometryDef> = FastStringMap(),
val skinDefs: FastStringMap<SkinDef> = FastStringMap(),
val animationDefs: FastStringMap<Animation3D> = FastStringMap()
) {
suspend fun loadTextures() {
imageDefs.fastValueForEach { image ->
image.texure = resourcesVfs[image.initFrom].readBitmap()
}
}
val boneDefs = FastStringMap<BoneDef>()
fun instantiateMaterials() {
geometryDefs.fastValueForEach { geom ->
for (bone in geom.skin?.bones ?: listOf()) {
boneDefs[bone.name] = bone
}
geom.mesh.material = geom.material?.instantiate()
}
}
val library = this
val mainScene = Scene3D(this).apply {
id = "MainScene"
name = "MainScene"
}
var scenes = FastStringMap<Scene3D>()
open class Instance3D(val library: Library3D) {
val transform = Matrix3D()
var def: Def? = null
val children = arrayListOf<Instance3D>()
var id: String = ""
var sid: String? = null
var name: String = ""
var type: String = ""
var skin: SkinDef? = null
var skeleton: Instance3D? = null
var skeletonId: String? = null
}
open class Scene3D(library: Library3D) : Instance3D(library) {
}
open class Def
open class Pong
open class ImageDef(val id: String, val name: String, val initFrom: String, var texure: Bitmap? = null) : Def() {
}
open class ObjectDef : Def()
open class MaterialDef(val id: String, val name: String, val effects: List<EffectDef>) : Def()
open class LightDef : ObjectDef()
open class CameraDef : ObjectDef()
data class PerspectiveCameraDef(val xfov: Angle, val zmin: Double, val zmax: Double) : CameraDef()
interface LightKindDef {
val sid: String
}
open class LightTexDef(override val sid: String, val texture: EffectParamSampler2D?, val lightKind: String) :
LightKindDef
open class LightColorDef(override val sid: String, val color: RGBA, val lightKind: String) : LightKindDef
data class EffectParamSurface(val surfaceType: String, val initFrom: ImageDef?)
data class EffectParamSampler2D(val surface: EffectParamSurface?)
open class EffectDef() : Def()
data class StandardEffectDef(
val id: String,
val name: String,
val emission: LightKindDef?,
val ambient: LightKindDef?,
val diffuse: LightKindDef?,
val specular: LightKindDef?,
val shininess: Float?,
val index_of_refraction: Float?
) : EffectDef()
data class GeometryDef(
val mesh: Mesh3D,
val skin: SkinDef? = null,
val material: MaterialDef? = null
) : ObjectDef()
data class BoneDef constructor(val index: Int, val name: String, val invBindMatrix: Matrix3D) : Def() {
lateinit var skin: SkinDef
fun toBone() = Bone3D(index, name, invBindMatrix.clone())
}
data class SkinDef(
val controllerId: String,
val controllerName: String,
val bindShapeMatrix: Matrix3D,
val skinSource: String,
val bones: List<BoneDef>
) : Def() {
fun toSkin() = Skin3D(bindShapeMatrix, bones.map { it.toBone() })
}
class PointLightDef(
val color: RGBA,
val constantAttenuation: Double,
val linearAttenuation: Double,
val quadraticAttenuation: Double
) : LightDef()
class AmbientLightDef(
val color: RGBA
) : LightDef()
}
@Korge3DExperimental
class LibraryInstantiateContext {
val viewsById = FastStringMap<View3D>()
}
@Korge3DExperimental
fun Library3D.Instance3D.instantiate(jointParent: Joint3D? = null, ctx: LibraryInstantiateContext = LibraryInstantiateContext()): View3D {
val def = this.def
val view: View3D = when (def) {
null -> {
if (type.equals("JOINT", ignoreCase = true)) {
val it = Joint3D(id, name, sid ?: "unknownSid", jointParent, this.transform)
jointParent?.childJoints?.add(it)
jointParent?.children?.add(it)
it
} else {
Container3D()
}
}
is Library3D.GeometryDef -> {
val skeletonInstance = if (skeletonId != null) ctx.viewsById[skeletonId!!] as? Joint3D? else null
ViewWithMesh3D(def.mesh, skeletonInstance?.let { Skeleton3D(def.mesh.skin!!, it) })
}
is Library3D.PerspectiveCameraDef -> {
Camera3D.Perspective(def.xfov, def.zmin, def.zmax)
}
is Library3D.PointLightDef -> {
Light3D(def.color, def.constantAttenuation, def.linearAttenuation, def.quadraticAttenuation)
}
is Library3D.AmbientLightDef -> {
Light3D(def.color, 0.00001, 0.00001, 0.00001)
}
else -> TODO("def=$def")
}
view.id = this.id
ctx.viewsById[this.id] = view
view.name = this.name
//view.localTransform.setMatrix(this.transform.clone().transpose())
view.transform.setMatrix(this.transform)
if (view is Joint3D) {
for (child in children) {
child.instantiate(view, ctx)
}
} else if (view is Container3D) {
for (child in children) {
view.addChild(child.instantiate(null, ctx))
}
}
return view
}
@Korge3DExperimental
fun Library3D.LightKindDef.instantiate(): Material3D.Light {
return when (this) {
is Library3D.LightTexDef -> Material3D.LightTexture(this.texture?.surface?.initFrom?.texure)
is Library3D.LightColorDef -> Material3D.LightColor(this.color)
else -> error("Unsupported $this")
}
}
@Korge3DExperimental
fun Library3D.MaterialDef.instantiate(): Material3D {
val effect = this.effects.firstOrNull() as? Library3D.StandardEffectDef?
return Material3D(
emission = effect?.emission?.instantiate() ?: Material3D.LightColor(Colors.BLACK),
ambient = effect?.ambient?.instantiate() ?: Material3D.LightColor(Colors.BLACK),
diffuse = effect?.diffuse?.instantiate() ?: Material3D.LightColor(Colors.BLACK),
specular = effect?.specular?.instantiate() ?: Material3D.LightColor(Colors.BLACK),
shininess = effect?.shininess ?: 0.5f,
indexOfRefraction = effect?.index_of_refraction ?: 1f
)
}
| apache-2.0 | 1b2c1802e166b939d4b7f268b61697ed | 28.952381 | 138 | 0.713672 | 3.24394 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/test/kotlin/co/nums/intellij/aem/action/MarkAsJcrRootActionTest.kt | 1 | 7407 | package co.nums.intellij.aem.action
import co.nums.intellij.aem.icons.AemIcons
import co.nums.intellij.aem.service.JcrRoots
import co.nums.intellij.aem.test.util.*
import com.intellij.ide.projectView.ProjectView
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.VIRTUAL_FILE_ARRAY
import com.intellij.openapi.application.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiManager
import org.junit.jupiter.api.*
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
class MarkAsJcrRootActionTest {
private lateinit var event: AnActionEvent
private lateinit var project: Project
private lateinit var jcrRoots: JcrRoots
private lateinit var sut: MarkAsJcrRootAction
@BeforeEach
fun setUp() {
event = mock(AnActionEvent::class.java, RETURNS_DEEP_STUBS)
project = mock(Project::class.java, RETURNS_DEEP_STUBS)
`when`(event.project).thenReturn(project)
jcrRoots = mock(JcrRoots::class.java)
whenGetService<JcrRoots>(project).thenReturn(jcrRoots)
sut = MarkAsJcrRootAction()
}
@Test
fun shouldHideActionWhenDirsIsNull() {
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(null)
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldHideActionWhenDirsIsEmpty() {
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(emptyArray())
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldHideActionWhenProjectIsNull() {
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(arrayOf(directory("any_dir")))
`when`(event.project).thenReturn(null)
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldHideActionWhenAnyOfFilesIsNotDir() {
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(arrayOf(
directory("dir1"),
file("not_dir"),
directory("dir2")))
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldShowMarkAsJcrRootAction() {
val testSelectedDirs = arrayOf(directory("dir1"), directory("dir2"))
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(testSelectedDirs)
testSelectedDirs.forEach { `when`(jcrRoots.contains(it)).thenReturn(false) }
sut.update(event)
verify(event.presentation).icon = AemIcons.JCR_ROOT_DIR
}
@Test
fun shouldDisableMarkAsJcrRootActionWhenAtLeastOneDirIsMarkedAlready() {
val jcrRoot = directory("jcr_root")
val notMarkedDirs = arrayOf(directory("dir1"), directory("dir2"))
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(notMarkedDirs + jcrRoot)
notMarkedDirs.forEach { `when`(jcrRoots.contains(it)).thenReturn(false) }
`when`(jcrRoots.contains(jcrRoot)).thenReturn(true)
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldShowUnmarkAsJcrRootAction() {
val testSelectedDirs = arrayOf(directory("dir1"), directory("dir2"))
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(testSelectedDirs)
testSelectedDirs.forEach { `when`(jcrRoots.isJcrContentRoot(it)).thenReturn(true) }
sut.update(event)
verify(event.presentation).icon = AemIcons.JCR_ROOT_DIR
}
@Test
fun shouldDisableUnmarkAsJcrRootActionWhenAtLeastOneDirIsNotJcrRoot() {
val notJcrRoot = directory("jcr_root")
val jcrRootsDirs = arrayOf(directory("dir1"), directory("dir2"))
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(jcrRootsDirs + notJcrRoot)
jcrRootsDirs.forEach { `when`(this.jcrRoots.contains(it)).thenReturn(true) }
`when`(jcrRoots.contains(notJcrRoot)).thenReturn(false)
sut.update(event)
verify(event.presentation).isEnabledAndVisible = false
}
@Test
fun shouldNotPerformAnyActionWhenPresentationIsDisabled() {
`when`(event.presentation.isEnabledAndVisible).thenReturn(false)
sut.actionPerformed(event)
verifyZeroInteractions(jcrRoots)
}
@Test
fun shouldNotPerformAnyActionWhenProjectIsNull() {
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.project).thenReturn(null)
sut.actionPerformed(event)
verifyZeroInteractions(jcrRoots)
}
@Test
fun shouldNotPerformAnyActionWhenDirsIsNull() {
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(null)
sut.actionPerformed(event)
verifyZeroInteractions(jcrRoots)
}
@Test
fun shouldNotPerformAnyActionWhenDirsIsEmpty() {
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(emptyArray())
sut.actionPerformed(event)
verifyZeroInteractions(jcrRoots)
}
@Test
fun shouldNotPerformAnyActionWhenAnyOfSelectedFilesIsNotDirectory() {
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(arrayOf(directory("dir1"), file("not_dir"), directory("dir2")))
sut.actionPerformed(event)
verifyZeroInteractions(jcrRoots)
}
@Test
fun shouldMarkDirectoriesAsJcrRoots() {
val dirsToMark = arrayOf(directory("dir1"), directory("dir2").withChildren(file("test.html")))
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(dirsToMark)
dirsToMark.forEach { `when`(jcrRoots.contains(it)).thenReturn(false) }
whenGetService<ProjectView>(project).thenReturn(mock(ProjectView::class.java, RETURNS_DEEP_STUBS))
`when`(project.getComponent(PsiManager::class.java)).thenReturn(mock(PsiManager::class.java))
ApplicationManager.setApplication(mock(Application::class.java), mock(Disposable::class.java))
sut.actionPerformed(event)
dirsToMark.forEach { verify(jcrRoots).markAsJcrRoot(it) }
}
@Test
fun shouldUnmarkDirectoriesAsJcrRoots() {
val dirsToUnmark = arrayOf(directory("dir1").withChildren(file("test.html")), directory("dir2"))
`when`(event.presentation.isEnabledAndVisible).thenReturn(true)
`when`(event.getData(VIRTUAL_FILE_ARRAY)).thenReturn(dirsToUnmark)
dirsToUnmark.forEach { `when`(jcrRoots.contains(it)).thenReturn(true) }
dirsToUnmark.forEach { `when`(jcrRoots.isJcrContentRoot(it)).thenReturn(true) }
whenGetService<ProjectView>(project).thenReturn(mock(ProjectView::class.java, RETURNS_DEEP_STUBS))
`when`(project.getComponent(PsiManager::class.java)).thenReturn(mock(PsiManager::class.java))
ApplicationManager.setApplication(mock(Application::class.java), mock(Disposable::class.java))
sut.actionPerformed(event)
dirsToUnmark.forEach { verify(jcrRoots).unmarkAsJcrRoot(it) }
}
}
| gpl-3.0 | c7fd5c043e69a5079e66e19e201c4f1a | 34.956311 | 124 | 0.705954 | 4.281503 | false | true | false | false |
HochschuleHofStundenplanapp/AndroidStundenplanHof | app/src/main/java/de/hof/university/app/widget/adapters/GenericRemoteViewsFactory.kt | 1 | 6163 | /* Copyright © 2018 Jan Gaida licensed under GNU GPLv3 */
@file:Suppress("SpellCheckingInspection")
package de.hof.university.app.widget.adapters
import android.annotation.SuppressLint
import android.content.Context
import androidx.core.content.ContextCompat
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import de.hof.university.app.R
import de.hof.university.app.widget.data.AppWidgetDataCache
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
/**
* What is this?
* Similar to [de.hof.university.app.adapter] this is used as a 'special' Adapter for a ListView in a Widget,
* this is the base implementation for a RemoteViewFactory which full functionality is gained by a final implementation of it.
*
* What is a RemoteViewFactory?
* An interface for an adapter between a remote collection view (ListView, GridView, etc) and the underlying data for that view.
* The implementor is responsible for making a RemoteView for each item in the data set. This interface is a thin wrapper around Adapter.
* @see RemoteViewsService.RemoteViewsFactory - https://developer.android.com/reference/android/widget/RemoteViewsService.RemoteViewsFactory
*
* Whats does the abstract-class do?
* storing the data, adding the 'lastSaved'-Element and requesting at the correct position,
* basic-functionality (i.e. [getCount], [hasStableIds], ... ) while supplying concrete functions to implementations (i.e. [setData], [getRemoteView], ... )
*
* What does a implementation of it do?
* Offering a [context], a [amountOfViewTypes] and obviously a [DATATYPE]. When [getRemoteView] is called the requested [DATATYPE] for this will be delivered.
* When [setData] or [getRemoteViewForLastSaved] is called the [AppWidgetDataCache]-instance will be delivered, requested shortly before to full-fill the task.
* For more information on abstract-declared functions read their comments
*
* !! CAUTION !!
* Avoid any [de.hof.university.app.data.DataManager.getInstance]-Calls (Reason can be found in description of [AppWidgetDataCache])
* They are hidden in [de.hof.university.app.model] !
*
* @author Jan Gaida
* @since Version 4.8(37)
* @date 18.02.2018
*/
internal abstract class GenericRemoteViewsFactory<DATATYPE>(
internal val context: Context,
lightStyleIsSelected: Boolean,
private val amountOfViewTypes: Int
): RemoteViewsService.RemoteViewsFactory {
/**
* HELPER-VARS
*/
internal val packageName = context.packageName
private var data: ArrayList<DATATYPE> = setDataAndSize()
private var dataSizePlusOne: Int = 0
private var injectedCount = 0
internal val primaryTextColor: Int
internal val secondaryTextColor: Int
internal val dissatisfiedIcon: Int
init {
if(lightStyleIsSelected) {
primaryTextColor = ContextCompat.getColor(context, R.color.AppWidget_Text_Color_Primary_For_LightStyle)
secondaryTextColor = ContextCompat.getColor(context, R.color.AppWidget_Text_Color_Secondary_For_LightStyle)
dissatisfiedIcon = R.drawable.ic_baseline_search_light_24
} else {
primaryTextColor = ContextCompat.getColor(context, R.color.AppWidget_Text_Color_Primary_For_DarkStyle)
secondaryTextColor = ContextCompat.getColor(context, R.color.AppWidget_Text_Color_Secondary_For_DarkStyle)
dissatisfiedIcon = R.drawable.ic_baseline_search_dark_24
}
}
/**
* HELPER-FUNS
*/
internal fun Date.toDayString(): String = dateFormatter.format(this)
internal fun Date.toHourString(): String = hourFormatter.format(this)
/**
* COMPANION
*/
private companion object {
@SuppressLint("SimpleDateFormat") // default local will be used
private val dateFormatter = SimpleDateFormat("dd.MM.yyyy, HH:mm ")
@SuppressLint("SimpleDateFormat") // default local will be used
private val hourFormatter = SimpleDateFormat("HH:mm")
}
/**
* OVERRIDES
*/
override fun onDataSetChanged() { data = setDataAndSize() }
private fun setDataAndSize() = setData(AppWidgetDataCache.getInstance()).also{ dataSizePlusOne = it.size + 1}.also { injectedCount = injectCount(dataSizePlusOne - 1) }
override fun onCreate() {}
override fun onDestroy() {}
override fun getCount(): Int = dataSizePlusOne + injectedCount // i.e. (orginal + lastSaved) + (emptyView) for Changes
open fun injectCount(size: Int):Int = 0
override fun hasStableIds(): Boolean = true
override fun getItemId(position: Int): Long = position.toLong()
override fun getLoadingView(): RemoteViews = RemoteViews(packageName, R.layout.widget_list_item_loading).apply { setTextColor(R.id.widget_list_item_loading, primaryTextColor) }
override fun getViewAt(position: Int): RemoteViews
= when {
position < dataSizePlusOne - 1 - injectedCount -> getRemoteView(data[position])
position == 0 && dataSizePlusOne == 1 -> getRemoteViewForEmptyView()
else -> getRemoteViewForLastSaved(AppWidgetDataCache.getInstance())
}
override fun getViewTypeCount(): Int = amountOfViewTypes
/**
* ABSTRACT-FUNS
*/
/**
* Function to set the [data] of type [ArrayList]<GIVEN_DATA_TYPE> used.
*
* @param dataCache - [AppWidgetDataCache]-Object delivered
*
* @return the [ArrayList] full of data which should be used
*/
internal abstract fun setData(dataCache: AppWidgetDataCache): ArrayList<DATATYPE>
/**
* Function to initialize a [RemoteViews] at position of the ListView.
*
* @param data - the Data-Object which should be the source for the RemoteViews
*
* @return the [RemoteViews]-Objects used in the ListView a 'regular'-item
*/
internal abstract fun getRemoteView(data: DATATYPE): RemoteViews
/**
* Function to initialize a [RemoteViews] at the last position of the ListView.
*
* @param dataCache - [AppWidgetDataCache]-Object delivered
*
* @return the [RemoteViews]-Objects used in the ListView for a 'LastSaved'-Item
*/
internal abstract fun getRemoteViewForLastSaved(dataCache: AppWidgetDataCache): RemoteViews
/**
* Function to initalize a [RemoteViews] if the [data] was empty
*
* @return the [RemoteViews]-Objects used in the ListView to indicate a empty [data]
*/
internal abstract fun getRemoteViewForEmptyView(): RemoteViews
}
| gpl-3.0 | 4d1ac1e9eb0237c133008e63cb8f6e39 | 38.248408 | 177 | 0.757546 | 4.038008 | false | false | false | false |
AndroidX/androidx | camera/integration-tests/avsynctestapp/src/main/java/androidx/camera/integration/avsync/SignalGeneratorViewModel.kt | 3 | 6305 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.camera.integration.avsync
import android.content.Context
import android.content.Context.AUDIO_SERVICE
import android.media.AudioManager
import androidx.camera.core.Logger
import androidx.camera.integration.avsync.model.AudioGenerator
import androidx.camera.integration.avsync.model.CameraHelper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.util.Preconditions
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
private const val ACTIVE_LENGTH_SEC: Double = 0.5
private const val ACTIVE_INTERVAL_SEC: Double = 1.0
private const val ACTIVE_DELAY_SEC: Double = 0.0
private const val VOLUME_PERCENTAGE: Double = 1.0
private const val TAG = "SignalGeneratorViewModel"
enum class ActivationSignal {
Active, Inactive
}
class SignalGeneratorViewModel : ViewModel() {
private var signalGenerationJob: Job? = null
private lateinit var audioGenerator: AudioGenerator
private val cameraHelper = CameraHelper()
private lateinit var audioManager: AudioManager
private var originalVolume: Int = 0
var isGeneratorReady: Boolean by mutableStateOf(false)
private set
var isRecorderReady: Boolean by mutableStateOf(false)
private set
var isSignalGenerating: Boolean by mutableStateOf(false)
private set
var isActivePeriod: Boolean by mutableStateOf(false)
private set
var isRecording: Boolean by mutableStateOf(false)
private set
var isPaused: Boolean by mutableStateOf(false)
private set
suspend fun initialRecorder(context: Context, lifecycleOwner: LifecycleOwner) {
withContext(Dispatchers.Main) {
isRecorderReady = cameraHelper.bindCamera(context, lifecycleOwner)
}
}
suspend fun initialSignalGenerator(context: Context, beepFrequency: Int, beepEnabled: Boolean) {
audioManager = context.getSystemService(AUDIO_SERVICE) as AudioManager
saveOriginalVolume()
withContext(Dispatchers.Default) {
audioGenerator = AudioGenerator(beepEnabled)
audioGenerator.initial(
context = context,
frequency = beepFrequency,
beepLengthInSec = ACTIVE_LENGTH_SEC,
)
isGeneratorReady = true
}
}
private fun setVolume(percentage: Double = VOLUME_PERCENTAGE) {
Preconditions.checkArgument(percentage in 0.0..1.0)
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val targetVolume = (maxVolume * percentage).toInt()
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, targetVolume, 0)
}
fun startSignalGeneration() {
Logger.d(TAG, "Start signal generation.")
Preconditions.checkState(isGeneratorReady)
setVolume()
signalGenerationJob?.cancel()
isSignalGenerating = true
signalGenerationJob = activationSignalFlow().map { activationSignal ->
when (activationSignal) {
ActivationSignal.Active -> {
isActivePeriod = true
playBeepSound()
}
ActivationSignal.Inactive -> {
isActivePeriod = false
stopBeepSound()
}
}
}.onCompletion {
stopBeepSound()
restoreOriginalVolume()
isActivePeriod = false
}.launchIn(viewModelScope)
}
fun stopSignalGeneration() {
Logger.d(TAG, "Stop signal generation.")
Preconditions.checkState(isGeneratorReady)
isSignalGenerating = false
signalGenerationJob?.cancel()
signalGenerationJob = null
}
fun startRecording(context: Context) {
Logger.d(TAG, "Start recording.")
Preconditions.checkState(isRecorderReady)
cameraHelper.startRecording(context)
isRecording = true
}
fun stopRecording() {
Logger.d(TAG, "Stop recording.")
Preconditions.checkState(isRecorderReady)
cameraHelper.stopRecording()
isRecording = false
isPaused = false
}
fun pauseRecording() {
Logger.d(TAG, "Pause recording.")
Preconditions.checkState(isRecorderReady)
cameraHelper.pauseRecording()
isPaused = true
}
fun resumeRecording() {
Logger.d(TAG, "Resume recording.")
Preconditions.checkState(isRecorderReady)
cameraHelper.resumeRecording()
isPaused = false
}
private fun saveOriginalVolume() {
originalVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
}
private fun restoreOriginalVolume() {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0)
}
private fun activationSignalFlow() = flow {
delay((ACTIVE_DELAY_SEC * 1000).toLong())
while (true) {
emit(ActivationSignal.Active)
delay((ACTIVE_LENGTH_SEC * 1000).toLong())
emit(ActivationSignal.Inactive)
delay((ACTIVE_INTERVAL_SEC * 1000).toLong())
}
}
private fun playBeepSound() {
audioGenerator.start()
}
private fun stopBeepSound() {
audioGenerator.stop()
}
} | apache-2.0 | e19eb4a02f5c52b08b084985dda663ef | 31.505155 | 100 | 0.686757 | 4.84255 | false | false | false | false |
nextras/orm-intellij | src/main/kotlin/org/nextras/orm/intellij/annotator/ModifierHighlighterAnnotator.kt | 1 | 2321 | package org.nextras.orm.intellij.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.jetbrains.php.lang.documentation.phpdoc.lexer.PhpDocTokenTypes
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocPropertyTag
import com.jetbrains.php.lang.psi.elements.impl.PhpPsiElementImpl
import org.nextras.orm.intellij.annotator.highlighter.ModifierHighlighter
/**
* This is a modifier highlighter.
*/
class ModifierHighlighterAnnotator : Annotator {
override fun annotate(psiElement: PsiElement, annotationHolder: AnnotationHolder) {
// currently PhpDoc property comment is always wrapped in this specific type
if (psiElement::class != PhpPsiElementImpl::class) return
if (psiElement.parent !is PhpDocPropertyTag) return
var isModifier = false
var isModifierName = false
var element: PsiElement? = psiElement.node.firstChildNode as? PsiElement ?: return
while (element != null) {
if (element.node.elementType == PhpDocTokenTypes.DOC_LBRACE) {
isModifier = true
isModifierName = true
annotationHolder
.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(element)
.textAttributes(ModifierHighlighter.BRACES)
.create()
} else if (element.node.elementType == PhpDocTokenTypes.DOC_RBRACE) {
isModifier = false
annotationHolder
.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(element)
.textAttributes(ModifierHighlighter.BRACES)
.create()
} else if (isModifier) {
if (isModifierName && element !is PsiWhiteSpace) {
annotationHolder
.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(element)
.textAttributes(ModifierHighlighter.MODIFIER)
.create()
} else if (!isModifierName && (element.node.elementType == PhpDocTokenTypes.DOC_IDENTIFIER || element.node.elementType == PhpDocTokenTypes.DOC_VARIABLE)) {
annotationHolder
.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(element)
.textAttributes(ModifierHighlighter.IDENTIFIER)
.create()
} else {
isModifierName = false
}
}
element = element.nextSibling
}
}
}
| mit | 635a5538610a04844f091edeb4018d5c | 34.166667 | 159 | 0.758294 | 4.17446 | false | false | false | false |
FDeityLink/KeroEdit | src/io/fdeitylink/util/Delegates.kt | 1 | 3874 | package io.fdeitylink.util
import kotlin.properties.ReadWriteProperty
import kotlin.properties.ObservableProperty
import kotlin.reflect.KProperty
/**
* A property delegate that emulates
* [Delegates.notNull][kotlin.properties.Delegates.notNull] while also
* allowing delegated properties to ensure that their values are only set
* to proper values so that invariants can be maintained. As such, any
* attempts to get the value of the delegated property before it is
* initialized will throw an [IllegalStateException]. Additionally, any
* attempts to set the value of the delegated property to an invalid value
* (checked via a function passed to the constructor for this class) will
* result in an [IllegalArgumentException]. This essentially emulates
* having a non-default setter for the delegated property while providing
* the features of the delegate returned by
* [Delegates.notNull][kotlin.properties.Delegates.notNull].
*
* @param T the type of the delegated property
*
* @constructor
*
* @param validator a function that will be called to ensure that values
* given to set() are valid for the delegated property. Its single parameter
* is the value passed to set() that needs to be validated. If calling [validator]
* with the value returns true, the given value is valid and will be set, otherwise
* the value is invalid and an [IllegalArgumentException] will be thrown.
*
* @param lazyMessage a supplier function that returns an [Any] whose [toString]
* method will be called to provide a message for any [IllegalArgumentException]s
* thrown when a value passed to set() is invalid. Appended to that string will be
* the string " (value: $value)" so the caller knows what was wrong with their input.
* Defaults to a function returning the String "Invalid value passed to set()".
*/
/*
* TODO:
* Turn validator: (T) -> Boolean into onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean
* Either create NotNullVetoable class or add throwExcept: Boolean = true to the constructor
* Turn into CustomNotNullVar class that takes a setter validator and a custom getter?
* Delegate to Delegates.notNull?
*/
class ValidatedNotNullVar<T : Any>(private val validator: (value: T) -> Boolean,
private val lazyMessage: () -> Any = { "Invalid value passed to set()" }
) : ReadWriteProperty<Any?, T> {
private var value: T? = null
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
//TODO: Add name of class/object to exception string
return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.")
}
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
require(validator(value)) { lazyMessage().toString() + " (value: $value)" }
this.value = value
}
}
class ReInitializableVar<T> : ReadWriteProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
class ObservableValue<T>(initialValue: T) : ObservableProperty<T>(initialValue) {
private val listeners: MutableList<ChangeListener<T>> = mutableListOf()
fun addListener(listener: ChangeListener<T>) {
listeners.add(listener)
}
fun removeListener(listener: ChangeListener<T>) {
listeners.remove(listener)
}
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) =
listeners.forEach { it(property, oldValue, newValue) }
}
typealias ChangeListener<T> = (property: KProperty<*>, oldValue: T, newValue: T) -> Unit | apache-2.0 | 24dc844e378a939199dae76949e7f46d | 43.034091 | 114 | 0.718379 | 4.499419 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/AdminHandler.kt | 1 | 6424 | package au.com.codeka.warworlds.server.admin.handlers
import au.com.codeka.carrot.CarrotEngine
import au.com.codeka.carrot.Configuration
import au.com.codeka.carrot.bindings.MapBindings
import au.com.codeka.carrot.resource.FileResourceLocator
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.AdminRole
import au.com.codeka.warworlds.server.admin.Session
import au.com.codeka.warworlds.server.handlers.RequestException
import au.com.codeka.warworlds.server.handlers.RequestHandler
import au.com.codeka.warworlds.server.store.DataStore
import com.google.common.base.Throwables
import com.google.common.collect.ImmutableMap
import com.google.common.collect.Lists
import com.google.gson.Gson
import java.io.File
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URI
import java.net.URISyntaxException
import java.net.URLEncoder
import java.util.*
import java.util.regex.Matcher
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
open class AdminHandler : RequestHandler() {
private var sessionNoError: Session? = null
/**
* Gets a collection of roles, one of which the current user must be in to access this handler.
*
* <p>Override this if you want to specify a different list of roles.
*/
protected open val requiredRoles: Collection<AdminRole>?
get() = Lists.newArrayList(AdminRole.ADMINISTRATOR)
/** Set up this [RequestHandler], must be called before any other methods. */
open fun setup(
routeMatcher: Matcher,
extraOption: String?,
session: Session?,
request: HttpServletRequest,
response: HttpServletResponse) {
super.setup(routeMatcher, extraOption, request, response)
sessionNoError = session
}
public override fun onBeforeHandle(): Boolean {
val requiredRoles = requiredRoles
if (requiredRoles != null) {
val session = sessionNoError
if (session == null) {
authenticate()
return false
} else {
var allowed = requiredRoles.isEmpty() // if requiredRoles is empty, they're OK.
for (role in requiredRoles) {
allowed = allowed || session.isInRole(role)
}
if (!allowed) {
// you're not in a required role.
log.warning("User '%s' is not in any required role: %s",
session.email, requiredRoles)
redirect("/admin")
return false
}
}
}
return true
}
override fun handleException(e: RequestException) {
try {
render("exception.html", ImmutableMap.builder<String, Any>()
.put("e", e)
.put("stack_trace", Throwables.getStackTraceAsString(e))
.build())
e.populate(response)
} catch (e2: Exception) {
log.error("Error loading exception.html template.", e2)
setResponseText(e2.toString())
}
}
protected fun render(path: String, data: Map<String, Any>?) {
val mutableData: MutableMap<String, Any> = when (data) {
null -> TreeMap()
is HashMap<String, Any> -> data
is TreeMap<String, Any> -> data
else -> TreeMap<String, Any>(data)
}
val session = sessionNoError
if (session != null) {
mutableData["session"] = session
}
mutableData["num_backend_users"] = DataStore.i.adminUsers().count()
val contentType: String = when {
path.endsWith(".css") -> "text/css"
path.endsWith(".js") -> "text/javascript"
path.endsWith(".html") -> "text/html"
else -> "text/plain"
}
response.contentType = contentType
response.setHeader("Content-Type", contentType)
response.writer.write(CARROT.process(path, MapBindings(mutableData)))
}
protected fun write(text: String) {
response.contentType = "text/plain"
response.setHeader("Content-Type", "text/plain; charset=utf-8")
try {
response.writer.write(text)
} catch (e: IOException) {
log.error("Error writing output!", e)
}
}
protected fun getSession(): Session {
if (sessionNoError == null) {
throw RequestException(403)
}
return sessionNoError!!
}
/** Checks whether the current user is in the given role. */
protected fun isInRole(role: AdminRole): Boolean {
return if (sessionNoError == null) {
false
} else sessionNoError!!.isInRole(role)
}
private fun authenticate() {
val requestUrl: URI
requestUrl = try {
URI(super.requestUrl)
} catch (e: URISyntaxException) {
throw RuntimeException(e)
}
var finalUrl = requestUrl.path
if (requestUrl.query != "") {
finalUrl += "?" + requestUrl.query
}
var redirectUrl = requestUrl.resolve("/admin/login").toString()
try {
redirectUrl += "?continue=" + URLEncoder.encode(finalUrl, "utf-8")
} catch (e: UnsupportedEncodingException) {
// should never happen
}
redirect(redirectUrl)
}
private class SessionHelper {
fun isInRole(session: Session, roleName: String?): Boolean {
val role = AdminRole.valueOf(roleName!!)
return session.isInRole(role)
}
}
private class StringHelper {
// Used by template engine.
fun trunc(s: String, maxLength: Int): String {
return if (s.length > maxLength - 3) {
s.substring(0, maxLength - 3) + "..."
} else s
}
}
private class GsonHelper {
// Used by template engine.
fun encode(obj: Any?): String {
return Gson().toJson(obj)
}
}
companion object {
private val log = Log("AdminHandler")
private val CARROT = CarrotEngine(
Configuration.Builder()
.setResourceLocator(
FileResourceLocator.Builder(File("data/admin/tmpl").absolutePath))
.setLogger { level: Int, msg: String ->
val message = msg.replace("%", "%%")
when (level) {
Configuration.Logger.LEVEL_DEBUG -> log.debug("CARROT: %s", message)
Configuration.Logger.LEVEL_INFO -> log.info("CARROT: %s", message)
Configuration.Logger.LEVEL_WARNING -> log.warning("CARROT: %s", message)
else -> log.error("(level: %d): CARROT: %s", level, message)
}
}
.build(),
MapBindings.Builder()
.set("Session", SessionHelper())
.set("String", StringHelper())
.set("Gson", GsonHelper()))
}
} | mit | 997f6035f97cfb7f63c54a729812c53f | 31.449495 | 97 | 0.648194 | 4.141844 | false | false | false | false |
colesadam/hill-lists | app/src/main/java/uk/colessoft/android/hilllist/domain/TinyHill.kt | 1 | 223 | package uk.colessoft.android.hilllist.domain
class TinyHill {
var _id: Long = 0
var hillname: String? = null
var latitude: Double? = null
var longitude: Double? = null
var isClimbed: Boolean = false
}
| mit | fecc1258582011d903b71ea20e4939d0 | 21.3 | 44 | 0.672646 | 3.539683 | false | false | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/members/MembersAPI.kt | 1 | 1506 | package com.twitter.meil_mitu.twitter4hk.api.lists.members
import com.twitter.meil_mitu.twitter4hk.AbsAPI
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.converter.api.IListsMembersConverter
class MembersAPI<TCursorUsers, TUser, TUserList>(
oauth: AbsOauth,
protected val json: IListsMembersConverter<TCursorUsers, TUser, TUserList>) :
AbsAPI(oauth) {
fun destroy() = Destroy(oauth, json)
fun createAll(listId: Long) = CreateAll(oauth, json, listId)
fun createAll(slug: String) = CreateAll(oauth, json, slug)
fun show(listId: Long, userId: Long) = Show(oauth, json, listId, userId)
fun show(listId: Long, screenName: String) = Show(oauth, json, listId, screenName)
fun show(slug: String, userId: Long) = Show(oauth, json, slug, userId)
fun show(slug: String, screenName: String) = Show(oauth, json, slug, screenName)
fun get(listId: Long) = Get(oauth, json, listId)
fun get(slug: String) = Get(oauth, json, slug)
fun create(listId: Long, userId: Long) = Create(oauth, json, listId, userId)
fun create(listId: Long, screenName: String) = Create(oauth, json, listId, screenName)
fun create(slug: String, userId: Long) = Create(oauth, json, slug, userId)
fun create(slug: String, screenName: String) = Create(oauth, json, slug, screenName)
fun destroyAll(listId: Long) = DestroyAll(oauth, json, listId)
fun destroyAll(slug: String) = DestroyAll(oauth, json, slug)
}
| mit | 51ddfd862d515ca41237350806aca8ea | 34.857143 | 90 | 0.709827 | 3.56872 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/indexes/RsLangItemIndex.kt | 2 | 1969 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
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.StubIndexKey
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import org.rust.cargo.util.AutoInjectedCrates
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.stubs.RsFileStub
import org.rust.openapiext.checkCommitIsNotInProgress
import org.rust.openapiext.getElements
import org.rust.stdext.singleOrFilter
class RsLangItemIndex : AbstractStubIndex<String, RsItemElement>() {
override fun getVersion(): Int = RsFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, RsItemElement> = KEY
override fun getKeyDescriptor(): KeyDescriptor<String> = EnumeratorStringDescriptor.INSTANCE
companion object {
fun findLangItem(
project: Project,
langAttribute: String,
crateName: String = AutoInjectedCrates.CORE
): RsNamedElement? {
checkCommitIsNotInProgress(project)
return getElements(KEY, langAttribute, project, GlobalSearchScope.allScope(project))
.filterIsInstance<RsNamedElement>()
.singleOrFilter { it.containingCrate.normName == crateName }
.singleOrFilter { it.existsAfterExpansion }
.firstOrNull()
}
fun index(psi: RsItemElement, sink: IndexSink) {
for (key in psi.getTraversedRawAttributes().langAttributes) {
sink.occurrence(KEY, key)
}
}
private val KEY: StubIndexKey<String, RsItemElement> =
StubIndexKey.createIndexKey("org.rust.lang.core.resolve.indexes.RsLangItemIndex")
}
}
| mit | 02826b6880a425a6863df9c17fda4ef3 | 38.38 | 96 | 0.715592 | 4.611241 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/suspendfun/InfiniteAnimationDemo.kt | 3 | 2315 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.suspendfun
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Composable
fun InfiniteAnimationDemo() {
val alpha = remember { mutableStateOf(1f) }
LaunchedEffect(Unit) {
animate(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
) { value, _ ->
alpha.value = value
}
}
Box(Modifier.fillMaxSize()) {
Icon(
Icons.Filled.Favorite,
contentDescription = null,
modifier = Modifier.align(Alignment.Center)
.graphicsLayer(
scaleX = 3.0f,
scaleY = 3.0f,
alpha = alpha.value
),
tint = Color.Red
)
}
} | apache-2.0 | c742a554081ceb815de4a4b8c12cddae | 33.567164 | 75 | 0.69676 | 4.584158 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/emoji/SimpleEmojiTextView.kt | 1 | 2281 | package org.thoughtcrime.securesms.components.emoji
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.ThrottledDebouncer
import java.util.Optional
open class SimpleEmojiTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private var bufferType: BufferType? = null
private val sizeChangeDebouncer: ThrottledDebouncer = ThrottledDebouncer(200)
init {
isEmojiCompatEnabled = isInEditMode || SignalStore.settings().isPreferSystemEmoji
}
override fun setText(text: CharSequence?, type: BufferType?) {
bufferType = type
val candidates = if (isInEditMode) null else EmojiProvider.getCandidates(text)
if (SignalStore.settings().isPreferSystemEmoji || candidates == null || candidates.size() == 0) {
super.setText(Optional.ofNullable(text).orElse(""), type)
} else {
val startDrawableSize: Int = compoundDrawables[0]?.let { it.intrinsicWidth + compoundDrawablePadding } ?: 0
val endDrawableSize: Int = compoundDrawables[1]?.let { it.intrinsicWidth + compoundDrawablePadding } ?: 0
val adjustedWidth: Int = width - startDrawableSize - endDrawableSize
val newCandidates = if (isInEditMode) null else EmojiProvider.getCandidates(text)
val newText = if (newCandidates == null || newCandidates.size() == 0) {
text
} else {
EmojiProvider.emojify(newCandidates, text, this, false)
}
val newContent = if (width == 0 || maxLines == -1) {
newText
} else {
TextUtils.ellipsize(newText, paint, (adjustedWidth * maxLines).toFloat(), TextUtils.TruncateAt.END, false, null)
}
bufferType = BufferType.SPANNABLE
super.setText(newContent, type)
}
}
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
sizeChangeDebouncer.publish {
if (width > 0 && oldWidth != width) {
setText(text, bufferType ?: BufferType.SPANNABLE)
}
}
}
}
| gpl-3.0 | 5d8cea5f80e0902dd4355cd3c965ed64 | 37.661017 | 120 | 0.715914 | 4.429126 | false | false | false | false |
google/android-auto-companion-android | trustagent/src/com/google/android/libraries/car/trustagent/Car.kt | 1 | 15584 | // Copyright 2021 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent
import androidx.annotation.GuardedBy
import androidx.annotation.VisibleForTesting
import com.google.android.companionprotos.OperationProto.OperationType
import com.google.android.companionprotos.Query as QueryProto
import com.google.android.companionprotos.QueryResponse as QueryResponseProto
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothConnectionManager
import com.google.android.libraries.car.trustagent.blemessagestream.MessageStream
import com.google.android.libraries.car.trustagent.blemessagestream.SppManager
import com.google.android.libraries.car.trustagent.blemessagestream.StreamMessage
import com.google.android.libraries.car.trustagent.util.bytesToUuid
import com.google.android.libraries.car.trustagent.util.loge
import com.google.android.libraries.car.trustagent.util.logi
import com.google.protobuf.InvalidProtocolBufferException
import java.util.ArrayDeque
import java.util.Queue
import java.util.UUID
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.ReentrantLock
import javax.crypto.SecretKey
import kotlin.concurrent.withLock
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/**
* Represents a connected remote device that runs Android Automotive OS.
*
* This class can be used to exchange messages with a Car.
*/
open class Car
internal constructor(
private val bluetoothManager: BluetoothConnectionManager,
internal open val messageStream: MessageStream,
@GuardedBy("lock")
@get:VisibleForTesting
// Only keep this var in this class so it can be passed through callback.
internal open val identificationKey: SecretKey,
open val deviceId: UUID,
open var name: String? = bluetoothManager.deviceName,
private val coroutineDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
/** The BluetoothDevice that this object represents (and is being connected to). */
open val bluetoothDevice = bluetoothManager.bluetoothDevice
private val coroutineScope = CoroutineScope(coroutineDispatcher)
private val lock = ReentrantLock()
/** Maps a recipient UUID to the callback to notify for events. */
@GuardedBy("lock") private val callbacks = mutableMapOf<UUID, Callback>()
/**
* Stores messages/queries for recipients that do not have registered callback.
*
* When a callback is registered, these messages/queries are dispatched in FIFO order.
*/
@GuardedBy("lock") private val unclaimedMessages = mutableMapOf<UUID, Queue<ByteArray>>()
@GuardedBy("lock") private val unclaimedQueries = mutableMapOf<UUID, Queue<QueryProto>>()
/** Maps a message Id to a recipient UUID. */
@GuardedBy("lock") private val messageIdMap = mutableMapOf<Int, UUID>()
/**
* The current id to use when sending a query. Utilize the [nextQueryId] method to retrieve the
* value. This ensures the id is correctly incremented.
*/
@VisibleForTesting internal val queryId = AtomicInteger(0)
/**
* Maps a query id to handlers that should be invoked when a response for that query has come back
* from the car.
*/
@GuardedBy("lock")
private val queryResponseHandlers = mutableMapOf<Int, (QueryResponse) -> Unit>()
@VisibleForTesting
internal val streamForwardingMessageCallback =
object : MessageStream.Callback {
override fun onMessageReceived(streamMessage: StreamMessage) {
when (streamMessage.operation) {
OperationType.CLIENT_MESSAGE -> handleMessage(streamMessage)
OperationType.QUERY -> handleQuery(streamMessage)
OperationType.QUERY_RESPONSE -> handleQueryResponse(streamMessage)
else -> loge(TAG, "Received non-client message: ${streamMessage.operation}. Ignored.")
}
}
override fun onMessageSent(messageId: Int) {
lock.withLock {
// Notify default recipient if incoming message doesn't specify one.
// This is to be backward compatible with v1 stream, which doesn't support recipient.
val recipient = messageIdMap.remove(messageId) ?: DEFAULT_FEATURE_ID
callbacks[recipient]?.onMessageSent(messageId)
}
}
}
private val gattCallback =
object : BluetoothConnectionManager.ConnectionCallback {
override fun onConnected() {
loge(TAG, "Unexpected BluetoothGattManager callback: onConnected.")
throw IllegalStateException()
}
override fun onConnectionFailed() {
loge(TAG, "Unexpected BluetoothGattManager callback: onConnectionFailed.")
throw IllegalStateException()
}
override fun onDisconnected() {
lock.withLock {
coroutineScope.cancel()
// Using `toList` to create a copy of the callbacks to notify in case the callbacks remove
// themselves when `onDisconnected` is triggered.
callbacks.values.toList().forEach { it.onDisconnected() }
}
}
}
init {
bluetoothManager.registerConnectionCallback(gattCallback)
messageStream.registerMessageEventCallback(streamForwardingMessageCallback)
}
override fun toString() = "[ID: $deviceId; name: $name; device: $bluetoothDevice]"
override fun equals(other: Any?): Boolean {
return if (other is Car) {
this.deviceId == other.deviceId
} else {
false
}
}
override fun hashCode(): Int = deviceId.hashCode()
/** Returns `true` if this car communicates through an SPP channel. */
open fun isSppDevice(): Boolean {
return bluetoothManager is SppManager
}
/**
* Sends message to remote device Car and returns the id generated for the message.
*
* @param message The bytes to be sent to remote device.
* @param recipient Identifies the recipient of [data] on remote device.
*/
open fun sendMessage(message: ByteArray, recipient: UUID): Int {
val messageId =
messageStream.sendMessage(
StreamMessage(
payload = message,
operation = OperationType.CLIENT_MESSAGE,
isPayloadEncrypted = true,
originalMessageSize = 0,
recipient = recipient
)
)
lock.withLock { messageIdMap[messageId] = recipient }
return messageId
}
/**
* Sends a query to the given [recipient] on a connected car.
*
* The format of the provided [Query] is feature defined and will be sent as-is to the car. The
* provided [onResponse] function will be invoked with a [QueryResponse] that was sent by the car.
*/
open fun sendQuery(query: Query, recipient: UUID, onResponse: (QueryResponse) -> Unit) {
val queryId = nextQueryId()
messageStream.sendMessage(
StreamMessage(
payload = query.toProtoByteArray(queryId = queryId, recipient = recipient),
operation = OperationType.QUERY,
isPayloadEncrypted = true,
originalMessageSize = 0,
recipient = recipient
)
)
lock.withLock { queryResponseHandlers[queryId] = onResponse }
}
/**
* Sends the [QueryResponse] to the specified [recipient] on the remote car.
*
* The `id` of the `QueryResponse` should match a previous query that was received via
* [Callback.onQueryReceived]. The contents of the response is feature defined and will be sent
* without modification to the car.
*/
open fun sendQueryResponse(queryResponse: QueryResponse, recipient: UUID) {
messageStream.sendMessage(
StreamMessage(
payload = queryResponse.toProtoByteArray(),
operation = OperationType.QUERY_RESPONSE,
isPayloadEncrypted = true,
originalMessageSize = 0,
recipient = recipient
)
)
}
internal open fun disconnect() {
bluetoothManager.disconnect()
}
/**
* Registers [Callback] for car updates.
*
* Only one callback can be registered per recipient. This is to prevent malicious features from
* listening on messages from other features. Registering more than one callback will throw an
* `IllegalStateException`.
*/
open fun setCallback(callback: Callback, recipient: UUID) {
lock.withLock {
if (callbacks.containsKey(recipient) && callbacks[recipient] != callback) {
throw IllegalStateException(
"Callback is already registered for recipient $recipient. Only one callback can be " +
"registered per recipient. This is to prevent malicious features from listening on " +
"your messages."
)
}
callbacks[recipient] = callback
}
coroutineScope.launch {
dispatchUnclaimedMessages(recipient, callback)
dispatchUnclaimedQueries(recipient, callback)
}
}
/** Dispatches unclaimed messages for [recipient] to [callback]. */
private fun dispatchUnclaimedMessages(recipient: UUID, callback: Callback) {
lock.withLock {
unclaimedMessages.remove(recipient)?.let { payloads ->
while (payloads.isNotEmpty()) {
payloads.poll()?.let {
logi(TAG, "Dispatching stored message to $recipient.")
callback.onMessageReceived(it)
}
}
}
}
}
private fun dispatchUnclaimedQueries(recipient: UUID, callback: Callback) {
lock.withLock {
unclaimedQueries.remove(recipient)?.let { queryProtos ->
while (queryProtos.isNotEmpty()) {
queryProtos.poll()?.let {
logi(TAG, "Dispatching stored query ${it.id} to $recipient.")
callback.onQueryReceived(it.id, bytesToUuid(it.sender.toByteArray()), it.toQuery())
}
}
}
}
}
/**
* Clears the callback registered for the given [recipient].
*
* The callback is only cleared if it matches the specified [callback]. This is to prevent
* malicious features from clearing a callback and registering themselves to listen on messages.
*/
open fun clearCallback(callback: Callback, recipient: UUID) {
lock.withLock {
callbacks[recipient]?.takeIf { it == callback }?.run { callbacks.remove(recipient) }
}
}
internal open fun toAssociatedCar() =
lock.withLock { AssociatedCar(deviceId, name, bluetoothDevice.address, identificationKey) }
private fun handleMessage(streamMessage: StreamMessage) {
lock.withLock {
// Notify default recipient if incoming message doesn't specify one.
// This is to be backward compatible with v1 stream, which doesn't support recipient.
val recipient = streamMessage.recipient ?: DEFAULT_FEATURE_ID
if (recipient in callbacks) {
callbacks[recipient]?.onMessageReceived(streamMessage.payload)
} else {
logi(TAG, "Received message for $recipient but no registered callback. Saving message.")
storeUnclaimedMessage(recipient, streamMessage.payload)
}
}
}
private fun storeUnclaimedMessage(recipient: UUID, payload: ByteArray) {
lock.withLock { unclaimedMessages.getOrPut(recipient) { ArrayDeque<ByteArray>() }.add(payload) }
}
private fun handleQuery(streamMessage: StreamMessage) {
val queryProto =
try {
QueryProto.parseFrom(streamMessage.payload)
} catch (e: InvalidProtocolBufferException) {
loge(TAG, "Received a query but unable to parse. Ignoring", e)
return
}
val recipient = streamMessage.recipient
if (recipient == null) {
loge(TAG, "Received query for null recipient. Ignoring.")
return
}
logi(TAG, "Received query for recipient: $recipient. Invoking callback")
lock.withLock {
if (recipient in callbacks) {
callbacks[recipient]?.onQueryReceived(
queryProto.id,
bytesToUuid(queryProto.sender.toByteArray()),
queryProto.toQuery()
)
} else {
logi(TAG, "Received query for $recipient but no registered callback. Saving query.")
storeUnclaimedQuery(recipient, queryProto)
}
}
}
private fun storeUnclaimedQuery(recipient: UUID, queryProto: QueryProto) {
lock.withLock {
unclaimedQueries.getOrPut(recipient) { ArrayDeque<QueryProto>() }.add(queryProto)
}
}
private fun handleQueryResponse(streamMessage: StreamMessage) {
val queryResponseProto =
try {
QueryResponseProto.parseFrom(streamMessage.payload)
} catch (e: InvalidProtocolBufferException) {
loge(TAG, "Received a query response but unable to parse. Ignoring", e)
return
}
val handler = lock.withLock { queryResponseHandlers.remove(queryResponseProto.queryId) }
if (handler == null) {
loge(
TAG,
"Received query response for query id ${queryResponseProto.queryId}, " +
"but no registered handler. Ignoring."
)
return
}
logi(
TAG,
"Received a query response for recipient: ${streamMessage.recipient}. Invoking callback"
)
handler(queryResponseProto.toQueryResponse())
}
/**
* Returns the id that should be used to construct a new
* [com.google.android.companionprotos.Query].
*
* Each call to this method will return an increment from a previous call up to the maximum
* integer value. When the maximum value is reached, the id wraps back to 0.
*/
private fun nextQueryId(): Int = queryId.getAndUpdate { if (it == Int.MAX_VALUE) 0 else it + 1 }
/** Converts this proto to its [Query] representation. */
private fun QueryProto.toQuery(): Query = Query(request.toByteArray(), parameters.toByteArray())
/** Converts this proto to its [QueryResponse] representation. */
private fun QueryResponseProto.toQueryResponse(): QueryResponse =
QueryResponse(queryId, success, response.toByteArray())
/** Callback for car interaction. */
interface Callback {
/** Invoked when a message has been received from car. */
fun onMessageReceived(data: ByteArray)
/** Invoked when the message with the specified [messageId] has been sent to the car. */
fun onMessageSent(messageId: Int)
/**
* Invoked when a query has been received from a car.
*
* The given [queryId] should be later used to respond to query. The formatting of the query
* `request` and `parameters` are feature defined and sent as-is from the car. The response
* should be sent to the specified [sender].
*/
fun onQueryReceived(queryId: Int, sender: UUID, query: Query)
/** Invoked when car has disconnected. This object should now be discarded. */
fun onDisconnected()
}
companion object {
private const val TAG = "Car"
// Default to recipient ID of trusted device manager.
// LINT.IfChange(DEFAULT_FEATURE_ID)
private val DEFAULT_FEATURE_ID: UUID = UUID.fromString("baf7b76f-d419-40ce-8aeb-2b80c6510123")
// LINT.ThenChange(//depot/google3/third_party/java_src/android_libs/automotive_trusteddevice/java/com/google/android/libraries/car/trusteddevice/TrustedDeviceManager.kt:FEATURE_ID)
}
}
| apache-2.0 | e578758fdeda1fa8cc248b22c6f15f0f | 36.193317 | 185 | 0.704376 | 4.701056 | false | false | false | false |
jeremymailen/kotlinter-gradle | src/main/kotlin/org/jmailen/gradle/kotlinter/KotlinterExtension.kt | 1 | 581 | package org.jmailen.gradle.kotlinter
import org.jmailen.gradle.kotlinter.support.ReporterType
open class KotlinterExtension {
companion object {
const val DEFAULT_IGNORE_FAILURES = false
const val DEFAULT_EXPERIMENTAL_RULES = false
val DEFAULT_REPORTER = ReporterType.checkstyle.name
val DEFAULT_DISABLED_RULES = emptyArray<String>()
}
var ignoreFailures = DEFAULT_IGNORE_FAILURES
var reporters = arrayOf(DEFAULT_REPORTER)
var experimentalRules = DEFAULT_EXPERIMENTAL_RULES
var disabledRules = DEFAULT_DISABLED_RULES
}
| apache-2.0 | 7fbaad0b30967fa9d78a51c56f737d32 | 28.05 | 59 | 0.740103 | 4.503876 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/model/user/SmsVerification.kt | 1 | 3246 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* SMS verification entity keeps track of client verification. It consists of two parts; 1) the
* actual SMS verification, which the user has to verify by receiving a SMS, and 2) a "hidden"
* client challenge sent from the server to the client. Since the SMS verification challenge
* is inheritedly weak a client challenge is used to strengthen security, thus forcing an
* attacker to guess also a client challenge.
*/
package dk.etiktak.backend.model.user
import org.springframework.format.annotation.DateTimeFormat
import java.util.*
import javax.persistence.*
@Entity(name = "sms_verifications")
class SmsVerification {
enum class SmsVerificationStatus {
UNKNOWN, PENDING, SENT, FAILED, VERIFIED
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "sms_verification_id")
var id: Long = 0
@Column(name = "mobileNumberHash", nullable = false, unique = true)
var mobileNumberHash: String = ""
@Column(name = "smsHandle")
var smsHandle: String? = null
@Column(name = "smsChallengeHash", nullable = false)
var smsChallengeHash: String? = null
@Column(name = "clientChallenge", nullable = false)
var clientChallenge: String? = null
@Column(name = "status", nullable = false)
var status = SmsVerificationStatus.UNKNOWN
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var creationTime = Date()
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var modificationTime = Date()
@PreUpdate
fun preUpdate() {
modificationTime = Date()
}
@PrePersist
fun prePersist() {
val now = Date()
creationTime = now
modificationTime = now
}
} | bsd-3-clause | bad03b6c07de24b9fff25674abc476f3 | 36.755814 | 95 | 0.727973 | 4.434426 | false | false | false | false |
sz-piotr/pik-projekt | backend/src/main/kotlin/app/test/Question.kt | 1 | 588 | package app.test
import com.fasterxml.jackson.annotation.JsonIgnore
import javax.persistence.*
/**
* Created by michal on 15/05/2017.
*/
@Entity
@Table(name="\"Question\"")
data class Question (val title: String? = null,
@ManyToOne @JoinColumn(name = "test_id") @JsonIgnore
val test: Test? = null,
@OneToMany(mappedBy = "question", cascade = arrayOf(CascadeType.ALL))
var answers: List<Answer>? = null,
@Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long? = null)
| mit | 336c934366a9efc242b9ae4b24c48261 | 35.75 | 94 | 0.595238 | 4.2 | false | true | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt | 1 | 17495 | package eu.kanade.tachiyomi.ui.main
import android.animation.ObjectAnimator
import android.app.ActivityManager
import android.app.SearchManager
import android.app.usage.UsageStatsManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.graphics.drawable.DrawerArrowDrawable
import android.support.v7.widget.Toolbar
import android.view.ViewGroup
import com.bluelinelabs.conductor.*
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.ui.base.activity.BaseActivity
import eu.kanade.tachiyomi.ui.base.controller.*
import eu.kanade.tachiyomi.ui.catalogue.CatalogueController
import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController
import eu.kanade.tachiyomi.ui.download.DownloadController
import eu.kanade.tachiyomi.ui.extension.ExtensionController
import eu.kanade.tachiyomi.ui.library.LibraryController
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.recent_updates.RecentChaptersController
import eu.kanade.tachiyomi.ui.recently_read.RecentlyReadController
import eu.kanade.tachiyomi.ui.setting.SettingsMainController
import exh.uconfig.WarnConfigureDialogController
import exh.ui.batchadd.BatchAddController
import exh.ui.lock.LockChangeHandler
import exh.ui.lock.LockController
import exh.ui.lock.lockEnabled
import exh.ui.lock.notifyLockSecurity
import kotlinx.android.synthetic.main.main_activity.*
import uy.kohesive.injekt.injectLazy
import android.text.TextUtils
import android.view.View
import eu.kanade.tachiyomi.util.vibrate
import exh.EXHMigrations
import exh.eh.EHentaiUpdateWorker
import exh.ui.migration.MetadataFetchDialog
import timber.log.Timber
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : BaseActivity() {
private lateinit var router: Router
val preferences: PreferencesHelper by injectLazy()
private var drawerArrow: DrawerArrowDrawable? = null
private var secondaryDrawer: ViewGroup? = null
private val startScreenId by lazy {
when (preferences.startScreen()) {
2 -> R.id.nav_drawer_recently_read
3 -> R.id.nav_drawer_recent_updates
else -> R.id.nav_drawer_library
}
}
lateinit var tabAnimator: TabsAnimator
// Idle-until-urgent
private var firstPaint = false
private val iuuQueue = LinkedList<() -> Unit>()
private fun initWhenIdle(task: () -> Unit) {
// Avoid sync issues by enforcing main thread
if(Looper.myLooper() != Looper.getMainLooper())
throw IllegalStateException("Can only be called on main thread!")
if(firstPaint) {
task()
} else {
iuuQueue += task
}
}
override fun onResume() {
super.onResume()
if(!firstPaint) {
drawer.postDelayed({
if(!firstPaint) {
firstPaint = true
iuuQueue.forEach { it() }
}
}, 1000)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(when (preferences.theme()) {
2 -> R.style.Theme_Tachiyomi_Dark
3 -> R.style.Theme_Tachiyomi_Amoled
4 -> R.style.Theme_Tachiyomi_DarkBlue
else -> R.style.Theme_Tachiyomi
})
super.onCreate(savedInstanceState)
// Do not let the launcher create a new activity http://stackoverflow.com/questions/16283079
if (!isTaskRoot) {
finish()
return
}
setContentView(R.layout.main_activity)
setSupportActionBar(toolbar)
drawerArrow = DrawerArrowDrawable(this)
drawerArrow?.color = Color.WHITE
toolbar.navigationIcon = drawerArrow
tabAnimator = TabsAnimator(tabs)
// Set behavior of Navigation drawer
nav_view.setNavigationItemSelectedListener { item ->
val id = item.itemId
val currentRoot = router.backstack.firstOrNull()
if (currentRoot?.tag()?.toIntOrNull() != id) {
when (id) {
R.id.nav_drawer_library -> setRoot(LibraryController(), id)
R.id.nav_drawer_recent_updates -> setRoot(RecentChaptersController(), id)
R.id.nav_drawer_recently_read -> setRoot(RecentlyReadController(), id)
R.id.nav_drawer_catalogues -> setRoot(CatalogueController(), id)
R.id.nav_drawer_extensions -> setRoot(ExtensionController(), id)
// --> EXH
R.id.nav_drawer_batch_add -> setRoot(BatchAddController(), id)
// <-- EHX
R.id.nav_drawer_downloads -> {
router.pushController(DownloadController().withFadeTransaction())
}
R.id.nav_drawer_settings -> {
router.pushController(SettingsMainController().withFadeTransaction())
}
}
}
drawer.closeDrawer(GravityCompat.START)
true
}
val container: ViewGroup = findViewById(R.id.controller_container)
router = Conductor.attachRouter(this, container, savedInstanceState)
if (!router.hasRootController()) {
// Set start screen
if (!handleIntentAction(intent)) {
setSelectedDrawerItem(startScreenId)
}
}
toolbar.setNavigationOnClickListener {
if (router.backstackSize == 1) {
drawer.openDrawer(GravityCompat.START)
} else {
onBackPressed()
}
}
router.addChangeListener(object : ControllerChangeHandler.ControllerChangeListener {
override fun onChangeStarted(to: Controller?, from: Controller?, isPush: Boolean,
container: ViewGroup, handler: ControllerChangeHandler) {
syncActivityViewWithController(to, from)
}
override fun onChangeCompleted(to: Controller?, from: Controller?, isPush: Boolean,
container: ViewGroup, handler: ControllerChangeHandler) {
}
})
// --> EH
initWhenIdle {
//Hook long press hamburger menu to lock
getToolbarNavigationIcon(toolbar)?.setOnLongClickListener {
if(lockEnabled(preferences)) {
doLock(true)
vibrate(50) // Notify user of lock
true
} else false
}
}
//Show lock
if (savedInstanceState == null) {
if (lockEnabled(preferences)) {
//Special case first lock
doLock()
//Check lock security
initWhenIdle {
notifyLockSecurity(this)
}
}
}
// <-- EH
syncActivityViewWithController(router.backstack.lastOrNull()?.controller())
if (savedInstanceState == null) {
// Show changelog if needed
// TODO
// if (Migrations.upgrade(preferences)) {
// ChangelogDialogController().showDialog(router)
// }
// EXH -->
// Perform EXH specific migrations
if(EXHMigrations.upgrade(preferences)) {
ChangelogDialogController().showDialog(router)
}
initWhenIdle {
// Migrate metadata if empty (EH)
if(!preferences.migrateLibraryAsked().getOrDefault()) {
MetadataFetchDialog().askMigration(this, false)
}
// Upload settings
if(preferences.enableExhentai().getOrDefault()
&& preferences.eh_showSettingsUploadWarning().getOrDefault())
WarnConfigureDialogController.uploadSettings(router)
// Scheduler uploader job if required
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
EHentaiUpdateWorker.scheduleBackground(this)
}
}
// EXH <--
}
}
override fun onNewIntent(intent: Intent) {
if (!handleIntentAction(intent)) {
super.onNewIntent(intent)
}
}
private fun handleIntentAction(intent: Intent): Boolean {
when (intent.action) {
SHORTCUT_LIBRARY -> setSelectedDrawerItem(R.id.nav_drawer_library)
SHORTCUT_RECENTLY_UPDATED -> setSelectedDrawerItem(R.id.nav_drawer_recent_updates)
SHORTCUT_RECENTLY_READ -> setSelectedDrawerItem(R.id.nav_drawer_recently_read)
SHORTCUT_CATALOGUES -> setSelectedDrawerItem(R.id.nav_drawer_catalogues)
SHORTCUT_MANGA -> {
val extras = intent.extras ?: return false
router.setRoot(RouterTransaction.with(MangaController(extras)))
}
SHORTCUT_DOWNLOADS -> {
if (router.backstack.none { it.controller() is DownloadController }) {
setSelectedDrawerItem(R.id.nav_drawer_downloads)
}
}
Intent.ACTION_SEARCH, "com.google.android.gms.actions.SEARCH_ACTION" -> {
//If the intent match the "standard" Android search intent
// or the Google-specific search intent (triggered by saying or typing "search *query* on *Tachiyomi*" in Google Search/Google Assistant)
//Get the search query provided in extras, and if not null, perform a global search with it.
val query = intent.getStringExtra(SearchManager.QUERY)
if (query != null && !query.isEmpty()) {
if (router.backstackSize > 1) {
router.popToRoot()
}
router.pushController(CatalogueSearchController(query).withFadeTransaction())
}
}
INTENT_SEARCH -> {
val query = intent.getStringExtra(INTENT_SEARCH_QUERY)
val filter = intent.getStringExtra(INTENT_SEARCH_FILTER)
if (query != null && !query.isEmpty()) {
if (router.backstackSize > 1) {
router.popToRoot()
}
router.pushController(CatalogueSearchController(query, filter).withFadeTransaction())
}
}
else -> return false
}
return true
}
override fun onDestroy() {
super.onDestroy()
nav_view?.setNavigationItemSelectedListener(null)
toolbar?.setNavigationOnClickListener(null)
}
override fun onBackPressed() {
val backstackSize = router.backstackSize
if (drawer.isDrawerOpen(GravityCompat.START) || drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawers()
} else if (backstackSize == 1 && router.getControllerWithTag("$startScreenId") == null) {
setSelectedDrawerItem(startScreenId)
} else if (backstackSize == 1 || !router.handleBack()) {
super.onBackPressed()
}
}
private fun setSelectedDrawerItem(itemId: Int) {
if (!isFinishing) {
nav_view.setCheckedItem(itemId)
nav_view.menu.performIdentifierAction(itemId, 0)
}
}
private fun setRoot(controller: Controller, id: Int) {
router.setRoot(controller.withFadeTransaction().tag(id.toString()))
}
fun getToolbarNavigationIcon(toolbar: Toolbar): View? {
try {
//check if contentDescription previously was set
val hadContentDescription = !TextUtils.isEmpty(toolbar.navigationContentDescription)
val contentDescription = if (!hadContentDescription) toolbar.navigationContentDescription else "navigationIcon"
toolbar.navigationContentDescription = contentDescription
val potentialViews = ArrayList<View>()
//find the view based on it's content description, set programmatically or with android:contentDescription
toolbar.findViewsWithText(potentialViews, contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
//Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
val navIcon = potentialViews.firstOrNull()
//Clear content description if not previously present
if (!hadContentDescription)
toolbar.navigationContentDescription = null
return navIcon
} catch(t: Throwable) {
Timber.w(t, "Could not find toolbar nav icon!")
return null
}
}
private fun syncActivityViewWithController(to: Controller?, from: Controller? = null) {
if (from is DialogController || to is DialogController) {
return
}
val showHamburger = router.backstackSize == 1
if (showHamburger) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
} else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
// --> EH
//Special case and hide drawer arrow for lock controller
if(to is LockController) {
supportActionBar?.setDisplayHomeAsUpEnabled(false)
toolbar.navigationIcon = null
} else {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.navigationIcon = drawerArrow
}
// <-- EH
ObjectAnimator.ofFloat(drawerArrow, "progress", if (showHamburger) 0f else 1f).start()
if (from is TabbedController) {
from.cleanupTabs(tabs)
}
if (to is TabbedController) {
tabAnimator.expand()
to.configureTabs(tabs)
} else {
tabAnimator.collapse()
tabs.setupWithViewPager(null)
}
if (from is SecondaryDrawerController) {
if (secondaryDrawer != null) {
from.cleanupSecondaryDrawer(drawer)
drawer.removeView(secondaryDrawer)
secondaryDrawer = null
}
}
if (to is SecondaryDrawerController) {
secondaryDrawer = to.createSecondaryDrawer(drawer)?.also { drawer.addView(it) }
}
if (to is NoToolbarElevationController) {
appbar.disableElevation()
} else {
appbar.enableElevation()
}
}
// --> EH
//Lock code
var willLock = false
override fun onRestart() {
super.onRestart()
if(willLock && lockEnabled()) {
doLock()
}
willLock = false
}
override fun onStop() {
super.onStop()
tryLock()
}
fun tryLock() {
//Do not double-lock
if(router.backstack.lastOrNull()?.controller() is LockController)
return
//Do not lock if manual lock enabled
if(preferences.eh_lockManually().getOrDefault())
return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val mUsageStatsManager = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val time = System.currentTimeMillis()
// We get usage stats for the last 20 seconds
val sortedStats =
mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 20,
time)
?.associateBy {
it.lastTimeUsed
}?.toSortedMap()
if(sortedStats != null && sortedStats.isNotEmpty())
if(sortedStats[sortedStats.lastKey()]?.packageName != packageName)
willLock = true
} else {
val am = getSystemService(Service.ACTIVITY_SERVICE) as ActivityManager
val running = am.getRunningTasks(1)[0]
if (running.topActivity.packageName != packageName) {
willLock = true
}
}
}
fun doLock(animate: Boolean = false) {
router.pushController(RouterTransaction.with(LockController())
.popChangeHandler(LockChangeHandler(animate)))
}
// <-- EH
companion object {
// Shortcut actions
const val SHORTCUT_LIBRARY = "eu.kanade.tachiyomi.SHOW_LIBRARY"
const val SHORTCUT_RECENTLY_UPDATED = "eu.kanade.tachiyomi.SHOW_RECENTLY_UPDATED"
const val SHORTCUT_RECENTLY_READ = "eu.kanade.tachiyomi.SHOW_RECENTLY_READ"
const val SHORTCUT_CATALOGUES = "eu.kanade.tachiyomi.SHOW_CATALOGUES"
const val SHORTCUT_DOWNLOADS = "eu.kanade.tachiyomi.SHOW_DOWNLOADS"
const val SHORTCUT_MANGA = "eu.kanade.tachiyomi.SHOW_MANGA"
const val INTENT_SEARCH = "eu.kanade.tachiyomi.SEARCH"
const val INTENT_SEARCH_QUERY = "query"
const val INTENT_SEARCH_FILTER = "filter"
}
}
| apache-2.0 | f5216c0d9a31eb2bfa56333eaa735d2e | 36.065678 | 153 | 0.605259 | 5.044694 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/components/MangaBottomActionMenu.kt | 1 | 12398 | package eu.kanade.presentation.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BookmarkAdd
import androidx.compose.material.icons.filled.BookmarkRemove
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.RemoveDone
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Label
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.kanade.tachiyomi.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds
@Composable
fun MangaBottomActionMenu(
visible: Boolean,
modifier: Modifier = Modifier,
onBookmarkClicked: (() -> Unit)? = null,
onRemoveBookmarkClicked: (() -> Unit)? = null,
onMarkAsReadClicked: (() -> Unit)? = null,
onMarkAsUnreadClicked: (() -> Unit)? = null,
onMarkPreviousAsReadClicked: (() -> Unit)? = null,
onDownloadClicked: (() -> Unit)? = null,
onDeleteClicked: (() -> Unit)? = null,
) {
AnimatedVisibility(
visible = visible,
enter = expandVertically(expandFrom = Alignment.Bottom),
exit = shrinkVertically(shrinkTowards = Alignment.Bottom),
) {
val scope = rememberCoroutineScope()
Surface(
modifier = modifier,
shape = MaterialTheme.shapes.large.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize),
tonalElevation = 3.dp,
) {
val haptic = LocalHapticFeedback.current
val confirm = remember { mutableStateListOf(false, false, false, false, false, false, false) }
var resetJob: Job? = remember { null }
val onLongClickItem: (Int) -> Unit = { toConfirmIndex ->
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
(0 until 7).forEach { i -> confirm[i] = i == toConfirmIndex }
resetJob?.cancel()
resetJob = scope.launch {
delay(1.seconds)
if (isActive) confirm[toConfirmIndex] = false
}
}
Row(
modifier = Modifier
.padding(WindowInsets.navigationBars.only(WindowInsetsSides.Bottom).asPaddingValues())
.padding(horizontal = 8.dp, vertical = 12.dp),
) {
if (onBookmarkClicked != null) {
Button(
title = stringResource(R.string.action_bookmark),
icon = Icons.Default.BookmarkAdd,
toConfirm = confirm[0],
onLongClick = { onLongClickItem(0) },
onClick = onBookmarkClicked,
)
}
if (onRemoveBookmarkClicked != null) {
Button(
title = stringResource(R.string.action_remove_bookmark),
icon = Icons.Default.BookmarkRemove,
toConfirm = confirm[1],
onLongClick = { onLongClickItem(1) },
onClick = onRemoveBookmarkClicked,
)
}
if (onMarkAsReadClicked != null) {
Button(
title = stringResource(R.string.action_mark_as_read),
icon = Icons.Default.DoneAll,
toConfirm = confirm[2],
onLongClick = { onLongClickItem(2) },
onClick = onMarkAsReadClicked,
)
}
if (onMarkAsUnreadClicked != null) {
Button(
title = stringResource(R.string.action_mark_as_unread),
icon = Icons.Default.RemoveDone,
toConfirm = confirm[3],
onLongClick = { onLongClickItem(3) },
onClick = onMarkAsUnreadClicked,
)
}
if (onMarkPreviousAsReadClicked != null) {
Button(
title = stringResource(R.string.action_mark_previous_as_read),
icon = ImageVector.vectorResource(id = R.drawable.ic_done_prev_24dp),
toConfirm = confirm[4],
onLongClick = { onLongClickItem(4) },
onClick = onMarkPreviousAsReadClicked,
)
}
if (onDownloadClicked != null) {
Button(
title = stringResource(R.string.action_download),
icon = Icons.Outlined.Download,
toConfirm = confirm[5],
onLongClick = { onLongClickItem(5) },
onClick = onDownloadClicked,
)
}
if (onDeleteClicked != null) {
Button(
title = stringResource(R.string.action_delete),
icon = Icons.Outlined.Delete,
toConfirm = confirm[6],
onLongClick = { onLongClickItem(6) },
onClick = onDeleteClicked,
)
}
}
}
}
}
@Composable
private fun RowScope.Button(
title: String,
icon: ImageVector,
toConfirm: Boolean,
onLongClick: () -> Unit,
onClick: () -> Unit,
) {
val animatedWeight by animateFloatAsState(if (toConfirm) 2f else 1f)
Column(
modifier = Modifier
.size(48.dp)
.weight(animatedWeight)
.combinedClickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = false),
onLongClick = onLongClick,
onClick = onClick,
),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
imageVector = icon,
contentDescription = title,
)
AnimatedVisibility(
visible = toConfirm,
enter = expandVertically(expandFrom = Alignment.Top) + fadeIn(),
exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut(),
) {
Text(
text = title,
overflow = TextOverflow.Visible,
maxLines = 1,
style = MaterialTheme.typography.labelSmall,
)
}
}
}
@Composable
fun LibraryBottomActionMenu(
visible: Boolean,
modifier: Modifier = Modifier,
onChangeCategoryClicked: (() -> Unit)?,
onMarkAsReadClicked: (() -> Unit)?,
onMarkAsUnreadClicked: (() -> Unit)?,
onDownloadClicked: (() -> Unit)?,
onDeleteClicked: (() -> Unit)?,
) {
AnimatedVisibility(
visible = visible,
enter = expandVertically(expandFrom = Alignment.Bottom),
exit = shrinkVertically(shrinkTowards = Alignment.Bottom),
) {
val scope = rememberCoroutineScope()
Surface(
modifier = modifier,
shape = MaterialTheme.shapes.large.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize),
tonalElevation = 3.dp,
) {
val haptic = LocalHapticFeedback.current
val confirm = remember { mutableStateListOf(false, false, false, false, false) }
var resetJob: Job? = remember { null }
val onLongClickItem: (Int) -> Unit = { toConfirmIndex ->
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
(0 until 5).forEach { i -> confirm[i] = i == toConfirmIndex }
resetJob?.cancel()
resetJob = scope.launch {
delay(1.seconds)
if (isActive) confirm[toConfirmIndex] = false
}
}
Row(
modifier = Modifier
.navigationBarsPadding()
.padding(horizontal = 8.dp, vertical = 12.dp),
) {
if (onChangeCategoryClicked != null) {
Button(
title = stringResource(R.string.action_move_category),
icon = Icons.Outlined.Label,
toConfirm = confirm[0],
onLongClick = { onLongClickItem(0) },
onClick = onChangeCategoryClicked,
)
}
if (onMarkAsReadClicked != null) {
Button(
title = stringResource(R.string.action_mark_as_read),
icon = Icons.Default.DoneAll,
toConfirm = confirm[1],
onLongClick = { onLongClickItem(1) },
onClick = onMarkAsReadClicked,
)
}
if (onMarkAsUnreadClicked != null) {
Button(
title = stringResource(R.string.action_mark_as_unread),
icon = Icons.Default.RemoveDone,
toConfirm = confirm[2],
onLongClick = { onLongClickItem(2) },
onClick = onMarkAsUnreadClicked,
)
}
if (onDownloadClicked != null) {
Button(
title = stringResource(R.string.action_download),
icon = Icons.Outlined.Download,
toConfirm = confirm[3],
onLongClick = { onLongClickItem(3) },
onClick = onDownloadClicked,
)
}
if (onDeleteClicked != null) {
Button(
title = stringResource(R.string.action_delete),
icon = Icons.Outlined.Delete,
toConfirm = confirm[4],
onLongClick = { onLongClickItem(4) },
onClick = onDeleteClicked,
)
}
}
}
}
}
| apache-2.0 | abf5f55be62e3779f92dc4f32f1a8c70 | 41.313993 | 110 | 0.565333 | 5.307363 | false | false | false | false |
square/wire | wire-library/wire-reflector/src/main/kotlin/com/squareup/wire/reflector/SchemaReflector.kt | 1 | 7533 | /*
* Copyright 2021 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.reflector
import com.squareup.wire.GrpcStatus
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.MessageType
import com.squareup.wire.schema.ProtoFile
import com.squareup.wire.schema.Schema
import com.squareup.wire.schema.internal.SchemaEncoder
import grpc.reflection.v1alpha.ErrorResponse
import grpc.reflection.v1alpha.ExtensionNumberResponse
import grpc.reflection.v1alpha.ExtensionRequest
import grpc.reflection.v1alpha.FileDescriptorResponse
import grpc.reflection.v1alpha.ListServiceResponse
import grpc.reflection.v1alpha.ServerReflectionRequest
import grpc.reflection.v1alpha.ServerReflectionResponse
import grpc.reflection.v1alpha.ServiceResponse
/**
* This converts a Wire Schema model to a protobuf DescriptorProtos model and serves that.
*/
class SchemaReflector(
private val schema: Schema,
private val includeDependencies: Boolean = true
) {
fun process(request: ServerReflectionRequest): ServerReflectionResponse {
val response = when {
request.list_services != null -> listServices()
request.file_by_filename != null -> fileByFilename(request)
request.file_containing_symbol != null -> fileContainingSymbol(request.file_containing_symbol)
request.all_extension_numbers_of_type != null -> allExtensionNumbersOfType(
request.all_extension_numbers_of_type
)
request.file_containing_extension != null -> fileContainingExtension(
request.file_containing_extension
)
else -> {
ServerReflectionResponse(
error_response = ErrorResponse(
error_code = GrpcStatus.INVALID_ARGUMENT.code,
"unsupported request"
)
)
}
}
return response.copy(
valid_host = request.host,
original_request = request
)
}
private fun allExtensionNumbersOfType(type: String): ServerReflectionResponse {
val wireType = schema.getType(type)
if (wireType == null || wireType !is MessageType) {
return ServerReflectionResponse(
error_response = ErrorResponse(
error_code = GrpcStatus.NOT_FOUND.code,
error_message = "unknown type: \"$type\""
)
)
}
val extensionNumbers = wireType.extensionFields.map { it.tag }
return ServerReflectionResponse(
all_extension_numbers_response = ExtensionNumberResponse(
base_type_name = type,
extension_number = extensionNumbers,
)
)
}
private fun fileContainingExtension(extension: ExtensionRequest): ServerReflectionResponse {
val wireType = schema.getType(extension.containing_type)
if (wireType == null || wireType !is MessageType) {
return ServerReflectionResponse(
error_response = ErrorResponse(
error_code = GrpcStatus.NOT_FOUND.code,
error_message = "unknown type: \"$extension.containing_type\""
)
)
}
val field = wireType.extensionFields
.firstOrNull { it.tag == extension.extension_number }
?: return ServerReflectionResponse(
error_response = ErrorResponse(
error_code = GrpcStatus.NOT_FOUND.code,
error_message = "unknown type: \"$extension.containing_type\""
)
)
val location = field.location
val protoFile = schema.protoFile(location.path)!!
val allProtoFiles = allDependencies(protoFile)
val schemaEncoder = SchemaEncoder(schema)
return ServerReflectionResponse(
file_descriptor_response = FileDescriptorResponse(allProtoFiles.map { schemaEncoder.encode(it) })
)
}
private fun listServices(): ServerReflectionResponse {
val allServiceNames = mutableListOf<ServiceResponse>()
for (protoFile in schema.protoFiles) {
for (service in protoFile.services) {
val packagePrefix = when {
protoFile.packageName != null -> protoFile.packageName + "."
else -> ""
}
val serviceName = packagePrefix + service.name
allServiceNames += ServiceResponse(name = serviceName)
}
}
return ServerReflectionResponse(
list_services_response = ListServiceResponse(
service = allServiceNames.sortedBy { it.name }
)
)
}
private fun fileByFilename(request: ServerReflectionRequest): ServerReflectionResponse {
val protoFile = schema.protoFile(request.file_by_filename!!)!!
val allProtoFiles = allDependencies(protoFile)
val schemaEncoder = SchemaEncoder(schema)
return ServerReflectionResponse(
file_descriptor_response = FileDescriptorResponse(allProtoFiles.map { schemaEncoder.encode(it) })
)
}
private fun fileContainingSymbol(file_containing_symbol: String): ServerReflectionResponse {
val symbol = file_containing_symbol.removePrefix(".")
val location = location(symbol)
?: return ServerReflectionResponse(
error_response = ErrorResponse(
error_code = GrpcStatus.NOT_FOUND.code,
"unknown symbol: $file_containing_symbol"
)
)
val protoFile = schema.protoFile(location.path)!!
val allProtoFiles = allDependencies(protoFile)
val schemaEncoder = SchemaEncoder(schema)
return ServerReflectionResponse(
file_descriptor_response = FileDescriptorResponse(allProtoFiles.map { schemaEncoder.encode(it) })
)
}
private fun location(symbol: String): Location? {
val service = schema.getService(symbol)
if (service != null) return service.location
val type = schema.getType(symbol)
if (type != null) return type.location
val beforeLastDotName = symbol.substringBeforeLast(".")
val afterLastDot = symbol.substring(beforeLastDotName.length + 1)
val serviceWithMethod = schema.getService(beforeLastDotName)
if (serviceWithMethod?.rpc(afterLastDot) != null) return serviceWithMethod.location
val extend = schema.protoFiles
.filter { it.packageName == beforeLastDotName }
.flatMap { it.extendList }
.flatMap { it.fields }
.firstOrNull { it.name == afterLastDot }
if (extend != null) return extend.location
return null
}
/**
* Returns [protoFile] and all its transitive dependencies in topographical order such that files
* always appear before their dependencies.
*/
private fun allDependencies(protoFile: ProtoFile): List<ProtoFile> {
if (!includeDependencies) return listOf(protoFile)
val result = mutableListOf<ProtoFile>()
collectAllDependencies(protoFile, mutableSetOf(), result)
return result
}
private fun collectAllDependencies(protoFile: ProtoFile, visited: MutableSet<String>, result: MutableList<ProtoFile>) {
if (visited.add(protoFile.name())) {
result.add(protoFile)
protoFile.imports.forEach {
collectAllDependencies(schema.protoFile(it)!!, visited, result)
}
protoFile.publicImports.forEach {
collectAllDependencies(schema.protoFile(it)!!, visited, result)
}
}
}
}
| apache-2.0 | 173bb5335f69dddb1a19a31de33a7b7d | 34.533019 | 121 | 0.708217 | 4.516187 | false | false | false | false |
TeamMeanMachine/meanlib | src/main/kotlin/org/team2471/frc/lib/math/Geometry.kt | 1 | 3276 | package org.team2471.frc.lib.math
import java.lang.Math.pow
import java.lang.Math.sqrt
data class Point(val x: Double, val y: Double) {
companion object {
@JvmStatic
val ORIGIN: Point = Point(0.0, 0.0)
}
operator fun unaryPlus() = this
operator fun unaryMinus() = Point(-x, -y)
operator fun plus(b: Point) = Point(x + b.x, y + b.y)
operator fun plus(vec: Vector2) = Point(x + vec.x, y + vec.y)
operator fun minus(b: Point) = Point(x - b.x, y - b.y)
operator fun minus(vec: Vector2) = Point(x - vec.x, y - vec.y)
operator fun times(scalar: Double) = Point(x * scalar, y * scalar)
operator fun div(scalar: Double) = Point(x / scalar, y / scalar)
fun distance(b: Point): Double = sqrt(pow(b.x - this.x, 2.0) + pow(b.y - this.y, 2.0))
fun vectorTo(b: Point): Vector2 = Vector2(b.x - this.x, b.y - this.y)
fun closestPoint(firstPoint: Point, vararg additionalPoints: Point): Point =
additionalPoints.fold(firstPoint) { result, next ->
if (distance(next) < distance(result)) next
else result
}
}
data class Line(val pointA: Point, val pointB: Point) {
val slope = (pointB.y - pointA.y) / (pointB.x - pointA.x)
val intercept = -slope * pointA.x + pointA.y
operator fun get(x: Double): Double = slope * x + intercept
operator fun plus(vec: Vector2) = Line(pointA + vec, pointB + vec)
operator fun minus(vec: Vector2) = Line(pointA - vec, pointB - vec)
fun pointInLine(point: Point): Boolean = point.y == this[point.x]
fun pointInSegment(point: Point): Boolean =
pointInLine(point) && point.distance(pointA) + point.distance(pointB) == pointA.distance(pointB)
}
data class Circle(val center: Point, val radius: Double) {
companion object {
@JvmStatic
val UNIT = Circle(Point.ORIGIN, 1.0)
}
// adapted from: https://stackoverflow.com/a/13055116
fun intersectingPoints(line: Line): Array<Point> {
val (pointA, pointB) = line
val baX = pointB.x - pointA.x
val baY = pointB.y - pointA.y
val caX = center.x - pointA.x
val caY = center.y - pointA.y
val a = baX * baX + baY * baY
val bBy2 = baX * caX + baY * caY
val c = caX * caX + caY * caY - radius * radius
val pBy2 = bBy2 / a
val q = c / a
val disc = pBy2 * pBy2 - q
if (disc < 0) {
return emptyArray()
}
// if disc == 0 ... dealt with later
val tmpSqrt = Math.sqrt(disc)
val abScalingFactor1 = -pBy2 + tmpSqrt
val abScalingFactor2 = -pBy2 - tmpSqrt
val p1 = Point(pointA.x - baX * abScalingFactor1, pointA.y - baY * abScalingFactor1)
if (disc == 0.0) { // abScalingFactor1 == abScalingFactor2
return arrayOf(p1)
}
val p2 = Point(pointA.x - baX * abScalingFactor2, pointA.y - baY * abScalingFactor2)
return arrayOf(p1, p2)
}
operator fun plus(vec: Vector2) = Circle(center + vec, radius)
operator fun minus(vec: Vector2) = Circle(center - vec, radius)
operator fun times(scalar: Double) = Circle(center, radius * scalar)
operator fun div(scalar: Double) = Circle(center, radius / scalar)
}
| unlicense | 6934e05558be311720e66e1a1a5bc5b7 | 31.117647 | 108 | 0.601038 | 3.394819 | false | false | false | false |
JoeSteven/HuaBan | app/src/main/java/com/joe/zatuji/module/setting/SettingActivity.kt | 1 | 1526 | package com.joe.zatuji.module.setting
import android.view.MenuItem
import com.joe.zatuji.R
import com.joe.zatuji.base.BaseActivity
import com.joe.zatuji.module.discover.DiscoverMenuDialog
import com.joe.zatuji.storege.SettingKeeper
import kotlinx.android.synthetic.main.activity_setting.*
/**
* Description:
* author:Joey
* date:2018/11/26
*/
class SettingActivity: BaseActivity() {
private val discoverMenuDialog: DiscoverMenuDialog by lazy { DiscoverMenuDialog(this).setOnMenuClickListener {
SettingKeeper.discoverTag = it
btnDiscover.setHint(it.name)
}}
override fun initLayout(): Int {
return R.layout.activity_setting
}
override fun initView() {
setSupportActionBar(toolbar)
title = getString(R.string.title_setting)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
btnDiscover.setHint(SettingKeeper.discoverTag.name)
btnCache.setCheckedImmediately(SettingKeeper.noCache)
btnNoWifi.setCheckedImmediately(SettingKeeper.noWifiHint)
btnDiscover.setOnClickListener { discoverMenuDialog.show() }
btnCache.setOnCheckedChangeListener { _, _, isChecked -> SettingKeeper.noCache = isChecked }
btnNoWifi.setOnCheckedChangeListener { _, _, isChecked -> SettingKeeper.noWifiHint = isChecked}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | 0b3e9967b5c76cf20ece9a13eb9d9698 | 34.511628 | 114 | 0.724115 | 4.541667 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinOtherSettingsPanel.kt | 1 | 2563 | // 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.formatter
import com.intellij.application.options.CodeStyleAbstractPanel
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.ui.OptionGroup
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.JCheckBox
import javax.swing.JPanel
class KotlinOtherSettingsPanel(settings: CodeStyleSettings) : CodeStyleAbstractPanel(KotlinLanguage.INSTANCE, null, settings) {
private val cbTrailingComma = JCheckBox(KotlinBundle.message("formatter.checkbox.text.use.trailing.comma"))
override fun getRightMargin() = throw UnsupportedOperationException()
override fun createHighlighter(scheme: EditorColorsScheme) = throw UnsupportedOperationException()
override fun getFileType() = throw UnsupportedOperationException()
override fun getPreviewText(): String? = null
override fun apply(settings: CodeStyleSettings) {
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = cbTrailingComma.isSelected
}
override fun isModified(settings: CodeStyleSettings): Boolean {
return settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA != cbTrailingComma.isSelected
}
override fun getPanel() = jPanel
override fun resetImpl(settings: CodeStyleSettings) {
cbTrailingComma.isSelected = settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA
}
override fun getTabTitle(): String = KotlinBundle.message("formatter.title.other")
private val jPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(
JBScrollPane(
JPanel(VerticalLayout(JBUI.scale(5))).apply {
border = BorderFactory.createEmptyBorder(0, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP)
add(
OptionGroup(KotlinBundle.message("formatter.title.trailing.comma")).apply {
add(cbTrailingComma)
}.createPanel()
)
}
)
)
}
}
| apache-2.0 | cbe5e3bbf7a8d6f71b798fe0b6f75fba | 40.33871 | 158 | 0.728443 | 5.045276 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ParentAndChildWithNulls.kt | 1 | 2826 | // 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.entities.test.api
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
interface ParentWithNulls : WorkspaceEntity {
val parentData: String
@Child
val child: ChildWithNulls?
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ParentWithNulls, ModifiableWorkspaceEntity<ParentWithNulls>, ObjBuilder<ParentWithNulls> {
override var parentData: String
override var entitySource: EntitySource
override var child: ChildWithNulls?
}
companion object: Type<ParentWithNulls, Builder>() {
operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNulls {
val builder = builder()
builder.parentData = parentData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ParentWithNulls, modification: ParentWithNulls.Builder.() -> Unit) = modifyEntity(ParentWithNulls.Builder::class.java, entity, modification)
//endregion
interface ChildWithNulls : WorkspaceEntity {
val childData: String
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ChildWithNulls, ModifiableWorkspaceEntity<ChildWithNulls>, ObjBuilder<ChildWithNulls> {
override var childData: String
override var entitySource: EntitySource
}
companion object: Type<ChildWithNulls, Builder>() {
operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNulls {
val builder = builder()
builder.childData = childData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildWithNulls, modification: ChildWithNulls.Builder.() -> Unit) = modifyEntity(ChildWithNulls.Builder::class.java, entity, modification)
var ChildWithNulls.Builder.parentEntity: ParentWithNulls?
by WorkspaceEntity.extension()
//endregion
val ChildWithNulls.parentEntity: ParentWithNulls?
by WorkspaceEntity.extension()
| apache-2.0 | 9805cbc4b9091f4b03653b226f5214f4 | 35.701299 | 186 | 0.757254 | 5.233333 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/CheesyDriveController.kt | 1 | 5387 | package org.snakeskin.utility
import org.snakeskin.component.IDifferentialDrivetrain
import org.snakeskin.logic.scalars.NoScaling
import org.snakeskin.logic.scalars.IScalar
import org.snakeskin.template.CheesyDriveParametersTemplate
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
/**
* @author Cameron Earle
* @version 12/8/2018
*
* Implements the Cheesy Poofs "Cheesy Drive"
*/
class CheesyDriveController(private val config: CheesyDriveParametersTemplate = DefaultParameters()) {
open class DefaultParameters: CheesyDriveParametersTemplate {
override val highWheelNonLinearity: Double = 0.65
override val lowWheelNonLinearity: Double = 0.5
override val highNegInertiaScalar: Double = 4.0
override val lowNegInertiaThreshold: Double = 0.65
override val lowNegInertiaTurnScalar: Double = 3.5
override val lowNegInertiaCloseScalar: Double = 4.0
override val lowNegInertiaFarScalar: Double = 5.0
override val highSensitivity: Double = 0.95
override val lowSensitivity: Double = 1.3
override val quickStopDeadband: Double = 0.2
override val quickStopWeight: Double = 0.1
override val quickStopScalar: Double = 5.0
override val lowSinCount: Int = 3
override val highSinCount: Int = 2
override val outputScalar: Double = 1.0
override val quickTurnScalar: IScalar = NoScaling
}
data class Output(val left: Double, val right: Double) {
/**
* Runs the command on a drivetrain
*/
fun applyTo(drivetrain: IDifferentialDrivetrain) {
drivetrain.tank(left, right)
}
}
private var oldWheel = 0.0
private var quickStopAccumulator = 0.0
private var negInertiaAccumulator = 0.0
private val highDenom = sin(Math.PI / 2.0 * config.highWheelNonLinearity)
private val lowDenom = sin(Math.PI / 2.0 * config.lowWheelNonLinearity)
fun reset() {
oldWheel = 0.0
quickStopAccumulator = 0.0
negInertiaAccumulator = 0.0
}
fun update(throttleIn: Double, wheelIn: Double, isHigh: Boolean, quickTurn: Boolean = false): Output {
var wheel = wheelIn
if (quickTurn) {
wheel = config.quickTurnScalar.scale(wheel)
}
val negInertia = wheel - oldWheel
oldWheel = wheel
if (isHigh) {
for (i in 0 until config.highSinCount) {
wheel = sin(Math.PI / 2.0 * config.highWheelNonLinearity * wheel) / highDenom
}
} else {
for (i in 0 until config.lowSinCount) {
wheel = sin(Math.PI / 2.0 * config.lowWheelNonLinearity * wheel) / lowDenom
}
}
var leftOut: Double
var rightOut: Double
val overPower: Double
val sensitivity: Double
val angularPower: Double
val linearPower: Double = throttleIn
val negInertiaScalar: Double
if (isHigh) {
negInertiaScalar = config.highNegInertiaScalar
sensitivity = config.highSensitivity
} else {
negInertiaScalar = if (wheel * negInertia > 0) {
config.lowNegInertiaTurnScalar
} else {
if (abs(wheel) > config.lowNegInertiaThreshold) {
config.lowNegInertiaFarScalar
} else {
config.lowNegInertiaCloseScalar
}
}
sensitivity = config.lowSensitivity
}
val negInertiaPower = negInertia * negInertiaScalar
negInertiaAccumulator += negInertiaPower
wheel += negInertiaAccumulator
when {
negInertiaAccumulator > 1.0 -> negInertiaAccumulator -= 1.0
negInertiaAccumulator < -1.0 -> negInertiaAccumulator += 1.0
else -> negInertiaAccumulator = 0.0
}
if (quickTurn) {
if (abs(linearPower) < config.quickStopDeadband) {
val alpha = config.quickStopWeight
quickStopAccumulator *= (1 - alpha)
+ alpha * min(1.0, max(-1.0, wheel)) * config.quickStopScalar
}
overPower = 1.0
angularPower = wheel
} else {
overPower = 0.0
angularPower = abs(throttleIn) * wheel * sensitivity - quickStopAccumulator
when {
quickStopAccumulator > 1 -> quickStopAccumulator -= 1.0
quickStopAccumulator < -1 -> quickStopAccumulator += 1
else -> quickStopAccumulator = 0.0
}
}
leftOut = linearPower + angularPower
rightOut = linearPower - angularPower
when {
leftOut > 1.0 -> {
rightOut -= overPower * (leftOut - 1.0)
leftOut = 1.0
}
rightOut > 1.0 -> {
leftOut -= overPower * (rightOut - 1.0)
rightOut = 1.0
}
leftOut < -1.0 -> {
rightOut += overPower * (-1.0 - leftOut)
leftOut = -1.0
}
rightOut < -1.0 -> {
leftOut += overPower * (-1.0 - rightOut)
rightOut = -1.0
}
}
return Output(leftOut * config.outputScalar, rightOut * config.outputScalar)
}
} | gpl-3.0 | 0360edf3e5ca7ddef766416e78fbc2f8 | 33.76129 | 106 | 0.588082 | 4.115355 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt | 3 | 14376 | // 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.refactoring.introduce.introduceTypeAlias
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.containers.LinkedMultiMap
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.refactoring.introduce.insertDeclaration
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnifierParameter
import org.jetbrains.kotlin.idea.util.psi.patternMatching.match
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.types.TypeUtils
sealed class IntroduceTypeAliasAnalysisResult {
class Error(@NlsContexts.DialogMessage val message: String) : IntroduceTypeAliasAnalysisResult()
class Success(val descriptor: IntroduceTypeAliasDescriptor) : IntroduceTypeAliasAnalysisResult()
}
private fun IntroduceTypeAliasData.getTargetScope() = targetSibling.getResolutionScope(bindingContext, resolutionFacade)
fun IntroduceTypeAliasData.analyze(): IntroduceTypeAliasAnalysisResult {
val psiFactory = KtPsiFactory(originalTypeElement)
val contextExpression = originalTypeElement.getStrictParentOfType<KtExpression>()!!
val targetScope = getTargetScope()
val dummyVar = psiFactory.createProperty("val a: Int").apply {
typeReference!!.replace(
originalTypeElement.parent as? KtTypeReference ?: if (originalTypeElement is KtTypeElement) psiFactory.createType(
originalTypeElement
) else psiFactory.createType(originalTypeElement.text)
)
}
val newTypeReference = dummyVar.typeReference!!
val newReferences = newTypeReference.collectDescendantsOfType<KtTypeReference> { it.resolveInfo != null }
val newContext = dummyVar.analyzeInContext(targetScope, contextExpression)
val project = originalTypeElement.project
val unifier = KotlinPsiUnifier.DEFAULT
val groupedReferencesToExtract = LinkedMultiMap<TypeReferenceInfo, TypeReferenceInfo>()
val forcedCandidates = if (extractTypeConstructor) newTypeReference.typeElement!!.typeArgumentsAsTypes else emptyList()
for (newReference in newReferences) {
val resolveInfo = newReference.resolveInfo!!
if (newReference !in forcedCandidates) {
val originalDescriptor = resolveInfo.type.constructor.declarationDescriptor
val newDescriptor = newContext[BindingContext.TYPE, newReference]?.constructor?.declarationDescriptor
if (compareDescriptors(project, originalDescriptor, newDescriptor)) continue
}
val equivalenceRepresentative = groupedReferencesToExtract
.keySet()
.firstOrNull { unifier.unify(it.reference, resolveInfo.reference).isMatched }
if (equivalenceRepresentative != null) {
groupedReferencesToExtract.putValue(equivalenceRepresentative, resolveInfo)
} else {
groupedReferencesToExtract.putValue(resolveInfo, resolveInfo)
}
val referencesToExtractIterator = groupedReferencesToExtract.values().iterator()
while (referencesToExtractIterator.hasNext()) {
val referenceToExtract = referencesToExtractIterator.next()
if (resolveInfo.reference.isAncestor(referenceToExtract.reference, true)) {
referencesToExtractIterator.remove()
}
}
}
val typeParameterNameValidator = CollectingNameValidator()
val brokenReferences = groupedReferencesToExtract.keySet().filter { groupedReferencesToExtract[it].isNotEmpty() }
val typeParameterNames = Fe10KotlinNameSuggester.suggestNamesForTypeParameters(brokenReferences.size, typeParameterNameValidator)
val typeParameters = (typeParameterNames zip brokenReferences).map { TypeParameter(it.first, groupedReferencesToExtract[it.second]) }
if (typeParameters.any { it.typeReferenceInfos.any { info -> info.reference.typeElement == originalTypeElement } }) {
return IntroduceTypeAliasAnalysisResult.Error(KotlinBundle.message("text.type.alias.cannot.refer.to.types.which.aren.t.accessible.in.the.scope.where.it.s.defined"))
}
val descriptor = IntroduceTypeAliasDescriptor(this, "Dummy", null, typeParameters)
val initialName = Fe10KotlinNameSuggester.suggestTypeAliasNameByPsi(descriptor.generateTypeAlias(true).getTypeReference()!!.typeElement!!) {
targetScope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null
}
return IntroduceTypeAliasAnalysisResult.Success(descriptor.copy(name = initialName))
}
fun IntroduceTypeAliasData.getApplicableVisibilities(): List<KtModifierKeywordToken> = when (targetSibling.parent) {
is KtClassBody -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD)
is KtFile -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD)
else -> emptyList()
}
fun IntroduceTypeAliasDescriptor.validate(): IntroduceTypeAliasDescriptorWithConflicts {
val conflicts = MultiMap<PsiElement, String>()
val originalType = originalData.originalTypeElement
when {
name.isEmpty() ->
conflicts.putValue(originalType, KotlinBundle.message("text.no.name.provided.for.type.alias"))
!name.isIdentifier() ->
conflicts.putValue(originalType, KotlinBundle.message("text.type.alias.name.must.be.a.valid.identifier.0", name))
originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null ->
conflicts.putValue(originalType, KotlinBundle.message("text.type.already.exists.in.the.target.scope", name))
}
if (typeParameters.distinctBy { it.name }.size != typeParameters.size) {
conflicts.putValue(originalType, KotlinBundle.message("text.type.parameter.names.must.be.distinct"))
}
if (visibility != null && visibility !in originalData.getApplicableVisibilities()) {
conflicts.putValue(originalType, KotlinBundle.message("text.0.is.not.allowed.in.the.target.context", visibility))
}
return IntroduceTypeAliasDescriptorWithConflicts(this, conflicts)
}
fun findDuplicates(typeAlias: KtTypeAlias): Map<KotlinPsiRange, () -> Unit> {
val aliasName = typeAlias.name?.quoteIfNeeded() ?: return emptyMap()
val aliasRange = typeAlias.textRange
val typeAliasDescriptor = typeAlias.unsafeResolveToDescriptor() as TypeAliasDescriptor
val unifierParameters = typeAliasDescriptor.declaredTypeParameters.map { UnifierParameter(it, null) }
val unifier = KotlinPsiUnifier(unifierParameters)
val psiFactory = KtPsiFactory(typeAlias)
fun replaceTypeElement(occurrence: KtTypeElement, typeArgumentsText: String) {
occurrence.replace(psiFactory.createType("$aliasName$typeArgumentsText").typeElement!!)
}
fun replaceOccurrence(occurrence: PsiElement, arguments: List<KtTypeElement>) {
val typeArgumentsText = if (arguments.isNotEmpty()) "<${arguments.joinToString { it.text }}>" else ""
when (occurrence) {
is KtTypeElement -> {
replaceTypeElement(occurrence, typeArgumentsText)
}
is KtSuperTypeCallEntry -> {
occurrence.calleeExpression.typeReference?.typeElement?.let { replaceTypeElement(it, typeArgumentsText) }
}
is KtCallElement -> {
val qualifiedExpression = occurrence.parent as? KtQualifiedExpression
val callExpression = if (qualifiedExpression != null && qualifiedExpression.selectorExpression == occurrence) {
qualifiedExpression.replaced(occurrence)
} else occurrence
val typeArgumentList = callExpression.typeArgumentList
if (arguments.isNotEmpty()) {
val newTypeArgumentList = psiFactory.createTypeArguments(typeArgumentsText)
typeArgumentList?.replace(newTypeArgumentList) ?: callExpression.addAfter(
newTypeArgumentList,
callExpression.calleeExpression
)
} else {
typeArgumentList?.delete()
}
callExpression.calleeExpression?.replace(psiFactory.createExpression(aliasName))
}
is KtExpression -> occurrence.replace(psiFactory.createExpression(aliasName))
}
}
val rangesWithReplacers = ArrayList<Pair<KotlinPsiRange, () -> Unit>>()
val originalTypePsi = typeAliasDescriptor.underlyingType.constructor.declarationDescriptor?.let {
DescriptorToSourceUtilsIde.getAnyDeclaration(typeAlias.project, it)
}
if (originalTypePsi != null) {
for (reference in ReferencesSearch.search(originalTypePsi, LocalSearchScope(typeAlias.parent))) {
val element = reference.element as? KtSimpleNameExpression ?: continue
if ((element.textRange.intersects(aliasRange))) continue
val arguments: List<KtTypeElement>
val occurrence: KtElement
val callElement = element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
occurrence = callElement
arguments = callElement.typeArguments.mapNotNull { it.typeReference?.typeElement }
} else {
val userType = element.getParentOfTypeAndBranch<KtUserType> { referenceExpression }
if (userType != null) {
occurrence = userType
arguments = userType.typeArgumentsAsTypes.mapNotNull { it.typeElement }
} else continue
}
if (arguments.size != typeAliasDescriptor.declaredTypeParameters.size) continue
if (TypeUtils.isNullableType(typeAliasDescriptor.underlyingType)
&& occurrence is KtUserType
&& occurrence.parent !is KtNullableType
) continue
rangesWithReplacers += occurrence.toRange() to { replaceOccurrence(occurrence, arguments) }
}
}
typeAlias
.getTypeReference()
?.typeElement
.toRange()
.match(typeAlias.parent, unifier)
.asSequence()
.filter { !(it.range.textRange.intersects(aliasRange)) }
.mapNotNullTo(rangesWithReplacers) { match ->
val occurrence = match.range.elements.singleOrNull() as? KtTypeElement ?: return@mapNotNullTo null
val arguments = unifierParameters.mapNotNull { (match.substitution[it] as? KtTypeReference)?.typeElement }
if (arguments.size != unifierParameters.size) return@mapNotNullTo null
match.range to { replaceOccurrence(occurrence, arguments) }
}
return rangesWithReplacers.toMap()
}
private var KtTypeReference.typeParameterInfo: TypeParameter? by CopyablePsiUserDataProperty(Key.create("TYPE_PARAMETER_INFO"))
fun IntroduceTypeAliasDescriptor.generateTypeAlias(previewOnly: Boolean = false): KtTypeAlias {
val originalElement = originalData.originalTypeElement
val psiFactory = KtPsiFactory(originalElement)
for (typeParameter in typeParameters)
for (it in typeParameter.typeReferenceInfos) {
it.reference.typeParameterInfo = typeParameter
}
val typeParameterNames = typeParameters.map { it.name }
val typeAlias = if (originalElement is KtTypeElement) {
psiFactory.createTypeAlias(name, typeParameterNames, originalElement)
} else {
psiFactory.createTypeAlias(name, typeParameterNames, originalElement.text)
}
if (visibility != null && visibility != DEFAULT_VISIBILITY_KEYWORD) {
typeAlias.addModifier(visibility)
}
for (typeParameter in typeParameters)
for (it in typeParameter.typeReferenceInfos) {
it.reference.typeParameterInfo = null
}
fun replaceUsage() {
val aliasInstanceText = if (typeParameters.isNotEmpty()) {
"$name<${typeParameters.joinToString { it.typeReferenceInfos.first().reference.text }}>"
} else {
name
}
when (originalElement) {
is KtTypeElement -> originalElement.replace(psiFactory.createType(aliasInstanceText).typeElement!!)
is KtExpression -> originalElement.replace(psiFactory.createExpression(aliasInstanceText))
}
}
fun introduceTypeParameters() {
typeAlias.getTypeReference()!!.forEachDescendantOfType<KtTypeReference> {
val typeParameter = it.typeParameterInfo ?: return@forEachDescendantOfType
val typeParameterReference = psiFactory.createType(typeParameter.name)
it.replace(typeParameterReference)
}
}
return if (previewOnly) {
introduceTypeParameters()
typeAlias
} else {
replaceUsage()
introduceTypeParameters()
insertDeclaration(typeAlias, originalData.targetSibling)
}
} | apache-2.0 | 3ad3cc24d169983872925b50a24f801f | 48.236301 | 172 | 0.725584 | 5.552723 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingClassKeywordIntention.kt | 3 | 2153 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class AddMissingClassKeywordIntention : SelfTargetingIntention<PsiElement>(
PsiElement::class.java,
KotlinBundle.lazyMessage("add.missing.class.keyword")
) {
companion object {
private val targetKeywords = listOf(
KtTokens.ANNOTATION_KEYWORD,
KtTokens.DATA_KEYWORD,
KtTokens.SEALED_KEYWORD,
KtTokens.INNER_KEYWORD
)
}
override fun isApplicableTo(element: PsiElement, caretOffset: Int): Boolean {
if (element.node?.elementType != KtTokens.IDENTIFIER) return false
val ktClass = element.parent as? KtClass
if (ktClass == null) {
val errorElement = element.parent as? PsiErrorElement ?: return false
val modifierList = errorElement.getPrevSiblingIgnoringWhitespaceAndComments() as? KtModifierList ?: return false
return targetKeywords.any { modifierList.hasModifier(it) }
} else {
return ktClass.isEnum() && ktClass.getClassKeyword() == null
}
}
override fun applyTo(element: PsiElement, editor: Editor?) {
val document = editor?.document ?: return
val targetElement = (element.parent as? PsiErrorElement) ?: element
document.insertString(targetElement.startOffset, "class ")
PsiDocumentManager.getInstance(element.project).commitDocument(document)
}
}
| apache-2.0 | 21967993ca2d719bc304d823b387a0cd | 43.854167 | 158 | 0.737111 | 4.871041 | false | false | false | false |
chiclaim/android-sample | language-kotlin/kotlin-sample/kotlin-in-action/src/new_class/ClassTest5.kt | 1 | 1801 | package new_class
/**
* Desc: 多个 Secondary Constructor 构造方法以及初始化代码块的执行实际有 演示
*
* Primary Constructor和Secondary Constructor对比
*
* Created by Chiclaim on 2018/9/19.
*/
//构造方法和class声明在同一行时,该构造方法被称之为 Primary Constructor
//如果构造方法在类的内部声明,该构造方法被称之为 Secondary Constructor
//Primary Constructor和 Secondary Constructor区别:
//Primary Constructor 构造方法的参数如果有val/var修饰,那么该类会生成和该参数一样的属性,以及与之对应setter和getter(如果是var修饰会有getter和setter,val修饰只有getter)
//Secondary Constructor 构造方法的参数不能用val/var属性
//Primary Constructor和 Secondary Constructor不可共存
open class Person5 {
var name: String? = null
var id: Int = 0
constructor(name: String) {
this.name = name
}
constructor(id: Int) : this("chiclaim") {
this.id = id
}
//构造对象的时候,init代码块只会被执行一次
init {
System.out.println("init----------")
}
}
/*
public class Person5 {
@Nullable
private String name;
private int id;
@Nullable
public final String getName() {
return this.name;
}
public final void setName(@Nullable String var1) {
this.name = var1;
}
public final int getId() {
return this.id;
}
public final void setId(int var1) {
this.id = var1;
}
public Person5(@NotNull String name) {
Intrinsics.checkParameterIsNotNull(name, "name");
super();
System.out.println("init----------");
this.name = name;
}
public Person5(int id) {
this("chiclaim");
this.id = id;
}
}
*/ | apache-2.0 | 401e42cf875b241bc36f975c5ccd70a1 | 18.473684 | 117 | 0.653144 | 3.279379 | false | false | false | false |
hanks-zyh/MaterialDesign | app/src/main/java/com/hanks/coor/RecyclerScrollListener.kt | 1 | 1325 | package com.hanks.coor
import android.support.v7.widget.RecyclerView
/**
* Created by Suleiman on 18-04-2015.
* update by hanks on 2015/11/14.
*/
abstract class RecyclerScrollListener : RecyclerView.OnScrollListener() {
internal var scrollDist = 0
private var isVisible = true
// We dont use this method because its action is called per pixel value change
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
// Check scrolled distance against the minimum
if (isVisible && scrollDist > HIDE_THRESHOLD) {
// Hide fab & reset scrollDist
hide()
scrollDist = 0
isVisible = false
} else if (!isVisible && scrollDist < -SHOW_THRESHOLD) {
// Show fab & reset scrollDist
show()
scrollDist = 0
isVisible = true
}// -MINIMUM because scrolling up gives - dy values
// Whether we scroll up or down, calculate scroll distance
if ((isVisible && dy > 0) || (!isVisible && dy < 0)) {
scrollDist += dy
}
}
abstract fun show()
abstract fun hide()
companion object {
private val HIDE_THRESHOLD = 100f
private val SHOW_THRESHOLD = 50f
}
}
| apache-2.0 | 84924b8d007a770daa30ce5aad75171a | 26.604167 | 85 | 0.600755 | 4.522184 | false | false | false | false |
ktorio/ktor | ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/RequestResponseBuilderTest.kt | 1 | 1407 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.http.cio
import io.ktor.http.*
import io.ktor.http.cio.*
import io.ktor.utils.io.streams.*
import kotlin.test.*
class RequestResponseBuilderTest {
private val builder = RequestResponseBuilder()
@AfterTest
fun tearDown() {
builder.release()
}
@Test
fun testBuildGet() {
builder.apply {
requestLine(HttpMethod.Get, "/", "HTTP/1.1")
headerLine("Host", "localhost")
headerLine("Connection", "close")
emptyLine()
}
val packet = builder.build()
val request = packet.inputStream().reader().readText()
assertEquals("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n", request)
}
@Test
fun testBuildOK() {
builder.apply {
responseLine("HTTP/1.1", 200, "OK")
headerLine("Content-Type", "text/plain")
headerLine("Connection", "close")
emptyLine()
line("Hello, World!")
}
val packet = builder.build()
val response = packet.inputStream().reader().readText()
assertEquals(
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nHello, World!\r\n",
response
)
}
}
| apache-2.0 | a7b7a7e0da2fd2274807f8b0b3ef5cdc | 25.54717 | 119 | 0.584932 | 3.952247 | false | true | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/nbt/Nbt.kt | 1 | 6867 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt
import com.demonwav.mcdev.nbt.tags.NbtTag
import com.demonwav.mcdev.nbt.tags.NbtTypeId
import com.demonwav.mcdev.nbt.tags.RootCompound
import com.demonwav.mcdev.nbt.tags.TagByte
import com.demonwav.mcdev.nbt.tags.TagByteArray
import com.demonwav.mcdev.nbt.tags.TagCompound
import com.demonwav.mcdev.nbt.tags.TagDouble
import com.demonwav.mcdev.nbt.tags.TagEnd
import com.demonwav.mcdev.nbt.tags.TagFloat
import com.demonwav.mcdev.nbt.tags.TagInt
import com.demonwav.mcdev.nbt.tags.TagIntArray
import com.demonwav.mcdev.nbt.tags.TagList
import com.demonwav.mcdev.nbt.tags.TagLong
import com.demonwav.mcdev.nbt.tags.TagLongArray
import com.demonwav.mcdev.nbt.tags.TagShort
import com.demonwav.mcdev.nbt.tags.TagString
import java.io.DataInputStream
import java.io.InputStream
import java.util.zip.GZIPInputStream
import java.util.zip.ZipException
object Nbt {
private fun getActualInputStream(stream: InputStream): Pair<DataInputStream, Boolean> {
return try {
DataInputStream(GZIPInputStream(stream)) to true
} catch (e: ZipException) {
stream.reset()
DataInputStream(stream) to false
}
}
/**
* Parse the NBT file from the InputStream and return the root TagCompound for the NBT file. This method closes the stream when
* it is finished with it.
*/
@Throws(MalformedNbtFileException::class)
fun buildTagTree(inputStream: InputStream, timeout: Long): Pair<RootCompound, Boolean> {
try {
val (stream, isCompressed) = getActualInputStream(inputStream)
stream.use {
val tagIdByte = stream.readByte()
val tagId = NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
if (tagId != NbtTypeId.COMPOUND) {
throw MalformedNbtFileException("Root tag in NBT file is not a compound.")
}
val start = System.currentTimeMillis()
return RootCompound(stream.readUTF(), stream.readCompoundTag(start, timeout).tagMap) to isCompressed
}
} catch (e: Throwable) {
if (e is MalformedNbtFileException) {
throw e
} else {
throw MalformedNbtFileException("Error reading file", e)
}
}
}
private fun DataInputStream.readCompoundTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagMap = HashMap<String, NbtTag>()
var tagIdByte = this.readByte()
var tagId = NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
while (tagId != NbtTypeId.END) {
val name = this.readUTF()
tagMap[name] = this.readTag(tagId, start, timeout)
tagIdByte = this.readByte()
tagId = NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
}
return@checkTimeout TagCompound(tagMap)
}
private fun DataInputStream.readByteTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagByte(this.readByte()) }
private fun DataInputStream.readShortTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagShort(this.readShort()) }
private fun DataInputStream.readIntTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagInt(this.readInt()) }
private fun DataInputStream.readLongTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagLong(this.readLong()) }
private fun DataInputStream.readFloatTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagFloat(this.readFloat()) }
private fun DataInputStream.readDoubleTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagDouble(this.readDouble()) }
private fun DataInputStream.readStringTag(start: Long, timeout: Long) = checkTimeout(start, timeout) { TagString(this.readUTF()) }
private fun DataInputStream.readListTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagIdByte = this.readByte()
val tagId = NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
val length = this.readInt()
if (length <= 0) {
return@checkTimeout TagList(tagId, emptyList())
}
val list = List(length) {
this.readTag(tagId, start, timeout)
}
return@checkTimeout TagList(tagId, list)
}
private fun DataInputStream.readByteArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val bytes = ByteArray(length)
this.readFully(bytes)
return@checkTimeout TagByteArray(bytes)
}
private fun DataInputStream.readIntArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val ints = IntArray(length) {
this.readInt()
}
return@checkTimeout TagIntArray(ints)
}
private fun DataInputStream.readLongArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val longs = LongArray(length) {
this.readLong()
}
return@checkTimeout TagLongArray(longs)
}
private fun DataInputStream.readTag(tagId: NbtTypeId, start: Long, timeout: Long): NbtTag {
return when (tagId) {
NbtTypeId.END -> TagEnd
NbtTypeId.BYTE -> this.readByteTag(start, timeout)
NbtTypeId.SHORT -> this.readShortTag(start, timeout)
NbtTypeId.INT -> this.readIntTag(start, timeout)
NbtTypeId.LONG -> this.readLongTag(start, timeout)
NbtTypeId.FLOAT -> this.readFloatTag(start, timeout)
NbtTypeId.DOUBLE -> this.readDoubleTag(start, timeout)
NbtTypeId.BYTE_ARRAY -> this.readByteArrayTag(start, timeout)
NbtTypeId.STRING -> this.readStringTag(start, timeout)
NbtTypeId.LIST -> this.readListTag(start, timeout)
NbtTypeId.COMPOUND -> this.readCompoundTag(start, timeout)
NbtTypeId.INT_ARRAY -> this.readIntArrayTag(start, timeout)
NbtTypeId.LONG_ARRAY -> this.readLongArrayTag(start, timeout)
}
}
private inline fun <T : Any> checkTimeout(start: Long, timeout: Long, action: () -> T): T {
val now = System.currentTimeMillis()
val took = now - start
if (took > timeout) {
throw MalformedNbtFileException("NBT parse timeout exceeded - Parse time: $took, Timeout: $timeout.")
}
return action()
}
}
| mit | 63c02dea00edcfb6a71d089b10c56b62 | 39.157895 | 137 | 0.66754 | 4.254647 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/nbt/tags/NbtValueTag.kt | 1 | 1247 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
abstract class NbtValueTag<T : Any>(private val valueClass: Class<T>) : NbtTag {
abstract val value: T
override fun equals(other: Any?): Boolean {
if (other !is NbtValueTag<*>) {
return false
}
if (other === this) {
return true
}
if (!this.javaClass.isAssignableFrom(other.javaClass)) {
return false
}
@Suppress("UNCHECKED_CAST")
return valueEquals(other.value as T)
}
override fun hashCode() = value.hashCode()
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState) = sb.append(value)!!
override fun copy(): NbtValueTag<T> {
val const = typeId.tagClass.java.getConstructor(valueClass)
@Suppress("UNCHECKED_CAST")
return const.newInstance(valueCopy()) as NbtValueTag<T>
}
protected open fun valueEquals(otherValue: T) = this.value == otherValue
protected open fun valueCopy() = this.value
}
| mit | 9d8187009646319838703a1cb02010d8 | 24.44898 | 109 | 0.636728 | 4.156667 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/spvc/src/templates/kotlin/spvc/templates/Spv.kt | 3 | 79411 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package spvc.templates
import org.lwjgl.generator.*
val Spv = "Spv".nativeClass(Module.SPVC, prefix = "Spv", prefixConstant = "Spv", prefixMethod = "Spv") {
documentation = "Enumeration tokens for SPIR-V."
IntConstant("", "SPV_VERSION".."0x10600").noPrefix()
IntConstant("", "SPV_REVISION".."1").noPrefix()
IntConstant("", "MagicNumber".."0x07230203")
IntConstant("", "Version".."0x00010600")
IntConstant("", "Revision".."1")
IntConstant("", "OpCodeMask".."0xffff")
IntConstant("", "WordCountShift".."16")
EnumConstant(
"{@code SpvSourceLanguage}",
"SourceLanguageUnknown".."0",
"SourceLanguageESSL".."1",
"SourceLanguageGLSL".."2",
"SourceLanguageOpenCL_C".."3",
"SourceLanguageOpenCL_CPP".."4",
"SourceLanguageHLSL".."5",
"SourceLanguageCPP_for_OpenCL".."6",
"SourceLanguageSYCL".."7",
"SourceLanguageMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvExecutionModel}",
"ExecutionModelVertex".."0",
"ExecutionModelTessellationControl".."1",
"ExecutionModelTessellationEvaluation".."2",
"ExecutionModelGeometry".."3",
"ExecutionModelFragment".."4",
"ExecutionModelGLCompute".."5",
"ExecutionModelKernel".."6",
"ExecutionModelTaskNV".."5267",
"ExecutionModelMeshNV".."5268",
"ExecutionModelRayGenerationKHR".."5313",
"ExecutionModelRayGenerationNV".."5313",
"ExecutionModelIntersectionKHR".."5314",
"ExecutionModelIntersectionNV".."5314",
"ExecutionModelAnyHitKHR".."5315",
"ExecutionModelAnyHitNV".."5315",
"ExecutionModelClosestHitKHR".."5316",
"ExecutionModelClosestHitNV".."5316",
"ExecutionModelMissKHR".."5317",
"ExecutionModelMissNV".."5317",
"ExecutionModelCallableKHR".."5318",
"ExecutionModelCallableNV".."5318",
"ExecutionModelTaskEXT".."5364",
"ExecutionModelMeshEXT".."5365",
"ExecutionModelMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvAddressingModel}",
"AddressingModelLogical".."0",
"AddressingModelPhysical32".."1",
"AddressingModelPhysical64".."2",
"AddressingModelPhysicalStorageBuffer64".."5348",
"AddressingModelPhysicalStorageBuffer64EXT".."5348",
"AddressingModelMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvMemoryModel}",
"MemoryModelSimple".."0",
"MemoryModelGLSL450".."1",
"MemoryModelOpenCL".."2",
"MemoryModelVulkan".."3",
"MemoryModelVulkanKHR".."3",
"MemoryModelMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvExecutionMode}",
"ExecutionModeInvocations".."0",
"ExecutionModeSpacingEqual".."1",
"ExecutionModeSpacingFractionalEven".."2",
"ExecutionModeSpacingFractionalOdd".."3",
"ExecutionModeVertexOrderCw".."4",
"ExecutionModeVertexOrderCcw".."5",
"ExecutionModePixelCenterInteger".."6",
"ExecutionModeOriginUpperLeft".."7",
"ExecutionModeOriginLowerLeft".."8",
"ExecutionModeEarlyFragmentTests".."9",
"ExecutionModePointMode".."10",
"ExecutionModeXfb".."11",
"ExecutionModeDepthReplacing".."12",
"ExecutionModeDepthGreater".."14",
"ExecutionModeDepthLess".."15",
"ExecutionModeDepthUnchanged".."16",
"ExecutionModeLocalSize".."17",
"ExecutionModeLocalSizeHint".."18",
"ExecutionModeInputPoints".."19",
"ExecutionModeInputLines".."20",
"ExecutionModeInputLinesAdjacency".."21",
"ExecutionModeTriangles".."22",
"ExecutionModeInputTrianglesAdjacency".."23",
"ExecutionModeQuads".."24",
"ExecutionModeIsolines".."25",
"ExecutionModeOutputVertices".."26",
"ExecutionModeOutputPoints".."27",
"ExecutionModeOutputLineStrip".."28",
"ExecutionModeOutputTriangleStrip".."29",
"ExecutionModeVecTypeHint".."30",
"ExecutionModeContractionOff".."31",
"ExecutionModeInitializer".."33",
"ExecutionModeFinalizer".."34",
"ExecutionModeSubgroupSize".."35",
"ExecutionModeSubgroupsPerWorkgroup".."36",
"ExecutionModeSubgroupsPerWorkgroupId".."37",
"ExecutionModeLocalSizeId".."38",
"ExecutionModeLocalSizeHintId".."39",
"ExecutionModeSubgroupUniformControlFlowKHR".."4421",
"ExecutionModePostDepthCoverage".."4446",
"ExecutionModeDenormPreserve".."4459",
"ExecutionModeDenormFlushToZero".."4460",
"ExecutionModeSignedZeroInfNanPreserve".."4461",
"ExecutionModeRoundingModeRTE".."4462",
"ExecutionModeRoundingModeRTZ".."4463",
"ExecutionModeEarlyAndLateFragmentTestsAMD".."5017",
"ExecutionModeStencilRefReplacingEXT".."5027",
"ExecutionModeStencilRefUnchangedFrontAMD".."5079",
"ExecutionModeStencilRefGreaterFrontAMD".."5080",
"ExecutionModeStencilRefLessFrontAMD".."5081",
"ExecutionModeStencilRefUnchangedBackAMD".."5082",
"ExecutionModeStencilRefGreaterBackAMD".."5083",
"ExecutionModeStencilRefLessBackAMD".."5084",
"ExecutionModeOutputLinesEXT".."5269",
"ExecutionModeOutputLinesNV".."5269",
"ExecutionModeOutputPrimitivesEXT".."5270",
"ExecutionModeOutputPrimitivesNV".."5270",
"ExecutionModeDerivativeGroupQuadsNV".."5289",
"ExecutionModeDerivativeGroupLinearNV".."5290",
"ExecutionModeOutputTrianglesEXT".."5298",
"ExecutionModeOutputTrianglesNV".."5298",
"ExecutionModePixelInterlockOrderedEXT".."5366",
"ExecutionModePixelInterlockUnorderedEXT".."5367",
"ExecutionModeSampleInterlockOrderedEXT".."5368",
"ExecutionModeSampleInterlockUnorderedEXT".."5369",
"ExecutionModeShadingRateInterlockOrderedEXT".."5370",
"ExecutionModeShadingRateInterlockUnorderedEXT".."5371",
"ExecutionModeSharedLocalMemorySizeINTEL".."5618",
"ExecutionModeRoundingModeRTPINTEL".."5620",
"ExecutionModeRoundingModeRTNINTEL".."5621",
"ExecutionModeFloatingPointModeALTINTEL".."5622",
"ExecutionModeFloatingPointModeIEEEINTEL".."5623",
"ExecutionModeMaxWorkgroupSizeINTEL".."5893",
"ExecutionModeMaxWorkDimINTEL".."5894",
"ExecutionModeNoGlobalOffsetINTEL".."5895",
"ExecutionModeNumSIMDWorkitemsINTEL".."5896",
"ExecutionModeSchedulerTargetFmaxMhzINTEL".."5903",
"ExecutionModeNamedBarrierCountINTEL".."6417",
"ExecutionModeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvStorageClass}",
"StorageClassUniformConstant".."0",
"StorageClassInput".."1",
"StorageClassUniform".."2",
"StorageClassOutput".."3",
"StorageClassWorkgroup".."4",
"StorageClassCrossWorkgroup".."5",
"StorageClassPrivate".."6",
"StorageClassFunction".."7",
"StorageClassGeneric".."8",
"StorageClassPushConstant".."9",
"StorageClassAtomicCounter".."10",
"StorageClassImage".."11",
"StorageClassStorageBuffer".."12",
"StorageClassCallableDataKHR".."5328",
"StorageClassCallableDataNV".."5328",
"StorageClassIncomingCallableDataKHR".."5329",
"StorageClassIncomingCallableDataNV".."5329",
"StorageClassRayPayloadKHR".."5338",
"StorageClassRayPayloadNV".."5338",
"StorageClassHitAttributeKHR".."5339",
"StorageClassHitAttributeNV".."5339",
"StorageClassIncomingRayPayloadKHR".."5342",
"StorageClassIncomingRayPayloadNV".."5342",
"StorageClassShaderRecordBufferKHR".."5343",
"StorageClassShaderRecordBufferNV".."5343",
"StorageClassPhysicalStorageBuffer".."5349",
"StorageClassPhysicalStorageBufferEXT".."5349",
"StorageClassTaskPayloadWorkgroupEXT".."5402",
"StorageClassCodeSectionINTEL".."5605",
"StorageClassDeviceOnlyINTEL".."5936",
"StorageClassHostOnlyINTEL".."5937",
"StorageClassMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvDim}",
"Dim1D".."0",
"Dim2D".."1",
"Dim3D".."2",
"DimCube".."3",
"DimRect".."4",
"DimBuffer".."5",
"DimSubpassData".."6",
"DimMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvSamplerAddressingMode}",
"SamplerAddressingModeNone".."0",
"SamplerAddressingModeClampToEdge".."1",
"SamplerAddressingModeClamp".."2",
"SamplerAddressingModeRepeat".."3",
"SamplerAddressingModeRepeatMirrored".."4",
"SamplerAddressingModeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvSamplerFilterMode}",
"SamplerFilterModeNearest".."0",
"SamplerFilterModeLinear".."1",
"SamplerFilterModeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvImageFormat}",
"ImageFormatUnknown".."0",
"ImageFormatRgba32f".."1",
"ImageFormatRgba16f".."2",
"ImageFormatR32f".."3",
"ImageFormatRgba8".."4",
"ImageFormatRgba8Snorm".."5",
"ImageFormatRg32f".."6",
"ImageFormatRg16f".."7",
"ImageFormatR11fG11fB10f".."8",
"ImageFormatR16f".."9",
"ImageFormatRgba16".."10",
"ImageFormatRgb10A2".."11",
"ImageFormatRg16".."12",
"ImageFormatRg8".."13",
"ImageFormatR16".."14",
"ImageFormatR8".."15",
"ImageFormatRgba16Snorm".."16",
"ImageFormatRg16Snorm".."17",
"ImageFormatRg8Snorm".."18",
"ImageFormatR16Snorm".."19",
"ImageFormatR8Snorm".."20",
"ImageFormatRgba32i".."21",
"ImageFormatRgba16i".."22",
"ImageFormatRgba8i".."23",
"ImageFormatR32i".."24",
"ImageFormatRg32i".."25",
"ImageFormatRg16i".."26",
"ImageFormatRg8i".."27",
"ImageFormatR16i".."28",
"ImageFormatR8i".."29",
"ImageFormatRgba32ui".."30",
"ImageFormatRgba16ui".."31",
"ImageFormatRgba8ui".."32",
"ImageFormatR32ui".."33",
"ImageFormatRgb10a2ui".."34",
"ImageFormatRg32ui".."35",
"ImageFormatRg16ui".."36",
"ImageFormatRg8ui".."37",
"ImageFormatR16ui".."38",
"ImageFormatR8ui".."39",
"ImageFormatR64ui".."40",
"ImageFormatR64i".."41",
"ImageFormatMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvImageChannelOrder}",
"ImageChannelOrderR".."0",
"ImageChannelOrderA".."1",
"ImageChannelOrderRG".."2",
"ImageChannelOrderRA".."3",
"ImageChannelOrderRGB".."4",
"ImageChannelOrderRGBA".."5",
"ImageChannelOrderBGRA".."6",
"ImageChannelOrderARGB".."7",
"ImageChannelOrderIntensity".."8",
"ImageChannelOrderLuminance".."9",
"ImageChannelOrderRx".."10",
"ImageChannelOrderRGx".."11",
"ImageChannelOrderRGBx".."12",
"ImageChannelOrderDepth".."13",
"ImageChannelOrderDepthStencil".."14",
"ImageChannelOrdersRGB".."15",
"ImageChannelOrdersRGBx".."16",
"ImageChannelOrdersRGBA".."17",
"ImageChannelOrdersBGRA".."18",
"ImageChannelOrderABGR".."19",
"ImageChannelOrderMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvImageChannelDataType}",
"ImageChannelDataTypeSnormInt8".."0",
"ImageChannelDataTypeSnormInt16".."1",
"ImageChannelDataTypeUnormInt8".."2",
"ImageChannelDataTypeUnormInt16".."3",
"ImageChannelDataTypeUnormShort565".."4",
"ImageChannelDataTypeUnormShort555".."5",
"ImageChannelDataTypeUnormInt101010".."6",
"ImageChannelDataTypeSignedInt8".."7",
"ImageChannelDataTypeSignedInt16".."8",
"ImageChannelDataTypeSignedInt32".."9",
"ImageChannelDataTypeUnsignedInt8".."10",
"ImageChannelDataTypeUnsignedInt16".."11",
"ImageChannelDataTypeUnsignedInt32".."12",
"ImageChannelDataTypeHalfFloat".."13",
"ImageChannelDataTypeFloat".."14",
"ImageChannelDataTypeUnormInt24".."15",
"ImageChannelDataTypeUnormInt101010_2".."16",
"ImageChannelDataTypeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvImageOperandsShift}",
"ImageOperandsBiasShift".."0",
"ImageOperandsLodShift".."1",
"ImageOperandsGradShift".."2",
"ImageOperandsConstOffsetShift".."3",
"ImageOperandsOffsetShift".."4",
"ImageOperandsConstOffsetsShift".."5",
"ImageOperandsSampleShift".."6",
"ImageOperandsMinLodShift".."7",
"ImageOperandsMakeTexelAvailableShift".."8",
"ImageOperandsMakeTexelAvailableKHRShift".."8",
"ImageOperandsMakeTexelVisibleShift".."9",
"ImageOperandsMakeTexelVisibleKHRShift".."9",
"ImageOperandsNonPrivateTexelShift".."10",
"ImageOperandsNonPrivateTexelKHRShift".."10",
"ImageOperandsVolatileTexelShift".."11",
"ImageOperandsVolatileTexelKHRShift".."11",
"ImageOperandsSignExtendShift".."12",
"ImageOperandsZeroExtendShift".."13",
"ImageOperandsNontemporalShift".."14",
"ImageOperandsOffsetsShift".."16",
"ImageOperandsMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvImageOperandsMask}",
"ImageOperandsMaskNone".."0",
"ImageOperandsBiasMask".."0x00000001",
"ImageOperandsLodMask".."0x00000002",
"ImageOperandsGradMask".."0x00000004",
"ImageOperandsConstOffsetMask".."0x00000008",
"ImageOperandsOffsetMask".."0x00000010",
"ImageOperandsConstOffsetsMask".."0x00000020",
"ImageOperandsSampleMask".."0x00000040",
"ImageOperandsMinLodMask".."0x00000080",
"ImageOperandsMakeTexelAvailableMask".."0x00000100",
"ImageOperandsMakeTexelAvailableKHRMask".."0x00000100",
"ImageOperandsMakeTexelVisibleMask".."0x00000200",
"ImageOperandsMakeTexelVisibleKHRMask".."0x00000200",
"ImageOperandsNonPrivateTexelMask".."0x00000400",
"ImageOperandsNonPrivateTexelKHRMask".."0x00000400",
"ImageOperandsVolatileTexelMask".."0x00000800",
"ImageOperandsVolatileTexelKHRMask".."0x00000800",
"ImageOperandsSignExtendMask".."0x00001000",
"ImageOperandsZeroExtendMask".."0x00002000",
"ImageOperandsNontemporalMask".."0x00004000",
"ImageOperandsOffsetsMask".."0x00010000"
)
EnumConstant(
"{@code SpvFPFastMathModeShift}",
"FPFastMathModeNotNaNShift".."0",
"FPFastMathModeNotInfShift".."1",
"FPFastMathModeNSZShift".."2",
"FPFastMathModeAllowRecipShift".."3",
"FPFastMathModeFastShift".."4",
"FPFastMathModeAllowContractFastINTELShift".."16",
"FPFastMathModeAllowReassocINTELShift".."17",
"FPFastMathModeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvFPFastMathModeMask}",
"FPFastMathModeMaskNone".."0",
"FPFastMathModeNotNaNMask".."0x00000001",
"FPFastMathModeNotInfMask".."0x00000002",
"FPFastMathModeNSZMask".."0x00000004",
"FPFastMathModeAllowRecipMask".."0x00000008",
"FPFastMathModeFastMask".."0x00000010",
"FPFastMathModeAllowContractFastINTELMask".."0x00010000",
"FPFastMathModeAllowReassocINTELMask".."0x00020000"
)
EnumConstant(
"{@code SpvFPRoundingMode}",
"FPRoundingModeRTE".."0",
"FPRoundingModeRTZ".."1",
"FPRoundingModeRTP".."2",
"FPRoundingModeRTN".."3",
"FPRoundingModeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvLinkageType}",
"LinkageTypeExport".."0",
"LinkageTypeImport".."1",
"LinkageTypeLinkOnceODR".."2",
"LinkageTypeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvAccessQualifier}",
"AccessQualifierReadOnly".."0",
"AccessQualifierWriteOnly".."1",
"AccessQualifierReadWrite".."2",
"AccessQualifierMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvFunctionParameterAttribute}",
"FunctionParameterAttributeZext".."0",
"FunctionParameterAttributeSext".."1",
"FunctionParameterAttributeByVal".."2",
"FunctionParameterAttributeSret".."3",
"FunctionParameterAttributeNoAlias".."4",
"FunctionParameterAttributeNoCapture".."5",
"FunctionParameterAttributeNoWrite".."6",
"FunctionParameterAttributeNoReadWrite".."7",
"FunctionParameterAttributeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvDecoration}",
"DecorationRelaxedPrecision".."0",
"DecorationSpecId".."1",
"DecorationBlock".."2",
"DecorationBufferBlock".."3",
"DecorationRowMajor".."4",
"DecorationColMajor".."5",
"DecorationArrayStride".."6",
"DecorationMatrixStride".."7",
"DecorationGLSLShared".."8",
"DecorationGLSLPacked".."9",
"DecorationCPacked".."10",
"DecorationBuiltIn".."11",
"DecorationNoPerspective".."13",
"DecorationFlat".."14",
"DecorationPatch".."15",
"DecorationCentroid".."16",
"DecorationSample".."17",
"DecorationInvariant".."18",
"DecorationRestrict".."19",
"DecorationAliased".."20",
"DecorationVolatile".."21",
"DecorationConstant".."22",
"DecorationCoherent".."23",
"DecorationNonWritable".."24",
"DecorationNonReadable".."25",
"DecorationUniform".."26",
"DecorationUniformId".."27",
"DecorationSaturatedConversion".."28",
"DecorationStream".."29",
"DecorationLocation".."30",
"DecorationComponent".."31",
"DecorationIndex".."32",
"DecorationBinding".."33",
"DecorationDescriptorSet".."34",
"DecorationOffset".."35",
"DecorationXfbBuffer".."36",
"DecorationXfbStride".."37",
"DecorationFuncParamAttr".."38",
"DecorationFPRoundingMode".."39",
"DecorationFPFastMathMode".."40",
"DecorationLinkageAttributes".."41",
"DecorationNoContraction".."42",
"DecorationInputAttachmentIndex".."43",
"DecorationAlignment".."44",
"DecorationMaxByteOffset".."45",
"DecorationAlignmentId".."46",
"DecorationMaxByteOffsetId".."47",
"DecorationNoSignedWrap".."4469",
"DecorationNoUnsignedWrap".."4470",
"DecorationExplicitInterpAMD".."4999",
"DecorationOverrideCoverageNV".."5248",
"DecorationPassthroughNV".."5250",
"DecorationViewportRelativeNV".."5252",
"DecorationSecondaryViewportRelativeNV".."5256",
"DecorationPerPrimitiveEXT".."5271",
"DecorationPerPrimitiveNV".."5271",
"DecorationPerViewNV".."5272",
"DecorationPerTaskNV".."5273",
"DecorationPerVertexKHR".."5285",
"DecorationPerVertexNV".."5285",
"DecorationNonUniform".."5300",
"DecorationNonUniformEXT".."5300",
"DecorationRestrictPointer".."5355",
"DecorationRestrictPointerEXT".."5355",
"DecorationAliasedPointer".."5356",
"DecorationAliasedPointerEXT".."5356",
"DecorationBindlessSamplerNV".."5398",
"DecorationBindlessImageNV".."5399",
"DecorationBoundSamplerNV".."5400",
"DecorationBoundImageNV".."5401",
"DecorationSIMTCallINTEL".."5599",
"DecorationReferencedIndirectlyINTEL".."5602",
"DecorationClobberINTEL".."5607",
"DecorationSideEffectsINTEL".."5608",
"DecorationVectorComputeVariableINTEL".."5624",
"DecorationFuncParamIOKindINTEL".."5625",
"DecorationVectorComputeFunctionINTEL".."5626",
"DecorationStackCallINTEL".."5627",
"DecorationGlobalVariableOffsetINTEL".."5628",
"DecorationCounterBuffer".."5634",
"DecorationHlslCounterBufferGOOGLE".."5634",
"DecorationHlslSemanticGOOGLE".."5635",
"DecorationUserSemantic".."5635",
"DecorationUserTypeGOOGLE".."5636",
"DecorationFunctionRoundingModeINTEL".."5822",
"DecorationFunctionDenormModeINTEL".."5823",
"DecorationRegisterINTEL".."5825",
"DecorationMemoryINTEL".."5826",
"DecorationNumbanksINTEL".."5827",
"DecorationBankwidthINTEL".."5828",
"DecorationMaxPrivateCopiesINTEL".."5829",
"DecorationSinglepumpINTEL".."5830",
"DecorationDoublepumpINTEL".."5831",
"DecorationMaxReplicatesINTEL".."5832",
"DecorationSimpleDualPortINTEL".."5833",
"DecorationMergeINTEL".."5834",
"DecorationBankBitsINTEL".."5835",
"DecorationForcePow2DepthINTEL".."5836",
"DecorationBurstCoalesceINTEL".."5899",
"DecorationCacheSizeINTEL".."5900",
"DecorationDontStaticallyCoalesceINTEL".."5901",
"DecorationPrefetchINTEL".."5902",
"DecorationStallEnableINTEL".."5905",
"DecorationFuseLoopsInFunctionINTEL".."5907",
"DecorationAliasScopeINTEL".."5914",
"DecorationNoAliasINTEL".."5915",
"DecorationBufferLocationINTEL".."5921",
"DecorationIOPipeStorageINTEL".."5944",
"DecorationFunctionFloatingPointModeINTEL".."6080",
"DecorationSingleElementVectorINTEL".."6085",
"DecorationVectorComputeCallableFunctionINTEL".."6087",
"DecorationMediaBlockIOINTEL".."6140",
"DecorationMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvBuiltIn}",
"BuiltInPosition".."0",
"BuiltInPointSize".."1",
"BuiltInClipDistance".."3",
"BuiltInCullDistance".."4",
"BuiltInVertexId".."5",
"BuiltInInstanceId".."6",
"BuiltInPrimitiveId".."7",
"BuiltInInvocationId".."8",
"BuiltInLayer".."9",
"BuiltInViewportIndex".."10",
"BuiltInTessLevelOuter".."11",
"BuiltInTessLevelInner".."12",
"BuiltInTessCoord".."13",
"BuiltInPatchVertices".."14",
"BuiltInFragCoord".."15",
"BuiltInPointCoord".."16",
"BuiltInFrontFacing".."17",
"BuiltInSampleId".."18",
"BuiltInSamplePosition".."19",
"BuiltInSampleMask".."20",
"BuiltInFragDepth".."22",
"BuiltInHelperInvocation".."23",
"BuiltInNumWorkgroups".."24",
"BuiltInWorkgroupSize".."25",
"BuiltInWorkgroupId".."26",
"BuiltInLocalInvocationId".."27",
"BuiltInGlobalInvocationId".."28",
"BuiltInLocalInvocationIndex".."29",
"BuiltInWorkDim".."30",
"BuiltInGlobalSize".."31",
"BuiltInEnqueuedWorkgroupSize".."32",
"BuiltInGlobalOffset".."33",
"BuiltInGlobalLinearId".."34",
"BuiltInSubgroupSize".."36",
"BuiltInSubgroupMaxSize".."37",
"BuiltInNumSubgroups".."38",
"BuiltInNumEnqueuedSubgroups".."39",
"BuiltInSubgroupId".."40",
"BuiltInSubgroupLocalInvocationId".."41",
"BuiltInVertexIndex".."42",
"BuiltInInstanceIndex".."43",
"BuiltInSubgroupEqMask".."4416",
"BuiltInSubgroupEqMaskKHR".."4416",
"BuiltInSubgroupGeMask".."4417",
"BuiltInSubgroupGeMaskKHR".."4417",
"BuiltInSubgroupGtMask".."4418",
"BuiltInSubgroupGtMaskKHR".."4418",
"BuiltInSubgroupLeMask".."4419",
"BuiltInSubgroupLeMaskKHR".."4419",
"BuiltInSubgroupLtMask".."4420",
"BuiltInSubgroupLtMaskKHR".."4420",
"BuiltInBaseVertex".."4424",
"BuiltInBaseInstance".."4425",
"BuiltInDrawIndex".."4426",
"BuiltInPrimitiveShadingRateKHR".."4432",
"BuiltInDeviceIndex".."4438",
"BuiltInViewIndex".."4440",
"BuiltInShadingRateKHR".."4444",
"BuiltInBaryCoordNoPerspAMD".."4992",
"BuiltInBaryCoordNoPerspCentroidAMD".."4993",
"BuiltInBaryCoordNoPerspSampleAMD".."4994",
"BuiltInBaryCoordSmoothAMD".."4995",
"BuiltInBaryCoordSmoothCentroidAMD".."4996",
"BuiltInBaryCoordSmoothSampleAMD".."4997",
"BuiltInBaryCoordPullModelAMD".."4998",
"BuiltInFragStencilRefEXT".."5014",
"BuiltInViewportMaskNV".."5253",
"BuiltInSecondaryPositionNV".."5257",
"BuiltInSecondaryViewportMaskNV".."5258",
"BuiltInPositionPerViewNV".."5261",
"BuiltInViewportMaskPerViewNV".."5262",
"BuiltInFullyCoveredEXT".."5264",
"BuiltInTaskCountNV".."5274",
"BuiltInPrimitiveCountNV".."5275",
"BuiltInPrimitiveIndicesNV".."5276",
"BuiltInClipDistancePerViewNV".."5277",
"BuiltInCullDistancePerViewNV".."5278",
"BuiltInLayerPerViewNV".."5279",
"BuiltInMeshViewCountNV".."5280",
"BuiltInMeshViewIndicesNV".."5281",
"BuiltInBaryCoordKHR".."5286",
"BuiltInBaryCoordNV".."5286",
"BuiltInBaryCoordNoPerspKHR".."5287",
"BuiltInBaryCoordNoPerspNV".."5287",
"BuiltInFragSizeEXT".."5292",
"BuiltInFragmentSizeNV".."5292",
"BuiltInFragInvocationCountEXT".."5293",
"BuiltInInvocationsPerPixelNV".."5293",
"BuiltInPrimitivePointIndicesEXT".."5294",
"BuiltInPrimitiveLineIndicesEXT".."5295",
"BuiltInPrimitiveTriangleIndicesEXT".."5296",
"BuiltInCullPrimitiveEXT".."5299",
"BuiltInLaunchIdKHR".."5319",
"BuiltInLaunchIdNV".."5319",
"BuiltInLaunchSizeKHR".."5320",
"BuiltInLaunchSizeNV".."5320",
"BuiltInWorldRayOriginKHR".."5321",
"BuiltInWorldRayOriginNV".."5321",
"BuiltInWorldRayDirectionKHR".."5322",
"BuiltInWorldRayDirectionNV".."5322",
"BuiltInObjectRayOriginKHR".."5323",
"BuiltInObjectRayOriginNV".."5323",
"BuiltInObjectRayDirectionKHR".."5324",
"BuiltInObjectRayDirectionNV".."5324",
"BuiltInRayTminKHR".."5325",
"BuiltInRayTminNV".."5325",
"BuiltInRayTmaxKHR".."5326",
"BuiltInRayTmaxNV".."5326",
"BuiltInInstanceCustomIndexKHR".."5327",
"BuiltInInstanceCustomIndexNV".."5327",
"BuiltInObjectToWorldKHR".."5330",
"BuiltInObjectToWorldNV".."5330",
"BuiltInWorldToObjectKHR".."5331",
"BuiltInWorldToObjectNV".."5331",
"BuiltInHitTNV".."5332",
"BuiltInHitKindKHR".."5333",
"BuiltInHitKindNV".."5333",
"BuiltInCurrentRayTimeNV".."5334",
"BuiltInIncomingRayFlagsKHR".."5351",
"BuiltInIncomingRayFlagsNV".."5351",
"BuiltInRayGeometryIndexKHR".."5352",
"BuiltInWarpsPerSMNV".."5374",
"BuiltInSMCountNV".."5375",
"BuiltInWarpIDNV".."5376",
"BuiltInSMIDNV".."5377",
"BuiltInCullMaskKHR".."6021",
"BuiltInMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvSelectionControlShift}",
"SelectionControlFlattenShift".."0",
"SelectionControlDontFlattenShift".."1",
"SelectionControlMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvSelectionControlMask}",
"SelectionControlMaskNone".."0",
"SelectionControlFlattenMask".."0x00000001",
"SelectionControlDontFlattenMask".."0x00000002"
)
EnumConstant(
"{@code SpvLoopControlShift}",
"LoopControlUnrollShift".."0",
"LoopControlDontUnrollShift".."1",
"LoopControlDependencyInfiniteShift".."2",
"LoopControlDependencyLengthShift".."3",
"LoopControlMinIterationsShift".."4",
"LoopControlMaxIterationsShift".."5",
"LoopControlIterationMultipleShift".."6",
"LoopControlPeelCountShift".."7",
"LoopControlPartialCountShift".."8",
"LoopControlInitiationIntervalINTELShift".."16",
"LoopControlMaxConcurrencyINTELShift".."17",
"LoopControlDependencyArrayINTELShift".."18",
"LoopControlPipelineEnableINTELShift".."19",
"LoopControlLoopCoalesceINTELShift".."20",
"LoopControlMaxInterleavingINTELShift".."21",
"LoopControlSpeculatedIterationsINTELShift".."22",
"LoopControlNoFusionINTELShift".."23",
"LoopControlMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvLoopControlMask}",
"LoopControlMaskNone".."0",
"LoopControlUnrollMask".."0x00000001",
"LoopControlDontUnrollMask".."0x00000002",
"LoopControlDependencyInfiniteMask".."0x00000004",
"LoopControlDependencyLengthMask".."0x00000008",
"LoopControlMinIterationsMask".."0x00000010",
"LoopControlMaxIterationsMask".."0x00000020",
"LoopControlIterationMultipleMask".."0x00000040",
"LoopControlPeelCountMask".."0x00000080",
"LoopControlPartialCountMask".."0x00000100",
"LoopControlInitiationIntervalINTELMask".."0x00010000",
"LoopControlMaxConcurrencyINTELMask".."0x00020000",
"LoopControlDependencyArrayINTELMask".."0x00040000",
"LoopControlPipelineEnableINTELMask".."0x00080000",
"LoopControlLoopCoalesceINTELMask".."0x00100000",
"LoopControlMaxInterleavingINTELMask".."0x00200000",
"LoopControlSpeculatedIterationsINTELMask".."0x00400000",
"LoopControlNoFusionINTELMask".."0x00800000"
)
EnumConstant(
"{@code SpvFunctionControlShift}",
"FunctionControlInlineShift".."0",
"FunctionControlDontInlineShift".."1",
"FunctionControlPureShift".."2",
"FunctionControlConstShift".."3",
"FunctionControlOptNoneINTELShift".."16",
"FunctionControlMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvFunctionControlMask}",
"FunctionControlMaskNone".."0",
"FunctionControlInlineMask".."0x00000001",
"FunctionControlDontInlineMask".."0x00000002",
"FunctionControlPureMask".."0x00000004",
"FunctionControlConstMask".."0x00000008",
"FunctionControlOptNoneINTELMask".."0x00010000"
)
EnumConstant(
"{@code SpvMemorySemanticsShift}",
"MemorySemanticsAcquireShift".."1",
"MemorySemanticsReleaseShift".."2",
"MemorySemanticsAcquireReleaseShift".."3",
"MemorySemanticsSequentiallyConsistentShift".."4",
"MemorySemanticsUniformMemoryShift".."6",
"MemorySemanticsSubgroupMemoryShift".."7",
"MemorySemanticsWorkgroupMemoryShift".."8",
"MemorySemanticsCrossWorkgroupMemoryShift".."9",
"MemorySemanticsAtomicCounterMemoryShift".."10",
"MemorySemanticsImageMemoryShift".."11",
"MemorySemanticsOutputMemoryShift".."12",
"MemorySemanticsOutputMemoryKHRShift".."12",
"MemorySemanticsMakeAvailableShift".."13",
"MemorySemanticsMakeAvailableKHRShift".."13",
"MemorySemanticsMakeVisibleShift".."14",
"MemorySemanticsMakeVisibleKHRShift".."14",
"MemorySemanticsVolatileShift".."15",
"MemorySemanticsMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvMemorySemanticsMask}",
"MemorySemanticsMaskNone".."0",
"MemorySemanticsAcquireMask".."0x00000002",
"MemorySemanticsReleaseMask".."0x00000004",
"MemorySemanticsAcquireReleaseMask".."0x00000008",
"MemorySemanticsSequentiallyConsistentMask".."0x00000010",
"MemorySemanticsUniformMemoryMask".."0x00000040",
"MemorySemanticsSubgroupMemoryMask".."0x00000080",
"MemorySemanticsWorkgroupMemoryMask".."0x00000100",
"MemorySemanticsCrossWorkgroupMemoryMask".."0x00000200",
"MemorySemanticsAtomicCounterMemoryMask".."0x00000400",
"MemorySemanticsImageMemoryMask".."0x00000800",
"MemorySemanticsOutputMemoryMask".."0x00001000",
"MemorySemanticsOutputMemoryKHRMask".."0x00001000",
"MemorySemanticsMakeAvailableMask".."0x00002000",
"MemorySemanticsMakeAvailableKHRMask".."0x00002000",
"MemorySemanticsMakeVisibleMask".."0x00004000",
"MemorySemanticsMakeVisibleKHRMask".."0x00004000",
"MemorySemanticsVolatileMask".."0x00008000"
)
EnumConstant(
"{@code SpvMemoryAccessShift}",
"MemoryAccessVolatileShift".."0",
"MemoryAccessAlignedShift".."1",
"MemoryAccessNontemporalShift".."2",
"MemoryAccessMakePointerAvailableShift".."3",
"MemoryAccessMakePointerAvailableKHRShift".."3",
"MemoryAccessMakePointerVisibleShift".."4",
"MemoryAccessMakePointerVisibleKHRShift".."4",
"MemoryAccessNonPrivatePointerShift".."5",
"MemoryAccessNonPrivatePointerKHRShift".."5",
"MemoryAccessAliasScopeINTELMaskShift".."16",
"MemoryAccessNoAliasINTELMaskShift".."17",
"MemoryAccessMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvMemoryAccessMask}",
"MemoryAccessMaskNone".."0",
"MemoryAccessVolatileMask".."0x00000001",
"MemoryAccessAlignedMask".."0x00000002",
"MemoryAccessNontemporalMask".."0x00000004",
"MemoryAccessMakePointerAvailableMask".."0x00000008",
"MemoryAccessMakePointerAvailableKHRMask".."0x00000008",
"MemoryAccessMakePointerVisibleMask".."0x00000010",
"MemoryAccessMakePointerVisibleKHRMask".."0x00000010",
"MemoryAccessNonPrivatePointerMask".."0x00000020",
"MemoryAccessNonPrivatePointerKHRMask".."0x00000020",
"MemoryAccessAliasScopeINTELMaskMask".."0x00010000",
"MemoryAccessNoAliasINTELMaskMask".."0x00020000"
)
EnumConstant(
"{@code SpvScope}",
"ScopeCrossDevice".."0",
"ScopeDevice".."1",
"ScopeWorkgroup".."2",
"ScopeSubgroup".."3",
"ScopeInvocation".."4",
"ScopeQueueFamily".."5",
"ScopeQueueFamilyKHR".."5",
"ScopeShaderCallKHR".."6",
"ScopeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvGroupOperation}",
"GroupOperationReduce".."0",
"GroupOperationInclusiveScan".."1",
"GroupOperationExclusiveScan".."2",
"GroupOperationClusteredReduce".."3",
"GroupOperationPartitionedReduceNV".."6",
"GroupOperationPartitionedInclusiveScanNV".."7",
"GroupOperationPartitionedExclusiveScanNV".."8",
"GroupOperationMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvKernelEnqueueFlags}",
"KernelEnqueueFlagsNoWait".."0",
"KernelEnqueueFlagsWaitKernel".."1",
"KernelEnqueueFlagsWaitWorkGroup".."2",
"KernelEnqueueFlagsMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvKernelProfilingInfoShift}",
"KernelProfilingInfoCmdExecTimeShift".."0",
"KernelProfilingInfoMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvKernelProfilingInfoMask}",
"KernelProfilingInfoMaskNone".."0",
"KernelProfilingInfoCmdExecTimeMask".."0x00000001"
)
EnumConstant(
"{@code SpvCapability}",
"CapabilityMatrix".."0",
"CapabilityShader".."1",
"CapabilityGeometry".."2",
"CapabilityTessellation".."3",
"CapabilityAddresses".."4",
"CapabilityLinkage".."5",
"CapabilityKernel".."6",
"CapabilityVector16".."7",
"CapabilityFloat16Buffer".."8",
"CapabilityFloat16".."9",
"CapabilityFloat64".."10",
"CapabilityInt64".."11",
"CapabilityInt64Atomics".."12",
"CapabilityImageBasic".."13",
"CapabilityImageReadWrite".."14",
"CapabilityImageMipmap".."15",
"CapabilityPipes".."17",
"CapabilityGroups".."18",
"CapabilityDeviceEnqueue".."19",
"CapabilityLiteralSampler".."20",
"CapabilityAtomicStorage".."21",
"CapabilityInt16".."22",
"CapabilityTessellationPointSize".."23",
"CapabilityGeometryPointSize".."24",
"CapabilityImageGatherExtended".."25",
"CapabilityStorageImageMultisample".."27",
"CapabilityUniformBufferArrayDynamicIndexing".."28",
"CapabilitySampledImageArrayDynamicIndexing".."29",
"CapabilityStorageBufferArrayDynamicIndexing".."30",
"CapabilityStorageImageArrayDynamicIndexing".."31",
"CapabilityClipDistance".."32",
"CapabilityCullDistance".."33",
"CapabilityImageCubeArray".."34",
"CapabilitySampleRateShading".."35",
"CapabilityImageRect".."36",
"CapabilitySampledRect".."37",
"CapabilityGenericPointer".."38",
"CapabilityInt8".."39",
"CapabilityInputAttachment".."40",
"CapabilitySparseResidency".."41",
"CapabilityMinLod".."42",
"CapabilitySampled1D".."43",
"CapabilityImage1D".."44",
"CapabilitySampledCubeArray".."45",
"CapabilitySampledBuffer".."46",
"CapabilityImageBuffer".."47",
"CapabilityImageMSArray".."48",
"CapabilityStorageImageExtendedFormats".."49",
"CapabilityImageQuery".."50",
"CapabilityDerivativeControl".."51",
"CapabilityInterpolationFunction".."52",
"CapabilityTransformFeedback".."53",
"CapabilityGeometryStreams".."54",
"CapabilityStorageImageReadWithoutFormat".."55",
"CapabilityStorageImageWriteWithoutFormat".."56",
"CapabilityMultiViewport".."57",
"CapabilitySubgroupDispatch".."58",
"CapabilityNamedBarrier".."59",
"CapabilityPipeStorage".."60",
"CapabilityGroupNonUniform".."61",
"CapabilityGroupNonUniformVote".."62",
"CapabilityGroupNonUniformArithmetic".."63",
"CapabilityGroupNonUniformBallot".."64",
"CapabilityGroupNonUniformShuffle".."65",
"CapabilityGroupNonUniformShuffleRelative".."66",
"CapabilityGroupNonUniformClustered".."67",
"CapabilityGroupNonUniformQuad".."68",
"CapabilityShaderLayer".."69",
"CapabilityShaderViewportIndex".."70",
"CapabilityUniformDecoration".."71",
"CapabilityFragmentShadingRateKHR".."4422",
"CapabilitySubgroupBallotKHR".."4423",
"CapabilityDrawParameters".."4427",
"CapabilityWorkgroupMemoryExplicitLayoutKHR".."4428",
"CapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR".."4429",
"CapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR".."4430",
"CapabilitySubgroupVoteKHR".."4431",
"CapabilityStorageBuffer16BitAccess".."4433",
"CapabilityStorageUniformBufferBlock16".."4433",
"CapabilityStorageUniform16".."4434",
"CapabilityUniformAndStorageBuffer16BitAccess".."4434",
"CapabilityStoragePushConstant16".."4435",
"CapabilityStorageInputOutput16".."4436",
"CapabilityDeviceGroup".."4437",
"CapabilityMultiView".."4439",
"CapabilityVariablePointersStorageBuffer".."4441",
"CapabilityVariablePointers".."4442",
"CapabilityAtomicStorageOps".."4445",
"CapabilitySampleMaskPostDepthCoverage".."4447",
"CapabilityStorageBuffer8BitAccess".."4448",
"CapabilityUniformAndStorageBuffer8BitAccess".."4449",
"CapabilityStoragePushConstant8".."4450",
"CapabilityDenormPreserve".."4464",
"CapabilityDenormFlushToZero".."4465",
"CapabilitySignedZeroInfNanPreserve".."4466",
"CapabilityRoundingModeRTE".."4467",
"CapabilityRoundingModeRTZ".."4468",
"CapabilityRayQueryProvisionalKHR".."4471",
"CapabilityRayQueryKHR".."4472",
"CapabilityRayTraversalPrimitiveCullingKHR".."4478",
"CapabilityRayTracingKHR".."4479",
"CapabilityFloat16ImageAMD".."5008",
"CapabilityImageGatherBiasLodAMD".."5009",
"CapabilityFragmentMaskAMD".."5010",
"CapabilityStencilExportEXT".."5013",
"CapabilityImageReadWriteLodAMD".."5015",
"CapabilityInt64ImageEXT".."5016",
"CapabilityShaderClockKHR".."5055",
"CapabilitySampleMaskOverrideCoverageNV".."5249",
"CapabilityGeometryShaderPassthroughNV".."5251",
"CapabilityShaderViewportIndexLayerEXT".."5254",
"CapabilityShaderViewportIndexLayerNV".."5254",
"CapabilityShaderViewportMaskNV".."5255",
"CapabilityShaderStereoViewNV".."5259",
"CapabilityPerViewAttributesNV".."5260",
"CapabilityFragmentFullyCoveredEXT".."5265",
"CapabilityMeshShadingNV".."5266",
"CapabilityImageFootprintNV".."5282",
"CapabilityMeshShadingEXT".."5283",
"CapabilityFragmentBarycentricKHR".."5284",
"CapabilityFragmentBarycentricNV".."5284",
"CapabilityComputeDerivativeGroupQuadsNV".."5288",
"CapabilityFragmentDensityEXT".."5291",
"CapabilityShadingRateNV".."5291",
"CapabilityGroupNonUniformPartitionedNV".."5297",
"CapabilityShaderNonUniform".."5301",
"CapabilityShaderNonUniformEXT".."5301",
"CapabilityRuntimeDescriptorArray".."5302",
"CapabilityRuntimeDescriptorArrayEXT".."5302",
"CapabilityInputAttachmentArrayDynamicIndexing".."5303",
"CapabilityInputAttachmentArrayDynamicIndexingEXT".."5303",
"CapabilityUniformTexelBufferArrayDynamicIndexing".."5304",
"CapabilityUniformTexelBufferArrayDynamicIndexingEXT".."5304",
"CapabilityStorageTexelBufferArrayDynamicIndexing".."5305",
"CapabilityStorageTexelBufferArrayDynamicIndexingEXT".."5305",
"CapabilityUniformBufferArrayNonUniformIndexing".."5306",
"CapabilityUniformBufferArrayNonUniformIndexingEXT".."5306",
"CapabilitySampledImageArrayNonUniformIndexing".."5307",
"CapabilitySampledImageArrayNonUniformIndexingEXT".."5307",
"CapabilityStorageBufferArrayNonUniformIndexing".."5308",
"CapabilityStorageBufferArrayNonUniformIndexingEXT".."5308",
"CapabilityStorageImageArrayNonUniformIndexing".."5309",
"CapabilityStorageImageArrayNonUniformIndexingEXT".."5309",
"CapabilityInputAttachmentArrayNonUniformIndexing".."5310",
"CapabilityInputAttachmentArrayNonUniformIndexingEXT".."5310",
"CapabilityUniformTexelBufferArrayNonUniformIndexing".."5311",
"CapabilityUniformTexelBufferArrayNonUniformIndexingEXT".."5311",
"CapabilityStorageTexelBufferArrayNonUniformIndexing".."5312",
"CapabilityStorageTexelBufferArrayNonUniformIndexingEXT".."5312",
"CapabilityRayTracingNV".."5340",
"CapabilityRayTracingMotionBlurNV".."5341",
"CapabilityVulkanMemoryModel".."5345",
"CapabilityVulkanMemoryModelKHR".."5345",
"CapabilityVulkanMemoryModelDeviceScope".."5346",
"CapabilityVulkanMemoryModelDeviceScopeKHR".."5346",
"CapabilityPhysicalStorageBufferAddresses".."5347",
"CapabilityPhysicalStorageBufferAddressesEXT".."5347",
"CapabilityComputeDerivativeGroupLinearNV".."5350",
"CapabilityRayTracingProvisionalKHR".."5353",
"CapabilityCooperativeMatrixNV".."5357",
"CapabilityFragmentShaderSampleInterlockEXT".."5363",
"CapabilityFragmentShaderShadingRateInterlockEXT".."5372",
"CapabilityShaderSMBuiltinsNV".."5373",
"CapabilityFragmentShaderPixelInterlockEXT".."5378",
"CapabilityDemoteToHelperInvocation".."5379",
"CapabilityDemoteToHelperInvocationEXT".."5379",
"CapabilityBindlessTextureNV".."5390",
"CapabilitySubgroupShuffleINTEL".."5568",
"CapabilitySubgroupBufferBlockIOINTEL".."5569",
"CapabilitySubgroupImageBlockIOINTEL".."5570",
"CapabilitySubgroupImageMediaBlockIOINTEL".."5579",
"CapabilityRoundToInfinityINTEL".."5582",
"CapabilityFloatingPointModeINTEL".."5583",
"CapabilityIntegerFunctions2INTEL".."5584",
"CapabilityFunctionPointersINTEL".."5603",
"CapabilityIndirectReferencesINTEL".."5604",
"CapabilityAsmINTEL".."5606",
"CapabilityAtomicFloat32MinMaxEXT".."5612",
"CapabilityAtomicFloat64MinMaxEXT".."5613",
"CapabilityAtomicFloat16MinMaxEXT".."5616",
"CapabilityVectorComputeINTEL".."5617",
"CapabilityVectorAnyINTEL".."5619",
"CapabilityExpectAssumeKHR".."5629",
"CapabilitySubgroupAvcMotionEstimationINTEL".."5696",
"CapabilitySubgroupAvcMotionEstimationIntraINTEL".."5697",
"CapabilitySubgroupAvcMotionEstimationChromaINTEL".."5698",
"CapabilityVariableLengthArrayINTEL".."5817",
"CapabilityFunctionFloatControlINTEL".."5821",
"CapabilityFPGAMemoryAttributesINTEL".."5824",
"CapabilityFPFastMathModeINTEL".."5837",
"CapabilityArbitraryPrecisionIntegersINTEL".."5844",
"CapabilityArbitraryPrecisionFloatingPointINTEL".."5845",
"CapabilityUnstructuredLoopControlsINTEL".."5886",
"CapabilityFPGALoopControlsINTEL".."5888",
"CapabilityKernelAttributesINTEL".."5892",
"CapabilityFPGAKernelAttributesINTEL".."5897",
"CapabilityFPGAMemoryAccessesINTEL".."5898",
"CapabilityFPGAClusterAttributesINTEL".."5904",
"CapabilityLoopFuseINTEL".."5906",
"CapabilityMemoryAccessAliasingINTEL".."5910",
"CapabilityFPGABufferLocationINTEL".."5920",
"CapabilityArbitraryPrecisionFixedPointINTEL".."5922",
"CapabilityUSMStorageClassesINTEL".."5935",
"CapabilityIOPipesINTEL".."5943",
"CapabilityBlockingPipesINTEL".."5945",
"CapabilityFPGARegINTEL".."5948",
"CapabilityDotProductInputAll".."6016",
"CapabilityDotProductInputAllKHR".."6016",
"CapabilityDotProductInput4x8Bit".."6017",
"CapabilityDotProductInput4x8BitKHR".."6017",
"CapabilityDotProductInput4x8BitPacked".."6018",
"CapabilityDotProductInput4x8BitPackedKHR".."6018",
"CapabilityDotProduct".."6019",
"CapabilityDotProductKHR".."6019",
"CapabilityRayCullMaskKHR".."6020",
"CapabilityBitInstructions".."6025",
"CapabilityGroupNonUniformRotateKHR".."6026",
"CapabilityAtomicFloat32AddEXT".."6033",
"CapabilityAtomicFloat64AddEXT".."6034",
"CapabilityLongConstantCompositeINTEL".."6089",
"CapabilityOptNoneINTEL".."6094",
"CapabilityAtomicFloat16AddEXT".."6095",
"CapabilityDebugInfoModuleINTEL".."6114",
"CapabilitySplitBarrierINTEL".."6141",
"CapabilityGroupUniformArithmeticKHR".."6400",
"CapabilityMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvRayFlagsShift}",
"RayFlagsOpaqueKHRShift".."0",
"RayFlagsNoOpaqueKHRShift".."1",
"RayFlagsTerminateOnFirstHitKHRShift".."2",
"RayFlagsSkipClosestHitShaderKHRShift".."3",
"RayFlagsCullBackFacingTrianglesKHRShift".."4",
"RayFlagsCullFrontFacingTrianglesKHRShift".."5",
"RayFlagsCullOpaqueKHRShift".."6",
"RayFlagsCullNoOpaqueKHRShift".."7",
"RayFlagsSkipTrianglesKHRShift".."8",
"RayFlagsSkipAABBsKHRShift".."9",
"RayFlagsMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvRayFlagsMask}",
"RayFlagsMaskNone".."0",
"RayFlagsOpaqueKHRMask".."0x00000001",
"RayFlagsNoOpaqueKHRMask".."0x00000002",
"RayFlagsTerminateOnFirstHitKHRMask".."0x00000004",
"RayFlagsSkipClosestHitShaderKHRMask".."0x00000008",
"RayFlagsCullBackFacingTrianglesKHRMask".."0x00000010",
"RayFlagsCullFrontFacingTrianglesKHRMask".."0x00000020",
"RayFlagsCullOpaqueKHRMask".."0x00000040",
"RayFlagsCullNoOpaqueKHRMask".."0x00000080",
"RayFlagsSkipTrianglesKHRMask".."0x00000100",
"RayFlagsSkipAABBsKHRMask".."0x00000200"
)
EnumConstant(
"{@code SpvRayQueryIntersection}",
"RayQueryIntersectionRayQueryCandidateIntersectionKHR".."0",
"RayQueryIntersectionRayQueryCommittedIntersectionKHR".."1",
"RayQueryIntersectionMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvRayQueryCommittedIntersectionType}",
"RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR".."0",
"RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR".."1",
"RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR".."2",
"RayQueryCommittedIntersectionTypeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvRayQueryCandidateIntersectionType}",
"RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR".."0",
"RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR".."1",
"RayQueryCandidateIntersectionTypeMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvFragmentShadingRateShift}",
"FragmentShadingRateVertical2PixelsShift".."0",
"FragmentShadingRateVertical4PixelsShift".."1",
"FragmentShadingRateHorizontal2PixelsShift".."2",
"FragmentShadingRateHorizontal4PixelsShift".."3",
"FragmentShadingRateMax".."0x7fffffff",
)
EnumConstant(
"{@code SpvFragmentShadingRateMask}",
"FragmentShadingRateMaskNone".."0",
"FragmentShadingRateVertical2PixelsMask".."0x00000001",
"FragmentShadingRateVertical4PixelsMask".."0x00000002",
"FragmentShadingRateHorizontal2PixelsMask".."0x00000004",
"FragmentShadingRateHorizontal4PixelsMask".."0x00000008"
)
EnumConstant(
"{@code SpvFPDenormMode}",
"FPDenormModePreserve".."0",
"FPDenormModeFlushToZero".."1",
"FPDenormModeMax".."0x7fffffff"
)
EnumConstant(
"{@code SpvFPOperationMode}",
"FPOperationModeIEEE".."0",
"FPOperationModeALT".."1",
"FPOperationModeMax".."0x7fffffff"
)
EnumConstant(
"{@code SpvQuantizationModes}",
"QuantizationModesTRN".."0",
"QuantizationModesTRN_ZERO".."1",
"QuantizationModesRND".."2",
"QuantizationModesRND_ZERO".."3",
"QuantizationModesRND_INF".."4",
"QuantizationModesRND_MIN_INF".."5",
"QuantizationModesRND_CONV".."6",
"QuantizationModesRND_CONV_ODD".."7",
"QuantizationModesMax".."0x7fffffff"
)
EnumConstant(
"{@code SpvOverflowModes}",
"OverflowModesWRAP".."0",
"OverflowModesSAT".."1",
"OverflowModesSAT_ZERO".."2",
"OverflowModesSAT_SYM".."3",
"OverflowModesMax".."0x7fffffff"
)
EnumConstant(
"{@code SpvPackedVectorFormat}",
"PackedVectorFormatPackedVectorFormat4x8Bit".."0",
"PackedVectorFormatPackedVectorFormat4x8BitKHR".."0",
"PackedVectorFormatMax".."0x7fffffff"
)
EnumConstant(
"{@code SpvOp}",
"OpNop".."0",
"OpUndef".."1",
"OpSourceContinued".."2",
"OpSource".."3",
"OpSourceExtension".."4",
"OpName".."5",
"OpMemberName".."6",
"OpString".."7",
"OpLine".."8",
"OpExtension".."10",
"OpExtInstImport".."11",
"OpExtInst".."12",
"OpMemoryModel".."14",
"OpEntryPoint".."15",
"OpExecutionMode".."16",
"OpCapability".."17",
"OpTypeVoid".."19",
"OpTypeBool".."20",
"OpTypeInt".."21",
"OpTypeFloat".."22",
"OpTypeVector".."23",
"OpTypeMatrix".."24",
"OpTypeImage".."25",
"OpTypeSampler".."26",
"OpTypeSampledImage".."27",
"OpTypeArray".."28",
"OpTypeRuntimeArray".."29",
"OpTypeStruct".."30",
"OpTypeOpaque".."31",
"OpTypePointer".."32",
"OpTypeFunction".."33",
"OpTypeEvent".."34",
"OpTypeDeviceEvent".."35",
"OpTypeReserveId".."36",
"OpTypeQueue".."37",
"OpTypePipe".."38",
"OpTypeForwardPointer".."39",
"OpConstantTrue".."41",
"OpConstantFalse".."42",
"OpConstant".."43",
"OpConstantComposite".."44",
"OpConstantSampler".."45",
"OpConstantNull".."46",
"OpSpecConstantTrue".."48",
"OpSpecConstantFalse".."49",
"OpSpecConstant".."50",
"OpSpecConstantComposite".."51",
"OpSpecConstantOp".."52",
"OpFunction".."54",
"OpFunctionParameter".."55",
"OpFunctionEnd".."56",
"OpFunctionCall".."57",
"OpVariable".."59",
"OpImageTexelPointer".."60",
"OpLoad".."61",
"OpStore".."62",
"OpCopyMemory".."63",
"OpCopyMemorySized".."64",
"OpAccessChain".."65",
"OpInBoundsAccessChain".."66",
"OpPtrAccessChain".."67",
"OpArrayLength".."68",
"OpGenericPtrMemSemantics".."69",
"OpInBoundsPtrAccessChain".."70",
"OpDecorate".."71",
"OpMemberDecorate".."72",
"OpDecorationGroup".."73",
"OpGroupDecorate".."74",
"OpGroupMemberDecorate".."75",
"OpVectorExtractDynamic".."77",
"OpVectorInsertDynamic".."78",
"OpVectorShuffle".."79",
"OpCompositeConstruct".."80",
"OpCompositeExtract".."81",
"OpCompositeInsert".."82",
"OpCopyObject".."83",
"OpTranspose".."84",
"OpSampledImage".."86",
"OpImageSampleImplicitLod".."87",
"OpImageSampleExplicitLod".."88",
"OpImageSampleDrefImplicitLod".."89",
"OpImageSampleDrefExplicitLod".."90",
"OpImageSampleProjImplicitLod".."91",
"OpImageSampleProjExplicitLod".."92",
"OpImageSampleProjDrefImplicitLod".."93",
"OpImageSampleProjDrefExplicitLod".."94",
"OpImageFetch".."95",
"OpImageGather".."96",
"OpImageDrefGather".."97",
"OpImageRead".."98",
"OpImageWrite".."99",
"OpImage".."100",
"OpImageQueryFormat".."101",
"OpImageQueryOrder".."102",
"OpImageQuerySizeLod".."103",
"OpImageQuerySize".."104",
"OpImageQueryLod".."105",
"OpImageQueryLevels".."106",
"OpImageQuerySamples".."107",
"OpConvertFToU".."109",
"OpConvertFToS".."110",
"OpConvertSToF".."111",
"OpConvertUToF".."112",
"OpUConvert".."113",
"OpSConvert".."114",
"OpFConvert".."115",
"OpQuantizeToF16".."116",
"OpConvertPtrToU".."117",
"OpSatConvertSToU".."118",
"OpSatConvertUToS".."119",
"OpConvertUToPtr".."120",
"OpPtrCastToGeneric".."121",
"OpGenericCastToPtr".."122",
"OpGenericCastToPtrExplicit".."123",
"OpBitcast".."124",
"OpSNegate".."126",
"OpFNegate".."127",
"OpIAdd".."128",
"OpFAdd".."129",
"OpISub".."130",
"OpFSub".."131",
"OpIMul".."132",
"OpFMul".."133",
"OpUDiv".."134",
"OpSDiv".."135",
"OpFDiv".."136",
"OpUMod".."137",
"OpSRem".."138",
"OpSMod".."139",
"OpFRem".."140",
"OpFMod".."141",
"OpVectorTimesScalar".."142",
"OpMatrixTimesScalar".."143",
"OpVectorTimesMatrix".."144",
"OpMatrixTimesVector".."145",
"OpMatrixTimesMatrix".."146",
"OpOuterProduct".."147",
"OpDot".."148",
"OpIAddCarry".."149",
"OpISubBorrow".."150",
"OpUMulExtended".."151",
"OpSMulExtended".."152",
"OpAny".."154",
"OpAll".."155",
"OpIsNan".."156",
"OpIsInf".."157",
"OpIsFinite".."158",
"OpIsNormal".."159",
"OpSignBitSet".."160",
"OpLessOrGreater".."161",
"OpOrdered".."162",
"OpUnordered".."163",
"OpLogicalEqual".."164",
"OpLogicalNotEqual".."165",
"OpLogicalOr".."166",
"OpLogicalAnd".."167",
"OpLogicalNot".."168",
"OpSelect".."169",
"OpIEqual".."170",
"OpINotEqual".."171",
"OpUGreaterThan".."172",
"OpSGreaterThan".."173",
"OpUGreaterThanEqual".."174",
"OpSGreaterThanEqual".."175",
"OpULessThan".."176",
"OpSLessThan".."177",
"OpULessThanEqual".."178",
"OpSLessThanEqual".."179",
"OpFOrdEqual".."180",
"OpFUnordEqual".."181",
"OpFOrdNotEqual".."182",
"OpFUnordNotEqual".."183",
"OpFOrdLessThan".."184",
"OpFUnordLessThan".."185",
"OpFOrdGreaterThan".."186",
"OpFUnordGreaterThan".."187",
"OpFOrdLessThanEqual".."188",
"OpFUnordLessThanEqual".."189",
"OpFOrdGreaterThanEqual".."190",
"OpFUnordGreaterThanEqual".."191",
"OpShiftRightLogical".."194",
"OpShiftRightArithmetic".."195",
"OpShiftLeftLogical".."196",
"OpBitwiseOr".."197",
"OpBitwiseXor".."198",
"OpBitwiseAnd".."199",
"OpNot".."200",
"OpBitFieldInsert".."201",
"OpBitFieldSExtract".."202",
"OpBitFieldUExtract".."203",
"OpBitReverse".."204",
"OpBitCount".."205",
"OpDPdx".."207",
"OpDPdy".."208",
"OpFwidth".."209",
"OpDPdxFine".."210",
"OpDPdyFine".."211",
"OpFwidthFine".."212",
"OpDPdxCoarse".."213",
"OpDPdyCoarse".."214",
"OpFwidthCoarse".."215",
"OpEmitVertex".."218",
"OpEndPrimitive".."219",
"OpEmitStreamVertex".."220",
"OpEndStreamPrimitive".."221",
"OpControlBarrier".."224",
"OpMemoryBarrier".."225",
"OpAtomicLoad".."227",
"OpAtomicStore".."228",
"OpAtomicExchange".."229",
"OpAtomicCompareExchange".."230",
"OpAtomicCompareExchangeWeak".."231",
"OpAtomicIIncrement".."232",
"OpAtomicIDecrement".."233",
"OpAtomicIAdd".."234",
"OpAtomicISub".."235",
"OpAtomicSMin".."236",
"OpAtomicUMin".."237",
"OpAtomicSMax".."238",
"OpAtomicUMax".."239",
"OpAtomicAnd".."240",
"OpAtomicOr".."241",
"OpAtomicXor".."242",
"OpPhi".."245",
"OpLoopMerge".."246",
"OpSelectionMerge".."247",
"OpLabel".."248",
"OpBranch".."249",
"OpBranchConditional".."250",
"OpSwitch".."251",
"OpKill".."252",
"OpReturn".."253",
"OpReturnValue".."254",
"OpUnreachable".."255",
"OpLifetimeStart".."256",
"OpLifetimeStop".."257",
"OpGroupAsyncCopy".."259",
"OpGroupWaitEvents".."260",
"OpGroupAll".."261",
"OpGroupAny".."262",
"OpGroupBroadcast".."263",
"OpGroupIAdd".."264",
"OpGroupFAdd".."265",
"OpGroupFMin".."266",
"OpGroupUMin".."267",
"OpGroupSMin".."268",
"OpGroupFMax".."269",
"OpGroupUMax".."270",
"OpGroupSMax".."271",
"OpReadPipe".."274",
"OpWritePipe".."275",
"OpReservedReadPipe".."276",
"OpReservedWritePipe".."277",
"OpReserveReadPipePackets".."278",
"OpReserveWritePipePackets".."279",
"OpCommitReadPipe".."280",
"OpCommitWritePipe".."281",
"OpIsValidReserveId".."282",
"OpGetNumPipePackets".."283",
"OpGetMaxPipePackets".."284",
"OpGroupReserveReadPipePackets".."285",
"OpGroupReserveWritePipePackets".."286",
"OpGroupCommitReadPipe".."287",
"OpGroupCommitWritePipe".."288",
"OpEnqueueMarker".."291",
"OpEnqueueKernel".."292",
"OpGetKernelNDrangeSubGroupCount".."293",
"OpGetKernelNDrangeMaxSubGroupSize".."294",
"OpGetKernelWorkGroupSize".."295",
"OpGetKernelPreferredWorkGroupSizeMultiple".."296",
"OpRetainEvent".."297",
"OpReleaseEvent".."298",
"OpCreateUserEvent".."299",
"OpIsValidEvent".."300",
"OpSetUserEventStatus".."301",
"OpCaptureEventProfilingInfo".."302",
"OpGetDefaultQueue".."303",
"OpBuildNDRange".."304",
"OpImageSparseSampleImplicitLod".."305",
"OpImageSparseSampleExplicitLod".."306",
"OpImageSparseSampleDrefImplicitLod".."307",
"OpImageSparseSampleDrefExplicitLod".."308",
"OpImageSparseSampleProjImplicitLod".."309",
"OpImageSparseSampleProjExplicitLod".."310",
"OpImageSparseSampleProjDrefImplicitLod".."311",
"OpImageSparseSampleProjDrefExplicitLod".."312",
"OpImageSparseFetch".."313",
"OpImageSparseGather".."314",
"OpImageSparseDrefGather".."315",
"OpImageSparseTexelsResident".."316",
"OpNoLine".."317",
"OpAtomicFlagTestAndSet".."318",
"OpAtomicFlagClear".."319",
"OpImageSparseRead".."320",
"OpSizeOf".."321",
"OpTypePipeStorage".."322",
"OpConstantPipeStorage".."323",
"OpCreatePipeFromPipeStorage".."324",
"OpGetKernelLocalSizeForSubgroupCount".."325",
"OpGetKernelMaxNumSubgroups".."326",
"OpTypeNamedBarrier".."327",
"OpNamedBarrierInitialize".."328",
"OpMemoryNamedBarrier".."329",
"OpModuleProcessed".."330",
"OpExecutionModeId".."331",
"OpDecorateId".."332",
"OpGroupNonUniformElect".."333",
"OpGroupNonUniformAll".."334",
"OpGroupNonUniformAny".."335",
"OpGroupNonUniformAllEqual".."336",
"OpGroupNonUniformBroadcast".."337",
"OpGroupNonUniformBroadcastFirst".."338",
"OpGroupNonUniformBallot".."339",
"OpGroupNonUniformInverseBallot".."340",
"OpGroupNonUniformBallotBitExtract".."341",
"OpGroupNonUniformBallotBitCount".."342",
"OpGroupNonUniformBallotFindLSB".."343",
"OpGroupNonUniformBallotFindMSB".."344",
"OpGroupNonUniformShuffle".."345",
"OpGroupNonUniformShuffleXor".."346",
"OpGroupNonUniformShuffleUp".."347",
"OpGroupNonUniformShuffleDown".."348",
"OpGroupNonUniformIAdd".."349",
"OpGroupNonUniformFAdd".."350",
"OpGroupNonUniformIMul".."351",
"OpGroupNonUniformFMul".."352",
"OpGroupNonUniformSMin".."353",
"OpGroupNonUniformUMin".."354",
"OpGroupNonUniformFMin".."355",
"OpGroupNonUniformSMax".."356",
"OpGroupNonUniformUMax".."357",
"OpGroupNonUniformFMax".."358",
"OpGroupNonUniformBitwiseAnd".."359",
"OpGroupNonUniformBitwiseOr".."360",
"OpGroupNonUniformBitwiseXor".."361",
"OpGroupNonUniformLogicalAnd".."362",
"OpGroupNonUniformLogicalOr".."363",
"OpGroupNonUniformLogicalXor".."364",
"OpGroupNonUniformQuadBroadcast".."365",
"OpGroupNonUniformQuadSwap".."366",
"OpCopyLogical".."400",
"OpPtrEqual".."401",
"OpPtrNotEqual".."402",
"OpPtrDiff".."403",
"OpTerminateInvocation".."4416",
"OpSubgroupBallotKHR".."4421",
"OpSubgroupFirstInvocationKHR".."4422",
"OpSubgroupAllKHR".."4428",
"OpSubgroupAnyKHR".."4429",
"OpSubgroupAllEqualKHR".."4430",
"OpGroupNonUniformRotateKHR".."4431",
"OpSubgroupReadInvocationKHR".."4432",
"OpTraceRayKHR".."4445",
"OpExecuteCallableKHR".."4446",
"OpConvertUToAccelerationStructureKHR".."4447",
"OpIgnoreIntersectionKHR".."4448",
"OpTerminateRayKHR".."4449",
"OpSDot".."4450",
"OpSDotKHR".."4450",
"OpUDot".."4451",
"OpUDotKHR".."4451",
"OpSUDot".."4452",
"OpSUDotKHR".."4452",
"OpSDotAccSat".."4453",
"OpSDotAccSatKHR".."4453",
"OpUDotAccSat".."4454",
"OpUDotAccSatKHR".."4454",
"OpSUDotAccSat".."4455",
"OpSUDotAccSatKHR".."4455",
"OpTypeRayQueryKHR".."4472",
"OpRayQueryInitializeKHR".."4473",
"OpRayQueryTerminateKHR".."4474",
"OpRayQueryGenerateIntersectionKHR".."4475",
"OpRayQueryConfirmIntersectionKHR".."4476",
"OpRayQueryProceedKHR".."4477",
"OpRayQueryGetIntersectionTypeKHR".."4479",
"OpGroupIAddNonUniformAMD".."5000",
"OpGroupFAddNonUniformAMD".."5001",
"OpGroupFMinNonUniformAMD".."5002",
"OpGroupUMinNonUniformAMD".."5003",
"OpGroupSMinNonUniformAMD".."5004",
"OpGroupFMaxNonUniformAMD".."5005",
"OpGroupUMaxNonUniformAMD".."5006",
"OpGroupSMaxNonUniformAMD".."5007",
"OpFragmentMaskFetchAMD".."5011",
"OpFragmentFetchAMD".."5012",
"OpReadClockKHR".."5056",
"OpImageSampleFootprintNV".."5283",
"OpEmitMeshTasksEXT".."5294",
"OpSetMeshOutputsEXT".."5295",
"OpGroupNonUniformPartitionNV".."5296",
"OpWritePackedPrimitiveIndices4x8NV".."5299",
"OpReportIntersectionKHR".."5334",
"OpReportIntersectionNV".."5334",
"OpIgnoreIntersectionNV".."5335",
"OpTerminateRayNV".."5336",
"OpTraceNV".."5337",
"OpTraceMotionNV".."5338",
"OpTraceRayMotionNV".."5339",
"OpTypeAccelerationStructureKHR".."5341",
"OpTypeAccelerationStructureNV".."5341",
"OpExecuteCallableNV".."5344",
"OpTypeCooperativeMatrixNV".."5358",
"OpCooperativeMatrixLoadNV".."5359",
"OpCooperativeMatrixStoreNV".."5360",
"OpCooperativeMatrixMulAddNV".."5361",
"OpCooperativeMatrixLengthNV".."5362",
"OpBeginInvocationInterlockEXT".."5364",
"OpEndInvocationInterlockEXT".."5365",
"OpDemoteToHelperInvocation".."5380",
"OpDemoteToHelperInvocationEXT".."5380",
"OpIsHelperInvocationEXT".."5381",
"OpConvertUToImageNV".."5391",
"OpConvertUToSamplerNV".."5392",
"OpConvertImageToUNV".."5393",
"OpConvertSamplerToUNV".."5394",
"OpConvertUToSampledImageNV".."5395",
"OpConvertSampledImageToUNV".."5396",
"OpSamplerImageAddressingModeNV".."5397",
"OpSubgroupShuffleINTEL".."5571",
"OpSubgroupShuffleDownINTEL".."5572",
"OpSubgroupShuffleUpINTEL".."5573",
"OpSubgroupShuffleXorINTEL".."5574",
"OpSubgroupBlockReadINTEL".."5575",
"OpSubgroupBlockWriteINTEL".."5576",
"OpSubgroupImageBlockReadINTEL".."5577",
"OpSubgroupImageBlockWriteINTEL".."5578",
"OpSubgroupImageMediaBlockReadINTEL".."5580",
"OpSubgroupImageMediaBlockWriteINTEL".."5581",
"OpUCountLeadingZerosINTEL".."5585",
"OpUCountTrailingZerosINTEL".."5586",
"OpAbsISubINTEL".."5587",
"OpAbsUSubINTEL".."5588",
"OpIAddSatINTEL".."5589",
"OpUAddSatINTEL".."5590",
"OpIAverageINTEL".."5591",
"OpUAverageINTEL".."5592",
"OpIAverageRoundedINTEL".."5593",
"OpUAverageRoundedINTEL".."5594",
"OpISubSatINTEL".."5595",
"OpUSubSatINTEL".."5596",
"OpIMul32x16INTEL".."5597",
"OpUMul32x16INTEL".."5598",
"OpConstantFunctionPointerINTEL".."5600",
"OpFunctionPointerCallINTEL".."5601",
"OpAsmTargetINTEL".."5609",
"OpAsmINTEL".."5610",
"OpAsmCallINTEL".."5611",
"OpAtomicFMinEXT".."5614",
"OpAtomicFMaxEXT".."5615",
"OpAssumeTrueKHR".."5630",
"OpExpectKHR".."5631",
"OpDecorateString".."5632",
"OpDecorateStringGOOGLE".."5632",
"OpMemberDecorateString".."5633",
"OpMemberDecorateStringGOOGLE".."5633",
"OpVmeImageINTEL".."5699",
"OpTypeVmeImageINTEL".."5700",
"OpTypeAvcImePayloadINTEL".."5701",
"OpTypeAvcRefPayloadINTEL".."5702",
"OpTypeAvcSicPayloadINTEL".."5703",
"OpTypeAvcMcePayloadINTEL".."5704",
"OpTypeAvcMceResultINTEL".."5705",
"OpTypeAvcImeResultINTEL".."5706",
"OpTypeAvcImeResultSingleReferenceStreamoutINTEL".."5707",
"OpTypeAvcImeResultDualReferenceStreamoutINTEL".."5708",
"OpTypeAvcImeSingleReferenceStreaminINTEL".."5709",
"OpTypeAvcImeDualReferenceStreaminINTEL".."5710",
"OpTypeAvcRefResultINTEL".."5711",
"OpTypeAvcSicResultINTEL".."5712",
"OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL".."5713",
"OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL".."5714",
"OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL".."5715",
"OpSubgroupAvcMceSetInterShapePenaltyINTEL".."5716",
"OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL".."5717",
"OpSubgroupAvcMceSetInterDirectionPenaltyINTEL".."5718",
"OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL".."5719",
"OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL".."5720",
"OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL".."5721",
"OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL".."5722",
"OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL".."5723",
"OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL".."5724",
"OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL".."5725",
"OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL".."5726",
"OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL".."5727",
"OpSubgroupAvcMceSetAcOnlyHaarINTEL".."5728",
"OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL".."5729",
"OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL".."5730",
"OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL".."5731",
"OpSubgroupAvcMceConvertToImePayloadINTEL".."5732",
"OpSubgroupAvcMceConvertToImeResultINTEL".."5733",
"OpSubgroupAvcMceConvertToRefPayloadINTEL".."5734",
"OpSubgroupAvcMceConvertToRefResultINTEL".."5735",
"OpSubgroupAvcMceConvertToSicPayloadINTEL".."5736",
"OpSubgroupAvcMceConvertToSicResultINTEL".."5737",
"OpSubgroupAvcMceGetMotionVectorsINTEL".."5738",
"OpSubgroupAvcMceGetInterDistortionsINTEL".."5739",
"OpSubgroupAvcMceGetBestInterDistortionsINTEL".."5740",
"OpSubgroupAvcMceGetInterMajorShapeINTEL".."5741",
"OpSubgroupAvcMceGetInterMinorShapeINTEL".."5742",
"OpSubgroupAvcMceGetInterDirectionsINTEL".."5743",
"OpSubgroupAvcMceGetInterMotionVectorCountINTEL".."5744",
"OpSubgroupAvcMceGetInterReferenceIdsINTEL".."5745",
"OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL".."5746",
"OpSubgroupAvcImeInitializeINTEL".."5747",
"OpSubgroupAvcImeSetSingleReferenceINTEL".."5748",
"OpSubgroupAvcImeSetDualReferenceINTEL".."5749",
"OpSubgroupAvcImeRefWindowSizeINTEL".."5750",
"OpSubgroupAvcImeAdjustRefOffsetINTEL".."5751",
"OpSubgroupAvcImeConvertToMcePayloadINTEL".."5752",
"OpSubgroupAvcImeSetMaxMotionVectorCountINTEL".."5753",
"OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL".."5754",
"OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL".."5755",
"OpSubgroupAvcImeSetWeightedSadINTEL".."5756",
"OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL".."5757",
"OpSubgroupAvcImeEvaluateWithDualReferenceINTEL".."5758",
"OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL".."5759",
"OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL".."5760",
"OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL".."5761",
"OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL".."5762",
"OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL".."5763",
"OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL".."5764",
"OpSubgroupAvcImeConvertToMceResultINTEL".."5765",
"OpSubgroupAvcImeGetSingleReferenceStreaminINTEL".."5766",
"OpSubgroupAvcImeGetDualReferenceStreaminINTEL".."5767",
"OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL".."5768",
"OpSubgroupAvcImeStripDualReferenceStreamoutINTEL".."5769",
"OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL".."5770",
"OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL".."5771",
"OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL".."5772",
"OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL".."5773",
"OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL".."5774",
"OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL".."5775",
"OpSubgroupAvcImeGetBorderReachedINTEL".."5776",
"OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL".."5777",
"OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL".."5778",
"OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL".."5779",
"OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL".."5780",
"OpSubgroupAvcFmeInitializeINTEL".."5781",
"OpSubgroupAvcBmeInitializeINTEL".."5782",
"OpSubgroupAvcRefConvertToMcePayloadINTEL".."5783",
"OpSubgroupAvcRefSetBidirectionalMixDisableINTEL".."5784",
"OpSubgroupAvcRefSetBilinearFilterEnableINTEL".."5785",
"OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL".."5786",
"OpSubgroupAvcRefEvaluateWithDualReferenceINTEL".."5787",
"OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL".."5788",
"OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL".."5789",
"OpSubgroupAvcRefConvertToMceResultINTEL".."5790",
"OpSubgroupAvcSicInitializeINTEL".."5791",
"OpSubgroupAvcSicConfigureSkcINTEL".."5792",
"OpSubgroupAvcSicConfigureIpeLumaINTEL".."5793",
"OpSubgroupAvcSicConfigureIpeLumaChromaINTEL".."5794",
"OpSubgroupAvcSicGetMotionVectorMaskINTEL".."5795",
"OpSubgroupAvcSicConvertToMcePayloadINTEL".."5796",
"OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL".."5797",
"OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL".."5798",
"OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL".."5799",
"OpSubgroupAvcSicSetBilinearFilterEnableINTEL".."5800",
"OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL".."5801",
"OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL".."5802",
"OpSubgroupAvcSicEvaluateIpeINTEL".."5803",
"OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL".."5804",
"OpSubgroupAvcSicEvaluateWithDualReferenceINTEL".."5805",
"OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL".."5806",
"OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL".."5807",
"OpSubgroupAvcSicConvertToMceResultINTEL".."5808",
"OpSubgroupAvcSicGetIpeLumaShapeINTEL".."5809",
"OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL".."5810",
"OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL".."5811",
"OpSubgroupAvcSicGetPackedIpeLumaModesINTEL".."5812",
"OpSubgroupAvcSicGetIpeChromaModeINTEL".."5813",
"OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL".."5814",
"OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL".."5815",
"OpSubgroupAvcSicGetInterRawSadsINTEL".."5816",
"OpVariableLengthArrayINTEL".."5818",
"OpSaveMemoryINTEL".."5819",
"OpRestoreMemoryINTEL".."5820",
"OpArbitraryFloatSinCosPiINTEL".."5840",
"OpArbitraryFloatCastINTEL".."5841",
"OpArbitraryFloatCastFromIntINTEL".."5842",
"OpArbitraryFloatCastToIntINTEL".."5843",
"OpArbitraryFloatAddINTEL".."5846",
"OpArbitraryFloatSubINTEL".."5847",
"OpArbitraryFloatMulINTEL".."5848",
"OpArbitraryFloatDivINTEL".."5849",
"OpArbitraryFloatGTINTEL".."5850",
"OpArbitraryFloatGEINTEL".."5851",
"OpArbitraryFloatLTINTEL".."5852",
"OpArbitraryFloatLEINTEL".."5853",
"OpArbitraryFloatEQINTEL".."5854",
"OpArbitraryFloatRecipINTEL".."5855",
"OpArbitraryFloatRSqrtINTEL".."5856",
"OpArbitraryFloatCbrtINTEL".."5857",
"OpArbitraryFloatHypotINTEL".."5858",
"OpArbitraryFloatSqrtINTEL".."5859",
"OpArbitraryFloatLogINTEL".."5860",
"OpArbitraryFloatLog2INTEL".."5861",
"OpArbitraryFloatLog10INTEL".."5862",
"OpArbitraryFloatLog1pINTEL".."5863",
"OpArbitraryFloatExpINTEL".."5864",
"OpArbitraryFloatExp2INTEL".."5865",
"OpArbitraryFloatExp10INTEL".."5866",
"OpArbitraryFloatExpm1INTEL".."5867",
"OpArbitraryFloatSinINTEL".."5868",
"OpArbitraryFloatCosINTEL".."5869",
"OpArbitraryFloatSinCosINTEL".."5870",
"OpArbitraryFloatSinPiINTEL".."5871",
"OpArbitraryFloatCosPiINTEL".."5872",
"OpArbitraryFloatASinINTEL".."5873",
"OpArbitraryFloatASinPiINTEL".."5874",
"OpArbitraryFloatACosINTEL".."5875",
"OpArbitraryFloatACosPiINTEL".."5876",
"OpArbitraryFloatATanINTEL".."5877",
"OpArbitraryFloatATanPiINTEL".."5878",
"OpArbitraryFloatATan2INTEL".."5879",
"OpArbitraryFloatPowINTEL".."5880",
"OpArbitraryFloatPowRINTEL".."5881",
"OpArbitraryFloatPowNINTEL".."5882",
"OpLoopControlINTEL".."5887",
"OpAliasDomainDeclINTEL".."5911",
"OpAliasScopeDeclINTEL".."5912",
"OpAliasScopeListDeclINTEL".."5913",
"OpFixedSqrtINTEL".."5923",
"OpFixedRecipINTEL".."5924",
"OpFixedRsqrtINTEL".."5925",
"OpFixedSinINTEL".."5926",
"OpFixedCosINTEL".."5927",
"OpFixedSinCosINTEL".."5928",
"OpFixedSinPiINTEL".."5929",
"OpFixedCosPiINTEL".."5930",
"OpFixedSinCosPiINTEL".."5931",
"OpFixedLogINTEL".."5932",
"OpFixedExpINTEL".."5933",
"OpPtrCastToCrossWorkgroupINTEL".."5934",
"OpCrossWorkgroupCastToPtrINTEL".."5938",
"OpReadPipeBlockingINTEL".."5946",
"OpWritePipeBlockingINTEL".."5947",
"OpFPGARegINTEL".."5949",
"OpRayQueryGetRayTMinKHR".."6016",
"OpRayQueryGetRayFlagsKHR".."6017",
"OpRayQueryGetIntersectionTKHR".."6018",
"OpRayQueryGetIntersectionInstanceCustomIndexKHR".."6019",
"OpRayQueryGetIntersectionInstanceIdKHR".."6020",
"OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR".."6021",
"OpRayQueryGetIntersectionGeometryIndexKHR".."6022",
"OpRayQueryGetIntersectionPrimitiveIndexKHR".."6023",
"OpRayQueryGetIntersectionBarycentricsKHR".."6024",
"OpRayQueryGetIntersectionFrontFaceKHR".."6025",
"OpRayQueryGetIntersectionCandidateAABBOpaqueKHR".."6026",
"OpRayQueryGetIntersectionObjectRayDirectionKHR".."6027",
"OpRayQueryGetIntersectionObjectRayOriginKHR".."6028",
"OpRayQueryGetWorldRayDirectionKHR".."6029",
"OpRayQueryGetWorldRayOriginKHR".."6030",
"OpRayQueryGetIntersectionObjectToWorldKHR".."6031",
"OpRayQueryGetIntersectionWorldToObjectKHR".."6032",
"OpAtomicFAddEXT".."6035",
"OpTypeBufferSurfaceINTEL".."6086",
"OpTypeStructContinuedINTEL".."6090",
"OpConstantCompositeContinuedINTEL".."6091",
"OpSpecConstantCompositeContinuedINTEL".."6092",
"OpControlBarrierArriveINTEL".."6142",
"OpControlBarrierWaitINTEL".."6143",
"OpGroupIMulKHR".."6401",
"OpGroupFMulKHR".."6402",
"OpGroupBitwiseAndKHR".."6403",
"OpGroupBitwiseOrKHR".."6404",
"OpGroupBitwiseXorKHR".."6405",
"OpGroupLogicalAndKHR".."6406",
"OpGroupLogicalOrKHR".."6407",
"OpGroupLogicalXorKHR".."6408",
"OpMax".."0x7fffffff",
)
}
| bsd-3-clause | 874cc92b297ea2093aa98c49ac11e57e | 39.702717 | 104 | 0.640264 | 5.000693 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/data/models/Favorite.kt | 1 | 262 | package com.ashish.movieguide.data.models
import com.squareup.moshi.Json
data class Favorite(
val favorite: Boolean? = null,
@Json(name = "media_id") val mediaId: Long? = null,
@Json(name = "media_type") val mediaType: String? = null
)
| apache-2.0 | 2dbb56093509beeb72a65500edf8ae51 | 28.111111 | 64 | 0.660305 | 3.493333 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/ui/season/SeasonDelegateAdapter.kt | 1 | 1947 | package com.ashish.movieguide.ui.season
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.ashish.movieguide.R
import com.ashish.movieguide.data.models.Season
import com.ashish.movieguide.ui.base.recyclerview.BaseContentHolder
import com.ashish.movieguide.ui.common.adapter.OnItemClickListener
import com.ashish.movieguide.ui.common.adapter.RemoveListener
import com.ashish.movieguide.ui.common.adapter.ViewType
import com.ashish.movieguide.ui.common.adapter.ViewTypeDelegateAdapter
import com.ashish.movieguide.utils.extensions.applyText
import com.ashish.movieguide.utils.extensions.getPosterUrl
/**
* Created by Ashish on Jan 04.
*/
class SeasonDelegateAdapter(
private val layoutId: Int,
private var onItemClickListener: OnItemClickListener?
) : ViewTypeDelegateAdapter, RemoveListener {
override fun onCreateViewHolder(parent: ViewGroup) = SeasonHolder(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
(holder as SeasonHolder).bindData(item as Season)
}
override fun removeListener() {
onItemClickListener = null
}
inner class SeasonHolder(parent: ViewGroup) : BaseContentHolder<Season>(parent, layoutId) {
override fun bindData(item: Season) = with(item) {
val context = itemView.context
if (seasonNumber != null && seasonNumber > 0) {
contentTitle.applyText(String.format(context.getString(R.string.season_number_format), seasonNumber))
} else {
contentTitle.setText(R.string.season_specials)
}
contentSubtitle.applyText(String.format(context.getString(R.string.episode_count_format), episodeCount))
super.bindData(item)
}
override fun getItemClickListener() = onItemClickListener
override fun getImageUrl(item: Season) = item.posterPath.getPosterUrl()
}
} | apache-2.0 | 63aac216051a2582362e365ca0d86a77 | 37.196078 | 117 | 0.736518 | 4.570423 | false | false | false | false |
mdanielwork/intellij-community | platform/lang-impl/src/com/intellij/ide/customize/WelcomeWizardHelper.kt | 1 | 2200 | // 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.ide.customize
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.ide.projectView.impl.ProjectViewSharedSettings
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.UISettings
import com.intellij.lang.Language
import com.intellij.openapi.components.BaseComponent
import com.intellij.openapi.util.registry.Registry
class WelcomeWizardHelper : BaseComponent {
override fun initComponent() {
//Project View settings
WelcomeWizardUtil.getAutoScrollToSource()?.let {
ProjectViewSharedSettings.instance.autoscrollToSource = it
}
WelcomeWizardUtil.getManualOrder()?.let {
ProjectViewSharedSettings.instance.manualOrder = it
}
//Debugger settings
WelcomeWizardUtil.getDisableBreakpointsOnClick()?.let{
Registry.get("debugger.click.disable.breakpoints").setValue(it)
}
//Code insight settings
WelcomeWizardUtil.getCompletionCaseSensitive()?.let {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = it
}
//Code style settings
WelcomeWizardUtil.getContinuationIndent()?.let {
Language.getRegisteredLanguages()
.map { CodeStyle.getDefaultSettings().getIndentOptions(it.associatedFileType) }
.filter { it.CONTINUATION_INDENT_SIZE > WelcomeWizardUtil.getContinuationIndent() }
.forEach { it.CONTINUATION_INDENT_SIZE = WelcomeWizardUtil.getContinuationIndent() }
}
//UI settings
WelcomeWizardUtil.getTabsPlacement()?.let {
UISettings.instance.editorTabPlacement = it
}
WelcomeWizardUtil.getAppearanceFontSize()?.let {
val settings = UISettings.instance.state
settings.overrideLafFonts = true
UISettings.instance.state.fontSize = it
}
WelcomeWizardUtil.getAppearanceFontFace()?.let {
val settings = UISettings.instance.state
settings.overrideLafFonts = true
settings.fontFace = it
}
LafManager.getInstance().updateUI()
}
}
| apache-2.0 | d407826eed32f6fe71fe5709d97a7c3e | 37.596491 | 140 | 0.755 | 4.977376 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt | 3 | 23087 | // 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.EmptyDeclarativeInsertHandler
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.OffsetKey
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.*
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.isAlmostEverything
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addIfNotNull
interface InheritanceItemsSearcher {
fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit)
}
class SmartCompletion(
private val expression: KtExpression,
private val resolutionFacade: ResolutionFacade,
private val bindingContext: BindingContext,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val indicesHelper: KotlinIndicesHelper,
private val prefixMatcher: PrefixMatcher,
private val inheritorSearchScope: GlobalSearchScope,
private val toFromOriginalFileMapper: ToFromOriginalFileMapper,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>,
private val isJvmModule: Boolean,
private val forBasicCompletion: Boolean = false
) {
private val expressionWithType = when (callTypeAndReceiver) {
is CallTypeAndReceiver.DEFAULT ->
expression
is CallTypeAndReceiver.DOT,
is CallTypeAndReceiver.SAFE,
is CallTypeAndReceiver.SUPER_MEMBERS,
is CallTypeAndReceiver.INFIX,
is CallTypeAndReceiver.CALLABLE_REFERENCE ->
expression.parent as KtExpression
else -> // actually no smart completion for such places
expression
}
val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected()
val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
SmartCastCalculator(
bindingContext,
resolutionFacade.moduleDescriptor,
expression,
callTypeAndReceiver.receiver as? KtExpression,
resolutionFacade
)
}
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
filterDescriptor(descriptor, factory).map { postProcess(it) }
}.takeIf { expectedInfos.isNotEmpty() }
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)
val postProcessedItems = items.map { postProcess(it) }
//TODO: could not use "let" because of KT-8754
val postProcessedSearcher = if (inheritanceSearcher != null)
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearcher.search(nameFilter) { consumer(postProcess(it)) }
}
}
else
null
return postProcessedItems to postProcessedSearcher
}
val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>> {
when (val parent = expressionWithType.parent) {
is KtBinaryExpression -> {
if (parent.right == expressionWithType) {
val operationToken = parent.operationToken
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
val left = parent.left
if (left is KtReferenceExpression) {
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left]?.let(::setOf).orEmpty()
}
}
}
}
is KtWhenConditionWithExpression -> {
val entry = parent.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
if (subject is KtSimpleNameExpression) {
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject] as? VariableDescriptor
if (variable != null) {
descriptorsToSkip.add(variable)
}
}
val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet()
val classDescriptor = TypeUtils.getClassDescriptor(subjectType)
if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) {
val conditions =
whenExpression.entries.flatMap { it.conditions.toList() }.filterIsInstance<KtWhenConditionWithExpression>()
for (condition in conditions) {
val selectorExpr =
(condition.expression as? KtDotQualifiedExpression)?.selectorExpression as? KtReferenceExpression ?: continue
val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue
if (DescriptorUtils.isEnumEntry(target)) {
descriptorsToSkip.add(target)
}
}
}
return@lazy descriptorsToSkip
}
}
return@lazy emptySet()
}
private fun filterDescriptor(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
): Collection<LookupElement> {
ProgressManager.checkCanceled()
if (descriptor in descriptorsToSkip) return emptyList()
val result = SmartList<LookupElement>()
val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext)
val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
result.addLookupElements(
descriptor,
expectedInfos,
infoMatcher,
noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT
) { declarationDescriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
result.addCallableReferenceLookupElements(descriptor, lookupElementFactory)
}
return result
}
private fun additionalItemsNoPostProcess(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val asTypePositionItems = buildForAsTypePosition(lookupElementFactory.basicFactory)
if (asTypePositionItems != null) {
assert(expectedInfos.isEmpty())
return Pair(asTypePositionItems, null)
}
val items = ArrayList<LookupElement>()
val inheritanceSearchers = ArrayList<InheritanceItemsSearcher>()
if (!forBasicCompletion) { // basic completion adds keyword values on its own
val keywordValueConsumer = object : KeywordValues.Consumer {
override fun consume(
lookupString: String,
expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch,
suitableOnPsiLevel: PsiElement.() -> Boolean,
priority: SmartCompletionItemPriority,
factory: () -> LookupElement
) {
items.addLookupElements(null, expectedInfos, expectedInfoMatcher) {
val lookupElement = factory()
lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority)
listOf(lookupElement)
}
}
}
KeywordValues.process(
keywordValueConsumer,
callTypeAndReceiver,
bindingContext,
resolutionFacade,
moduleDescriptor,
isJvmModule
)
}
if (expectedInfos.isNotEmpty()) {
items.addArrayLiteralsInAnnotationsCompletions()
if (!forBasicCompletion && (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT || callTypeAndReceiver is CallTypeAndReceiver.UNKNOWN /* after this@ */)) {
items.addThisItems(expression, expectedInfos, smartCastCalculator)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
TypeInstantiationItems(
resolutionFacade,
bindingContext,
visibilityFilter,
toFromOriginalFileMapper,
inheritorSearchScope,
lookupElementFactory,
forBasicCompletion,
indicesHelper
).addTo(items, inheritanceSearchers, expectedInfos)
if (expression is KtSimpleNameExpression) {
StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor).addToCollection(
items,
expectedInfos,
expression,
descriptorsToSkip
)
}
ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule)
items.addNamedArgumentsWithLiteralValueItems(expectedInfos)
LambdaSignatureItems.addToCollection(items, expressionWithType, bindingContext, resolutionFacade)
if (!forBasicCompletion) {
LambdaItems.addToCollection(items, expectedInfos)
val whenCondition = expressionWithType.parent as? KtWhenConditionWithExpression
if (whenCondition != null) {
val entry = whenCondition.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val entries = whenExpression.entries
if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) {
val lookupElement = LookupElementBuilder.create("else")
.bold()
.withTailText(" ->")
.withInsertHandler(
WithTailInsertHandler("->", spaceBefore = true, spaceAfter = true).asPostInsertHandler
)
items.add(lookupElement)
}
}
}
MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade).addToCollection(
items,
expectedInfos,
expression
)
}
}
val inheritanceSearcher = if (inheritanceSearchers.isNotEmpty())
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearchers.forEach { it.search(nameFilter, consumer) }
}
}
else
null
return Pair(items, inheritanceSearcher)
}
private fun postProcess(item: LookupElement): LookupElement {
if (forBasicCompletion) return item
return if (item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) == null) {
LookupElementDecorator.withDelegateInsertHandler(
item,
InsertHandler { context, element ->
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
val offset = context.offsetMap.tryGetOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
if (offset != null) {
context.document.deleteString(context.tailOffset, offset)
}
}
element.handleInsert(context)
}
)
} else {
item
}
}
private fun MutableCollection<LookupElement>.addThisItems(
place: KtExpression,
expectedInfos: Collection<ExpectedInfo>,
smartCastCalculator: SmartCastCalculator
) {
if (shouldCompleteThisItems(prefixMatcher)) {
val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade)
for (item in items) {
val types = smartCastCalculator.types(item.receiverParameter).map { it.toFuzzyType(emptyList()) }
val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
addLookupElements(null, expectedInfos, matcher) {
listOf(item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS))
}
}
}
}
private fun MutableCollection<LookupElement>.addNamedArgumentsWithLiteralValueItems(expectedInfos: Collection<ExpectedInfo>) {
data class NameAndValue(val name: Name, val value: String, val priority: SmartCompletionItemPriority)
val nameAndValues = HashMap<NameAndValue, MutableList<ExpectedInfo>>()
fun addNameAndValue(name: Name, value: String, priority: SmartCompletionItemPriority, expectedInfo: ExpectedInfo) {
nameAndValues.getOrPut(NameAndValue(name, value, priority)) { ArrayList() }.add(expectedInfo)
}
for (expectedInfo in expectedInfos) {
val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue
if (argumentData.namedArgumentCandidates.isEmpty()) continue
val parameters = argumentData.function.valueParameters
if (argumentData.argumentIndex >= parameters.size) continue
val parameterName = parameters[argumentData.argumentIndex].name
if (expectedInfo.fuzzyType?.type?.isBooleanOrNullableBoolean() == true) {
addNameAndValue(parameterName, "true", SmartCompletionItemPriority.NAMED_ARGUMENT_TRUE, expectedInfo)
addNameAndValue(parameterName, "false", SmartCompletionItemPriority.NAMED_ARGUMENT_FALSE, expectedInfo)
}
if (expectedInfo.fuzzyType?.type?.isMarkedNullable == true) {
addNameAndValue(parameterName, "null", SmartCompletionItemPriority.NAMED_ARGUMENT_NULL, expectedInfo)
}
}
for ((nameAndValue, infos) in nameAndValues) {
var lookupElement = createNamedArgumentWithValueLookupElement(nameAndValue.name, nameAndValue.value, nameAndValue.priority)
lookupElement = lookupElement.addTail(mergeTails(infos.map { it.tail }))
add(lookupElement)
}
}
private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement {
val lookupElement = LookupElementBuilder.create("${name.asString()} = $value")
.withIcon(KotlinIcons.PARAMETER)
.withInsertHandler { context, _ ->
context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value")
}
lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit)
lookupElement.assignSmartCompletionPriority(priority)
return lookupElement
}
private fun calcExpectedInfos(expression: KtExpression): Collection<ExpectedInfo> {
// if our expression is initializer of implicitly typed variable - take type of variable from original file (+ the same for function)
val declaration = implicitlyTypedDeclarationFromInitializer(expression)
if (declaration != null) {
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
if (originalDeclaration != null) {
val originalDescriptor = originalDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val returnType = originalDescriptor?.returnType
if (returnType != null && !returnType.isError) {
return listOf(ExpectedInfo(returnType, declaration.name, null))
}
}
}
// if expected types are too general, try to use expected type from outer calls
var count = 0
while (true) {
val infos =
ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count).calculate(expression)
if (count == 2 /* use two outer calls maximum */ || infos.none { it.fuzzyType?.isAlmostEverything() == true }) {
return if (forBasicCompletion)
infos.map { it.copy(tail = null) }
else
infos
}
count++
}
//TODO: we could always give higher priority to results with outer call expected type used
}
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
when (val parent = expression.parent) {
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
}
return null
}
private fun MutableCollection<LookupElement>.addCallableReferenceLookupElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
) {
if (callableTypeExpectedInfo.isEmpty()) return
fun toLookupElement(descriptor: CallableDescriptor): LookupElement? {
val callableReferenceType = descriptor.callableReferenceType(resolutionFacade, null) ?: return null
val matchedExpectedInfos = callableTypeExpectedInfo.filter { it.matchingSubstitutor(callableReferenceType) != null }
if (matchedExpectedInfos.isEmpty()) return null
var lookupElement =
lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true)
?: return null
lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() = "::" + delegate.lookupString
override fun getAllLookupStrings() = setOf(lookupString)
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = "::" + presentation.itemText
}
override fun getDelegateInsertHandler() = EmptyDeclarativeInsertHandler
}
return lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE)
.addTailAndNameSimilarity(matchedExpectedInfos)
}
when (descriptor) {
is CallableDescriptor -> {
// members and extensions are not supported after "::" currently
if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) {
addIfNotNull(toLookupElement(descriptor))
}
}
is ClassDescriptor -> {
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
descriptor.constructors.filter(visibilityFilter).mapNotNullTo(this, ::toLookupElement)
}
}
}
}
private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection<LookupElement>? {
val binaryExpression =
((expression.parent as? KtUserType)?.parent as? KtTypeReference)?.parent as? KtBinaryExpressionWithTypeRHS ?: return null
val elementType = binaryExpression.operationReference.getReferencedNameElementType()
if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null
val expectedInfos = calcExpectedInfos(binaryExpression)
val expectedInfosGrouped: Map<KotlinType?, List<ExpectedInfo>> = expectedInfos.groupBy { it.fuzzyType?.type?.makeNotNullable() }
val items = ArrayList<LookupElement>()
for ((type, infos) in expectedInfosGrouped) {
if (type == null) continue
val lookupElement = lookupElementFactory.createLookupElementForType(type) ?: continue
items.add(lookupElement.addTailAndNameSimilarity(infos))
}
return items
}
private fun MutableCollection<LookupElement>.addArrayLiteralsInAnnotationsCompletions() {
this.addAll(ArrayLiteralsInAnnotationItems.collect(expectedInfos, expression))
}
companion object {
val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
}
}
| apache-2.0 | 86b39e5f9eeb013788940dd5b139a3a2 | 46.799172 | 166 | 0.6482 | 6.248173 | false | false | false | false |
TechzoneMC/SonarPet | api/src/main/kotlin/net/techcable/sonarpet/utils/asm.kt | 1 | 890 | @file:Suppress("NOTHING_TO_INLINE") // I know what i'm doing
package net.techcable.sonarpet.utils
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import org.objectweb.asm.Type.*
import kotlin.reflect.KClass
val Class<*>.internalName: String
inline get() = Type.getInternalName(this)
val KClass<*>.internalName: String
inline get() = this.java.internalName
val Class<*>.asmType: Type
inline get() = Type.getType(this)
val KClass<*>.asmType: Type
inline get() = this.java.asmType
fun MethodVisitor.invokeVirtual(
name: String,
ownerType: Type,
returnType: Type = VOID_TYPE,
parameterTypes: List<Type> = listOf()
) {
val desc = getMethodDescriptor(returnType, *parameterTypes.toTypedArray())
return visitMethodInsn(INVOKEVIRTUAL, ownerType.internalName, name, desc, false)
}
| gpl-3.0 | 47db8f46402215aff233310ece1a9b74 | 28.666667 | 84 | 0.724719 | 4.027149 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/insight/ColorLineMarkerProvider.kt | 1 | 3434 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.MinecraftSettings
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.codeInsight.daemon.NavigateAction
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtilBase
import com.intellij.util.FunctionUtil
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.ColorsIcon
import java.awt.Color
import javax.swing.Icon
class ColorLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
if (!MinecraftSettings.instance.isShowChatColorGutterIcons) {
return null
}
val info = element.findColor { map, chosen -> ColorInfo(element, chosen.value, map) }
if (info != null) {
NavigateAction.setNavigateAction(info, "Change color", null)
}
return info
}
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: Collection<LineMarkerInfo<*>>) {}
open class ColorInfo : MergeableLineMarkerInfo<PsiElement> {
protected val color: Color
constructor(element: PsiElement, color: Color, map: Map<String, Color>) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
GutterIconNavigationHandler handler@{ _, psiElement ->
if (!psiElement.isWritable || !element.isValid) {
return@handler
}
val editor = PsiUtilBase.findEditor(element) ?: return@handler
val picker = ColorPicker(map, editor.component)
val newColor = picker.showDialog()
if (newColor != null) {
element.setColor(newColor)
}
},
GutterIconRenderer.Alignment.RIGHT
) {
this.color = color
}
constructor(element: PsiElement, color: Color, handler: GutterIconNavigationHandler<PsiElement>) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
handler,
GutterIconRenderer.Alignment.RIGHT
) {
this.color = color
}
override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is ColorInfo
override fun getCommonIconAlignment(infos: List<MergeableLineMarkerInfo<*>>) =
GutterIconRenderer.Alignment.RIGHT
override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>): Icon {
if (infos.size == 2 && infos[0] is ColorInfo && infos[1] is ColorInfo) {
return ColorsIcon(12, (infos[0] as ColorInfo).color, (infos[1] as ColorInfo).color)
}
return AllIcons.Gutter.Colors
}
override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<*>>) =
FunctionUtil.nullConstant<PsiElement, String>()
}
}
| mit | eb065cafcc48e2656b5a7f3313615b5b | 34.402062 | 113 | 0.654339 | 4.998544 | false | false | false | false |
paplorinc/intellij-community | plugins/git4idea/src/git4idea/ignore/GitIgnoredFilesHolder.kt | 2 | 1215 | // 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 git4idea.ignore
import com.intellij.dvcs.ignore.VcsIgnoredFilesHolderBase
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangesViewRefresher
import com.intellij.openapi.vcs.changes.VcsIgnoredFilesHolder
import git4idea.GitVcs
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
class GitIgnoredFilesHolder(val project: Project, val manager: GitRepositoryManager)
: VcsIgnoredFilesHolderBase<GitRepository>(manager) {
override fun getHolder(repository: GitRepository) = repository.ignoredFilesHolder
override fun copy() = GitIgnoredFilesHolder(project, manager)
class Provider(val project: Project, val manager: GitRepositoryManager) : VcsIgnoredFilesHolder.Provider, ChangesViewRefresher {
private val gitVcs = GitVcs.getInstance(project)
override fun getVcs() = gitVcs
override fun createHolder() = GitIgnoredFilesHolder(project, manager)
override fun refresh(project: Project) {
manager.repositories.forEach { r -> r.ignoredFilesHolder.startRescan() }
}
}
} | apache-2.0 | 378f8badfb0dc96d77cda007596cff1f | 39.533333 | 140 | 0.802469 | 4.567669 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizeActionGroupPanel.kt | 2 | 9733 | // 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 com.intellij.ide.ui.customization
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.customization.CustomizeActionGroupPanel.Companion.showDialog
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.*
import com.intellij.ui.components.JBList
import com.intellij.ui.components.dialog
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.intellij.util.Function
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.Nls
import java.awt.Component
import java.awt.Dimension
import java.awt.event.KeyEvent
import java.util.function.Supplier
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JList
/**
* An actions list with search field and control buttons: add, remove, move and reset.
*
* @param [groupId] id of group that is used to show actions
* @param [addActionGroupIds] ids of groups that are shown when Add action is called.
* If empty all actions are shown by default.
* Use [addActionHandler] to override default dialog.
*
* @see showDialog
*/
class CustomizeActionGroupPanel(
val groupId: String,
val addActionGroupIds: List<String> = emptyList(),
) : BorderLayoutPanel() {
private val list: JBList<Any>
/**
* Handles Add action event for adding new actions. Returns a list of objects.
*
* @see CustomizationUtil.acceptObjectIconAndText
*/
var addActionHandler: () -> List<Any>? = {
ActionGroupPanel.showDialog(
IdeBundle.message("group.customizations.add.action.group"),
*addActionGroupIds.toTypedArray()
)
}
init {
list = JBList<Any>().apply {
model = CollectionListModel(collectActions(groupId, CustomActionsSchema.getInstance()))
cellRenderer = MyListCellRender()
}
preferredSize = Dimension(420, 300)
addToTop(BorderLayoutPanel().apply {
addToRight(createActionToolbar())
addToCenter(createSearchComponent())
})
addToCenter(createCentralPanel(list))
}
private fun collectActions(groupId: String, schema: CustomActionsSchema): List<Any> {
return ActionGroupPanel.getActions(listOf(groupId), schema).first().children
}
fun getActions(): List<Any> = (list.model as CollectionListModel).toList()
private fun createActionToolbar(): JComponent {
val group = DefaultActionGroup().apply {
val addActionGroup = DefaultActionGroup().apply {
templatePresentation.text = IdeBundle.message("group.customizations.add.action.group")
templatePresentation.icon = AllIcons.General.Add
isPopup = true
}
addActionGroup.addAll(
AddAction(IdeBundle.messagePointer("button.add.action")) { selected, model ->
addActionHandler()?.let { result ->
result.forEachIndexed { i, value ->
model.add(selected + i + 1, value)
}
list.selectedIndices = IntArray(result.size) { i -> selected + i + 1 }
}
},
AddAction(IdeBundle.messagePointer("button.add.separator")) { selected, model ->
model.add(selected + 1, Separator.create())
list.selectedIndex = selected + 1
}
)
add(addActionGroup)
add(RemoveAction(IdeBundle.messagePointer("button.remove"), AllIcons.General.Remove))
add(MoveAction(Direction.UP, IdeBundle.messagePointer("button.move.up"), AllIcons.Actions.MoveUp))
add(MoveAction(Direction.DOWN, IdeBundle.messagePointer("button.move.down"), AllIcons.Actions.MoveDown))
add(RestoreAction(IdeBundle.messagePointer("button.restore.all"), AllIcons.Actions.Rollback))
}
return ActionManager.getInstance().createActionToolbar("CustomizeActionGroupPanel", group, true).apply {
targetComponent = list
setReservePlaceAutoPopupIcon(false)
}.component
}
private fun createSearchComponent(): Component {
val speedSearch = object : ListSpeedSearch<Any>(list, Function {
when (it) {
is String -> ActionManager.getInstance().getAction(it).templateText
else -> null
}
}) {
override fun isPopupActive() = true
override fun showPopup(searchText: String?) {}
override fun isSpeedSearchEnabled() = false
override fun showPopup() {}
}
val filterComponent = object : FilterComponent("CUSTOMIZE_ACTIONS", 5) {
override fun filter() {
speedSearch.findAndSelectElement(filter)
speedSearch.component.repaint()
}
}
for (keyCode in intArrayOf(KeyEvent.VK_HOME, KeyEvent.VK_END, KeyEvent.VK_UP, KeyEvent.VK_DOWN)) {
object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val filter: String = filterComponent.filter
if (!StringUtil.isEmpty(filter)) {
speedSearch.adjustSelection(keyCode, filter)
}
}
}.registerCustomShortcutSet(keyCode, 0, filterComponent.textEditor)
}
return filterComponent
}
private fun createCentralPanel(list: JBList<Any>): Component {
return Wrapper(ScrollPaneFactory.createScrollPane(list)).apply {
border = JBUI.Borders.empty(3)
}
}
companion object {
fun showDialog(groupId: String, sourceGroupIds: List<String>, @Nls title: String, customize: CustomizeActionGroupPanel.() -> Unit = {}): List<Any>? {
val panel = CustomizeActionGroupPanel(groupId, sourceGroupIds)
panel.preferredSize = Dimension(480, 360)
panel.customize()
val dialog = dialog(
title = title,
panel = panel,
resizable = true,
focusedComponent = panel.list
)
return if (dialog.showAndGet()) panel.getActions() else null
}
}
private inner class AddAction(
text: Supplier<String>,
val block: (selected: Int, model: CollectionListModel<Any>) -> Unit
) : DumbAwareAction(text, Presentation.NULL_STRING, null) {
override fun actionPerformed(e: AnActionEvent) {
val selected = list.selectedIndices?.lastOrNull() ?: (list.model.size - 1)
val model = (list.model as CollectionListModel)
block(selected, model)
}
}
private inner class MoveAction(
val direction: Direction,
text: Supplier<String>,
icon: Icon
) : DumbAwareAction(text, Presentation.NULL_STRING, icon) {
init {
registerCustomShortcutSet(direction.shortcut, list)
}
override fun actionPerformed(e: AnActionEvent) {
val model = list.model as CollectionListModel
val indices = list.selectedIndices
for (i in indices.indices) {
val index = indices[i]
model.exchangeRows(index, index + direction.sign)
indices[i] = index + direction.sign
}
list.selectedIndices = indices
list.scrollRectToVisible(list.getCellBounds(indices.first(), indices.last()))
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = direction.test(list.selectedIndices, list.model.size)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
}
private inner class RemoveAction(
text: Supplier<String>,
icon: Icon
) : DumbAwareAction(text, Presentation.NULL_STRING, icon) {
init {
registerCustomShortcutSet(CommonShortcuts.getDelete(), list)
}
override fun actionPerformed(e: AnActionEvent) {
val model = list.model as CollectionListModel
val selectedIndices = list.selectedIndices
selectedIndices.reversedArray().forEach(model::remove)
selectedIndices.firstOrNull()?.let { list.selectedIndex = it.coerceAtMost(model.size - 1) }
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = list.selectedIndices.isNotEmpty()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
}
private inner class RestoreAction(
text: Supplier<String>,
icon: Icon
) : DumbAwareAction(text, Presentation.NULL_STRING, icon) {
private val defaultActions = collectActions(groupId, CustomActionsSchema())
override fun actionPerformed(e: AnActionEvent) {
list.model = CollectionListModel(defaultActions)
}
override fun update(e: AnActionEvent) {
val current = (list.model as CollectionListModel).items
e.presentation.isEnabled = defaultActions != current
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
}
enum class Direction(val sign: Int, val shortcut: ShortcutSet, val test: (index: IntArray, size: Int) -> Boolean) {
UP(-1, CommonShortcuts.MOVE_UP, { index, _ -> index.isNotEmpty() && index.first() >= 1 }),
DOWN(1, CommonShortcuts.MOVE_DOWN, { index, size -> index.isNotEmpty() && index.last() < size - 1 });
}
private class MyListCellRender : ColoredListCellRenderer<Any>() {
override fun customizeCellRenderer(list: JList<out Any>, value: Any?, index: Int, selected: Boolean, hasFocus: Boolean) {
CustomizationUtil.acceptObjectIconAndText(value) { text, description, icon ->
SpeedSearchUtil.appendFragmentsForSpeedSearch(list, text, SimpleTextAttributes.REGULAR_ATTRIBUTES, selected, this)
if (description != null) {
append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES, false)
append(description, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
setIcon(icon)
}
}
}
} | apache-2.0 | f19e629c38459c7c771625154d58b768 | 35.185874 | 158 | 0.698962 | 4.597544 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinJpsPluginSettings.kt | 2 | 11207 | // 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.compiler.configuration
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.io.exists
import com.intellij.util.xmlb.XmlSerializer
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.config.JpsPluginSettings
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.SettingConstants
import org.jetbrains.kotlin.config.SettingConstants.KOTLIN_JPS_PLUGIN_SETTINGS_SECTION
import org.jetbrains.kotlin.config.toKotlinVersion
import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle
import java.nio.file.Path
import kotlin.io.path.bufferedReader
@State(name = KOTLIN_JPS_PLUGIN_SETTINGS_SECTION, storages = [(Storage(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE))])
class KotlinJpsPluginSettings(project: Project) : BaseKotlinCompilerSettings<JpsPluginSettings>(project) {
override fun createSettings() = JpsPluginSettings()
fun setVersion(jpsVersion: String) {
if (jpsVersion == settings.version) return
update { version = jpsVersion }
}
fun dropExplicitVersion(): Unit = setVersion("")
companion object {
// Use bundled by default because this will work even without internet connection
@JvmStatic
val rawBundledVersion: String get() = bundledVersion.rawVersion
// Use stable 1.6.21 for outdated compiler versions in order to work with old LV settings
@JvmStatic
val fallbackVersionForOutdatedCompiler: String get() = "1.6.21"
@JvmStatic
val bundledVersion: IdeKotlinVersion get() = KotlinPluginLayout.standaloneCompilerVersion
@JvmStatic
val jpsMinimumSupportedVersion: KotlinVersion = IdeKotlinVersion.get("1.6.0").kotlinVersion
@JvmStatic
val jpsMaximumSupportedVersion: KotlinVersion = LanguageVersion.values().last().toKotlinVersion()
fun validateSettings(project: Project) {
val jpsPluginSettings = project.service<KotlinJpsPluginSettings>()
if (jpsPluginSettings.settings.version.isEmpty() && bundledVersion.buildNumber == null) {
// Encourage user to specify desired Kotlin compiler version in project settings for sake of reproducible builds
// it's important to trigger `.idea/kotlinc.xml` file creation
jpsPluginSettings.setVersion(rawBundledVersion)
}
}
fun jpsVersion(project: Project): String = getInstance(project).settings.versionWithFallback
/**
* @see readFromKotlincXmlOrIpr
*/
@JvmStatic
fun getInstance(project: Project): KotlinJpsPluginSettings = project.service()
/**
* @param jpsVersion version to parse
* @param fromFile true if [jpsVersion] come from kotlin.xml
* @return error message if [jpsVersion] is not valid
*/
@Nls
fun checkJpsVersion(jpsVersion: String, fromFile: Boolean = false): UnsupportedJpsVersionError? {
val parsedKotlinVersion = IdeKotlinVersion.opt(jpsVersion)?.kotlinVersion
if (parsedKotlinVersion == null) {
return ParsingError(
if (fromFile) {
KotlinBasePluginBundle.message(
"failed.to.parse.kotlin.version.0.from.1",
jpsVersion,
SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE,
)
} else {
KotlinBasePluginBundle.message("failed.to.parse.kotlin.version.0", jpsVersion)
}
)
}
if (parsedKotlinVersion < jpsMinimumSupportedVersion) {
return OutdatedCompilerVersion(KotlinBasePluginBundle.message(
"kotlin.jps.compiler.minimum.supported.version.not.satisfied",
jpsMinimumSupportedVersion,
jpsVersion,
))
}
if (parsedKotlinVersion > jpsMaximumSupportedVersion) {
return NewCompilerVersion(KotlinBasePluginBundle.message(
"kotlin.jps.compiler.maximum.supported.version.not.satisfied",
jpsMaximumSupportedVersion,
jpsVersion,
))
}
return null
}
/**
* Replacement for [getInstance] for cases when it's not possible to use [getInstance] (e.g. project isn't yet initialized).
*
* Please, prefer [getInstance] if possible.
*/
fun readFromKotlincXmlOrIpr(path: Path) =
path.takeIf { it.fileIsNotEmpty() }
?.let { JDOMUtil.load(path) }
?.children
?.singleOrNull { it.getAttributeValue("name") == KotlinJpsPluginSettings::class.java.simpleName }
?.let { xmlElement ->
JpsPluginSettings().apply {
XmlSerializer.deserializeInto(this, xmlElement)
}
}
fun supportedJpsVersion(project: Project, onUnsupportedVersion: (String) -> Unit): String? {
val version = jpsVersion(project)
return when (val error = checkJpsVersion(version, fromFile = true)) {
is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler
is NewCompilerVersion, is ParsingError -> {
onUnsupportedVersion(error.message)
null
}
null -> version
}
}
/**
* @param isDelegatedToExtBuild `true` if compiled with Gradle/Maven. `false` if compiled with JPS
*/
fun importKotlinJpsVersionFromExternalBuildSystem(project: Project, rawVersion: String, isDelegatedToExtBuild: Boolean) {
val instance = getInstance(project)
if (rawVersion == rawBundledVersion) {
instance.setVersion(rawVersion)
return
}
val error = checkJpsVersion(rawVersion)
val version = when (error) {
is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler
is NewCompilerVersion, is ParsingError -> rawBundledVersion
null -> rawVersion
}
if (error != null && !isDelegatedToExtBuild) {
showNotificationUnsupportedJpsPluginVersion(
project,
KotlinBasePluginBundle.message("notification.title.unsupported.kotlin.jps.plugin.version"),
KotlinBasePluginBundle.message(
"notification.content.bundled.version.0.will.be.used.reason.1",
version,
error.message
),
)
}
when (error) {
is ParsingError, is NewCompilerVersion -> {
instance.dropExplicitVersion()
return
}
null, is OutdatedCompilerVersion -> Unit
}
if (!shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(IdeKotlinVersion.get(version))) {
instance.dropExplicitVersion()
return
}
if (!isDelegatedToExtBuild) {
downloadKotlinJpsInBackground(project, version)
}
instance.setVersion(version)
}
private fun downloadKotlinJpsInBackground(project: Project, version: String) {
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, KotlinBasePluginBundle.getMessage("progress.text.downloading.kotlinc.dist"), true) {
override fun run(indicator: ProgressIndicator) {
KotlinArtifactsDownloader.lazyDownloadMissingJpsPluginDependencies(
project,
version,
indicator,
onError = {
showNotificationUnsupportedJpsPluginVersion(
project,
KotlinBasePluginBundle.message("kotlin.dist.downloading.failed"),
it,
)
}
)
}
}
)
}
internal fun shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(version: IdeKotlinVersion): Boolean {
check(jpsMinimumSupportedVersion < IdeKotlinVersion.get("1.7.10").kotlinVersion) {
"${::shouldImportKotlinJpsPluginVersionFromExternalBuildSystem.name} makes sense when minimum supported version is lower " +
"than 1.7.20. If minimum supported version is already 1.7.20 then you can drop this function."
}
require(version.kotlinVersion >= jpsMinimumSupportedVersion) {
"${version.kotlinVersion} is lower than $jpsMinimumSupportedVersion"
}
val kt160 = IdeKotlinVersion.get("1.6.0")
val kt170 = IdeKotlinVersion.get("1.7.0")
// Until 1.6.0 none of unbundled Kotlin JPS artifacts was published to the Maven Central.
// In range [1.6.0, 1.7.0] unbundled Kotlin JPS artifacts were published only for release Kotlin versions.
return version > kt170 || version >= kt160 && version.isRelease && version.buildNumber == null
}
}
}
sealed class UnsupportedJpsVersionError(val message: String)
class ParsingError(message: String) : UnsupportedJpsVersionError(message)
class OutdatedCompilerVersion(message: String) : UnsupportedJpsVersionError(message)
class NewCompilerVersion(message: String) : UnsupportedJpsVersionError(message)
@get:NlsSafe
val JpsPluginSettings.versionWithFallback: String get() = version.ifEmpty { KotlinJpsPluginSettings.rawBundledVersion }
private fun showNotificationUnsupportedJpsPluginVersion(
project: Project,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent content: String,
) {
NotificationGroupManager.getInstance()
.getNotificationGroup("Kotlin JPS plugin")
.createNotification(title, content, NotificationType.WARNING)
.setImportant(true)
.notify(project)
}
fun Path.fileIsNotEmpty() = exists() && bufferedReader().use { it.readLine() != null }
| apache-2.0 | 278abec050b3eb9babeccafe6d829f7a | 43.472222 | 140 | 0.624788 | 5.493627 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2016/Day03.kt | 1 | 829 | package com.nibado.projects.advent.y2016
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day03 : Day {
private val input = resourceLines(2016, 3).map { it.trim().split(Regex("\\s+")).map { it.toInt() }.toList() }.toList()
override fun part1() = input.filter(Day03::valid).count().toString()
override fun part2() = byColumns(input).filter(Day03::valid).count().toString()
private fun byColumns(triangles: List<List<Int>>) =
(0 until triangles.size step 3).flatMap { a -> (0..2).map { Pair(a, it) } }
.map { listOf(triangles[it.first][it.second], triangles[it.first + 1][it.second], triangles[it.first + 2][it.second]) }
private fun valid(tr: List<Int>) = tr[0] + tr[1] > tr[2] && tr[0] + tr[2] > tr[1] && tr[1] + tr[2] > tr[0]
} | mit | 5f9dc0e1bbe2b36a602ec020a5a714c4 | 47.823529 | 139 | 0.632087 | 3.093284 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt | 1 | 10843 | // 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.intentions
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.codeinsight.utils.isAnnotatedDeep
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@Suppress("DEPRECATION")
class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) {
override fun additionalFixes(element: KtTypeArgumentList): List<LocalQuickFix>? {
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return null
if (!RemoveExplicitTypeIntention.isApplicableTo(declaration)) return null
return listOf(RemoveExplicitTypeFix(declaration.nameAsSafeName.asString()))
}
private class RemoveExplicitTypeFix(private val declarationName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.explicit.type.specification.from.0", declarationName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtTypeArgumentList ?: return
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return
RemoveExplicitTypeIntention.removeExplicitType(declaration)
}
}
}
/**
* Related tests:
* [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.RemoveExplicitTypeArguments]
* [org.jetbrains.kotlin.idea.intentions.IntentionTestGenerated.RemoveExplicitTypeArguments]
* [org.jetbrains.kotlin.idea.quickfix.QuickFixMultiFileTestGenerated.DeprecatedSymbolUsage.Imports.testAddImportForOperator]
* [org.jetbrains.kotlin.idea.quickfix.QuickFixTestGenerated.DeprecatedSymbolUsage.TypeArguments.WholeProject.testClassConstructor]
* [org.jetbrains.kotlin.idea.refactoring.inline.InlineTestGenerated]
* [org.jetbrains.kotlin.idea.refactoring.introduce.ExtractionTestGenerated.ExtractFunction]
* [org.jetbrains.kotlin.nj2k.*]
*/
class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>(
KtTypeArgumentList::class.java,
KotlinBundle.lazyMessage("remove.explicit.type.arguments")
) {
companion object {
private val INLINE_REIFIED_FUNCTIONS_WITH_INSIGNIFICANT_TYPE_ARGUMENTS: Set<String> = setOf(
"kotlin.arrayOf"
)
fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean {
val callExpression = element.parent as? KtCallExpression ?: return false
val typeArguments = callExpression.typeArguments
if (typeArguments.isEmpty()) return false
if (typeArguments.any { it.typeReference?.isAnnotatedDeep() == true }) return false
val resolutionFacade = callExpression.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_WITH_CFA)
val originalCall = callExpression.getResolvedCall(bindingContext) ?: return false
originalCall.resultingDescriptor.let {
if (it.isInlineFunctionWithReifiedTypeParameters() &&
it.fqNameSafe.asString() !in INLINE_REIFIED_FUNCTIONS_WITH_INSIGNIFICANT_TYPE_ARGUMENTS
) return false
}
val (contextExpression, expectedType) = findContextToAnalyze(callExpression, bindingContext)
val resolutionScope = contextExpression.getResolutionScope(bindingContext, resolutionFacade)
val key = Key<Unit>("RemoveExplicitTypeArgumentsIntention")
callExpression.putCopyableUserData(key, Unit)
val expressionToAnalyze = contextExpression.copied()
callExpression.putCopyableUserData(key, null)
val newCallExpression = expressionToAnalyze.findDescendantOfType<KtCallExpression> { it.getCopyableUserData(key) != null }!!
newCallExpression.typeArgumentList!!.delete()
val newBindingContext = expressionToAnalyze.analyzeInContext(
resolutionScope,
contextExpression,
trace = DelegatingBindingTrace(bindingContext, "Temporary trace"),
dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression),
expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE,
isStatement = contextExpression.isUsedAsStatement(bindingContext)
)
val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false
val args = originalCall.typeArguments
val newArgs = newCall.typeArguments
fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean {
return if (approximateFlexible) {
KotlinTypeChecker.DEFAULT.equalTypes(type1, type2)
} else {
type1 == type2
}
}
return args.size == newArgs.size &&
args.values.zip(newArgs.values).all { (argType, newArgType) -> equalTypes(argType, newArgType) } &&
(newBindingContext.diagnostics.asSequence() - bindingContext.diagnostics).none {
it.factory == INFERRED_INTO_DECLARED_UPPER_BOUNDS || it.factory == UNRESOLVED_REFERENCE ||
it.factory == BUILDER_INFERENCE_STUB_RECEIVER ||
// just for sure because its builder inference related
it.factory == COULD_BE_INFERRED_ONLY_WITH_UNRESTRICTED_BUILDER_INFERENCE
}
}
private fun CallableDescriptor.isInlineFunctionWithReifiedTypeParameters(): Boolean =
this is FunctionDescriptor && isInline && typeParameters.any { it.isReified }
private fun findContextToAnalyze(expression: KtExpression, bindingContext: BindingContext): Pair<KtExpression, KotlinType?> {
for (element in expression.parentsWithSelf) {
if (element !is KtExpression || element is KtEnumEntry) continue
if (element.getQualifiedExpressionForSelector() != null) continue
if (element is KtFunctionLiteral) continue
if (!element.isUsedAsExpression(bindingContext)) return element to null
when (val parent = element.parent) {
is KtNamedFunction -> {
val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType())
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
else
null
return element to expectedType
}
is KtVariableDeclaration -> {
val expectedType = if (element == parent.initializer && parent.typeReference != null)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtParameter -> {
val expectedType = if (element == parent.defaultValue)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtPropertyAccessor -> {
val property = parent.parent as KtProperty
val expectedType = when {
element != parent.bodyExpression || parent.hasBlockBody() -> null
parent.isSetter -> parent.builtIns.unitType
property.typeReference == null -> null
else -> (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
}
return element to expectedType
}
}
}
return expression to null
}
}
override fun isApplicableTo(element: KtTypeArgumentList): Boolean = isApplicableTo(element, approximateFlexible = false)
override fun applyTo(element: KtTypeArgumentList, editor: Editor?) {
val prevCallExpression = element.getPrevSiblingIgnoringWhitespaceAndComments() as? KtCallExpression
val isBetweenLambdaArguments = prevCallExpression?.lambdaArguments?.isNotEmpty() == true &&
element.getNextSiblingIgnoringWhitespaceAndComments() is KtLambdaArgument
element.delete()
if (isBetweenLambdaArguments) {
prevCallExpression?.replace(KtPsiFactory(element.project).createExpressionByPattern("($0)", prevCallExpression))
}
}
}
| apache-2.0 | dbca691766912439de63ffa7de70f6df | 52.413793 | 140 | 0.68671 | 5.880152 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/InterpolatedStringInjectorProcessor.kt | 1 | 7949 | // 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.injection
import com.intellij.injected.editor.InjectionMeta
import com.intellij.lang.injection.general.Injection
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementManipulators
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil.concat
import org.intellij.plugins.intelliLang.inject.InjectedLanguage
import org.intellij.plugins.intelliLang.inject.InjectorUtils
import org.intellij.plugins.intelliLang.inject.InjectorUtils.InjectionInfo
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
data class InjectionSplitResult(val isUnparsable: Boolean, val ranges: List<InjectionInfo>)
internal var PsiElement.trimIndent: String? by UserDataProperty(InjectionMeta.INJECTION_INDENT)
fun transformToInjectionParts(injection: Injection, literalOrConcatenation: KtElement): InjectionSplitResult? {
InjectorUtils.getLanguageByString(injection.injectedLanguageId) ?: return null
val indentHandler = literalOrConcatenation.indentHandler ?: NoIndentHandler
fun injectionRange(literal: KtStringTemplateExpression, range: TextRange, prefix: String, suffix: String): InjectionInfo {
TextRange.assertProperRange(range, injection)
val injectedLanguage = InjectedLanguage.create(injection.injectedLanguageId, prefix, suffix, true)!!
return InjectionInfo(literal, injectedLanguage, range)
}
tailrec fun collectInjections(
literal: KtStringTemplateExpression?,
children: List<PsiElement>,
pendingPrefix: String,
unparseable: Boolean,
collected: MutableList<InjectionInfo>
): InjectionSplitResult {
val child = children.firstOrNull() ?: return InjectionSplitResult(unparseable, collected)
val tail = children.subList(1, children.size)
val partOffsetInParent = child.startOffsetInParent
when {
child is KtBinaryExpression && child.operationToken == KtTokens.PLUS -> {
return collectInjections(null, concat(listOfNotNull(child.left, child.right), tail), pendingPrefix, unparseable, collected)
}
child is KtStringTemplateExpression -> {
if (child.children.isEmpty()) {
// empty range to save injection in the empty string
collected += injectionRange(
child,
ElementManipulators.getValueTextRange(child),
pendingPrefix,
if (tail.isEmpty()) injection.suffix else ""
)
}
return collectInjections(child, concat(child.children.toList(), tail), pendingPrefix, unparseable, collected)
}
literal == null -> {
val (prefix, myUnparseable) = makePlaceholder(child)
return collectInjections(literal = null, tail, pendingPrefix + prefix, unparseable || myUnparseable, collected)
}
child is KtLiteralStringTemplateEntry || child is KtEscapeStringTemplateEntry -> {
val consequentStringsCount = tail.asSequence()
.takeWhile { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry }
.count()
val lastChild = children[consequentStringsCount]
val remaining = tail.subList(consequentStringsCount, tail.size)
val rangesIterator = indentHandler.getUntrimmedRanges(
literal,
TextRange.create(
partOffsetInParent,
lastChild.startOffsetInParent + lastChild.textLength
)
).iterator()
var pendingPrefixForTrimmed = pendingPrefix
while (rangesIterator.hasNext()) {
val trimAwareRange = rangesIterator.next()
collected += injectionRange(
literal, trimAwareRange, pendingPrefixForTrimmed,
if (!rangesIterator.hasNext() && remaining.isEmpty()) injection.suffix else ""
)
pendingPrefixForTrimmed = ""
}
return collectInjections(literal, remaining, "", unparseable, collected)
}
else -> {
if (pendingPrefix.isNotEmpty() || collected.isEmpty()) {
// Store pending prefix before creating a new one,
// or if it is a first part then create a dummy injection to distinguish "inner" prefixes
collected += injectionRange(literal, getRangeForPlaceholder(literal, child) { startOffset }, pendingPrefix, "")
}
val (prefix, myUnparseable) = makePlaceholder(child)
if (tail.isEmpty()) {
// There won't be more elements, so create part with prefix right away
val rangeForPlaceHolder = getRangeForPlaceholder(literal, child) { endOffset }
collected +=
if (literal.textRange.contains(child.textRange))
injectionRange(literal, rangeForPlaceHolder, prefix, injection.suffix)
else
// when the child is not a string we use the end of the current literal anyway (the concantenation case)
injectionRange(literal, rangeForPlaceHolder, "", prefix + injection.suffix)
}
return collectInjections(literal, tail, prefix, unparseable || myUnparseable, collected)
}
}
}
return collectInjections(null, listOf(literalOrConcatenation), injection.prefix, false, ArrayList())
}
private inline fun getRangeForPlaceholder(
literal: KtStringTemplateExpression,
child: PsiElement,
selector: TextRange.() -> Int
): TextRange {
val literalRange = literal.textRange
val childRange = child.textRange
if (literalRange.contains(childRange))
return TextRange.from(selector(childRange) - literalRange.startOffset, 0)
else
return ElementManipulators.getValueTextRange(literal).let { TextRange.from(selector(it), 0) }
}
private fun makePlaceholder(child: PsiElement): Pair<String, Boolean> = when (child) {
is KtSimpleNameStringTemplateEntry ->
tryEvaluateConstant(child.expression)?.let { it to false } ?: ((child.expression?.text ?: NO_VALUE_NAME) to true)
is KtBlockStringTemplateEntry ->
tryEvaluateConstant(child.expression)?.let { it to false } ?: (NO_VALUE_NAME to true)
else ->
((child.text ?: NO_VALUE_NAME) to true)
}
private fun tryEvaluateConstant(ktExpression: KtExpression?) =
ktExpression?.let { expression ->
ConstantExpressionEvaluator.getConstant(expression, expression.analyze())
?.takeUnless { it.isError }
?.getValue(TypeUtils.NO_EXPECTED_TYPE)
?.safeAs<String>()
}
private const val NO_VALUE_NAME = "missingValue"
internal fun flattenBinaryExpression(root: KtBinaryExpression): Sequence<KtExpression> = sequence {
root.left?.let { lOperand ->
if (lOperand.isConcatenationExpression())
yieldAll(flattenBinaryExpression(lOperand as KtBinaryExpression))
else
yield(lOperand)
}
root.right?.let { yield(it) }
}
fun PsiElement.isConcatenationExpression(): Boolean = this is KtBinaryExpression && this.operationToken == KtTokens.PLUS | apache-2.0 | 9e2b8ed2b6b9ccd14f3e7529dc0f61fe | 47.47561 | 158 | 0.65807 | 5.437073 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt | 1 | 4736 | // 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
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.quickfix.SpecifyTypeExplicitlyFix
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class FunctionWithLambdaExpressionBodyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (accessor.isSetter) return
if (accessor.returnTypeReference != null) return
check(accessor)
}
private fun check(element: KtDeclarationWithBody) {
val callableDeclaration = element.getNonStrictParentOfType<KtCallableDeclaration>() ?: return
if (callableDeclaration.typeReference != null) return
val lambda = element.bodyExpression as? KtLambdaExpression ?: return
val functionLiteral = lambda.functionLiteral
if (functionLiteral.arrow != null || functionLiteral.valueParameterList != null) return
val lambdaBody = functionLiteral.bodyBlockExpression ?: return
val used = ReferencesSearch.search(callableDeclaration).any()
val fixes = listOfNotNull(
IntentionWrapper(SpecifyTypeExplicitlyFix()),
IntentionWrapper(AddArrowIntention()),
if (!used &&
lambdaBody.statements.size == 1 &&
lambdaBody.allChildren.none { it is PsiComment }
)
RemoveBracesFix()
else
null,
if (!used) WrapRunFix() else null
)
holder.registerProblem(
lambda,
KotlinBundle.message("inspection.function.with.lambda.expression.body.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
}
private class AddArrowIntention : SpecifyExplicitLambdaSignatureIntention() {
override fun skipProcessingFurtherElementsAfter(element: PsiElement): Boolean = false
}
private class RemoveBracesFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.braces.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val singleStatement = lambda.functionLiteral.bodyExpression?.statements?.singleOrNull() ?: return
val replaced = lambda.replaced(singleStatement)
replaced.setTypeIfNeed()
}
}
private class WrapRunFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("wrap.run.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val body = lambda.functionLiteral.bodyExpression ?: return
val replaced = lambda.replaced(KtPsiFactory(project).createExpressionByPattern("run { $0 }", body.allChildren))
replaced.setTypeIfNeed()
}
}
}
private fun KtExpression.setTypeIfNeed() {
val declaration = getStrictParentOfType<KtCallableDeclaration>() ?: return
val type = (declaration.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType
if (type?.isNothing() == true) {
declaration.setType(type)
}
}
| apache-2.0 | daf5d15c7805fafe125987e74a55943a | 44.104762 | 158 | 0.700591 | 5.475145 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNameToArgumentIntention.kt | 1 | 3482 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntentionWithContext
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.addArgumentName
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.getArgumentNameIfCanBeUsedForCalls
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
internal class AddNameToArgumentIntention :
AbstractKotlinApplicableIntentionWithContext<KtValueArgument, AddNameToArgumentIntention.Context>(KtValueArgument::class),
LowPriorityAction {
class Context(val argumentName: Name)
override fun getFamilyName(): String = KotlinBundle.message("add.name.to.argument")
override fun getActionName(element: KtValueArgument, context: Context): String =
KotlinBundle.message("add.0.to.argument", context.argumentName)
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun isApplicableByPsi(element: KtValueArgument): Boolean {
if (element.isNamed()) return false
// Not applicable when lambda is trailing lambda after argument list (e.g., `run { }`); element is a KtLambdaArgument.
// Note: IS applicable when lambda is inside an argument list (e.g., `run({ })`); element is a KtValueArgument in this case.
if (element is KtLambdaArgument) return false
// Either mixed named arguments must be allowed or the element must be the last unnamed argument.
val argumentList = element.parent as? KtValueArgumentList ?: return false
return element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition) ||
element == argumentList.arguments.last { !it.isNamed() }
}
context(KtAnalysisSession)
override fun prepareContext(element: KtValueArgument): Context? {
val callElement = element.parent.parent as? KtCallElement ?: return null
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return null
if (!resolvedCall.symbol.hasStableParameterNames) {
return null
}
return getArgumentNameIfCanBeUsedForCalls(element, resolvedCall)?.let { Context(it) }
}
override fun apply(element: KtValueArgument, context: Context, project: Project, editor: Editor?) =
addArgumentName(element, context.argumentName)
override fun skipProcessingFurtherElementsAfter(element: PsiElement) =
element is KtValueArgumentList || element is KtContainerNode || super.skipProcessingFurtherElementsAfter(element)
} | apache-2.0 | 697b78147cc5a4677b3b5b29162b33e5 | 53.421875 | 133 | 0.785468 | 5.002874 | false | false | false | false |
allotria/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastUtils.kt | 1 | 10072 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ArrayUtil
import org.jetbrains.annotations.ApiStatus
import java.io.File
inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict)
@JvmOverloads
fun <T : UElement> UElement.getParentOfType(parentClass: Class<out T>, strict: Boolean = true): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun UElement.skipParentOfType(strict: Boolean, vararg parentClasses: Class<out UElement>): UElement? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (!parentClasses.any { it.isInstance(element) }) {
return element
}
element = element.uastParent ?: return null
}
}
@SafeVarargs
fun <T : UElement> UElement.getParentOfType(
parentClass: Class<out T>,
strict: Boolean = true,
vararg terminators: Class<out UElement>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (terminators.any { it.isInstance(element) }) {
return null
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
strict: Boolean = true,
firstParentClass: Class<out T>,
vararg parentClasses: Class<out T>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (firstParentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (parentClasses.any { it.isInstance(element) }) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
@JvmOverloads
fun UElement?.getUCallExpression(searchLimit: Int = Int.MAX_VALUE): UCallExpression? =
this?.withContainingElements?.take(searchLimit)?.mapNotNull {
when (it) {
is UCallExpression -> it
is UQualifiedReferenceExpression -> it.selector as? UCallExpression
else -> null
}
}?.firstOrNull()
fun UElement.getContainingUFile(): UFile? = getParentOfType(UFile::class.java, false)
fun UElement.getContainingUClass(): UClass? = getParentOfType(UClass::class.java)
fun UElement.getContainingUMethod(): UMethod? = getParentOfType(UMethod::class.java)
fun UElement.getContainingUVariable(): UVariable? = getParentOfType(UVariable::class.java)
fun <T : UElement> PsiElement?.findContaining(clazz: Class<T>): T? {
var element = this
while (element != null && element !is PsiFileSystemItem) {
element.toUElement(clazz)?.let { return it }
element = element.parent
}
return null
}
fun <T : UElement> PsiElement?.findAnyContaining(vararg types: Class<out T>): T? = findAnyContaining(Int.Companion.MAX_VALUE, *types)
fun <T : UElement> PsiElement?.findAnyContaining(depthLimit: Int, vararg types: Class<out T>): T? {
var element = this
var i = 0
while (i < depthLimit && element != null && element !is PsiFileSystemItem) {
element.toUElementOfExpectedTypes(*types)?.let { return it }
element = element.parent
i++
}
return null
}
fun isPsiAncestor(ancestor: UElement, child: UElement): Boolean {
val ancestorPsi = ancestor.sourcePsi ?: return false
val childPsi = child.sourcePsi ?: return false
return PsiTreeUtil.isAncestor(ancestorPsi, childPsi, false)
}
fun UElement.isUastChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean {
tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean {
return when (current) {
null -> false
probablyParent -> true
else -> isChildOf(current.uastParent, probablyParent)
}
}
if (probablyParent == null) return false
return isChildOf(if (strict) uastParent else this, probablyParent)
}
/**
* Resolves the receiver element if it implements [UResolvable].
*
* @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable].
*/
fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve()
fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement
fun UReferenceExpression?.getQualifiedName(): String? = (this?.resolve() as? PsiClass)?.qualifiedName
/**
* Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String.
*/
fun UExpression.evaluateString(): String? = evaluate() as? String
fun UExpression.skipParenthesizedExprDown(): UExpression? {
var expression = this
while (expression is UParenthesizedExpression) {
expression = expression.expression
}
return expression
}
fun skipParenthesizedExprUp(elem: UElement?): UElement? {
var parent = elem
while (parent is UParenthesizedExpression) {
parent = parent.uastParent
}
return parent
}
/**
* Get a physical [File] for this file, or null if there is no such file on disk.
*/
fun UFile.getIoFile(): File? = sourcePsi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) }
@Deprecated("use UastFacade", ReplaceWith("UastFacade"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
@Suppress("Deprecation")
tailrec fun UElement.getUastContext(): UastContext {
val psi = this.sourcePsi
if (psi != null) {
return ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext()
}
@Deprecated("could unexpectedly throw exception", ReplaceWith("UastFacade.findPlugin"))
tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin {
val psi = this.sourcePsi
if (psi != null) {
return UastFacade.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin()
}
fun Collection<UElement?>.toPsiElements(): List<PsiElement> = mapNotNull { it?.sourcePsi }
/**
* A helper function for getting parents for given [PsiElement] that could be considered as identifier.
* Useful for working with gutter according to recommendations in [com.intellij.codeInsight.daemon.LineMarkerProvider].
*
* @see [getUParentForAnnotationIdentifier] for working with annotations
*/
fun getUParentForIdentifier(identifier: PsiElement): UElement? {
val uIdentifier = identifier.toUElementOfType<UIdentifier>() ?: return null
return uIdentifier.uastParent
}
/**
* @param arg expression in call arguments list of [this]
* @return parameter that corresponds to the [arg] in declaration to which [this] resolves
*/
fun UCallExpression.getParameterForArgument(arg: UExpression): PsiParameter? {
val psiMethod = resolve() ?: return null
val parameters = psiMethod.parameterList.parameters
return parameters.withIndex().find { (i, p) ->
val argumentForParameter = getArgumentForParameter(i) ?: return@find false
if (wrapULiteral(argumentForParameter) == wrapULiteral(arg)) return@find true
if (arg is ULambdaExpression && arg.sourcePsi?.parent == argumentForParameter.sourcePsi) return@find true // workaround for KT-25297
if (p.isVarArgs && argumentForParameter is UExpressionList) return@find argumentForParameter.expressions.contains(arg)
return@find false
}?.value
}
@ApiStatus.Experimental
tailrec fun UElement.isLastElementInControlFlow(scopeElement: UElement? = null): Boolean =
when (val parent = this.uastParent) {
scopeElement -> if (scopeElement is UBlockExpression) scopeElement.expressions.lastOrNull() == this else true
is UBlockExpression -> if (parent.expressions.lastOrNull() == this) parent.isLastElementInControlFlow(scopeElement) else false
is UElement -> parent.isLastElementInControlFlow(scopeElement)
else -> false
}
fun UNamedExpression.getAnnotationMethod(): PsiMethod? {
val annotation : UAnnotation? = getParentOfType(UAnnotation::class.java, true)
val fqn = annotation?.qualifiedName ?: return null
val annotationSrc = annotation.sourcePsi
if (annotationSrc == null) return null
val psiClass = JavaPsiFacade.getInstance(annotationSrc.project).findClass(fqn, annotationSrc.resolveScope)
if (psiClass != null && psiClass.isAnnotationType) {
return ArrayUtil.getFirstElement(psiClass.findMethodsByName(this.name ?: "value", false))
}
return null
}
val UElement.textRange: TextRange?
get() = sourcePsi?.textRange
/**
* A helper function for getting [UMethod] for element for LineMarker.
* It handles cases, when [getUParentForIdentifier] returns same `parent` for more than one `identifier`.
* Such situations cause multiple LineMarkers for same declaration.
*/
inline fun <reified T : UDeclaration> getUParentForDeclarationLineMarkerElement(lineMarkerElement: PsiElement): T? {
val parent = getUParentForIdentifier(lineMarkerElement) as? T ?: return null
if (parent.uastAnchor.sourcePsiElement != lineMarkerElement) return null
return parent
} | apache-2.0 | c1fe4e12827bd5d00b6ea10f2bd32941 | 36.033088 | 136 | 0.736795 | 4.311644 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/volumes/OrthoView.kt | 1 | 5287 | @file:JvmName("OrthoView")
package graphics.scenery.volumes
import graphics.scenery.*
import graphics.scenery.controls.InputHandler
import graphics.scenery.controls.behaviours.MouseDragSphere
import graphics.scenery.effectors.LineRestrictionEffector
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.times
import kotlinx.coroutines.*
import org.joml.Vector3f
import java.lang.IllegalArgumentException
import java.lang.Thread.sleep
import kotlin.concurrent.thread
/**
* Creates three orthogonal, movable slicing planes through the volume.
* Attention! For movable planes a behavior like in [InputHandler.addOrthoViewDragBehavior] is needed.
* If [key] is set it will be added automatically if there is no other orthoPlane drag behavior already.
*
* To remove call [SlicingPlane.removeTargetVolume] on the leaf nodes and
* [Volume.slicingMode] should be set to [Volume.SlicingMode.None]
*
* @param key The input key for optional plane movement behavior. See Input Docs for format.
* @param hub only needed when [key] is set
*/
fun createOrthoView(volume: Volume, key: String? = null, hub: Hub?) {
volume.slicingMode = Volume.SlicingMode.Slicing
val sliceXZ = SlicingPlane()
val sliceXY = SlicingPlane()
val sliceYZ = SlicingPlane()
sliceXY.spatial().rotation = sliceXY.spatial().rotation.rotateX((Math.PI / 2).toFloat())
sliceYZ.spatial().rotation = sliceYZ.spatial().rotation.rotateZ((Math.PI / 2).toFloat())
sliceXZ.addTargetVolume(volume)
sliceXY.addTargetVolume(volume)
sliceYZ.addTargetVolume(volume)
volume.boundingBox?.let { boundingBox ->
val center = (boundingBox.max - boundingBox.min) * 0.5f
val planeXZ = Box(Vector3f(boundingBox.max.x, 1f, boundingBox.max.z))
val planeXY = Box(Vector3f(boundingBox.max.x, boundingBox.max.y, 1f))
val planeYZ = Box(Vector3f(1f, boundingBox.max.y, boundingBox.max.z))
planeXZ.spatial().position = center
planeXY.spatial().position = center
planeYZ.spatial().position = center
planeXZ.addAttribute(OrthoPlane::class.java, OrthoPlane())
planeXY.addAttribute(OrthoPlane::class.java, OrthoPlane())
planeYZ.addAttribute(OrthoPlane::class.java, OrthoPlane())
// make transparent
planeXZ.material {
blending.setOverlayBlending()
blending.transparent = true
blending.opacity = 0f
}
//planeXZ.material.wireframe = true
planeXY.setMaterial(planeXZ.material())
planeYZ.setMaterial(planeXZ.material())
planeXZ.addChild(sliceXZ)
planeXY.addChild(sliceXY)
planeYZ.addChild(sliceYZ)
volume.addChild(planeXZ)
volume.addChild(planeXY)
volume.addChild(planeYZ)
val yTop = RichNode()
yTop.spatial().position = Vector3f(center.x, boundingBox.max.y, center.z)
volume.addChild(yTop)
val yBottom = RichNode()
yBottom.spatial().position = Vector3f(center.x, boundingBox.min.y, center.z)
volume.addChild(yBottom)
LineRestrictionEffector(planeXZ, { yTop.spatial().position }, { yBottom.spatial().position })
val zTop = RichNode()
zTop.spatial().position = Vector3f(center.x, center.y, boundingBox.max.z)
volume.addChild(/*z*/zTop)
val zBottom = RichNode()
zBottom.spatial().position = Vector3f(center.x, center.y, boundingBox.min.z)
volume.addChild(zBottom)
LineRestrictionEffector(planeXY, { zTop.spatial().position }, { zBottom.spatial().position })
val xTop = RichNode()
xTop.spatial().position = Vector3f(boundingBox.max.x, center.y, center.z)
volume.addChild(xTop)
val xBottom = RichNode()
xBottom.spatial().position = Vector3f(boundingBox.min.x, center.y, center.z)
volume.addChild(xBottom)
LineRestrictionEffector(planeYZ, { xTop.spatial().position }, { xBottom.spatial().position })
}
key?.let {
if (hub == null){
throw IllegalArgumentException("Key is set, a hub is needed.")
}
GlobalScope.launch {
var inputHandler = hub.get<InputHandler>()
var count = 0
while (inputHandler == null) {
delay(1000L)
inputHandler = hub.get<InputHandler>()
if (count++ > 60) {
volume.logger.warn("Could not find input handler to attach orthoPlane drag behavior to.")
break
}
}
inputHandler?.let {
if (inputHandler.getBehaviour("dragOrthoPlane") == null) {
inputHandler.addOrthoViewDragBehavior(key)
}
}
}
}
}
/**
* Attribute class to tag othoplanes
*/
class OrthoPlane
/**
* Adds a [MouseDragSphere] behavior ortho view slices.
*/
fun InputHandler.addOrthoViewDragBehavior(key: String) {
addBehaviour(
"dragOrthoPlane", MouseDragSphere(
"dragOrthoPlane",
{ this.scene.findObserver() },
debugRaycast = false,
filter = { it.getAttributeOrNull(OrthoPlane::class.java) != null }
)
)
addKeyBinding("dragOrthoPlane", key)
}
| lgpl-3.0 | 429f78b6674eca74a9db51119261ed8c | 33.782895 | 109 | 0.655759 | 4.042049 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/AbstractCommitChangesAction.kt | 3 | 2191 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.actions.AbstractCommonCheckinAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.vcsUtil.VcsUtil.getFilePath
abstract class AbstractCommitChangesAction : AbstractCommonCheckinAction() {
override fun getRoots(dataContext: VcsContext): Array<FilePath> =
ProjectLevelVcsManager.getInstance(dataContext.project!!).allVersionedRoots.map { getFilePath(it) }.toTypedArray()
override fun approximatelyHasRoots(dataContext: VcsContext): Boolean =
ProjectLevelVcsManager.getInstance(dataContext.project!!).hasActiveVcss()
override fun update(vcsContext: VcsContext, presentation: Presentation) {
super.update(vcsContext, presentation)
if (presentation.isEnabledAndVisible) {
val changes = vcsContext.selectedChanges
if (vcsContext.place == ActionPlaces.CHANGES_VIEW_POPUP) {
val changeLists = vcsContext.selectedChangeLists
presentation.isEnabled =
if (changeLists.isNullOrEmpty()) !changes.isNullOrEmpty() else changeLists.size == 1 && !changeLists[0].changes.isEmpty()
}
if (presentation.isEnabled && !changes.isNullOrEmpty()) {
disableIfAnyHijackedChanges(vcsContext.project!!, presentation, changes)
}
}
}
private fun disableIfAnyHijackedChanges(project: Project, presentation: Presentation, changes: Array<Change>) {
val manager = ChangeListManager.getInstance(project)
val hasHijackedChanges = changes.any { it.fileStatus == FileStatus.HIJACKED && manager.getChangeList(it) == null }
presentation.isEnabled = !hasHijackedChanges
}
} | apache-2.0 | 00a08e9437ad3b2efd4dc8475a5978d3 | 43.734694 | 140 | 0.783204 | 4.555094 | false | false | false | false |
DeflatedPickle/Quiver | tableviewer/src/main/kotlin/com/deflatedpickle/tableviewer/TableViewerPlugin.kt | 1 | 1377 | /* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.tableviewer
import com.deflatedpickle.haruhi.api.Registry
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventProgramFinishSetup
import com.deflatedpickle.haruhi.util.RegistryUtil
import com.deflatedpickle.quiver.filepanel.api.Viewer
@Suppress("unused")
@Plugin(
value = "$[name]",
author = "$[author]",
version = "$[version]",
description = """
<br>
A viewer for lang and properties files
""",
type = PluginType.OTHER,
dependencies = [
"deflatedpickle@file_panel#>=1.0.0"
]
)
object TableViewerPlugin {
private val extensionSet = setOf(
"properties"
)
init {
EventProgramFinishSetup.addListener {
val registry = RegistryUtil.get("viewer") as Registry<String, MutableList<Viewer<Any>>>?
if (registry != null) {
for (i in this.extensionSet) {
if (registry.get(i) == null) {
registry.register(i, mutableListOf(TableViewer as Viewer<Any>))
} else {
registry.get(i)!!.add(TableViewer as Viewer<Any>)
}
}
}
}
}
}
| mit | 0521613929bb9ea7ebb0f8ba063c53cc | 28.934783 | 100 | 0.607117 | 4.357595 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/database/downloads/DownloadsDatabase.kt | 1 | 5319 | package acr.browser.lightning.database.downloads
import acr.browser.lightning.database.databaseDelegate
import acr.browser.lightning.extensions.firstOrNullMap
import acr.browser.lightning.extensions.useMap
import android.app.Application
import android.content.ContentValues
import android.database.Cursor
import android.database.DatabaseUtils
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import javax.inject.Inject
import javax.inject.Singleton
/**
* The disk backed download database. See [DownloadsRepository] for function documentation.
*/
@Singleton
class DownloadsDatabase @Inject constructor(
application: Application
) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), DownloadsRepository {
private val database: SQLiteDatabase by databaseDelegate()
// Creating Tables
override fun onCreate(db: SQLiteDatabase) {
val createDownloadsTable =
"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_DOWNLOADS)}(" +
"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY," +
"${DatabaseUtils.sqlEscapeString(KEY_URL)} TEXT," +
"${DatabaseUtils.sqlEscapeString(KEY_TITLE)} TEXT," +
"${DatabaseUtils.sqlEscapeString(KEY_SIZE)} TEXT" +
')'
db.execSQL(createDownloadsTable)
}
// Upgrading database
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_DOWNLOADS)}")
// Create tables again
onCreate(db)
}
override fun findDownloadForUrl(url: String): Maybe<DownloadEntry> = Maybe.fromCallable {
database.query(
TABLE_DOWNLOADS,
null,
"$KEY_URL=?",
arrayOf(url),
null,
null,
"1"
).firstOrNullMap { it.bindToDownloadItem() }
}
override fun isDownload(url: String): Single<Boolean> = Single.fromCallable {
database.query(
TABLE_DOWNLOADS,
null,
"$KEY_URL=?",
arrayOf(url),
null,
null,
null,
"1"
).use {
return@fromCallable it.moveToFirst()
}
}
override fun addDownloadIfNotExists(entry: DownloadEntry): Single<Boolean> =
Single.fromCallable {
database.query(
TABLE_DOWNLOADS,
null,
"$KEY_URL=?",
arrayOf(entry.url),
null,
null,
"1"
).use {
if (it.moveToFirst()) {
return@fromCallable false
}
}
val id = database.insert(TABLE_DOWNLOADS, null, entry.toContentValues())
return@fromCallable id != -1L
}
override fun addDownloadsList(downloadEntries: List<DownloadEntry>): Completable =
Completable.fromAction {
database.apply {
beginTransaction()
setTransactionSuccessful()
for (item in downloadEntries) {
addDownloadIfNotExists(item).subscribe()
}
endTransaction()
}
}
override fun deleteDownload(url: String): Single<Boolean> = Single.fromCallable {
return@fromCallable database.delete(TABLE_DOWNLOADS, "$KEY_URL=?", arrayOf(url)) > 0
}
override fun deleteAllDownloads(): Completable = Completable.fromAction {
database.run {
delete(TABLE_DOWNLOADS, null, null)
close()
}
}
override fun getAllDownloads(): Single<List<DownloadEntry>> = Single.fromCallable {
return@fromCallable database.query(
TABLE_DOWNLOADS,
null,
null,
null,
null,
null,
"$KEY_ID DESC"
).useMap { it.bindToDownloadItem() }
}
override fun count(): Long = DatabaseUtils.queryNumEntries(database, TABLE_DOWNLOADS)
/**
* Maps the fields of [DownloadEntry] to [ContentValues].
*/
private fun DownloadEntry.toContentValues() = ContentValues(3).apply {
put(KEY_TITLE, title)
put(KEY_URL, url)
put(KEY_SIZE, contentSize)
}
/**
* Binds a [Cursor] to a single [DownloadEntry].
*/
private fun Cursor.bindToDownloadItem() = DownloadEntry(
url = getString(getColumnIndex(KEY_URL)),
title = getString(getColumnIndex(KEY_TITLE)),
contentSize = getString(getColumnIndex(KEY_SIZE))
)
companion object {
// Database version
private const val DATABASE_VERSION = 1
// Database name
private const val DATABASE_NAME = "downloadManager"
// DownloadItem table name
private const val TABLE_DOWNLOADS = "download"
// DownloadItem table columns names
private const val KEY_ID = "id"
private const val KEY_URL = "url"
private const val KEY_TITLE = "title"
private const val KEY_SIZE = "size"
}
}
| mpl-2.0 | 302c95f204df11edb2149582cc44cc24 | 29.924419 | 95 | 0.603309 | 4.947907 | false | false | false | false |
chiuki/espresso-samples | rotate-screen/app/src/androidTest/java/com/sqisland/espresso/rotate_screen/MainActivityTest.kt | 1 | 2044 | package com.sqisland.espresso.rotate_screen
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.rule.ActivityTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
@Before
fun checkInitialCount() {
onView(withId(R.id.count))
.check(matches(withText("0")))
}
@Test
fun increment() {
onView(withId(R.id.increment_button))
.check(matches(withText(R.string.increment)))
.perform(click())
onView(withId(R.id.count))
.check(matches(withText("1")))
}
@Test
fun incrementTwiceAndRotateScreen() {
onView(withId(R.id.increment_button))
.check(matches(withText(R.string.increment)))
.perform(click())
.perform(click())
onView(withId(R.id.count))
.check(matches(withText("2")))
rotateScreen()
onView(withId(R.id.count))
.check(matches(withText("2")))
}
@Test
fun noIncrementRotateScreen() {
rotateScreen()
onView(withId(R.id.count))
.check(matches(withText("0")))
}
private fun rotateScreen() {
val context = ApplicationProvider.getApplicationContext<Context>()
val orientation = context.resources.configuration.orientation
val activity = activityRule.activity
activity.requestedOrientation = if (orientation == Configuration.ORIENTATION_PORTRAIT)
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
} | apache-2.0 | ef3d59d2fe2618a6f488f009e8c0bfb8 | 27.802817 | 90 | 0.74364 | 4.07984 | false | true | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/CustomHeader.kt | 1 | 14979 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.customFrameDecorations.header
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.UISettings
import com.intellij.jdkEx.JdkEx
import com.intellij.jna.JnaLoader
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.WindowsRegistryUtil
import com.intellij.openapi.wm.impl.IdeMenuBar
import com.intellij.openapi.wm.impl.IdeRootPane
import com.intellij.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons
import com.intellij.ui.AppUIUtil
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.ui.paint.LinePainter2D
import com.intellij.ui.scale.ScaleContext
import com.intellij.ui.scale.ScaleType
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.sun.jna.platform.win32.Advapi32Util
import com.sun.jna.platform.win32.WinReg
import java.awt.*
import java.awt.event.*
import java.beans.PropertyChangeListener
import java.util.*
import javax.swing.*
import javax.swing.border.Border
import kotlin.math.roundToInt
abstract class CustomHeader(private val window: Window) : JPanel(), Disposable {
companion object {
private val LOGGER = logger<CustomHeader>()
val H
get() = 7
val V
get() = 5
val LABEL_BORDER get() = JBUI.Borders.empty(V, 0)
val WINDOWS_VERSION = getWindowsReleaseId()
private fun getWindowsReleaseId(): String? {
try {
if (JnaLoader.isLoaded()) {
return Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
"ReleaseId")
}
}
catch (e: Throwable) {
LOGGER.warn(e)
}
return WindowsRegistryUtil.readRegistryValue("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId")
}
fun create(window: Window): CustomHeader {
return if (window is JFrame) {
if(window.rootPane is IdeRootPane) {
createMainFrameHeader(window, null)
} else {
createFrameHeader(window)
}
} else {
DialogHeader(window)
}
}
private fun createFrameHeader(frame: JFrame): DefaultFrameHeader = DefaultFrameHeader(frame)
@JvmStatic
fun createMainFrameHeader(frame: JFrame, delegatingMenuBar: IdeMenuBar?): MainFrameHeader = MainFrameHeader(frame, delegatingMenuBar)
}
private var windowListener: WindowAdapter
private val myComponentListener: ComponentListener
private val myIconProvider = ScaleContext.Cache { ctx -> getFrameIcon(ctx) }
protected var myActive = false
protected val windowRootPane: JRootPane? = when (window) {
is JWindow -> window.rootPane
is JDialog -> window.rootPane
is JFrame -> window.rootPane
else -> null
}
private var customFrameTopBorder: CustomFrameTopBorder? = null
private val icon: Icon
get() = getFrameIcon()
protected val iconSize = (16 * UISettings.defFontScale).toInt()
private fun getFrameIcon(): Icon {
val ctx = ScaleContext.create(window)
ctx.overrideScale(ScaleType.USR_SCALE.of(UISettings.defFontScale.toDouble()))
return myIconProvider.getOrProvide(ctx)!!
}
protected open fun getFrameIcon(ctx: ScaleContext): Icon {
return AppUIUtil.loadSmallApplicationIcon(ctx, iconSize)
}
protected val productIcon: JComponent by lazy {
createProductIcon()
}
protected val buttonPanes: CustomFrameTitleButtons by lazy {
createButtonsPane()
}
init {
isOpaque = true
background = JBUI.CurrentTheme.CustomFrameDecorations.titlePaneBackground()
fun onClose() {
Disposer.dispose(this)
}
windowListener = object : WindowAdapter() {
override fun windowActivated(ev: WindowEvent?) {
setActive(true)
}
override fun windowDeactivated(ev: WindowEvent?) {
setActive(false)
}
override fun windowClosed(e: WindowEvent?) {
onClose()
}
override fun windowStateChanged(e: WindowEvent?) {
windowStateChanged()
}
}
myComponentListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
SwingUtilities.invokeLater{updateCustomDecorationHitTestSpots()}
}
}
setCustomFrameTopBorder()
}
protected fun setCustomFrameTopBorder(isTopNeeded: ()-> Boolean = {true}, isBottomNeeded: ()-> Boolean = {false}) {
customFrameTopBorder = CustomFrameTopBorder(isTopNeeded, isBottomNeeded)
border = customFrameTopBorder
}
abstract fun createButtonsPane(): CustomFrameTitleButtons
open fun windowStateChanged() {
updateCustomDecorationHitTestSpots()
}
private var added = false
override fun addNotify() {
super.addNotify()
added = true
installListeners()
updateCustomDecorationHitTestSpots()
customFrameTopBorder!!.addNotify()
}
override fun removeNotify() {
added = false
super.removeNotify()
uninstallListeners()
customFrameTopBorder!!.removeNotify()
}
protected open fun installListeners() {
updateActive()
window.addWindowListener(windowListener)
window.addWindowStateListener(windowListener)
window.addComponentListener(myComponentListener)
}
protected open fun uninstallListeners() {
window.removeWindowListener(windowListener)
window.removeWindowStateListener(windowListener)
window.removeComponentListener(myComponentListener)
}
protected fun updateCustomDecorationHitTestSpots() {
if(!added) return
if ((window is JDialog && window.isUndecorated) ||
(window is JFrame && window.isUndecorated)) {
JdkEx.setCustomDecorationHitTestSpots(window, Collections.emptyList())
JdkEx.setCustomDecorationTitleBarHeight(window, 0)
} else {
val toList = getHitTestSpots().map { it.getRectangleOn(window) }.toList()
JdkEx.setCustomDecorationHitTestSpots(window, toList)
JdkEx.setCustomDecorationTitleBarHeight(window, height)
}
}
abstract fun getHitTestSpots(): List<RelativeRectangle>
private fun setActive(value: Boolean) {
myActive = value
updateActive()
updateCustomDecorationHitTestSpots()
}
protected open fun updateActive() {
buttonPanes.isSelected = myActive
buttonPanes.updateVisibility()
customFrameTopBorder?.repaintBorder()
background = JBUI.CurrentTheme.CustomFrameDecorations.titlePaneBackground(myActive)
}
protected val myCloseAction: Action = CustomFrameAction("Close", AllIcons.Windows.CloseSmall) { close() }
protected fun close() {
window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING))
}
override fun dispose() {
}
protected class CustomFrameAction(name: String, icon: Icon, val action: () -> Unit) : AbstractAction(name, icon) {
override fun actionPerformed(e: ActionEvent) = action()
}
private fun createProductIcon(): JComponent {
val menu = JPopupMenu()
val ic = object : JLabel(){
override fun getIcon(): Icon {
return [email protected]
}
}
ic.addMouseListener(object : MouseAdapter(){
override fun mousePressed(e: MouseEvent?) {
menu.show(ic, 0, ic.height)
}
})
menu.isFocusable = false
menu.isBorderPainted = true
addMenuItems(menu)
return ic
}
open fun addMenuItems(menu: JPopupMenu) {
val closeMenuItem = menu.add(myCloseAction)
closeMenuItem.font = JBFont.label().deriveFont(Font.BOLD)
}
inner class CustomFrameTopBorder(val isTopNeeded: ()-> Boolean = {true}, val isBottomNeeded: ()-> Boolean = {false}) : Border {
val thickness = 1
// In reality, Windows uses alpha-blending with alpha=0.34 by default, but we have no (easy) way of doing the same, so let's just
// use the value without alpha. Unfortunately, DWM doesn't offer an API to determine this value.
private val defaultActiveBorder = Color(0x262626)
private val inactiveColor = Color(0xaaaaaa)
private val menuBarBorderColor: Color = JBColor.namedColor("MenuBar.borderColor", JBColor(Gray.xCD, Gray.x51))
private var colorizationAffectsBorders: Boolean = false
private var activeColor: Color = defaultActiveBorder
private fun calculateAffectsBorders(): Boolean {
val windowsVersion = WINDOWS_VERSION?.toIntOrNull() ?: 0
if (windowsVersion < 1809) return false
return Toolkit.getDefaultToolkit().getDesktopProperty("win.dwm.colorizationColor.affects.borders") as Boolean? ?: true
}
private fun calculateActiveBorderColor(): Color {
if (!colorizationAffectsBorders)
return defaultActiveBorder
Toolkit.getDefaultToolkit().apply {
val colorizationColor = getDesktopProperty("win.dwm.colorizationColor") as Color?
if (colorizationColor != null) {
// The border color is a result of an alpha blend of colorization color and #D9D9D9 with the alpha value set by the
// colorization color balance.
var colorizationColorBalance = getDesktopProperty("win.dwm.colorizationColorBalance") as Int?
if (colorizationColorBalance != null) {
// If the desktop setting "Automatically pick an accent color from my background" is active, then the border color
// should be the same as the colorization color read from the registry. To detect that setting, we use the fact that
// colorization color balance is set to 0xfffffff3 when the setting is active.
if (colorizationColorBalance < 0)
colorizationColorBalance = 100
return when (colorizationColorBalance) {
0 -> Color(0xD9D9D9)
100 -> colorizationColor
else -> {
val alpha = colorizationColorBalance / 100.0f
val remainder = 1 - alpha
val r = (colorizationColor.red * alpha + 0xD9 * remainder).roundToInt()
val g = (colorizationColor.green * alpha + 0xD9 * remainder).roundToInt()
val b = (colorizationColor.blue * alpha + 0xD9 * remainder).roundToInt()
Color(r, g, b)
}
}
}
}
return colorizationColor
?: getDesktopProperty("win.frame.activeBorderColor") as Color?
?: menuBarBorderColor
}
}
private val listeners = mutableListOf<Pair<String, PropertyChangeListener>>()
private inline fun listenForPropertyChanges(vararg propertyNames: String, crossinline action: () -> Unit) {
val toolkit = Toolkit.getDefaultToolkit()
val listener = PropertyChangeListener { action() }
for (property in propertyNames) {
toolkit.addPropertyChangeListener(property, listener)
listeners.add(property to listener)
}
}
fun addNotify() {
colorizationAffectsBorders = calculateAffectsBorders()
listenForPropertyChanges("win.dwm.colorizationColor.affects.borders") {
colorizationAffectsBorders = calculateAffectsBorders()
activeColor = calculateActiveBorderColor() // active border color is dependent on whether colorization affects borders or not
}
activeColor = calculateActiveBorderColor()
listenForPropertyChanges("win.dwm.colorizationColor", "win.dwm.colorizationColorBalance", "win.frame.activeBorderColor") {
activeColor = calculateActiveBorderColor()
}
}
fun removeNotify() {
val toolkit = Toolkit.getDefaultToolkit()
for ((propertyName, listener) in listeners)
toolkit.removePropertyChangeListener(propertyName, listener)
listeners.clear()
}
fun repaintBorder() {
val borderInsets = getBorderInsets(this@CustomHeader)
repaint(0, 0, width, thickness)
repaint(0, height - borderInsets.bottom, width, borderInsets.bottom)
}
private val shouldDrawTopBorder: Boolean
get() {
val drawTopBorderActive = myActive && (colorizationAffectsBorders || UIUtil.isUnderIntelliJLaF()) // omit in Darcula with colorization disabled
val drawTopBorderInactive = !myActive && UIUtil.isUnderIntelliJLaF()
return drawTopBorderActive || drawTopBorderInactive
}
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
if (isTopNeeded() && shouldDrawTopBorder) {
g.color = if (myActive) activeColor else inactiveColor
LinePainter2D.paint(g as Graphics2D, x.toDouble(), y.toDouble(), width.toDouble(), y.toDouble())
}
if (isBottomNeeded()) {
g.color = menuBarBorderColor
val y1 = y + height - JBUI.scale(thickness)
LinePainter2D.paint(g as Graphics2D, x.toDouble(), y1.toDouble(), width.toDouble(), y1.toDouble())
}
}
override fun getBorderInsets(c: Component): Insets {
val scale = JBUI.scale(thickness)
val top = if (isTopNeeded() && (colorizationAffectsBorders || UIUtil.isUnderIntelliJLaF())) thickness else 0
return Insets(top, 0, if (isBottomNeeded()) scale else 0, 0)
}
override fun isBorderOpaque(): Boolean {
return true
}
}
}
| apache-2.0 | ec55096ac8a50844484923a6f8e96485 | 37.805699 | 159 | 0.625809 | 5.034958 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/UserTimelineFragment.kt | 1 | 1735 | /*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte
import android.os.Bundle
import com.github.moko256.latte.client.base.entity.Paging
import com.github.moko256.twitlatte.entity.Client
import com.github.moko256.twitlatte.viewmodel.ListViewModel
/**
* Created by moko256 on 2016/06/30.
*
* @author moko256
*/
class UserTimelineFragment : BaseTweetListFragment(), ToolbarTitleInterface {
override val titleResourceId = R.string.post
override val listRepository = object : ListViewModel.ListRepository() {
var userId = 0L
override fun onCreate(client: Client, bundle: Bundle) {
super.onCreate(client, bundle)
userId = bundle.getLong("userId")
}
override fun name() = "UserTimeline_$userId"
override fun request(paging: Paging) = client.apiClient.getUserTimeline(userId, paging)
}
companion object {
fun newInstance(userId: Long): UserTimelineFragment {
return UserTimelineFragment().apply {
arguments = Bundle().apply {
putLong("userId", userId)
}
}
}
}
} | apache-2.0 | 3479c7e5d7cf1d5cb92b5eb9e2a575f0 | 31.148148 | 95 | 0.685303 | 4.381313 | false | false | false | false |
muhrifqii/Maos | app/src/main/java/io/github/muhrifqii/maos/libs/ViewModelLifecycleTransformer.kt | 1 | 3434 | /*
* Copyright 2017 Muhammad Rifqi Fatchurrahman Putra Danar
*
* 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 io.github.muhrifqii.maos.libs
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.android.FragmentEvent
import io.reactivex.BackpressureStrategy.LATEST
import io.reactivex.Completable
import io.reactivex.CompletableSource
import io.reactivex.CompletableTransformer
import io.reactivex.Flowable
import io.reactivex.FlowableTransformer
import io.reactivex.Maybe
import io.reactivex.MaybeSource
import io.reactivex.MaybeTransformer
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.Single
import io.reactivex.SingleSource
import io.reactivex.SingleTransformer
import org.reactivestreams.Publisher
import timber.log.Timber
import java.util.concurrent.CancellationException
/**
* Created on : 25/01/17
* Author : muhrifqii
* Name : Muhammad Rifqi Fatchurrahman Putra Danar
* Github : https://github.com/muhrifqii
* LinkedIn : https://linkedin.com/in/muhrifqii
*
* Custom lifecycleStream transformation to support viewmodel
*/
class ViewModelLifecycleTransformer<Stream>(
private val lifecycleStream: Observable<out LifecycleType<out Any>>) :
ObservableTransformer<Stream, Stream>, FlowableTransformer<Stream, Stream>,
MaybeTransformer<Stream, Stream>, SingleTransformer<Stream, Stream>, CompletableTransformer {
override fun apply(upstream: Observable<Stream>): ObservableSource<Stream> {
return upstream.takeUntil(lifecycle())
}
override fun apply(upstream: Flowable<Stream>): Publisher<Stream> {
return upstream.takeUntil(lifecycle().toFlowable(LATEST))
}
override fun apply(upstream: Maybe<Stream>): MaybeSource<Stream> {
return upstream.takeUntil(lifecycle().firstElement())
}
override fun apply(upstream: Single<Stream>): SingleSource<Stream> {
return upstream.takeUntil(lifecycle().firstOrError())
}
override fun apply(upstream: Completable): CompletableSource {
return Completable.ambArray(upstream,
lifecycle().flatMapCompletable { Completable.error(CancellationException()) })
// remember that flatmap returns all stream from flatten function
}
override fun hashCode(): Int {
return lifecycleStream.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other === null || other.javaClass != javaClass) return false
return lifecycleStream == (other as ViewModelLifecycleTransformer<*>).lifecycleStream
}
private fun lifecycle() = lifecycleStream.switchMap { it.lifecycle() }.filter {
when (it) {
is ActivityEvent -> it === ActivityEvent.DESTROY
is FragmentEvent -> it === FragmentEvent.DETACH
else -> {
Timber.e("error")
false
}
}
}
} | apache-2.0 | 62d76098a325f08c49d0de88d2936c9f | 34.78125 | 97 | 0.746069 | 4.597055 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/runtime/collections/BitSet.kt | 1 | 13549 | package runtime.collections.BitSet
import kotlin.test.*
fun assertContainsOnly(bitSet: BitSet, trueBits: Set<Int>, size: Int) {
for (i in 0 until size) {
val expectedBit = i in trueBits
if (bitSet[i] != expectedBit) {
throw AssertionError()
}
}
}
fun assertNotContainsOnly(bitSet: BitSet, falseBits: Set<Int>, size: Int) {
for (i in 0 until size) {
val expectedBit = i !in falseBits
if (bitSet[i] != expectedBit) {
throw AssertionError()
}
}
}
fun assertTrue(str: String, cond: Boolean) { if (!cond) throw AssertionError(str) }
fun assertFalse(str: String, cond: Boolean) { if (cond) throw AssertionError(str) }
fun <T> assertEquals(str: String, a: T, b: T) { if (a != b) throw AssertionError(str) }
fun assertTrue(cond: Boolean) = assertTrue("", cond)
fun assertFalse(cond: Boolean) = assertFalse("", cond)
fun <T> assertEquals(a: T, b: T) = assertEquals("", a, b)
fun fail(): Unit = throw AssertionError()
fun testConstructor() {
var b = BitSet(12)
assertContainsOnly(b, setOf(), 12)
b = BitSet(12) { it == 0 || it in 5..6 || it == 11 }
assertContainsOnly(b, setOf(0, 5, 6, 11), 12)
}
fun testSet() {
var b = BitSet(0)
assertEquals(b.lastTrueIndex, -1)
b = BitSet(2)
// Test set and clear operation for single index.
assertTrue(b.isEmpty)
b.set(0, true)
b.set(3, true)
assertEquals(b.lastTrueIndex, 3)
assertFalse(b.isEmpty)
assertContainsOnly(b, setOf(0, 3), 4)
b.clear()
assertContainsOnly(b, setOf(), 4)
b.set(1)
b.set(5)
assertEquals(b.lastTrueIndex, 5)
assertContainsOnly(b, setOf(1, 5), 6)
b.set(1, false)
b.set(7, false)
assertEquals(b.lastTrueIndex, 5)
assertContainsOnly(b, setOf(5), 8)
b.clear(5)
assertEquals(b.lastTrueIndex, -1)
assertContainsOnly(b, setOf(), 8)
b.set(70)
assertEquals(b.lastTrueIndex, 70)
assertContainsOnly(b, setOf(70), 71)
b.clear(70)
assertEquals(b.lastTrueIndex, -1)
assertContainsOnly(b, setOf(), 71)
// Test set and clear operations for ranges.
// Set false and clear.
b = BitSet(2)
assertContainsOnly(b, setOf(), 2)
b.set(0..70, true)
assertNotContainsOnly(b, setOf(), 71)
b.set(0..2, false)
assertNotContainsOnly(b, setOf(0, 1, 2), 71)
b.set(63..65, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 71)
b.set(68..70, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 71)
b.set(68..72, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.set(0..72, false)
assertContainsOnly(b, setOf(), 73)
b.set(0..72)
assertNotContainsOnly(b, setOf(), 73)
b.clear(0..2)
assertNotContainsOnly(b, setOf(0, 1, 2), 73)
b.clear(63..65)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.clear(68..70)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 73)
b.clear(68..72)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.clear(0..72)
assertContainsOnly(b, setOf(), 73)
// Set true.
b.set(0..2, true)
assertContainsOnly(b, setOf(0, 1, 2), 73)
b.set(63..65, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.set(70..72, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72), 73)
b.set(73..74, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72, 73, 74), 75)
b.set(0..74, true)
assertNotContainsOnly(b, setOf(), 75)
// Test set and clear for pair of indices.
b = BitSet(2)
assertContainsOnly(b, setOf(), 71)
b.set(0, 71, true)
assertNotContainsOnly(b, setOf(), 71)
b.set(0, 3, false)
assertNotContainsOnly(b, setOf(0, 1, 2), 71)
b.set(63, 66, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 71)
b.set(68, 71, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 71)
b.set(68, 73, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.set(0, 73, false)
assertContainsOnly(b, setOf(), 73)
b.set(0, 73)
assertNotContainsOnly(b, setOf(), 73)
b.clear(0, 3)
assertNotContainsOnly(b, setOf(0, 1, 2), 73)
b.clear(63, 66)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.clear(68, 71)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 73)
b.clear(68, 73)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.clear(0, 73)
assertContainsOnly(b, setOf(), 73)
// Set true.
b.set(0, 3, true)
assertContainsOnly(b, setOf(0, 1, 2), 73)
b.set(63, 66, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.set(70, 73, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72), 73)
b.set(73, 75, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72, 73, 74), 75)
b.set(0, 75, true)
assertNotContainsOnly(b, setOf(), 75)
// Access to negative elements must cause an exception
try {
b.set(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.clear(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.clear(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.set(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b[-1]
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun testFlip() {
val b = BitSet(2)
b.set(0, true)
b.set(70, true)
b.set(63..65, true)
assertEquals(b.lastTrueIndex, 70)
// 0 element
assertContainsOnly(b, setOf(0, 63, 64, 65, 70), 71)
b.flip(0)
assertContainsOnly(b, setOf(63, 64, 65, 70), 71)
b.flip(1)
assertContainsOnly(b, setOf(1, 63, 64, 65, 70), 71)
b.flip(0)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 70), 71)
// last element
b.flip(70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65), 71)
b.flip(69)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69), 71)
b.flip(70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// element in the middle
b.flip(64)
assertContainsOnly(b, setOf(0, 1, 63, 65, 69, 70), 71)
b.flip(65)
assertContainsOnly(b, setOf(0, 1, 63, 69, 70), 71)
b.flip(65)
b.flip(64)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// range in the beginning
b.flip(0..2)
assertContainsOnly(b, setOf(2, 63, 64, 65, 69, 70), 71)
b.flip(0, 3)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// In the end
b.flip(68..70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 68), 71)
b.flip(68, 71)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// In the middle
b.flip(64..66)
assertContainsOnly(b, setOf(0, 1, 63, 66, 69, 70), 71)
b.flip(64, 67)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// Access to a negative element must cause an exception.
try {
b.flip(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.flip(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun testNextBit() {
val b = BitSet(71)
b.set(0)
b.set(65)
b.set(70)
assertEquals(b.nextSetBit(), 0)
assertEquals(b.nextSetBit(0), 0)
assertEquals(b.nextSetBit(1), 65)
assertEquals(b.nextSetBit(65), 65)
assertEquals(b.nextSetBit(66), 70)
assertEquals(b.nextSetBit(70), 70)
assertEquals(b.nextSetBit(71), -1)
assertEquals(b.previousSetBit(0), 0)
assertEquals(b.previousSetBit(64), 0)
assertEquals(b.previousSetBit(65), 65)
assertEquals(b.previousSetBit(69), 65)
assertEquals(b.previousSetBit(70), 70)
assertEquals(b.previousSetBit(71), 70)
b.clear()
assertEquals(b.nextSetBit(), -1)
assertEquals(b.previousSetBit(70), -1)
b.set(0..70)
assertEquals(b.nextClearBit(), 71)
assertEquals(b.previousClearBit(70), -1)
b.clear(0)
b.clear(65)
b.clear(70)
assertEquals(b.nextClearBit(), 0)
assertEquals(b.nextClearBit(0), 0)
assertEquals(b.nextClearBit(1), 65)
assertEquals(b.nextClearBit(65), 65)
assertEquals(b.nextClearBit(66), 70)
assertEquals(b.nextClearBit(70), 70)
assertEquals(b.nextClearBit(71), 71) // assume that the bitset is extended here (virtually).
assertEquals(b.previousClearBit(0), 0)
assertEquals(b.previousClearBit(64), 0)
assertEquals(b.previousClearBit(65), 65)
assertEquals(b.previousClearBit(69), 65)
assertEquals(b.previousClearBit(70), 70)
assertEquals(b.previousClearBit(71), 71)
// See http://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html#previousClearBit-int-
assertEquals(b.previousClearBit(-1), -1)
assertEquals(b.previousSetBit(-1), -1)
// Test behaviour on the right border of the bit vector.
// We assume that the vector is infinite and have zeros after (size - 1)th bit.
var a = BitSet(64)
assertEquals(a.nextClearBit(63), 63)
assertEquals(a.nextClearBit(64), 64)
assertEquals(a.nextSetBit(63), -1)
assertEquals(a.nextSetBit(64), -1)
a.set(0, 64)
assertEquals(a.nextClearBit(63), 64)
assertEquals(a.nextClearBit(64), 64)
assertEquals(a.nextSetBit(63), 63)
assertEquals(a.nextSetBit(64), -1)
a.clear()
assertEquals(a.previousClearBit(63), 63)
assertEquals(a.previousClearBit(64), 64)
assertEquals(a.previousSetBit(63), -1)
assertEquals(a.previousSetBit(64), -1)
a.set(0, 64)
assertEquals(a.previousClearBit(63), -1)
assertEquals(a.previousClearBit(64), 64)
assertEquals(a.previousSetBit(63), 63)
assertEquals(a.previousSetBit(64), 63)
a = BitSet(0)
assertEquals(a.nextSetBit(0), -1)
assertEquals(a.nextClearBit(0), 0)
assertEquals(a.previousSetBit(0), -1)
assertEquals(a.previousClearBit(0), 0)
// Access to a negative element must cause an exception.
try {
b.previousSetBit(-2)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.previousClearBit(-2)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.nextSetBit(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.nextClearBit(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun BitSet.setBits(vararg indices: Int, value: Boolean = true) {
indices.forEach {
set(it, value)
}
}
fun testLogic() {
var b2 = BitSet(76)
b2.setBits(1, 3,
61, 63,
65, 67,
70, 72)
// and
var b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.and(b2)
assertContainsOnly(b1, setOf(3, 63, 67, 72), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.and(b2)
assertContainsOnly(b1, setOf(3, 63, 67, 72), 129)
// or
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.or(b2)
assertContainsOnly(b1, setOf(1, 2, 3, 61, 62, 63, 65, 66, 67, 70, 71, 72), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.or(b2)
assertContainsOnly(b1, setOf(1, 2, 3, 61, 62, 63, 65, 66, 67, 70, 71, 72, 128), 129)
// xor
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.xor(b2)
assertContainsOnly(b1, setOf(1, 2, 61, 62, 65, 66, 70, 71), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.xor(b2)
assertContainsOnly(b1, setOf(1, 2, 61, 62, 65, 66, 70, 71, 128), 129)
// andNot
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.andNot(b2)
assertContainsOnly(b1, setOf(2, 62, 66, 71), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.andNot(b2)
assertContainsOnly(b1, setOf(2, 62, 66, 71, 128), 129)
// intersects
b1 = BitSet(73)
b1.set(0..1); b1.set(62..63); b1.set(64..65); b1.set(71..72)
b2.clear(); b2.set(0)
assertTrue(b1.intersects(b2))
b2.clear(); b2.set(62..65)
assertTrue(b1.intersects(b2))
b2.clear(); b2.set(72)
assertTrue(b1.intersects(b2))
b2.clear()
assertFalse(b1.intersects(b2))
b2.set(128)
assertFalse(b1.intersects(b2))
}
// Based on Harmony tests.
fun testEqualsHashCode() {
// HashCode.
val b = BitSet()
b.set(0..7)
b.clear(2)
b.clear(6)
assertEquals("BitSet returns wrong hash value", 1129, b.hashCode())
b.set(10)
b.clear(3)
assertEquals("BitSet returns wrong hash value", 97, b.hashCode())
// Equals.
val b1 = BitSet()
val b2 = BitSet()
b1.set(0..7)
b2.set(0..7)
assertTrue("Same BitSet returned false", b1 == b1)
assertTrue("Identical BitSet returned false", b1 == b2)
b2.clear(6)
assertFalse("Different BitSets returned true", b1 == b2)
val b3 = BitSet()
b3.set(0..7)
b3.set(128)
assertFalse("Different sized BitSet with higher bit set returned true", b1 == b3)
b3.clear(128)
assertTrue("Different sized BitSet with higher bits not set returned false", b1 == b3)
}
@Test fun runTest() {
testConstructor()
testSet()
testFlip()
testNextBit()
testLogic()
testEqualsHashCode()
} | apache-2.0 | c7a45d0f5cede4deb8e533adc9fca0cd | 29.044346 | 96 | 0.602628 | 2.906887 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/modcrafters/mclib/registries/BaseRecipeRegistry.kt | 1 | 2935 | package net.modcrafters.mclib.registries
import net.minecraft.util.ResourceLocation
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.event.RegistryEvent
import net.minecraftforge.fml.common.discovery.ASMDataTable
import net.minecraftforge.fml.common.eventhandler.GenericEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.registry.GameRegistry
import net.minecraftforge.registries.*
import net.modcrafters.mclib.recipes.IMachineRecipe
import net.ndrei.teslacorelib.annotations.IRegistryHandler
abstract class BaseRecipeRegistry<T: IMachineRecipe<T>>(modId: String, registryName: String, private val type: Class<T>)
: IRegistryHandler, IRecipeRegistry<T> {
override val registryName = ResourceLocation(modId, registryName)
override fun construct(asm: ASMDataTable) {
super.construct(asm)
MinecraftForge.EVENT_BUS.register(this)
}
@SubscribeEvent
fun registerRegistry(ev: RegistryEvent.NewRegistry) {
RegistryBuilder<T>()
.setName(registryName)
.setMaxID(MAX_RECIPE_ID)
.setType(this.type)
.add(AddCallback(this.type))
.add(ClearCallback(this.type))
.disableSaving()
.allowModification()
.create()
}
class AddCallback<T : IForgeRegistryEntry<T>>(private val type: Class<T>) : IForgeRegistry.AddCallback<T> {
override fun onAdd(owner: IForgeRegistryInternal<T>?, stage: RegistryManager?, id: Int, obj: T, oldObj: T?) {
MinecraftForge.EVENT_BUS.post(EntryAddedEvent(this.type, obj))
}
}
class ClearCallback<T : IForgeRegistryEntry<T>>(private val type: Class<T>) : IForgeRegistry.ClearCallback<T> {
override fun onClear(owner: IForgeRegistryInternal<T>?, stage: RegistryManager?) {
if (owner != null) {
MinecraftForge.EVENT_BUS.post(RegistryClearEvent(this.type, owner))
}
}
}
class EntryAddedEvent<T : IForgeRegistryEntry<T>> internal constructor(type: Class<T>, val entry: T) : GenericEvent<T>(type)
class RegistryClearEvent<T : IForgeRegistryEntry<T>> internal constructor(type: Class<T>, val registry: IForgeRegistry<T>) : GenericEvent<T>(type)
class DefaultRegistrationCompletedEvent<T: IMachineRecipe<T>> internal constructor(type: Class<T>, val registry: IRecipeRegistry<T>): GenericEvent<T>(type)
override final var isRegistrationCompleted = false
private set
protected fun registrationCompleted() {
MinecraftForge.EVENT_BUS.post(DefaultRegistrationCompletedEvent(this.type, this))
this.isRegistrationCompleted = true
}
override val registry get(): IForgeRegistryModifiable<T>? = GameRegistry.findRegistry(this.type) as? IForgeRegistryModifiable<T>
companion object {
const val MAX_RECIPE_ID = Integer.MAX_VALUE shr 5
}
}
| mit | a71c4dcaf66adb659059d183f1c02134 | 42.161765 | 159 | 0.719591 | 4.426848 | false | false | false | false |
google/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/diff/MutableDiffRequestChainProcessor.kt | 6 | 3813 | // 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 com.intellij.collaboration.ui.codereview.diff
import com.intellij.diff.chains.AsyncDiffRequestChain
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.impl.CacheDiffRequestProcessor
import com.intellij.diff.util.DiffUserDataKeysEx.ScrollToPolicy
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.actions.diff.PresentableGoToChangePopupAction
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain
import kotlin.properties.Delegates
abstract class MutableDiffRequestChainProcessor(project: Project, chain: DiffRequestChain?) : CacheDiffRequestProcessor.Simple(project) {
private val asyncChangeListener = AsyncDiffRequestChain.Listener {
dropCaches()
currentIndex = (this.chain?.index ?: 0)
updateRequest(true)
}
var chain: DiffRequestChain? by Delegates.observable(null) { _, oldValue, newValue ->
if (oldValue is AsyncDiffRequestChain) {
oldValue.onAssigned(false)
oldValue.removeListener(asyncChangeListener)
}
if (newValue is AsyncDiffRequestChain) {
newValue.onAssigned(true)
// listener should be added after `onAssigned` call to avoid notification about synchronously loaded requests
newValue.addListener(asyncChangeListener, this)
}
currentIndex = newValue?.index ?: 0
updateRequest()
}
private var currentIndex: Int = 0
init {
this.chain = chain
}
override fun onDispose() {
val chain = chain
if (chain is AsyncDiffRequestChain) chain.onAssigned(false)
super.onDispose()
}
override fun getCurrentRequestProvider(): DiffRequestProducer? {
val requests = chain?.requests ?: return null
return if (currentIndex < 0 || currentIndex >= requests.size) null else requests[currentIndex]
}
override fun hasNextChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex < chain.requests.lastIndex
}
override fun hasPrevChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex > 0 && chain.requests.size > 1
}
override fun goToNextChange(fromDifferences: Boolean) {
currentIndex += 1
selectCurrentChange()
updateRequest(false, if (fromDifferences) ScrollToPolicy.FIRST_CHANGE else null)
}
override fun goToPrevChange(fromDifferences: Boolean) {
currentIndex -= 1
selectCurrentChange()
updateRequest(false, if (fromDifferences) ScrollToPolicy.LAST_CHANGE else null)
}
override fun isNavigationEnabled(): Boolean {
val chain = chain ?: return false
return chain.requests.size > 1
}
override fun createGoToChangeAction(): AnAction? {
return MyGoToChangePopupAction()
}
abstract fun selectFilePath(filePath: FilePath)
private fun selectCurrentChange() {
val producer = currentRequestProvider as? ChangeDiffRequestChain.Producer ?: return
selectFilePath(producer.filePath)
}
private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<ChangeDiffRequestChain.Producer>() {
override fun getChanges(): ListSelection<out ChangeDiffRequestChain.Producer> {
val requests = chain?.requests ?: return ListSelection.empty()
val list = ListSelection.createAt(requests, currentIndex)
return list.map { it as? ChangeDiffRequestChain.Producer }
}
override fun onSelected(change: ChangeDiffRequestChain.Producer) {
selectFilePath(change.filePath)
}
}
}
| apache-2.0 | 4aa63da1b5ab2e2b4db23832281420ea | 34.971698 | 158 | 0.760556 | 4.713226 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/login/StarView.kt | 1 | 1968 | package com.habitrpg.android.habitica.ui.views.login
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class StarView : AppCompatImageView {
private var blinkDurations: List<Int>? = null
private var blinkIndex = 0
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context) : super(context) {
this.scaleType = ScaleType.CENTER
}
fun setStarSize(size: Int) {
when (size) {
0 -> {
this.setImageBitmap(HabiticaIconsHelper.imageOfStarSmall())
}
1 -> {
this.setImageBitmap(HabiticaIconsHelper.imageOfStarMedium())
}
2 -> {
this.setImageBitmap(HabiticaIconsHelper.imageOfStarLarge())
}
}
}
fun setBlinkDurations(blinkDurations: List<Int>) {
this.blinkDurations = blinkDurations
runBlink()
}
private fun runBlink() {
if (blinkIndex >= blinkDurations?.size ?: 0) {
blinkIndex = 0
}
val animator = ObjectAnimator.ofFloat<View>(this, View.ALPHA, 0f)
animator.duration = 1000
animator.startDelay = blinkDurations?.get(blinkIndex)?.toLong() ?: 0
animator.repeatCount = 1
animator.repeatMode = ValueAnimator.REVERSE
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
blinkIndex++
runBlink()
}
})
try {
animator.start()
} catch (ignored: NullPointerException) {
}
}
}
| gpl-3.0 | 3620b87f9ef9b64077879bb031369020 | 28.818182 | 79 | 0.637195 | 4.92 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/jetpack/paging/PagingDemoAdapter.kt | 1 | 2338 | package com.zeke.demo.jetpack.paging
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.zeke.demo.R
/**
* author: King.Z <br>
* date: 2021/8/22 21:42 <br>
* description: <br>
*/
class PagingDemoAdapter : PagingDataAdapter<Data, PagingDemoAdapter.ViewHolder>(DataDifferntiator) {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.findViewById<TextView>(R.id.tvUser).text = "${getItem(position)?.first_name} ${getItem(position)?.last_name}"
holder.itemView.findViewById<TextView>(R.id.tvScore).text = getItem(position)?.email
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.item_rank, parent, false)
)
}
/**
* Paging接收一个DiffUtil的Callback处理Item的diff,这里定一个DataDifferntiator
*/
object DataDifferntiator : DiffUtil.ItemCallback<Data>() {
override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
return oldItem == newItem
}
}
}
/**
* 创建HeaderFooterAdapter继承自LoadStateAdapter,onBindViewHolder中可以返回LoadState
* 通过withLoadStateHeaderAndFooter将其添加到MainListAdapter
*/
//class HeaderFooterAdapter() : LoadStateAdapter<HeaderFooterAdapter.ViewHolder>() {
//
// override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
//
// if (loadState == LoadState.Loading) {
// //show progress viewe
// } else //hide the view
//
// }
//
// override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder {
// return LoadStateViewHolder(
// //layout file
// )
// }
//
// class ViewHolder(private val view: View) : RecyclerView.ViewHolder(view)
//}
| gpl-2.0 | 9b18346497ba04a8770d186e3aefa671 | 31.485714 | 133 | 0.691293 | 4.218924 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/util/TipsOrderUtil.kt | 1 | 5760 | // 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 com.intellij.ide.util
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.internal.statistic.eventLog.EventLogConfiguration
import com.intellij.internal.statistic.local.ActionSummary
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.internal.statistic.utils.StatisticsUploadAssistant
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.util.PlatformUtils
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.io.HttpRequests
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
private val LOG = logger<TipsOrderUtil>()
private const val RANDOM_SHUFFLE_ALGORITHM = "default_shuffle"
private const val TIPS_SERVER_URL = "https://feature-recommendation.analytics.aws.intellij.net/tips/v1"
internal data class RecommendationDescription(val algorithm: String, val tips: List<TipAndTrickBean>, val version: String?)
private fun getUtilityExperiment(): TipsUtilityExperiment? {
if (!ApplicationManager.getApplication().isEAP) return null
return when (EventLogConfiguration.getInstance().bucket) {
in 50..74 -> TipsUtilityExperiment.BY_TIP_UTILITY
in 75..99 -> TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED
else -> null
}
}
private fun randomShuffle(tips: List<TipAndTrickBean>): RecommendationDescription {
return RecommendationDescription(RANDOM_SHUFFLE_ALGORITHM, tips.shuffled(), null)
}
@Service
internal class TipsOrderUtil {
private class RecommendationsStartupActivity : StartupActivity.Background {
private val scheduledFuture = AtomicReference<ScheduledFuture<*>>()
override fun runActivity(project: Project) {
val app = ApplicationManager.getApplication()
if (!app.isEAP || app.isHeadlessEnvironment || !StatisticsUploadAssistant.isSendAllowed()) {
return
}
scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable {
try {
sync()
}
finally {
scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable(::sync), 3, TimeUnit.HOURS))
?.cancel(false)
}
}, 5, TimeUnit.MILLISECONDS))
?.cancel(false)
}
}
companion object {
private fun sync() {
LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread)
LOG.debug { "Fetching tips order from the server: ${TIPS_SERVER_URL}" }
val allTips = TipAndTrickBean.EP_NAME.iterable.map { it.fileName }
val actionsSummary = service<ActionsLocalSummary>().getActionsStats()
val startTimestamp = System.currentTimeMillis()
HttpRequests.post(TIPS_SERVER_URL, HttpRequests.JSON_CONTENT_TYPE)
.connect(HttpRequests.RequestProcessor { request ->
val bucket = EventLogConfiguration.getInstance().bucket
val tipsRequest = TipsRequest(allTips, actionsSummary, PlatformUtils.getPlatformPrefix(), bucket)
val objectMapper = ObjectMapper()
request.write(objectMapper.writeValueAsBytes(tipsRequest))
val recommendation = objectMapper.readValue(request.readString(), ServerRecommendation::class.java)
LOG.debug {
val duration = System.currentTimeMillis() - startTimestamp
val algorithmInfo = "${recommendation.usedAlgorithm}:${recommendation.version}"
"Server recommendation made. Algorithm: $algorithmInfo. Duration: ${duration}"
}
service<TipsOrderUtil>().serverRecommendation = recommendation
}, null, LOG)
}
}
@Volatile
private var serverRecommendation: ServerRecommendation? = null
/**
* Reorders tips to show the most useful ones in the beginning
*
* @return object that contains sorted tips and describes approach of how the tips are sorted
*/
fun sort(tips: List<TipAndTrickBean>): RecommendationDescription {
getUtilityExperiment()?.let {
return service<TipsUsageManager>().sortByUtility(tips, it)
}
serverRecommendation?.let { return it.reorder(tips) }
return randomShuffle(tips)
}
}
enum class TipsUtilityExperiment {
BY_TIP_UTILITY {
override fun toString(): String = "tip_utility"
},
BY_TIP_UTILITY_IGNORE_USED {
override fun toString(): String = "tip_utility_and_ignore_used"
}
}
private data class TipsRequest(
val tips: List<String>,
val usageInfo: Map<String, ActionSummary>,
val ideName: String, // product code
val bucket: Int
)
private class ServerRecommendation {
@JvmField
var showingOrder = emptyList<String>()
@JvmField
var usedAlgorithm = "unknown"
@JvmField
var version: String? = null
fun reorder(tips: List<TipAndTrickBean>): RecommendationDescription {
val tipToIndex = Object2IntOpenHashMap<String>(showingOrder.size)
showingOrder.forEachIndexed { index, tipFile -> tipToIndex.put(tipFile, index) }
for (tip in tips) {
if (!tipToIndex.containsKey(tip.fileName)) {
LOG.error("Unknown tips file: ${tip.fileName}")
return randomShuffle(tips)
}
}
return RecommendationDescription(usedAlgorithm, tips.sortedBy { tipToIndex.getInt(it.fileName) }, version)
}
} | apache-2.0 | afb54e4d0d92648f6f0382a1cb9ca685 | 37.66443 | 158 | 0.742882 | 4.663968 | false | false | false | false |
danielgindi/android-helpers | Helpers/src/main/java/com/dg/helpers/DoubleHelper.kt | 1 | 1161 | package com.dg.helpers
@Suppress("unused")
object DoubleHelper
{
@Suppress("MemberVisibilityCanBePrivate")
fun withObject(value: Any?): Double?
{
when (value)
{
null -> return null
is Double -> return value
is Float -> return value.toDouble()
is Int -> return value.toDouble()
is Short -> return value.toDouble()
is String -> try
{
return java.lang.Double.parseDouble(value)
}
catch (ignored: Exception)
{
}
}
return null
}
@Suppress("MemberVisibilityCanBePrivate")
fun withObject(value: Any?, defaultValue: Double): Double
{
return withObject(value) ?: defaultValue
}
fun toArray(inArray: Array<Float?>): FloatArray
{
val array = FloatArray(inArray.size)
var i = 0
val len = inArray.size
while (i < len)
{
val value = inArray[i]
if (value != null)
{
array[i] = value
}
i++
}
return array
}
}
| mit | 7b487ce8c248b4074ad7e90b631c307b | 22.22 | 61 | 0.491817 | 4.797521 | false | false | false | false |
petuhovskiy/JValuer-CLI | src/main/kotlin/com/petukhovsky/jvaluer/cli/DB.kt | 1 | 1775 | package com.petukhovsky.jvaluer.cli
import com.petukhovsky.jvaluer.cli.objectMapper
import com.petukhovsky.jvaluer.util.FilesUtils
import java.nio.file.*
val dbDir = configDir.resolve("db/")
class DbObject<T>(path: String, val c: Class<T>) {
val bak = dbDir.resolve("$path.bak")
val json = dbDir.resolve("$path.json")
fun exists() = Files.exists(bak) || Files.exists(json)
fun get(): T? {
if (!exists()) return null
if (Files.exists(bak)) {
Files.move(bak, json, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
return get()
}
assert(Files.exists(json), {"Unexpected missing file: ${json.toAbsolutePath()}"})
Files.newInputStream(json).use {
return objectMapper.readValue(it, c)
}
}
fun getOrDefault(): T {
return try { get() } catch (e: Exception) { null } ?: c.newInstance()
}
fun save(value: T) {
Files.createDirectories(json.parent)
if (Files.exists(json)) Files.move(json, bak, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
Files.newOutputStream(json).use { objectMapper.writeValue(it, value) }
Files.deleteIfExists(bak)
}
}
inline fun <reified T : Any> db(path: String) = DbObject(path, T::class.java)
val objectsDir = configDir.resolve("objects/").apply { Files.createDirectories(this) }
fun saveObject(path: Path): MySHA {
val hash = hashOf(path)
val nPath = objectsDir.resolve(hash.string)
if (Files.notExists(nPath) || hashOf(nPath) != hash) {
Files.copy(path, nPath)
}
return hash
}
fun getObject(hash: MySHA): Path? {
val path = objectsDir.resolve(hash.string)
return if (Files.notExists(path)) null else path
}
| mit | ab63579c2538fdc8ea3f08c26c562d43 | 30.696429 | 122 | 0.653521 | 3.682573 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/semantics/SemanticsProperties.kt | 3 | 37665 | /*
* 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.ui.semantics
import androidx.compose.runtime.Immutable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import kotlin.reflect.KProperty
/**
* General semantics properties, mainly used for accessibility and testing.
*
* Each of these is intended to be set by the respective SemanticsPropertyReceiver extension
* instead of used directly.
*/
/*@VisibleForTesting*/
object SemanticsProperties {
/**
* @see SemanticsPropertyReceiver.contentDescription
*/
val ContentDescription = SemanticsPropertyKey<List<String>>(
name = "ContentDescription",
mergePolicy = { parentValue, childValue ->
parentValue?.toMutableList()?.also { it.addAll(childValue) } ?: childValue
}
)
/**
* @see SemanticsPropertyReceiver.stateDescription
*/
val StateDescription = SemanticsPropertyKey<String>("StateDescription")
/**
* @see SemanticsPropertyReceiver.progressBarRangeInfo
*/
val ProgressBarRangeInfo =
SemanticsPropertyKey<ProgressBarRangeInfo>("ProgressBarRangeInfo")
/**
* @see SemanticsPropertyReceiver.paneTitle
*/
val PaneTitle = SemanticsPropertyKey<String>(
name = "PaneTitle",
mergePolicy = { _, _ ->
throw IllegalStateException(
"merge function called on unmergeable property PaneTitle."
)
}
)
/** @see SemanticsPropertyReceiver.selectableGroup */
val SelectableGroup = SemanticsPropertyKey<Unit>("SelectableGroup")
/** @see SemanticsPropertyReceiver.collectionInfo */
val CollectionInfo = SemanticsPropertyKey<CollectionInfo>("CollectionInfo")
/** @see SemanticsPropertyReceiver.collectionItemInfo */
val CollectionItemInfo = SemanticsPropertyKey<CollectionItemInfo>("CollectionItemInfo")
/**
* @see SemanticsPropertyReceiver.heading
*/
val Heading = SemanticsPropertyKey<Unit>("Heading")
/**
* @see SemanticsPropertyReceiver.disabled
*/
val Disabled = SemanticsPropertyKey<Unit>("Disabled")
/**
* @see SemanticsPropertyReceiver.liveRegion
*/
val LiveRegion = SemanticsPropertyKey<LiveRegionMode>("LiveRegion")
/**
* @see SemanticsPropertyReceiver.focused
*/
val Focused = SemanticsPropertyKey<Boolean>("Focused")
/**
* @see SemanticsPropertyReceiver.invisibleToUser
*/
@ExperimentalComposeUiApi
val InvisibleToUser = SemanticsPropertyKey<Unit>(
name = "InvisibleToUser",
mergePolicy = { parentValue, _ ->
parentValue
}
)
/**
* @see SemanticsPropertyReceiver.horizontalScrollAxisRange
*/
val HorizontalScrollAxisRange =
SemanticsPropertyKey<ScrollAxisRange>("HorizontalScrollAxisRange")
/**
* @see SemanticsPropertyReceiver.verticalScrollAxisRange
*/
val VerticalScrollAxisRange =
SemanticsPropertyKey<ScrollAxisRange>("VerticalScrollAxisRange")
/**
* @see SemanticsPropertyReceiver.popup
*/
val IsPopup = SemanticsPropertyKey<Unit>(
name = "IsPopup",
mergePolicy = { _, _ ->
throw IllegalStateException(
"merge function called on unmergeable property IsPopup. " +
"A popup should not be a child of a clickable/focusable node."
)
}
)
/**
* @see SemanticsPropertyReceiver.dialog
*/
val IsDialog = SemanticsPropertyKey<Unit>(
name = "IsDialog",
mergePolicy = { _, _ ->
throw IllegalStateException(
"merge function called on unmergeable property IsDialog. " +
"A dialog should not be a child of a clickable/focusable node."
)
}
)
/**
* The type of user interface element. Accessibility services might use this to describe the
* element or do customizations. Most roles can be automatically resolved by the semantics
* properties of this element. But some elements with subtle differences need an exact role. If
* an exact role is not listed in [Role], this property should not be set and the framework will
* automatically resolve it.
*
* @see SemanticsPropertyReceiver.role
*/
val Role = SemanticsPropertyKey<Role>("Role") { parentValue, _ -> parentValue }
/**
* @see SemanticsPropertyReceiver.testTag
*/
val TestTag = SemanticsPropertyKey<String>(
name = "TestTag",
mergePolicy = { parentValue, _ ->
// Never merge TestTags, to avoid leaking internal test tags to parents.
parentValue
}
)
/**
* @see SemanticsPropertyReceiver.text
*/
val Text = SemanticsPropertyKey<List<AnnotatedString>>(
name = "Text",
mergePolicy = { parentValue, childValue ->
parentValue?.toMutableList()?.also { it.addAll(childValue) } ?: childValue
}
)
/**
* @see SemanticsPropertyReceiver.editableText
*/
val EditableText = SemanticsPropertyKey<AnnotatedString>(name = "EditableText")
/**
* @see SemanticsPropertyReceiver.textSelectionRange
*/
val TextSelectionRange = SemanticsPropertyKey<TextRange>("TextSelectionRange")
/**
* @see SemanticsPropertyReceiver.imeAction
*/
val ImeAction = SemanticsPropertyKey<ImeAction>("ImeAction")
/**
* @see SemanticsPropertyReceiver.selected
*/
val Selected = SemanticsPropertyKey<Boolean>("Selected")
/**
* @see SemanticsPropertyReceiver.toggleableState
*/
val ToggleableState = SemanticsPropertyKey<ToggleableState>("ToggleableState")
/**
* @see SemanticsPropertyReceiver.password
*/
val Password = SemanticsPropertyKey<Unit>("Password")
/**
* @see SemanticsPropertyReceiver.error
*/
val Error = SemanticsPropertyKey<String>("Error")
/**
* @see SemanticsPropertyReceiver.indexForKey
*/
val IndexForKey = SemanticsPropertyKey<(Any) -> Int>("IndexForKey")
}
/**
* Ths object defines keys of the actions which can be set in semantics and performed on the
* semantics node.
*
* Each of these is intended to be set by the respective SemanticsPropertyReceiver extension
* instead of used directly.
*/
/*@VisibleForTesting*/
object SemanticsActions {
/**
* @see SemanticsPropertyReceiver.getTextLayoutResult
*/
val GetTextLayoutResult =
ActionPropertyKey<(MutableList<TextLayoutResult>) -> Boolean>("GetTextLayoutResult")
/**
* @see SemanticsPropertyReceiver.onClick
*/
val OnClick = ActionPropertyKey<() -> Boolean>("OnClick")
/**
* @see SemanticsPropertyReceiver.onLongClick
*/
val OnLongClick = ActionPropertyKey<() -> Boolean>("OnLongClick")
/**
* @see SemanticsPropertyReceiver.scrollBy
*/
val ScrollBy = ActionPropertyKey<(x: Float, y: Float) -> Boolean>("ScrollBy")
/**
* @see SemanticsPropertyReceiver.scrollToIndex
*/
val ScrollToIndex = ActionPropertyKey<(Int) -> Boolean>("ScrollToIndex")
/**
* @see SemanticsPropertyReceiver.setProgress
*/
val SetProgress = ActionPropertyKey<(progress: Float) -> Boolean>("SetProgress")
/**
* @see SemanticsPropertyReceiver.setSelection
*/
val SetSelection = ActionPropertyKey<(Int, Int, Boolean) -> Boolean>("SetSelection")
/**
* @see SemanticsPropertyReceiver.setText
*/
val SetText = ActionPropertyKey<(AnnotatedString) -> Boolean>("SetText")
/**
* @see SemanticsPropertyReceiver.copyText
*/
val CopyText = ActionPropertyKey<() -> Boolean>("CopyText")
/**
* @see SemanticsPropertyReceiver.cutText
*/
val CutText = ActionPropertyKey<() -> Boolean>("CutText")
/**
* @see SemanticsPropertyReceiver.pasteText
*/
val PasteText = ActionPropertyKey<() -> Boolean>("PasteText")
/**
* @see SemanticsPropertyReceiver.expand
*/
val Expand = ActionPropertyKey<() -> Boolean>("Expand")
/**
* @see SemanticsPropertyReceiver.collapse
*/
val Collapse = ActionPropertyKey<() -> Boolean>("Collapse")
/**
* @see SemanticsPropertyReceiver.dismiss
*/
val Dismiss = ActionPropertyKey<() -> Boolean>("Dismiss")
/**
* @see SemanticsPropertyReceiver.requestFocus
*/
val RequestFocus = ActionPropertyKey<() -> Boolean>("RequestFocus")
/**
* @see SemanticsPropertyReceiver.customActions
*/
val CustomActions =
SemanticsPropertyKey<List<CustomAccessibilityAction>>("CustomActions")
}
/**
* SemanticsPropertyKey is the infrastructure for setting key/value pairs inside semantics blocks
* in a type-safe way. Each key has one particular statically defined value type T.
*/
class SemanticsPropertyKey<T>(
/**
* The name of the property. Should be the same as the constant from which it is accessed.
*/
val name: String,
internal val mergePolicy: (T?, T) -> T? = { parentValue, childValue ->
parentValue ?: childValue
}
) {
/**
* Method implementing the semantics merge policy of a particular key.
*
* When mergeDescendants is set on a semantics node, then this function will called for each
* descendant node of a given key in depth-first-search order. The parent
* value accumulates the result of merging the values seen so far, similar to reduce().
*
* The default implementation returns the parent value if one exists, otherwise uses the
* child element. This means by default, a SemanticsNode with mergeDescendants = true
* winds up with the first value found for each key in its subtree in depth-first-search order.
*/
fun merge(parentValue: T?, childValue: T): T? {
return mergePolicy(parentValue, childValue)
}
/**
* Throws [UnsupportedOperationException]. Should not be called.
*/
// TODO(KT-6519): Remove this getter
// TODO(KT-32770): Cannot deprecate this either as the getter is considered called by "by"
final operator fun getValue(thisRef: SemanticsPropertyReceiver, property: KProperty<*>): T {
return throwSemanticsGetNotSupported()
}
final operator fun setValue(
thisRef: SemanticsPropertyReceiver,
property: KProperty<*>,
value: T
) {
thisRef[this] = value
}
override fun toString(): String {
return "SemanticsPropertyKey: $name"
}
}
private fun <T> throwSemanticsGetNotSupported(): T {
throw UnsupportedOperationException(
"You cannot retrieve a semantics property directly - " +
"use one of the SemanticsConfiguration.getOr* methods instead"
)
}
/**
* Standard accessibility action.
*
* @param label The description of this action
* @param action The function to invoke when this action is performed. The function should return
* a boolean result indicating whether the action is successfully handled. For example, a scroll
* forward action should return false if the widget is not enabled or has reached the end of the
* list. If multiple semantics blocks with the same AccessibilityAction are provided, the
* resulting AccessibilityAction's label/action will be the label/action of the outermost
* modifier with this key and nonnull label/action, or null if no nonnull label/action is found.
*/
class AccessibilityAction<T : Function<Boolean>>(val label: String?, val action: T?) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AccessibilityAction<*>) return false
if (label != other.label) return false
if (action != other.action) return false
return true
}
override fun hashCode(): Int {
var result = label?.hashCode() ?: 0
result = 31 * result + action.hashCode()
return result
}
override fun toString(): String {
return "AccessibilityAction(label=$label, action=$action)"
}
}
@Suppress("NOTHING_TO_INLINE")
// inline to break static initialization cycle issue
private inline fun <T : Function<Boolean>> ActionPropertyKey(
name: String
): SemanticsPropertyKey<AccessibilityAction<T>> {
return SemanticsPropertyKey(
name = name,
mergePolicy = { parentValue, childValue ->
AccessibilityAction(
parentValue?.label ?: childValue.label,
parentValue?.action ?: childValue.action
)
}
)
}
/**
* Custom accessibility action.
*
* @param label The description of this action
* @param action The function to invoke when this action is performed. The function should have no
* arguments and return a boolean result indicating whether the action is successfully handled.
*/
class CustomAccessibilityAction(val label: String, val action: () -> Boolean) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CustomAccessibilityAction) return false
if (label != other.label) return false
if (action != other.action) return false
return true
}
override fun hashCode(): Int {
var result = label.hashCode()
result = 31 * result + action.hashCode()
return result
}
override fun toString(): String {
return "CustomAccessibilityAction(label=$label, action=$action)"
}
}
/**
* Accessibility range information, to represent the status of a progress bar or
* seekable progress bar.
*
* @param current current value in the range. Must not be NaN.
* @param range range of this node
* @param steps if greater than `0`, specifies the number of discrete values, evenly distributed
* between across the whole value range. If `0`, any value from the range specified can be chosen.
* Cannot be less than `0`.
*/
class ProgressBarRangeInfo(
val current: Float,
val range: ClosedFloatingPointRange<Float>,
/*@IntRange(from = 0)*/
val steps: Int = 0
) {
init {
require(!current.isNaN()) { "current must not be NaN" }
}
companion object {
/**
* Accessibility range information to present indeterminate progress bar
*/
val Indeterminate = ProgressBarRangeInfo(0f, 0f..0f)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProgressBarRangeInfo) return false
if (current != other.current) return false
if (range != other.range) return false
if (steps != other.steps) return false
return true
}
override fun hashCode(): Int {
var result = current.hashCode()
result = 31 * result + range.hashCode()
result = 31 * result + steps
return result
}
override fun toString(): String {
return "ProgressBarRangeInfo(current=$current, range=$range, steps=$steps)"
}
}
/**
* Information about the collection.
*
* A collection of items has [rowCount] rows and [columnCount] columns.
* For example, a vertical list is a collection with one column, as many rows as the list items
* that are important for accessibility; A table is a collection with several rows and several
* columns.
*
* @param rowCount the number of rows in the collection, or -1 if unknown
* @param columnCount the number of columns in the collection, or -1 if unknown
*/
class CollectionInfo(val rowCount: Int, val columnCount: Int)
/**
* Information about the item of a collection.
*
* A collection item is contained in a collection, it starts at a given [rowIndex] and
* [columnIndex] in the collection, and spans one or more rows and columns. For example, a header
* of two related table columns starts at the first row and the first column, spans one row and
* two columns.
*
* @param rowIndex the index of the row at which item is located
* @param rowSpan the number of rows the item spans
* @param columnIndex the index of the column at which item is located
* @param columnSpan the number of columns the item spans
*/
class CollectionItemInfo(
val rowIndex: Int,
val rowSpan: Int,
val columnIndex: Int,
val columnSpan: Int
)
/**
* The scroll state of one axis if this node is scrollable.
*
* @param value current 0-based scroll position value (either in pixels, or lazy-item count)
* @param maxValue maximum bound for [value], or [Float.POSITIVE_INFINITY] if still unknown
* @param reverseScrolling for horizontal scroll, when this is `true`, 0 [value] will mean right,
* when`false`, 0 [value] will mean left. For vertical scroll, when this is `true`, 0 [value] will
* mean bottom, when `false`, 0 [value] will mean top
*/
class ScrollAxisRange(
val value: () -> Float,
val maxValue: () -> Float,
val reverseScrolling: Boolean = false
) {
override fun toString(): String =
"ScrollAxisRange(value=${value()}, maxValue=${maxValue()}, " +
"reverseScrolling=$reverseScrolling)"
}
/**
* The type of user interface element. Accessibility services might use this to describe the
* element or do customizations. Most roles can be automatically resolved by the semantics
* properties of this element. But some elements with subtle differences need an exact role. If an
* exact role is not listed, [SemanticsPropertyReceiver.role] should not be set and the framework
* will automatically resolve it.
*/
@Immutable
@kotlin.jvm.JvmInline
value class Role private constructor(@Suppress("unused") private val value: Int) {
companion object {
/**
* This element is a button control. Associated semantics properties for accessibility:
* [SemanticsProperties.Disabled], [SemanticsActions.OnClick]
*/
val Button = Role(0)
/**
* This element is a Checkbox which is a component that represents two states (checked /
* unchecked). Associated semantics properties for accessibility:
* [SemanticsProperties.Disabled], [SemanticsProperties.StateDescription],
* [SemanticsActions.OnClick]
*/
val Checkbox = Role(1)
/**
* This element is a Switch which is a two state toggleable component that provides on/off
* like options. Associated semantics properties for accessibility:
* [SemanticsProperties.Disabled], [SemanticsProperties.StateDescription],
* [SemanticsActions.OnClick]
*/
val Switch = Role(2)
/**
* This element is a RadioButton which is a component to represent two states, selected and not
* selected. Associated semantics properties for accessibility: [SemanticsProperties.Disabled],
* [SemanticsProperties.StateDescription], [SemanticsActions.OnClick]
*/
val RadioButton = Role(3)
/**
* This element is a Tab which represents a single page of content using a text label and/or
* icon. A Tab also has two states: selected and not selected. Associated semantics properties
* for accessibility: [SemanticsProperties.Disabled], [SemanticsProperties.StateDescription],
* [SemanticsActions.OnClick]
*/
val Tab = Role(4)
/**
* This element is an image. Associated semantics properties for accessibility:
* [SemanticsProperties.ContentDescription]
*/
val Image = Role(5)
}
override fun toString() = when (this) {
Button -> "Button"
Checkbox -> "Checkbox"
Switch -> "Switch"
RadioButton -> "RadioButton"
Tab -> "Tab"
Image -> "Image"
else -> "Unknown"
}
}
/**
* The mode of live region. Live region indicates to accessibility services they should
* automatically notify the user about changes to the node's content description or text, or to
* the content descriptions or text of the node's children (where applicable).
*/
@Immutable
@kotlin.jvm.JvmInline
value class LiveRegionMode private constructor(@Suppress("unused") private val value: Int) {
companion object {
/**
* Live region mode specifying that accessibility services should announce
* changes to this node.
*/
val Polite = LiveRegionMode(0)
/**
* Live region mode specifying that accessibility services should interrupt
* ongoing speech to immediately announce changes to this node.
*/
val Assertive = LiveRegionMode(1)
}
override fun toString() = when (this) {
Polite -> "Polite"
Assertive -> "Assertive"
else -> "Unknown"
}
}
/**
* SemanticsPropertyReceiver is the scope provided by semantics {} blocks, letting you set
* key/value pairs primarily via extension functions.
*/
interface SemanticsPropertyReceiver {
operator fun <T> set(key: SemanticsPropertyKey<T>, value: T)
}
/**
* Developer-set content description of the semantics node.
*
* If this is not set, accessibility services will present the [text][SemanticsProperties.Text] of
* this node as the content.
*
* This typically should not be set directly by applications, because some screen readers will
* cease presenting other relevant information when this property is present. This is intended
* to be used via Foundation components which are inherently intractable to automatically
* describe, such as Image, Icon, and Canvas.
*/
var SemanticsPropertyReceiver.contentDescription: String
get() = throwSemanticsGetNotSupported()
set(value) { set(SemanticsProperties.ContentDescription, listOf(value)) }
/**
* Developer-set state description of the semantics node.
*
* For example: on/off. If this not set, accessibility services will derive the state from
* other semantics properties, like [ProgressBarRangeInfo], but it is not guaranteed and the format
* will be decided by accessibility services.
*/
var SemanticsPropertyReceiver.stateDescription by SemanticsProperties.StateDescription
/**
* The semantics is represents a range of possible values with a current value.
* For example, when used on a slider control, this will allow screen readers to communicate
* the slider's state.
*/
var SemanticsPropertyReceiver.progressBarRangeInfo by SemanticsProperties.ProgressBarRangeInfo
/**
* The node is marked as heading for accessibility.
*
* @see SemanticsProperties.Heading
*/
fun SemanticsPropertyReceiver.heading() {
this[SemanticsProperties.Heading] = Unit
}
/**
* Accessibility-friendly title for a screen's pane. For accessibility purposes, a pane is a
* visually distinct portion of a window, such as the contents of a open drawer. In order for
* accessibility services to understand a pane's window-like behavior, you should give
* descriptive titles to your app's panes. Accessibility services can then provide more granular
* information to users when a pane's appearance or content changes.
*
* @see SemanticsProperties.PaneTitle
*/
var SemanticsPropertyReceiver.paneTitle by SemanticsProperties.PaneTitle
/**
* Whether this semantics node is disabled. Note that proper [SemanticsActions] should still
* be added when this property is set.
*
* @see SemanticsProperties.Disabled
*/
fun SemanticsPropertyReceiver.disabled() {
this[SemanticsProperties.Disabled] = Unit
}
/**
* This node is marked as live region for accessibility. This indicates to accessibility services
* they should automatically notify the user about changes to the node's content description or
* text, or to the content descriptions or text of the node's children (where applicable). It
* should be used with caution, especially with assertive mode which immediately stops the
* current audio and the user does not hear the rest of the content. An example of proper use is
* a Snackbar which is marked as [LiveRegionMode.Polite].
*
* @see SemanticsProperties.LiveRegion
* @see LiveRegionMode
*/
var SemanticsPropertyReceiver.liveRegion by SemanticsProperties.LiveRegion
/**
* Whether this semantics node is focused. The presence of this property indicates this node is
* focusable
*
* @see SemanticsProperties.Focused
*/
var SemanticsPropertyReceiver.focused by SemanticsProperties.Focused
/**
* Whether this node is specially known to be invisible to the user.
*
* For example, if the node is currently occluded by a dark semitransparent
* pane above it, then for all practical purposes the node is invisible to the user,
* but the system cannot automatically determine that. To make the screen reader linear
* navigation skip over this type of invisible node, this property can be set.
*
* If looking for a way to hide semantics of small items from screen readers because they're
* redundant with semantics of their parent, consider [SemanticsModifier.clearAndSetSemantics]
* instead.
*/
@ExperimentalComposeUiApi
fun SemanticsPropertyReceiver.invisibleToUser() {
this[SemanticsProperties.InvisibleToUser] = Unit
}
/**
* The horizontal scroll state of this node if this node is scrollable.
*/
var SemanticsPropertyReceiver.horizontalScrollAxisRange
by SemanticsProperties.HorizontalScrollAxisRange
/**
* The vertical scroll state of this node if this node is scrollable.
*/
var SemanticsPropertyReceiver.verticalScrollAxisRange
by SemanticsProperties.VerticalScrollAxisRange
/**
* Whether this semantics node represents a Popup. Not to be confused with if this node is
* _part of_ a Popup.
*/
fun SemanticsPropertyReceiver.popup() {
this[SemanticsProperties.IsPopup] = Unit
}
/**
* Whether this element is a Dialog. Not to be confused with if this element is _part of_ a Dialog.
*/
fun SemanticsPropertyReceiver.dialog() {
this[SemanticsProperties.IsDialog] = Unit
}
/**
* The type of user interface element. Accessibility services might use this to describe the
* element or do customizations. Most roles can be automatically resolved by the semantics
* properties of this element. But some elements with subtle differences need an exact role. If
* an exact role is not listed in [Role], this property should not be set and the framework will
* automatically resolve it.
*/
var SemanticsPropertyReceiver.role by SemanticsProperties.Role
/**
* Test tag attached to this semantics node.
*
* This can be used to find nodes in testing frameworks:
* - In Compose's built-in unit test framework, use with
* [onNodeWithTag][androidx.compose.ui.test.onNodeWithTag].
* - For newer AccessibilityNodeInfo-based integration test frameworks, it can be matched in the
* extras with key "androidx.compose.ui.semantics.testTag"
* - For legacy AccessibilityNodeInfo-based integration tests, it's optionally exposed as the
* resource id if [testTagsAsResourceId] is true (for matching with 'By.res' in UIAutomator).
*/
var SemanticsPropertyReceiver.testTag by SemanticsProperties.TestTag
/**
* Text of the semantics node. It must be real text instead of developer-set content description.
*
* @see SemanticsPropertyReceiver.editableText
*/
var SemanticsPropertyReceiver.text: AnnotatedString
get() = throwSemanticsGetNotSupported()
set(value) { set(SemanticsProperties.Text, listOf(value)) }
/**
* Input text of the text field with visual transformation applied to it. It must be a real text
* entered by the user with visual transformation applied on top of the input text instead of a
* developer-set content description.
*/
var SemanticsPropertyReceiver.editableText by SemanticsProperties.EditableText
/**
* Text selection range for the text field.
*/
var SemanticsPropertyReceiver.textSelectionRange by SemanticsProperties.TextSelectionRange
/**
* Contains the IME action provided by the node.
*
* For example, "go to next form field" or "submit".
*/
var SemanticsPropertyReceiver.imeAction by SemanticsProperties.ImeAction
/**
* Whether this element is selected (out of a list of possible selections).
*
* The presence of this property indicates that the element is selectable.
*/
var SemanticsPropertyReceiver.selected by SemanticsProperties.Selected
/**
* This semantics marks node as a collection and provides the required information.
*
* @see collectionItemInfo
*/
var SemanticsPropertyReceiver.collectionInfo by SemanticsProperties.CollectionInfo
/**
* This semantics marks node as an items of a collection and provides the required information.
*
* If you mark items of a collection, you should also be marking the collection with
* [collectionInfo].
*/
var SemanticsPropertyReceiver.collectionItemInfo by SemanticsProperties.CollectionItemInfo
/**
* The state of a toggleable component.
*
* The presence of this property indicates that the element is toggleable.
*/
var SemanticsPropertyReceiver.toggleableState by SemanticsProperties.ToggleableState
/**
* The node is marked as a password.
*/
fun SemanticsPropertyReceiver.password() {
this[SemanticsProperties.Password] = Unit
}
/**
* Mark semantics node that contains invalid input or error.
*
* @param [description] a localized description explaining an error to the accessibility user
*/
fun SemanticsPropertyReceiver.error(description: String) {
this[SemanticsProperties.Error] = description
}
/**
* The index of an item identified by a given key. The key is usually defined during the creation
* of the container. If the key did not match any of the items' keys, the [mapping] must return -1.
*/
fun SemanticsPropertyReceiver.indexForKey(mapping: (Any) -> Int) {
this[SemanticsProperties.IndexForKey] = mapping
}
/**
* The node is marked as a collection of horizontally or vertically stacked selectable elements.
*
* Unlike [collectionInfo] which marks a collection of any elements and asks developer to
* provide all the required information like number of elements etc., this semantics will
* populate the number of selectable elements automatically. Note that if you use this semantics
* with lazy collections, it won't get the number of elements in the collection.
*
* @see SemanticsPropertyReceiver.selected
*/
fun SemanticsPropertyReceiver.selectableGroup() {
this[SemanticsProperties.SelectableGroup] = Unit
}
/**
* Custom actions which are defined by app developers.
*/
var SemanticsPropertyReceiver.customActions by SemanticsActions.CustomActions
/**
* Action to get a Text/TextField node's [TextLayoutResult]. The result is the first element
* of layout (the argument of the AccessibilityAction).
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.GetTextLayoutResult] is called.
*/
fun SemanticsPropertyReceiver.getTextLayoutResult(
label: String? = null,
action: ((MutableList<TextLayoutResult>) -> Boolean)?
) {
this[SemanticsActions.GetTextLayoutResult] = AccessibilityAction(label, action)
}
/**
* Action to be performed when the node is clicked (single-tapped).
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.OnClick] is called.
*/
fun SemanticsPropertyReceiver.onClick(label: String? = null, action: (() -> Boolean)?) {
this[SemanticsActions.OnClick] = AccessibilityAction(label, action)
}
/**
* Action to be performed when the node is long clicked (long-pressed).
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.OnLongClick] is called.
*/
fun SemanticsPropertyReceiver.onLongClick(label: String? = null, action: (() -> Boolean)?) {
this[SemanticsActions.OnLongClick] = AccessibilityAction(label, action)
}
/**
* Action to scroll by a specified amount.
*
* Expected to be used in conjunction with verticalScrollAxisRange/horizontalScrollAxisRange.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.ScrollBy] is called.
*/
fun SemanticsPropertyReceiver.scrollBy(
label: String? = null,
action: ((x: Float, y: Float) -> Boolean)?
) {
this[SemanticsActions.ScrollBy] = AccessibilityAction(label, action)
}
/**
* Action to scroll a container to the index of one of its items.
*
* The [action] should throw an [IllegalArgumentException] if the index is out of bounds.
*/
fun SemanticsPropertyReceiver.scrollToIndex(
label: String? = null,
action: (Int) -> Boolean
) {
this[SemanticsActions.ScrollToIndex] = AccessibilityAction(label, action)
}
/**
* Action to set the current value of the progress bar.
*
* Expected to be used in conjunction with progressBarRangeInfo.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.SetProgress] is called.
*/
fun SemanticsPropertyReceiver.setProgress(label: String? = null, action: ((Float) -> Boolean)?) {
this[SemanticsActions.SetProgress] = AccessibilityAction(label, action)
}
/**
* Action to set the text contents of this node.
*
* Expected to be used on editable text fields.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.SetText] is called.
*/
fun SemanticsPropertyReceiver.setText(
label: String? = null,
action: ((AnnotatedString) -> Boolean)?
) {
this[SemanticsActions.SetText] = AccessibilityAction(label, action)
}
/**
* Action to set text selection by character index range.
*
* If this action is provided, the selection data must be provided
* using [textSelectionRange].
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.SetSelection] is called.
*/
fun SemanticsPropertyReceiver.setSelection(
label: String? = null,
action: ((startIndex: Int, endIndex: Int, traversalMode: Boolean) -> Boolean)?
) {
this[SemanticsActions.SetSelection] = AccessibilityAction(label, action)
}
/**
* Action to copy the text to the clipboard.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.CopyText] is called.
*/
fun SemanticsPropertyReceiver.copyText(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.CopyText] = AccessibilityAction(label, action)
}
/**
* Action to cut the text and copy it to the clipboard.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.CutText] is called.
*/
fun SemanticsPropertyReceiver.cutText(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.CutText] = AccessibilityAction(label, action)
}
/**
* This function adds the [SemanticsActions.PasteText] to the [SemanticsPropertyReceiver].
* Use it to indicate that element is open for accepting paste data from the clipboard. There is
* no need to check if the clipboard data available as this is done by the framework.
* For this action to be triggered, the element must also have the [SemanticsProperties.Focused]
* property set.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.PasteText] is called.
*
* @see focused
*/
fun SemanticsPropertyReceiver.pasteText(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.PasteText] = AccessibilityAction(label, action)
}
/**
* Action to expand an expandable node.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.Expand] is called.
*/
fun SemanticsPropertyReceiver.expand(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.Expand] = AccessibilityAction(label, action)
}
/**
* Action to collapse an expandable node.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.Collapse] is called.
*/
fun SemanticsPropertyReceiver.collapse(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.Collapse] = AccessibilityAction(label, action)
}
/**
* Action to dismiss a dismissible node.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.Dismiss] is called.
*/
fun SemanticsPropertyReceiver.dismiss(
label: String? = null,
action: (() -> Boolean)?
) {
this[SemanticsActions.Dismiss] = AccessibilityAction(label, action)
}
/**
* Action that gives input focus to this node.
*
* @param label Optional label for this action.
* @param action Action to be performed when the [SemanticsActions.RequestFocus] is called.
*/
fun SemanticsPropertyReceiver.requestFocus(label: String? = null, action: (() -> Boolean)?) {
this[SemanticsActions.RequestFocus] = AccessibilityAction(label, action)
}
| apache-2.0 | 7f4806e257ebdf17b2e2bcf15cd47584 | 33.555046 | 103 | 0.707713 | 4.637405 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/src/androidMain/kotlin/androidx/compose/foundation/layout/WindowInsetsPadding.android.kt | 3 | 11530 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.layout
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.debugInspectorInfo
/**
* Adds padding to accommodate the [safe drawing][WindowInsets.Companion.safeDrawing] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.safeDrawing] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [statusBarsPadding], the area that the parent
* pads for the status bars will not be padded again by this [safeDrawingPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.safeDrawingPaddingSample
*/
fun Modifier.safeDrawingPadding() =
windowInsetsPadding(debugInspectorInfo { name = "safeDrawingPadding" }) { safeDrawing }
/**
* Adds padding to accommodate the [safe gestures][WindowInsets.Companion.safeGestures] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.safeGestures] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [navigationBarsPadding],
* the area that the parent layout pads for the status bars will not be padded again by this
* [safeGesturesPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.safeGesturesPaddingSample
*/
fun Modifier.safeGesturesPadding() =
windowInsetsPadding(debugInspectorInfo { name = "safeGesturesPadding" }) { safeGestures }
/**
* Adds padding to accommodate the [safe content][WindowInsets.Companion.safeContent] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.safeContent] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [navigationBarsPadding],
* the area that the parent layout pads for the status bars will not be padded again by this
* [safeContentPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.safeContentPaddingSample
*/
fun Modifier.safeContentPadding() =
windowInsetsPadding(debugInspectorInfo { name = "safeContentPadding" }) { safeContent }
/**
* Adds padding to accommodate the [system bars][WindowInsets.Companion.systemBars] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.systemBars] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [statusBarsPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [systemBarsPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.systemBarsPaddingSample
*/
fun Modifier.systemBarsPadding() =
windowInsetsPadding(debugInspectorInfo { name = "systemBarsPadding" }) { systemBars }
/**
* Adds padding to accommodate the [display cutout][WindowInsets.Companion.displayCutout].
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.displayCutout] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [statusBarsPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [displayCutoutPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.displayCutoutPaddingSample
*/
fun Modifier.displayCutoutPadding() =
windowInsetsPadding(debugInspectorInfo { name = "displayCutoutPadding" }) { displayCutout }
/**
* Adds padding to accommodate the [status bars][WindowInsets.Companion.statusBars] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.statusBars] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [displayCutoutPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [statusBarsPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.statusBarsAndNavigationBarsPaddingSample
*/
fun Modifier.statusBarsPadding() =
windowInsetsPadding(debugInspectorInfo { name = "statusBarsPadding" }) { statusBars }
/**
* Adds padding to accommodate the [ime][WindowInsets.Companion.ime] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.ime] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [navigationBarsPadding],
* the area that the parent layout pads for the status bars will not be padded again by this
* [imePadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.imePaddingSample
*/
fun Modifier.imePadding() =
windowInsetsPadding(debugInspectorInfo { name = "imePadding" }) { ime }
/**
* Adds padding to accommodate the [navigation bars][WindowInsets.Companion.navigationBars] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.navigationBars] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [systemBarsPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [navigationBarsPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.statusBarsAndNavigationBarsPaddingSample
*/
fun Modifier.navigationBarsPadding() =
windowInsetsPadding(debugInspectorInfo { name = "navigationBarsPadding" }) { navigationBars }
/**
* Adds padding to accommodate the [caption bar][WindowInsets.Companion.captionBar] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.captionBar] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [displayCutoutPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [captionBarPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.captionBarPaddingSample
*/
fun Modifier.captionBarPadding() =
windowInsetsPadding(debugInspectorInfo { name = "captionBarPadding" }) { captionBar }
/**
* Adds padding to accommodate the [waterfall][WindowInsets.Companion.waterfall] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.waterfall] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [systemGesturesPadding],
* the area that the parent layout pads for the status bars will not be padded again by this
* [waterfallPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.waterfallPaddingSample
*/
fun Modifier.waterfallPadding() =
windowInsetsPadding(debugInspectorInfo { name = "waterfallPadding" }) { waterfall }
/**
* Adds padding to accommodate the [system gestures][WindowInsets.Companion.systemGestures] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.systemGestures] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [waterfallPadding], the
* area that the parent layout pads for the status bars will not be padded again by this
* [systemGesturesPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.systemGesturesPaddingSample
*/
fun Modifier.systemGesturesPadding() =
windowInsetsPadding(debugInspectorInfo { name = "systemGesturesPadding" }) { systemGestures }
/**
* Adds padding to accommodate the
* [mandatory system gestures][WindowInsets.Companion.mandatorySystemGestures] insets.
*
* Any insets consumed by other insets padding modifiers or [consumedWindowInsets] on a parent layout
* will be excluded from the padding. [WindowInsets.Companion.mandatorySystemGestures] will be
* [consumed][consumedWindowInsets] for child layouts as well.
*
* For example, if a parent layout uses [navigationBarsPadding],
* the area that the parent layout pads for the status bars will not be padded again by this
* [mandatorySystemGesturesPadding] modifier.
*
* When used, the [WindowInsets][android.view.WindowInsets] will be consumed.
*
* @sample androidx.compose.foundation.layout.samples.mandatorySystemGesturesPaddingSample
*/
fun Modifier.mandatorySystemGesturesPadding() =
windowInsetsPadding(debugInspectorInfo { name = "mandatorySystemGesturesPadding" }) {
mandatorySystemGestures
}
@Suppress("NOTHING_TO_INLINE", "ModifierInspectorInfo")
@Stable
private inline fun Modifier.windowInsetsPadding(
noinline inspectorInfo: InspectorInfo.() -> Unit,
crossinline insetsCalculation: WindowInsetsHolder.() -> WindowInsets
): Modifier = composed(inspectorInfo) {
val composeInsets = WindowInsetsHolder.current()
remember(composeInsets) {
val insets = composeInsets.insetsCalculation()
InsetsPaddingModifier(insets)
}
} | apache-2.0 | 1d7b2eb5883ca02d73b032945b94f84c | 44.219608 | 101 | 0.77294 | 4.4569 | false | false | false | false |
yschimke/okhttp | okhttp/src/commonTest/kotlin/okhttp3/HeadersTest.kt | 1 | 9417 | /*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import kotlin.test.Test
import kotlin.test.fail
import okhttp3.Headers.Companion.headersOf
import okhttp3.Headers.Companion.toHeaders
class HeadersTest {
@Test fun ofTrims() {
val headers = headersOf("\t User-Agent \n", " \r OkHttp ")
assertThat(headers.name(0)).isEqualTo("User-Agent")
assertThat(headers.value(0)).isEqualTo("OkHttp")
}
@Test fun ofThrowsOddNumberOfHeaders() {
try {
headersOf("User-Agent", "OkHttp", "Content-Length")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofThrowsOnEmptyName() {
try {
headersOf("", "OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofAcceptsEmptyValue() {
val headers = headersOf("User-Agent", "")
assertThat(headers.value(0)).isEqualTo("")
}
@Test fun ofMakesDefensiveCopy() {
val namesAndValues = arrayOf(
"User-Agent",
"OkHttp"
)
val headers = headersOf(*namesAndValues)
namesAndValues[1] = "Chrome"
assertThat(headers.value(0)).isEqualTo("OkHttp")
}
@Test fun ofRejectsNullChar() {
try {
headersOf("User-Agent", "Square\u0000OkHttp")
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapThrowsOnEmptyName() {
try {
mapOf("" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapThrowsOnBlankName() {
try {
mapOf(" " to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapAcceptsEmptyValue() {
val headers = mapOf("User-Agent" to "").toHeaders()
assertThat(headers.value(0)).isEqualTo("")
}
@Test fun ofMapTrimsKey() {
val headers = mapOf(" User-Agent " to "OkHttp").toHeaders()
assertThat(headers.name(0)).isEqualTo("User-Agent")
}
@Test fun ofMapTrimsValue() {
val headers = mapOf("User-Agent" to " OkHttp ").toHeaders()
assertThat(headers.value(0)).isEqualTo("OkHttp")
}
@Test fun ofMapMakesDefensiveCopy() {
val namesAndValues = mutableMapOf<String, String>()
namesAndValues["User-Agent"] = "OkHttp"
val headers = namesAndValues.toHeaders()
namesAndValues["User-Agent"] = "Chrome"
assertThat(headers.value(0)).isEqualTo("OkHttp")
}
@Test fun ofMapRejectsNullCharInName() {
try {
mapOf("User-\u0000Agent" to "OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun ofMapRejectsNullCharInValue() {
try {
mapOf("User-Agent" to "Square\u0000OkHttp").toHeaders()
fail()
} catch (expected: IllegalArgumentException) {
}
}
@Test fun builderRejectsUnicodeInHeaderName() {
try {
Headers.Builder().add("héader1", "value1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun builderRejectsUnicodeInHeaderValue() {
try {
Headers.Builder().add("header1", "valué1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun varargFactoryRejectsUnicodeInHeaderName() {
try {
headersOf("héader1", "value1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun varargFactoryRejectsUnicodeInHeaderValue() {
try {
headersOf("header1", "valué1")
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun mapFactoryRejectsUnicodeInHeaderName() {
try {
mapOf("héader1" to "value1").toHeaders()
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 1 in header name: héader1")
}
}
@Test fun mapFactoryRejectsUnicodeInHeaderValue() {
try {
mapOf("header1" to "valué1").toHeaders()
fail("Should have complained about invalid value")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in header1 value: valué1")
}
}
@Test fun sensitiveHeadersNotIncludedInExceptions() {
try {
Headers.Builder().add("Authorization", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Authorization value")
}
try {
Headers.Builder().add("Cookie", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Cookie value")
}
try {
Headers.Builder().add("Proxy-Authorization", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Proxy-Authorization value")
}
try {
Headers.Builder().add("Set-Cookie", "valué1")
fail("Should have complained about invalid name")
} catch (expected: IllegalArgumentException) {
assertThat(expected.message)
.isEqualTo("Unexpected char 0xe9 at 4 in Set-Cookie value")
}
}
@Test fun headersEquals() {
val headers1 = Headers.Builder()
.add("Connection", "close")
.add("Transfer-Encoding", "chunked")
.build()
val headers2 = Headers.Builder()
.add("Connection", "close")
.add("Transfer-Encoding", "chunked")
.build()
assertThat(headers2).isEqualTo(headers1)
assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode())
}
@Test fun headersNotEquals() {
val headers1 = Headers.Builder()
.add("Connection", "close")
.add("Transfer-Encoding", "chunked")
.build()
val headers2 = Headers.Builder()
.add("Connection", "keep-alive")
.add("Transfer-Encoding", "chunked")
.build()
assertThat(headers2).isNotEqualTo(headers1)
assertThat(headers2.hashCode()).isNotEqualTo(headers1.hashCode().toLong())
}
@Test fun headersToString() {
val headers = Headers.Builder()
.add("A", "a")
.add("B", "bb")
.build()
assertThat(headers.toString()).isEqualTo("A: a\nB: bb\n")
}
@Test fun headersToStringRedactsSensitiveHeaders() {
val headers = Headers.Builder()
.add("content-length", "99")
.add("authorization", "peanutbutter")
.add("proxy-authorization", "chocolate")
.add("cookie", "drink=coffee")
.add("set-cookie", "accessory=sugar")
.add("user-agent", "OkHttp")
.build()
assertThat(headers.toString()).isEqualTo(
"""
|content-length: 99
|authorization: ██
|proxy-authorization: ██
|cookie: ██
|set-cookie: ██
|user-agent: OkHttp
|""".trimMargin()
)
}
@Test fun headersAddAll() {
val sourceHeaders = Headers.Builder()
.add("A", "aa")
.add("a", "aa")
.add("B", "bb")
.build()
val headers = Headers.Builder()
.add("A", "a")
.addAll(sourceHeaders)
.add("C", "c")
.build()
assertThat(headers.toString()).isEqualTo("A: a\nA: aa\na: aa\nB: bb\nC: c\n")
}
@Test fun nameIndexesAreStrict() {
val headers = Headers.headersOf("a", "b", "c", "d")
try {
headers.name(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
assertThat(headers.name(0)).isEqualTo("a")
assertThat(headers.name(1)).isEqualTo("c")
try {
headers.name(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
}
@Test fun valueIndexesAreStrict() {
val headers = Headers.headersOf("a", "b", "c", "d")
try {
headers.value(-1)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
assertThat(headers.value(0)).isEqualTo("b")
assertThat(headers.value(1)).isEqualTo("d")
try {
headers.value(2)
fail()
} catch (expected: IndexOutOfBoundsException) {
}
}
}
| apache-2.0 | ca721dd6b115942a5984c0057b1ad9b0 | 28.512579 | 81 | 0.644219 | 3.939966 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.