content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package graphics.scenery.backends.vulkan
import graphics.scenery.textures.Texture
import graphics.scenery.textures.Texture.BorderColor
import graphics.scenery.textures.UpdatableTexture.TextureExtents
import graphics.scenery.textures.Texture.RepeatMode
import graphics.scenery.textures.UpdatableTexture
import graphics.scenery.textures.UpdatableTexture.TextureUpdate
import graphics.scenery.utils.Image
import graphics.scenery.utils.LazyLogger
import net.imglib2.type.numeric.NumericType
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.DoubleType
import net.imglib2.type.numeric.real.FloatType
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.MemoryUtil.*
import org.lwjgl.vulkan.*
import org.lwjgl.vulkan.VK10.*
import org.lwjgl.vulkan.VkImageCreateInfo
import java.awt.color.ColorSpace
import java.awt.image.*
import java.io.FileInputStream
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.max
import kotlin.math.roundToLong
import kotlin.streams.toList
/**
* Vulkan Texture class. Creates a texture on the [device], with [width]x[height]x[depth],
* of [format], with a given number of [mipLevels]. Filtering can be set via
* [minFilterLinear] and [maxFilterLinear]. Needs to be supplied with a [queue] to execute
* generic operations on, and a [transferQueue] for transfer operations. Both are allowed to
* be the same.
*
* @author Ulrik Günther <[email protected]>
*/
open class VulkanTexture(val device: VulkanDevice,
val commandPools: VulkanRenderer.CommandPools, val queue: VkQueue, val transferQueue: VkQueue,
val width: Int, val height: Int, val depth: Int = 1,
val format: Int = VK_FORMAT_R8G8B8_SRGB, var mipLevels: Int = 1,
val minFilterLinear: Boolean = true, val maxFilterLinear: Boolean = true,
val usage: HashSet<Texture.UsageType> = hashSetOf(Texture.UsageType.Texture)) : AutoCloseable {
//protected val logger by LazyLogger()
private var initialised: Boolean = false
/** The Vulkan image associated with this texture. */
var image: VulkanImage
protected set
private var stagingImage: VulkanImage
private var gt: Texture? = null
var renderBarrier: VkImageMemoryBarrier? = null
protected set
/**
* Wrapper class for holding on to raw Vulkan [image]s backed by [memory].
*/
inner class VulkanImage(var image: Long = -1L, var memory: Long = -1L, val maxSize: Long = -1L) {
/** Raw Vulkan sampler. */
var sampler: Long = -1L
internal set
/** Raw Vulkan view. */
var view: Long = -1L
internal set
/**
* Copies the content of the image from [buffer]. This gets executed
* within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, buffer: VulkanBuffer, update: TextureUpdate? = null, bufferOffset: Long = 0) {
with(commandBuffer) {
val bufferImageCopy = VkBufferImageCopy.calloc(1)
bufferImageCopy.imageSubresource()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
bufferImageCopy.bufferOffset(bufferOffset)
if(update != null) {
bufferImageCopy.imageExtent().set(update.extents.w, update.extents.h, update.extents.d)
bufferImageCopy.imageOffset().set(update.extents.x, update.extents.y, update.extents.z)
} else {
bufferImageCopy.imageExtent().set(width, height, depth)
bufferImageCopy.imageOffset().set(0, 0, 0)
}
vkCmdCopyBufferToImage(this,
buffer.vulkanBuffer,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
bufferImageCopy)
bufferImageCopy.free()
}
update?.let {
it.consumed = true
}
}
/**
* Copies the content of the image to [buffer] from a series of [updates]. This gets executed
* within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, buffer: VulkanBuffer, updates: List<TextureUpdate>, bufferOffset: Long = 0) {
logger.debug("Got {} texture updates for {}", updates.size, this)
with(commandBuffer) {
val bufferImageCopy = VkBufferImageCopy.calloc(1)
var offset = bufferOffset
updates.forEach { update ->
val updateSize = update.contents.remaining()
bufferImageCopy.imageSubresource()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
bufferImageCopy.bufferOffset(offset)
bufferImageCopy.imageExtent().set(update.extents.w, update.extents.h, update.extents.d)
bufferImageCopy.imageOffset().set(update.extents.x, update.extents.y, update.extents.z)
vkCmdCopyBufferToImage(this,
buffer.vulkanBuffer,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
bufferImageCopy)
offset += updateSize
update.consumed = true
}
bufferImageCopy.free()
}
}
/**
* Copies the content of the image from a given [VulkanImage], [image].
* This gets executed within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, image: VulkanImage, extents: TextureExtents? = null) {
with(commandBuffer) {
val subresource = VkImageSubresourceLayers.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.mipLevel(0)
.layerCount(1)
val region = VkImageCopy.calloc(1)
.srcSubresource(subresource)
.dstSubresource(subresource)
if(extents != null) {
region.srcOffset().set(extents.x, extents.y, extents.z)
region.dstOffset().set(extents.x, extents.y, extents.z)
region.extent().set(extents.w, extents.h, extents.d)
} else {
region.srcOffset().set(0, 0, 0)
region.dstOffset().set(0, 0, 0)
region.extent().set(width, height, depth)
}
vkCmdCopyImage(this,
image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
region)
subresource.free()
region.free()
}
}
override fun toString(): String {
return "VulkanImage (${this.image.toHexString()}, ${width}x${height}x${depth}, format=$format, maxSize=${this.maxSize})"
}
}
init {
stagingImage = if(depth == 1) {
createImage(width, height, depth,
format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_TILING_LINEAR,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
mipLevels = 1
)
} else {
createImage(16, 16, 1,
format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_TILING_LINEAR,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
mipLevels = 1)
}
var usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT or VK_IMAGE_USAGE_SAMPLED_BIT or VK_IMAGE_USAGE_TRANSFER_SRC_BIT
if(device.formatFeatureSupported(format, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT, optimalTiling = true)) {
usage = usage or VK_IMAGE_USAGE_STORAGE_BIT
}
image = createImage(width, height, depth,
format, usage,
VK_IMAGE_TILING_OPTIMAL, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
mipLevels)
if (image.sampler == -1L) {
image.sampler = createSampler()
}
if (image.view == -1L) {
image.view = createImageView(image, format)
}
gt?.let { cache.put(it, this) }
}
/**
* Alternative constructor to create a [VulkanTexture] from a [Texture].
*/
constructor(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
texture: Texture, mipLevels: Int = 1) : this(device,
commandPools,
queue,
transferQueue,
texture.dimensions.x().toInt(),
texture.dimensions.y().toInt(),
texture.dimensions.z().toInt(),
texture.toVulkanFormat(),
mipLevels, texture.minFilter == Texture.FilteringMode.Linear, texture.maxFilter == Texture.FilteringMode.Linear, usage = texture.usageType) {
gt = texture
gt?.let { cache.put(it, this) }
}
/**
* Creates a Vulkan image of [format] with a given [width], [height], and [depth].
* [usage] and [memoryFlags] need to be given, as well as the [tiling] parameter and number of [mipLevels].
* A custom memory allocator may be used and given as [customAllocator].
*/
fun createImage(width: Int, height: Int, depth: Int, format: Int,
usage: Int, tiling: Int, memoryFlags: Int, mipLevels: Int,
initialLayout: Int? = null,
customAllocator: ((VkMemoryRequirements, Long) -> Long)? = null, imageCreateInfo: VkImageCreateInfo? = null): VulkanImage {
val imageInfo = if(imageCreateInfo != null) {
imageCreateInfo
} else {
val i = VkImageCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO)
.imageType(if (depth == 1) {
VK_IMAGE_TYPE_2D
} else {
VK_IMAGE_TYPE_3D
})
.mipLevels(mipLevels)
.arrayLayers(1)
.format(format)
.tiling(tiling)
.initialLayout(if(depth == 1) {VK_IMAGE_LAYOUT_PREINITIALIZED} else { VK_IMAGE_LAYOUT_UNDEFINED })
.usage(usage)
.sharingMode(VK_SHARING_MODE_EXCLUSIVE)
.samples(VK_SAMPLE_COUNT_1_BIT)
.flags(VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)
i.extent().set(width, height, depth)
i
}
if(initialLayout != null) {
imageInfo.initialLayout(initialLayout)
}
val image = VU.getLong("create staging image",
{ vkCreateImage(device.vulkanDevice, imageInfo, null, this) }, {})
val reqs = VkMemoryRequirements.calloc()
vkGetImageMemoryRequirements(device.vulkanDevice, image, reqs)
val memorySize = reqs.size()
val memory = if(customAllocator == null) {
val allocInfo = VkMemoryAllocateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
.pNext(NULL)
.allocationSize(memorySize)
.memoryTypeIndex(device.getMemoryType(reqs.memoryTypeBits(), memoryFlags).first())
VU.getLong("allocate image staging memory of size $memorySize",
{ vkAllocateMemory(device.vulkanDevice, allocInfo, null, this) },
{ imageInfo.free(); allocInfo.free() })
} else {
customAllocator.invoke(reqs, image)
}
reqs.free()
vkBindImageMemory(device.vulkanDevice, image, memory, 0)
return VulkanImage(image, memory, memorySize)
}
var tmpBuffer: VulkanBuffer? = null
/**
* Copies the data for this texture from a [ByteBuffer], [data].
*/
fun copyFrom(data: ByteBuffer): VulkanTexture {
if (depth == 1 && data.remaining() > stagingImage.maxSize) {
logger.warn("Allocated image size for $this (${stagingImage.maxSize}) less than copy source size ${data.remaining()}.")
return this
}
var deallocate = false
var sourceBuffer = data
gt?.let { gt ->
if (gt.channels == 3) {
logger.debug("Loading RGB texture, padding channels to 4 to fit RGBA")
val pixelByteSize = when (gt.type) {
is UnsignedByteType -> 1
is ByteType -> 1
is UnsignedShortType -> 2
is ShortType -> 2
is UnsignedIntType -> 4
is IntType -> 4
is FloatType -> 4
is DoubleType -> 8
else -> throw UnsupportedOperationException("Don't know how to handle textures of type ${gt.type.javaClass.simpleName}")
}
val storage = memAlloc(data.remaining() / 3 * 4)
val view = data.duplicate()
val tmp = ByteArray(pixelByteSize * 3)
val alpha = (0 until pixelByteSize).map { 255.toByte() }.toByteArray()
// pad buffer to 4 channels
while (view.hasRemaining()) {
view.get(tmp, 0, 3)
storage.put(tmp)
storage.put(alpha)
}
storage.flip()
deallocate = true
sourceBuffer = storage
} else {
deallocate = false
sourceBuffer = data
}
}
logger.debug("Updating {} with {} miplevels", this, mipLevels)
if (mipLevels == 1) {
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
if(!initialised) {
transitionLayout(stagingImage.image,
VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
}
if (depth == 1) {
val dest = memAllocPointer(1)
vkMapMemory(device, stagingImage.memory, 0, sourceBuffer.remaining() * 1L, 0, dest)
memCopy(memAddress(sourceBuffer), dest.get(0), sourceBuffer.remaining().toLong())
vkUnmapMemory(device, stagingImage.memory)
memFree(dest)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
image.copyFrom(this, stagingImage)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
} else {
val genericTexture = gt
val requiredCapacity = if(genericTexture is UpdatableTexture && genericTexture.hasConsumableUpdates()) {
genericTexture.getConsumableUpdates().map { it.contents.remaining() }.sum().toLong()
} else {
sourceBuffer.capacity().toLong()
}
logger.debug("{} has {} consumeable updates", this@VulkanTexture, (genericTexture as? UpdatableTexture)?.getConsumableUpdates()?.size)
if(tmpBuffer == null || (tmpBuffer?.size ?: 0) < requiredCapacity) {
logger.debug("(${this@VulkanTexture}) Reallocating tmp buffer, old size=${tmpBuffer?.size} new size = ${requiredCapacity.toFloat()/1024.0f/1024.0f} MiB")
tmpBuffer?.close()
// reserve a bit more space if the texture is small, to avoid reallocations
val reservedSize = if(requiredCapacity < 1024*1024*8) {
(requiredCapacity * 1.33).roundToLong()
} else {
requiredCapacity
}
tmpBuffer = VulkanBuffer([email protected],
max(reservedSize, 1024*1024),
VK_BUFFER_USAGE_TRANSFER_SRC_BIT or VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = false)
}
tmpBuffer?.let { buffer ->
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
if(genericTexture is UpdatableTexture) {
if(genericTexture.hasConsumableUpdates()) {
val contents = genericTexture.getConsumableUpdates().map { it.contents }
buffer.copyFrom(contents, keepMapped = true)
image.copyFrom(this, buffer, genericTexture.getConsumableUpdates())
genericTexture.clearConsumedUpdates()
} /*else {
// TODO: Semantics, do we want UpdateableTextures to be only
// updateable via updates, or shall they read from buffer on first init?
buffer.copyFrom(sourceBuffer)
image.copyFrom(this, buffer)
}*/
} else {
buffer.copyFrom(sourceBuffer)
image.copyFrom(this, buffer)
}
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
}
}
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
} else {
val buffer = VulkanBuffer(device,
sourceBuffer.limit().toLong(),
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
wantAligned = false)
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
buffer.copyFrom(sourceBuffer)
transitionLayout(image.image, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, commandBuffer = this,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT)
image.copyFrom(this, buffer)
transitionLayout(image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 1, commandBuffer = this,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT)
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
val imageBlit = VkImageBlit.calloc(1)
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) mipmapCreation@{
for (mipLevel in 1 until mipLevels) {
imageBlit.srcSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, mipLevel - 1, 0, 1)
imageBlit.srcOffsets(1).set(width shr (mipLevel - 1), height shr (mipLevel - 1), 1)
val dstWidth = width shr mipLevel
val dstHeight = height shr mipLevel
if (dstWidth < 2 || dstHeight < 2) {
break
}
imageBlit.dstSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, mipLevel, 0, 1)
imageBlit.dstOffsets(1).set(width shr (mipLevel), height shr (mipLevel), 1)
val mipSourceRange = VkImageSubresourceRange.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.layerCount(1)
.baseMipLevel(mipLevel - 1)
.levelCount(1)
val mipTargetRange = VkImageSubresourceRange.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.layerCount(1)
.baseMipLevel(mipLevel)
.levelCount(1)
if (mipLevel > 1) {
transitionLayout(image.image,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
subresourceRange = mipSourceRange,
srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this@mipmapCreation)
}
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
subresourceRange = mipTargetRange,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this@mipmapCreation)
vkCmdBlitImage(this@mipmapCreation,
image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
imageBlit, VK_FILTER_LINEAR)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange = mipSourceRange,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this@mipmapCreation)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange = mipTargetRange,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this@mipmapCreation)
mipSourceRange.free()
mipTargetRange.free()
}
[email protected]([email protected], commandPools.Standard, queue, flush = true, dealloc = true)
}
imageBlit.free()
buffer.close()
}
// deallocate in case we moved pixels around
if (deallocate) {
memFree(sourceBuffer)
}
// image.view = createImageView(image, format)
initialised = true
return this
}
/**
* Copies the first layer, first mipmap of the texture to [buffer].
*/
fun copyTo(buffer: ByteBuffer) {
if(tmpBuffer == null || (tmpBuffer != null && tmpBuffer?.size!! < image.maxSize)) {
tmpBuffer?.close()
tmpBuffer = VulkanBuffer([email protected],
image.maxSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT or VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = false)
}
tmpBuffer?.let { b ->
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
transitionLayout(image.image,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 1,
srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
val type = VK_IMAGE_ASPECT_COLOR_BIT
val subresource = VkImageSubresourceLayers.calloc()
.aspectMask(type)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
val regions = VkBufferImageCopy.calloc(1)
.bufferRowLength(0)
.bufferImageHeight(0)
.imageOffset(VkOffset3D.calloc().set(0, 0, 0))
.imageExtent(VkExtent3D.calloc().set(width, height, depth))
.imageSubresource(subresource)
vkCmdCopyImageToBuffer(
this,
image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
b.vulkanBuffer,
regions
)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 1,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
b.copyTo(buffer)
}
}
/**
* Creates a Vulkan image view with [format] for an [image].
*/
fun createImageView(image: VulkanImage, format: Int): Long {
if(image.view != -1L) {
vkDestroyImageView(device.vulkanDevice, image.view, null)
}
val subresourceRange = VkImageSubresourceRange.calloc().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, mipLevels, 0, 1)
val vi = VkImageViewCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
.pNext(NULL)
.image(image.image)
.viewType(if (depth > 1) {
VK_IMAGE_VIEW_TYPE_3D
} else {
VK_IMAGE_VIEW_TYPE_2D
})
.format(format)
.subresourceRange(subresourceRange)
if(gt?.channels == 1 && depth > 1) {
vi.components().set(VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R)
}
return VU.getLong("Creating image view",
{ vkCreateImageView(device.vulkanDevice, vi, null, this) },
{ vi.free(); subresourceRange.free(); })
}
private fun RepeatMode.toVulkan(): Int {
return when(this) {
RepeatMode.Repeat -> VK_SAMPLER_ADDRESS_MODE_REPEAT
RepeatMode.MirroredRepeat -> VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT
RepeatMode.ClampToEdge -> VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
RepeatMode.ClampToBorder -> VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER
}
}
private fun BorderColor.toVulkan(type: NumericType<*>): Int {
var color = when(this) {
BorderColor.TransparentBlack -> VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK
BorderColor.OpaqueBlack -> VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK
BorderColor.OpaqueWhite -> VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE
}
if(type !is FloatType) {
color += 1
}
return color
}
/**
* Creates a default sampler for this texture.
*/
fun createSampler(texture: Texture? = null): Long {
val t = texture ?: gt
val (repeatS, repeatT, repeatU) = if(t != null) {
Triple(
t.repeatUVW.first.toVulkan(),
t.repeatUVW.second.toVulkan(),
t.repeatUVW.third.toVulkan()
)
} else {
if(depth == 1) {
Triple(VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT)
} else {
Triple(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
}
}
val samplerInfo = VkSamplerCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO)
.pNext(NULL)
.magFilter(if(minFilterLinear) { VK_FILTER_LINEAR } else { VK_FILTER_NEAREST })
.minFilter(if(maxFilterLinear) { VK_FILTER_LINEAR } else { VK_FILTER_NEAREST })
.mipmapMode(if(depth == 1) { VK_SAMPLER_MIPMAP_MODE_LINEAR } else { VK_SAMPLER_MIPMAP_MODE_NEAREST })
.addressModeU(repeatS)
.addressModeV(repeatT)
.addressModeW(repeatU)
.mipLodBias(0.0f)
.anisotropyEnable(depth == 1)
.maxAnisotropy(if(depth == 1) { 8.0f } else { 1.0f })
.minLod(0.0f)
.maxLod(if(depth == 1) {mipLevels * 1.0f} else { 0.0f })
.borderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE)
.compareOp(VK_COMPARE_OP_NEVER)
if(t != null) {
samplerInfo.borderColor(t.borderColor.toVulkan(t.type))
}
val sampler = VU.getLong("creating sampler",
{ vkCreateSampler(device.vulkanDevice, samplerInfo, null, this) },
{ samplerInfo.free() })
logger.debug("Created sampler {}", sampler.toHexString().toLowerCase())
val oldSampler = image.sampler
image.sampler = sampler
if(oldSampler != -1L) {
vkDestroySampler(device.vulkanDevice, oldSampler, null)
}
return sampler
}
override fun toString(): String {
return "VulkanTexture on $device (${this.image.image.toHexString()}, ${width}x${height}x$depth, format=${this.format}, mipLevels=${mipLevels}, gt=${this.gt != null} minFilter=${this.minFilterLinear} maxFilter=${this.maxFilterLinear})"
}
/**
* Deallocates and destroys this [VulkanTexture] instance, freeing all memory
* related to it.
*/
override fun close() {
gt?.let { cache.remove(it) }
if (image.view != -1L) {
vkDestroyImageView(device.vulkanDevice, image.view, null)
image.view = -1L
}
if (image.image != -1L) {
vkDestroyImage(device.vulkanDevice, image.image, null)
image.image = -1L
}
if (image.sampler != -1L) {
vkDestroySampler(device.vulkanDevice, image.sampler, null)
image.sampler = -1L
}
if (image.memory != -1L) {
vkFreeMemory(device.vulkanDevice, image.memory, null)
image.memory = -1L
}
if (stagingImage.image != -1L) {
vkDestroyImage(device.vulkanDevice, stagingImage.image, null)
stagingImage.image = -1L
}
if (stagingImage.memory != -1L) {
vkFreeMemory(device.vulkanDevice, stagingImage.memory, null)
stagingImage.memory = -1L
}
tmpBuffer?.close()
}
/**
* Utility methods for [VulkanTexture].
*/
companion object {
@JvmStatic private val logger by LazyLogger()
private val cache = HashMap<Texture, VulkanTexture>()
private val StandardAlphaColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 8),
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE)
private val StandardColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 0),
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE)
fun getReference(texture: Texture): VulkanTexture? {
return cache.get(texture)
}
/**
* Loads a texture from a file given by [filename], and allocates the [VulkanTexture] on [device].
*/
fun loadFromFile(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools , queue: VkQueue, transferQueue: VkQueue,
filename: String,
linearMin: Boolean, linearMax: Boolean,
generateMipmaps: Boolean = true): VulkanTexture {
val stream = FileInputStream(filename)
val type = filename.substringAfterLast('.')
logger.debug("Loading${if(generateMipmaps) { " mipmapped" } else { "" }} texture from $filename")
return if(type == "raw") {
val path = Paths.get(filename)
val infoFile = path.resolveSibling(path.fileName.toString().substringBeforeLast(".") + ".info")
val dimensions = Files.lines(infoFile).toList().first().split(",").map { it.toLong() }.toLongArray()
loadFromFileRaw(device,
commandPools, queue, transferQueue,
stream, type, dimensions)
} else {
loadFromFile(device,
commandPools, queue, transferQueue,
stream, type, linearMin, linearMax, generateMipmaps)
}
}
/**
* Loads a texture from a file given by a [stream], and allocates the [VulkanTexture] on [device].
*/
fun loadFromFile(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
stream: InputStream, type: String,
linearMin: Boolean, linearMax: Boolean,
generateMipmaps: Boolean = true): VulkanTexture {
val image = Image.fromStream(stream, type, true)
var texWidth = 2
var texHeight = 2
var levelsW = 1
var levelsH = 1
while (texWidth < image.width) {
texWidth *= 2
levelsW++
}
while (texHeight < image.height) {
texHeight *= 2
levelsH++
}
val mipmapLevels = if(generateMipmaps) {
Math.min(levelsW, levelsH)
} else {
1
}
val tex = VulkanTexture(
device,
commandPools, queue, transferQueue,
texWidth, texHeight, 1,
VK_FORMAT_R8G8B8A8_SRGB,
mipmapLevels,
linearMin, linearMax)
tex.copyFrom(image.contents)
return tex
}
/**
* Loads a texture from a raw file given by a [stream], and allocates the [VulkanTexture] on [device].
*/
@Suppress("UNUSED_PARAMETER")
fun loadFromFileRaw(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
stream: InputStream, type: String, dimensions: LongArray): VulkanTexture {
val imageData: ByteBuffer = ByteBuffer.allocateDirect((2 * dimensions[0] * dimensions[1] * dimensions[2]).toInt())
val buffer = ByteArray(1024*1024)
var bytesRead = stream.read(buffer)
while(bytesRead > -1) {
imageData.put(buffer)
bytesRead = stream.read(buffer)
}
val tex = VulkanTexture(
device,
commandPools, queue, transferQueue,
dimensions[0].toInt(), dimensions[1].toInt(), dimensions[2].toInt(),
VK_FORMAT_R16_UINT, 1, true, true)
tex.copyFrom(imageData)
stream.close()
return tex
}
/**
* Transitions Vulkan image layouts, with [srcAccessMask] and [dstAccessMask] explicitly specified.
*/
fun transitionLayout(image: Long, from: Int, to: Int, mipLevels: Int = 1,
subresourceRange: VkImageSubresourceRange? = null,
srcStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dstStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
srcAccessMask: Int, dstAccessMask: Int,
commandBuffer: VkCommandBuffer, dependencyFlags: Int = 0, memoryBarrier: Boolean = false) {
stackPush().use { stack ->
val barrier = VkImageMemoryBarrier.callocStack(1, stack)
.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
.pNext(NULL)
.oldLayout(from)
.newLayout(to)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.srcAccessMask(srcAccessMask)
.dstAccessMask(dstAccessMask)
.image(image)
if (subresourceRange == null) {
barrier.subresourceRange()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseMipLevel(0)
.levelCount(mipLevels)
.baseArrayLayer(0)
.layerCount(1)
} else {
barrier.subresourceRange(subresourceRange)
}
logger.trace("Transition: {} -> {} with srcAccessMark={}, dstAccessMask={}, srcStage={}, dstStage={}", from, to, barrier.srcAccessMask(), barrier.dstAccessMask(), srcStage, dstStage)
val memoryBarriers = if(memoryBarrier) {
VkMemoryBarrier.callocStack(1, stack)
.sType(VK_STRUCTURE_TYPE_MEMORY_BARRIER)
.srcAccessMask(srcAccessMask)
.dstAccessMask(dstAccessMask)
} else {
null
}
vkCmdPipelineBarrier(
commandBuffer,
srcStage,
dstStage,
dependencyFlags,
memoryBarriers,
null,
barrier
)
}
}
/**
* Transitions Vulkan image layouts.
*/
fun transitionLayout(image: Long, oldLayout: Int, newLayout: Int, mipLevels: Int = 1,
subresourceRange: VkImageSubresourceRange? = null,
srcStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dstStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
commandBuffer: VkCommandBuffer) {
with(commandBuffer) {
val barrier = VkImageMemoryBarrier.calloc(1)
.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
.pNext(NULL)
.oldLayout(oldLayout)
.newLayout(newLayout)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.image(image)
if (subresourceRange == null) {
barrier.subresourceRange()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseMipLevel(0)
.levelCount(mipLevels)
.baseArrayLayer(0)
.layerCount(1)
} else {
barrier.subresourceRange(subresourceRange)
}
if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_HOST_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_HOST_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
if(dstStage == VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) {
barrier.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)
} else {
barrier.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
}
} else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier
.srcAccessMask(0)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
barrier.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
} else if(oldLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_MEMORY_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_MEMORY_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(0)
.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_SHADER_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_INPUT_ATTACHMENT_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else {
logger.error("Unsupported layout transition: $oldLayout -> $newLayout")
}
logger.trace("Transition: {} -> {} with srcAccessMark={}, dstAccessMask={}, srcStage={}, dstStage={}", oldLayout, newLayout, barrier.srcAccessMask(), barrier.dstAccessMask(), srcStage, dstStage)
vkCmdPipelineBarrier(this,
srcStage,
dstStage,
0, null, null, barrier)
barrier.free()
}
}
private fun Texture.toVulkanFormat(): Int {
var format = when(this.type) {
is ByteType -> when(this.channels) {
1 -> VK_FORMAT_R8_SNORM
2 -> VK_FORMAT_R8G8_SNORM
3 -> VK_FORMAT_R8G8B8A8_SNORM
4 -> VK_FORMAT_R8G8B8A8_SNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedByteType -> when(this.channels) {
1 -> VK_FORMAT_R8_UNORM
2 -> VK_FORMAT_R8G8_UNORM
3 -> VK_FORMAT_R8G8B8A8_UNORM
4 -> VK_FORMAT_R8G8B8A8_UNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is ShortType -> when(this.channels) {
1 -> VK_FORMAT_R16_SNORM
2 -> VK_FORMAT_R16G16_SNORM
3 -> VK_FORMAT_R16G16B16A16_SNORM
4 -> VK_FORMAT_R16G16B16A16_SNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedShortType -> when(this.channels) {
1 -> VK_FORMAT_R16_UNORM
2 -> VK_FORMAT_R16G16_UNORM
3 -> VK_FORMAT_R16G16B16A16_UNORM
4 -> VK_FORMAT_R16G16B16A16_UNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is IntType -> when(this.channels) {
1 -> VK_FORMAT_R32_SINT
2 -> VK_FORMAT_R32G32_SINT
3 -> VK_FORMAT_R32G32B32A32_SINT
4 -> VK_FORMAT_R32G32B32A32_SINT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedIntType -> when(this.channels) {
1 -> VK_FORMAT_R32_UINT
2 -> VK_FORMAT_R32G32_UINT
3 -> VK_FORMAT_R32G32B32A32_UINT
4 -> VK_FORMAT_R32G32B32A32_UINT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is FloatType -> when(this.channels) {
1 -> VK_FORMAT_R32_SFLOAT
2 -> VK_FORMAT_R32G32_SFLOAT
3 -> VK_FORMAT_R32G32B32A32_SFLOAT
4 -> VK_FORMAT_R32G32B32A32_SFLOAT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is DoubleType -> TODO("Double format textures are not supported")
else -> throw UnsupportedOperationException("Type ${type.javaClass.simpleName} is not supported")
}
if(!this.normalized && this.type !is FloatType && this.type !is ByteType && this.type !is IntType) {
format += 4
}
return format
}
}
}
| src/main/kotlin/graphics/scenery/backends/vulkan/VulkanTexture.kt | 2250653205 |
/*
* 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.fhir.datacapture.contrib.views.barcode.mlkit.md.camera
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
/** Custom animator for the object or barcode reticle in live camera. */
class CameraReticleAnimator(graphicOverlay: GraphicOverlay) {
/** Returns the scale value of ripple alpha ranges in [0, 1]. */
var rippleAlphaScale = 0f
private set
/** Returns the scale value of ripple size ranges in [0, 1]. */
var rippleSizeScale = 0f
private set
/** Returns the scale value of ripple stroke width ranges in [0, 1]. */
var rippleStrokeWidthScale = 1f
private set
private val animatorSet: AnimatorSet
init {
val rippleFadeInAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_FADE_IN_MS)
rippleFadeInAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleFadeOutAnimator =
ValueAnimator.ofFloat(1f, 0f).setDuration(DURATION_RIPPLE_FADE_OUT_MS)
rippleFadeOutAnimator.startDelay = START_DELAY_RIPPLE_FADE_OUT_MS
rippleFadeOutAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleExpandAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_EXPAND_MS)
rippleExpandAnimator.startDelay = START_DELAY_RIPPLE_EXPAND_MS
rippleExpandAnimator.interpolator = FastOutSlowInInterpolator()
rippleExpandAnimator.addUpdateListener { animation ->
rippleSizeScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleStrokeWidthShrinkAnimator =
ValueAnimator.ofFloat(1f, 0.5f).setDuration(DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS)
rippleStrokeWidthShrinkAnimator.startDelay = START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS
rippleStrokeWidthShrinkAnimator.interpolator = FastOutSlowInInterpolator()
rippleStrokeWidthShrinkAnimator.addUpdateListener { animation ->
rippleStrokeWidthScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val fakeAnimatorForRestartDelay =
ValueAnimator.ofInt(0, 0).setDuration(DURATION_RESTART_DORMANCY_MS)
fakeAnimatorForRestartDelay.startDelay = START_DELAY_RESTART_DORMANCY_MS
animatorSet = AnimatorSet()
animatorSet.playTogether(
rippleFadeInAnimator,
rippleFadeOutAnimator,
rippleExpandAnimator,
rippleStrokeWidthShrinkAnimator,
fakeAnimatorForRestartDelay
)
}
fun start() {
if (!animatorSet.isRunning) animatorSet.start()
}
fun cancel() {
animatorSet.cancel()
rippleAlphaScale = 0f
rippleSizeScale = 0f
rippleStrokeWidthScale = 1f
}
companion object {
private const val DURATION_RIPPLE_FADE_IN_MS: Long = 333
private const val DURATION_RIPPLE_FADE_OUT_MS: Long = 500
private const val DURATION_RIPPLE_EXPAND_MS: Long = 833
private const val DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 833
private const val DURATION_RESTART_DORMANCY_MS: Long = 1333
private const val START_DELAY_RIPPLE_FADE_OUT_MS: Long = 667
private const val START_DELAY_RIPPLE_EXPAND_MS: Long = 333
private const val START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 333
private const val START_DELAY_RESTART_DORMANCY_MS: Long = 1167
}
}
| contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/camera/CameraReticleAnimator.kt | 657330920 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package vulkan
import org.lwjgl.generator.*
import vulkan.templates.*
fun templateCustomization() {
PFN_vkDebugReportCallbackEXT.function.apply {
additionalCode = """
/**
* Converts the specified {@link VkDebugReportCallbackEXT} argument to a String.
*
* <p>This method may only be used inside a {@code VkDebugReportCallbackEXT} invocation.</p>
*
* @param string the argument to decode
*
* @return the message as a String
*/
public static String getString(long string) {
return memUTF8(string);
}
"""
}
VkShaderModuleCreateInfo.definition.apply {
AutoSize("pCode")..this["codeSize"]
PrimitiveType("uint32_t", PrimitiveMapping.BYTE).const.p("pCode", "points to code that is used to create the shader module")
.replace(this["pCode"])
}
VK10.apply {
IntConstant(
"""
The API version number for Vulkan 1.0.
The patch version number in this macro will always be zero. The supported patch version for a physical device <b>can</b> be queried with
#GetPhysicalDeviceProperties().
""",
"API_VERSION_1_0".."VK_MAKE_API_VERSION(0, 1, 0, 0)"
)
IntConstant(
"The Vulkan registry version used to generate the LWJGL bindings.",
"HEADER_VERSION".."228"
)
LongConstant(
"""
The reserved handle {@code VK_NULL_HANDLE} <b>can</b> be passed in place of valid object handles when explicitly called out in the specification. Any
command that creates an object successfully <b>must</b> not return {@code VK_NULL_HANDLE}. It is valid to pass {@code VK_NULL_HANDLE} to any
{@code vkDestroy*} or {@code vkFree*} command, which will silently ignore these values.
""",
"NULL_HANDLE"..0L
)
macro(expression = "(variant << 29) | (major << 22) | (minor << 12) | patch")..uint32_t(
"VK_MAKE_API_VERSION",
"""
Constructs an API version number.
This macro <b>can</b> be used when constructing the ##VkApplicationInfo{@code ::pname:apiVersion} parameter passed to #CreateInstance().
""",
uint32_t("variant", "the variant number"),
uint32_t("major", "the major version number"),
uint32_t("minor", "the minor version number"),
uint32_t("patch", "the patch version number"),
noPrefix = true
)
macro(expression = "version >>> 29")..uint32_t(
"VK_API_VERSION_VARIANT",
"Extracts the API variant version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 22) & 0x7F")..uint32_t(
"VK_API_VERSION_MAJOR",
"Extracts the API major version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 12) & 0x3FF")..uint32_t(
"VK_API_VERSION_MINOR",
"Extracts the API minor version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "version & 0xFFF")..uint32_t(
"VK_API_VERSION_PATCH",
"Extracts the API patch version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(major << 22) | (minor << 12) | patch")..uint32_t(
"VK_MAKE_VERSION",
"""
Constructs an API version number.
This macro <b>can</b> be used when constructing the ##VkApplicationInfo{@code ::pname:apiVersion} parameter passed to #CreateInstance().
<em>Deprecated</em>, #VK_MAKE_API_VERSION() should be used instead.
""",
uint32_t("major", "the major version number"),
uint32_t("minor", "the minor version number"),
uint32_t("patch", "the patch version number"),
noPrefix = true
)
macro(expression = "version >>> 22")..uint32_t(
"VK_VERSION_MAJOR",
"""
Extracts the API major version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_MAJOR() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 12) & 0x3FF")..uint32_t(
"VK_VERSION_MINOR",
"""
Extracts the API minor version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_MINOR() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "version & 0xFFF")..uint32_t(
"VK_VERSION_PATCH",
"""
Extracts the API patch version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_PATCH() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
IntConstant(
"API Constants",
"MAX_PHYSICAL_DEVICE_NAME_SIZE".."256",
"UUID_SIZE".."16",
"LUID_SIZE".."8",
"MAX_EXTENSION_NAME_SIZE".."256",
"MAX_DESCRIPTION_SIZE".."256",
"MAX_MEMORY_TYPES".."32",
"MAX_MEMORY_HEAPS".."16",
"REMAINING_MIP_LEVELS".."(~0)",
"REMAINING_ARRAY_LAYERS".."(~0)",
"ATTACHMENT_UNUSED".."(~0)",
"TRUE".."1",
"FALSE".."0",
"QUEUE_FAMILY_IGNORED".."(~0)",
"QUEUE_FAMILY_EXTERNAL".."(~0-1)",
"SUBPASS_EXTERNAL".."(~0)",
"MAX_DEVICE_GROUP_SIZE".."32",
"MAX_DRIVER_NAME_SIZE".."256",
"MAX_DRIVER_INFO_SIZE".."256"
)
FloatConstant(
"API Constants",
"LOD_CLAMP_NONE".."1000.0f"
)
LongConstant(
"API Constants",
"WHOLE_SIZE".."(~0L)"
)
nullable..this["GetInstanceProcAddr"].getParam("instance")
MultiType(
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG
)..this["GetQueryPoolResults"].getParam("pData")
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..this["CmdUpdateBuffer"].getParam("pData")
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..this["CmdPushConstants"].getParam("pValues")
SingleValue("pSubmit")..this["QueueSubmit"].getParam("pSubmits")
SingleValue("pMemoryRange")..this["FlushMappedMemoryRanges"].getParam("pMemoryRanges")
SingleValue("pMemoryRange")..this["InvalidateMappedMemoryRanges"].getParam("pMemoryRanges")
SingleValue("pBindInfo")..this["QueueBindSparse"].getParam("pBindInfo")
SingleValue("pFence")..this["ResetFences"].getParam("pFences")
SingleValue("pFence")..this["WaitForFences"].getParam("pFences")
SingleValue("pDescriptorSet")..this["FreeDescriptorSets"].getParam("pDescriptorSets")
SingleValue("pRange")..this["CmdClearColorImage"].getParam("pRanges")
SingleValue("pRange")..this["CmdClearDepthStencilImage"].getParam("pRanges")
SingleValue("pRegion")..this["CmdResolveImage"].getParam("pRegions")
SingleValue("pCommandBuffer")..this["CmdExecuteCommands"].getParam("pCommandBuffers")
SingleValue("pCommandBuffer")..this["FreeCommandBuffers"].getParam("pCommandBuffers")
}
VK11.apply {
documentation =
"""
The core Vulkan 1.1 functionality.
Vulkan Version 1.1 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_16bit_storage.link,
KHR_bind_memory2.link,
KHR_dedicated_allocation.link,
KHR_descriptor_update_template.link,
KHR_device_group.link,
KHR_device_group_creation.link,
KHR_external_memory.link,
KHR_external_memory_capabilities.link,
KHR_external_semaphore.link,
KHR_external_semaphore_capabilities.link,
KHR_external_fence.link,
KHR_external_fence_capabilities.link,
KHR_get_memory_requirements2.link,
KHR_get_physical_device_properties2.link,
KHR_maintenance1.link,
KHR_maintenance2.link,
KHR_maintenance3.link,
KHR_multiview.link,
KHR_relaxed_block_layout.link,
KHR_sampler_ycbcr_conversion.link,
KHR_shader_draw_parameters.link,
KHR_storage_buffer_storage_class.link,
KHR_variable_pointers.link
)}
The only changes to the functionality added by these extensions were to {@code VK_KHR_shader_draw_parameters}, which had a
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-features-shaderDrawParameters">feature bit</a>
added to determine support in the core API, and
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-features-variablePointersStorageBuffer">{@code variablePointersStorageBuffer}</a>
from {@code VK_KHR_variable_pointers} was made optional.
Additionally, Vulkan 1.1 added support for {@link VkPhysicalDeviceSubgroupProperties subgroup operations},
{@link VkPhysicalDeviceProtectedMemoryFeatures protected memory}, and a new command to {@link VK11\#vkEnumerateInstanceVersion enumerate the
instance version}.
"""
IntConstant(
"The API version number for Vulkan 1.1.",
"API_VERSION_1_1".."VK_MAKE_API_VERSION(0, 1, 1, 0)"
)
}
VK12.apply {
documentation =
"""
The core Vulkan 1.2 functionality.
Vulkan Version 1.2 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_8bit_storage.link,
KHR_buffer_device_address.link,
KHR_create_renderpass2.link,
KHR_depth_stencil_resolve.link,
KHR_draw_indirect_count.link,
KHR_driver_properties.link,
KHR_image_format_list.link,
KHR_imageless_framebuffer.link,
KHR_sampler_mirror_clamp_to_edge.link,
KHR_separate_depth_stencil_layouts.link,
KHR_shader_atomic_int64.link,
KHR_shader_float16_int8.link,
KHR_shader_float_controls.link,
KHR_shader_subgroup_extended_types.link,
KHR_spirv_1_4.link,
KHR_timeline_semaphore.link,
KHR_uniform_buffer_standard_layout.link,
KHR_vulkan_memory_model.link,
EXT_descriptor_indexing.link,
EXT_host_query_reset.link,
EXT_sampler_filter_minmax.link,
EXT_scalar_block_layout.link,
EXT_separate_stencil_usage.link,
EXT_shader_viewport_index_layer.link
)}
All differences in behavior between these extensions and the corresponding Vulkan 1.2 functionality are summarized below.
<h3>Differences relative to {@code VK_KHR_8bit_storage}</h3>
If the {@code VK_KHR_8bit_storage} extension is not supported, support for the SPIR-V {@code StorageBuffer8BitAccess} capability in shader modules
is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::storageBuffer8BitAccess} when queried via
#GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_KHR_draw_indirect_count}</h3>
If the {@code VK_KHR_draw_indirect_count} extension is not supported, support for the entry points #CmdDrawIndirectCount() and
#CmdDrawIndexedIndirectCount() is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::drawIndirectCount}
when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_KHR_sampler_mirror_clamp_to_edge}</h3>
If the {@code VK_KHR_sampler_mirror_clamp_to_edge} extension is not supported, support for the {@code VkSamplerAddressMode}
#SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE is optional. Support for this feature is defined by
##VkPhysicalDeviceVulkan12Features{@code ::samplerMirrorClampToEdge} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_descriptor_indexing}</h3>
If the {@code VK_EXT_descriptor_indexing} extension is not supported, support for the {@code descriptorIndexing} feature is optional. Support for
this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::descriptorIndexing} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_scalar_block_layout}</h3>
If the {@code VK_EXT_scalar_block_layout} extension is not supported, support for the {@code scalarBlockLayout} feature is optional. Support for
this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::scalarBlockLayout} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_shader_viewport_index_layer}</h3>
If the {@code VK_EXT_shader_viewport_index_layer} extension is not supported, support for the {@code ShaderViewportIndexLayerEXT} SPIR-V capability
is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::shaderOutputViewportIndex} and
##VkPhysicalDeviceVulkan12Features{@code ::shaderOutputLayer} when queried via #GetPhysicalDeviceFeatures2().
<h3>Additional Vulkan 1.2 Feature Support</h3>
In addition to the promoted extensions described above, Vulkan 1.2 added support for:
${ul(
"SPIR-V version 1.4.",
"SPIR-V version 1.5.",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-samplerMirrorClampToEdge">samplerMirrorClampToEdge</a>
feature which indicates whether the implementation supports the #SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE sampler address mode.
""",
"The {@code ShaderNonUniform} capability in SPIR-V version 1.5.",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-shaderOutputViewportIndex">shaderOutputViewportIndex</a>
feature which indicates that the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#spirvenv-capabilities-table-shader-viewport-index">{@code ShaderViewportIndex}</a>
capability can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-shaderOutputLayer">shaderOutputLayer</a>
feature which indicates that the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#spirvenv-capabilities-table-shader-layer">{@code ShaderLayer}</a>
capability can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-subgroupBroadcastDynamicId">subgroupBroadcastDynamicId</a>
feature which allows the "{@code Id}" operand of {@code OpGroupNonUniformBroadcast} to be dynamically uniform within a subgroup, and the
"{@code Index}" operand of {@code OpGroupNonUniformQuadBroadcast} to be dynamically uniform within a derivative group, in shader modules of
version 1.5 or higher.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-drawIndirectCount">drawIndirectCount</a>
feature which indicates whether the #CmdDrawIndirectCount() and #CmdDrawIndexedIndirectCount() functions can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-descriptorIndexing">descriptorIndexing</a>
feature which indicates the implementation supports the minimum number of descriptor indexing features as defined in the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-requirements">Feature Requirements</a>
section.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-samplerFilterMinmax">samplerFilterMinmax</a>
feature which indicates whether the implementation supports the minimum number of image formats that support the
#FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT feature bit as defined by the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#limits-filterMinmaxSingleComponentFormats-minimum-requirements">{@code filterMinmaxSingleComponentFormats}</a>
property minimum requirements.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#limits-framebufferIntegerColorSampleCounts">framebufferIntegerColorSampleCounts</a>
limit which indicates the color sample counts that are supported for all framebuffer color attachments with integer formats.
"""
)}
"""
IntConstant(
"The API version number for Vulkan 1.2.",
"API_VERSION_1_2".."VK_MAKE_API_VERSION(0, 1, 2, 0)"
)
}
VK13.apply {
documentation =
"""
The core Vulkan 1.3 functionality.
Vulkan Version 1.3 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_copy_commands2.link,
KHR_dynamic_rendering.link,
KHR_format_feature_flags2.link,
KHR_maintenance4.link,
KHR_shader_integer_dot_product.link,
KHR_shader_non_semantic_info.link,
KHR_shader_terminate_invocation.link,
KHR_synchronization2.link,
KHR_zero_initialize_workgroup_memory.link,
EXT_4444_formats.link,
EXT_extended_dynamic_state.link,
EXT_extended_dynamic_state2.link,
EXT_image_robustness.link,
EXT_inline_uniform_block.link,
EXT_pipeline_creation_cache_control.link,
EXT_pipeline_creation_feedback.link,
EXT_private_data.link,
EXT_shader_demote_to_helper_invocation.link,
EXT_subgroup_size_control.link,
EXT_texel_buffer_alignment.link,
EXT_texture_compression_astc_hdr.link,
EXT_tooling_info.link,
EXT_ycbcr_2plane_444_formats.link
)}
All differences in behavior between these extensions and the corresponding Vulkan 1.3 functionality are summarized below.
<h3>Differences relative to {@code VK_EXT_4444_formats}</h3>
If the {@code VK_EXT_4444_formats} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3. There are no
members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDevice4444FormatsFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_extended_dynamic_state}</h3>
All dynamic state enumerants and entry points defined by {@code VK_EXT_extended_dynamic_state} are required in Vulkan 1.3. There are no members in
the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceExtendedDynamicStateFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_extended_dynamic_state2}</h3>
The optional dynamic state enumerants and entry points defined by {@code VK_EXT_extended_dynamic_state2} for patch control points and logic op are
not promoted in Vulkan 1.3. There are no members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the
##VkPhysicalDeviceExtendedDynamicState2FeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_texel_buffer_alignment}</h3>
The more specific alignment requirements defined by ##VkPhysicalDeviceTexelBufferAlignmentProperties are required in Vulkan 1.3. There are no
members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_texture_compression_astc_hdr}</h3>
If the {@code VK_EXT_texture_compression_astc_hdr} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3.
The {@code textureCompressionASTC_HDR} member of ##VkPhysicalDeviceVulkan13Features indicates whether a Vulkan 1.3 implementation supports these
formats.
<h3>Differences relative to {@code VK_EXT_ycbcr_2plane_444_formats}</h3>
If the {@code VK_EXT_ycbcr_2plane_444_formats} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3. There
are no members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT
structure.
<h3>Additional Vulkan 1.3 Feature Support</h3>
In addition to the promoted extensions described above, Vulkan 1.3 added required support for:
${ul(
"SPIR-V version 1.6. SPIR-V 1.6 deprecates (but does not remove) the WorkgroupSize decoration.",
"""
The {@code bufferDeviceAddress} feature which indicates support for accessing memory in shaders as storage buffers via
#GetBufferDeviceAddress().
""",
"""
The {@code vulkanMemoryModel}, {@code vulkanMemoryModelDeviceScope}, and {@code vulkanMemoryModelAvailabilityVisibilityChains} features, which
indicate support for the corresponding Vulkan Memory Model capabilities.
""",
"The {@code maxInlineUniformTotalSize} limit is added to provide the total size of all inline uniform block bindings in a pipeline layout."
)}
"""
IntConstant(
"The API version number for Vulkan 1.3.",
"API_VERSION_1_3".."VK_MAKE_API_VERSION(0, 1, 3, 0)"
)
}
NV_ray_tracing.apply {
MultiType(PointerMapping.DATA_LONG)..this["GetAccelerationStructureHandleNV"].getParam("pData")
}
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/Custom.kt | 920624376 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.update
import com.intellij.util.ui.AsyncProcessIcon
import javax.swing.JButton
import javax.swing.JComboBox
import javax.swing.JLabel
import javax.swing.JPanel
class ConfigurePluginUpdatesForm {
lateinit var channelBox: JComboBox<String>
lateinit var checkForUpdatesNowButton: JButton
lateinit var panel: JPanel
lateinit var updateCheckInProgressIcon: AsyncProcessIcon
lateinit var updateStatusLabel: JLabel
lateinit var installButton: JButton
private fun createUIComponents() {
updateCheckInProgressIcon = AsyncProcessIcon("Plugin update check in progress")
}
}
| src/main/kotlin/com/demonwav/mcdev/update/ConfigurePluginUpdatesForm.kt | 441361549 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.generation
import com.demonwav.mcdev.insight.generation.GenerationData
data class SpongeGenerationData(val isIgnoreCanceled: Boolean, val eventOrder: String) : GenerationData
| src/main/kotlin/com/demonwav/mcdev/platform/sponge/generation/SpongeGenerationData.kt | 207309333 |
package it.codingjam.github.core
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
open class RepoId(val owner: String, val name: String) : Parcelable | core/src/main/java/it/codingjam/github/core/RepoId.kt | 316145123 |
// 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.configurationStore.statistic.eventLog
import com.intellij.internal.statistic.eventLog.FeatureUsageLogger
import com.intellij.internal.statistic.utils.getProjectId
import com.intellij.openapi.components.State
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.BeanBinding
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
import org.jdom.Element
import java.util.*
private val LOG = Logger.getInstance("com.intellij.configurationStore.statistic.eventLog.FeatureUsageSettingsEventPrinter")
private const val RECORDER_ID = "settings"
object FeatureUsageSettingsEvents {
val printer = FeatureUsageSettingsEventPrinter()
fun logDefaultConfigurationState(componentName: String, stateSpec: State, clazz: Class<*>, project: Project?) {
if (stateSpec.reportStatistic && FeatureUsageLogger.isEnabled()) {
printer.logDefaultConfigurationState(componentName, clazz, project)
}
}
fun logConfigurationState(componentName: String, stateSpec: State, state: Any?, project: Project?) {
if (stateSpec.reportStatistic && FeatureUsageLogger.isEnabled()) {
printer.logConfigurationState(componentName, state, project)
}
}
}
open class FeatureUsageSettingsEventPrinter {
private val defaultFilter = SkipDefaultsSerializationFilter()
fun logDefaultConfigurationState(componentName: String, clazz: Class<*>, project: Project?) {
try {
val default = defaultFilter.getDefaultValue(clazz)
logConfigurationState(componentName, default, project)
}
catch (e: Exception) {
LOG.warn("Cannot initialize default settings for '$componentName'")
}
}
fun logConfigurationState(componentName: String, state: Any?, project: Project?) {
if (state == null || state is Element) {
return
}
val accessors = BeanBinding.getAccessors(state.javaClass)
if (accessors.isEmpty()) {
return
}
val isDefaultProject = project?.isDefault == true
val hash = if (!isDefaultProject) toHash(project) else null
for (accessor in accessors) {
val type = accessor.genericType
if (type === Boolean::class.javaPrimitiveType) {
val value = accessor.read(state)
val isNotDefault = defaultFilter.accepts(accessor, state)
val content = HashMap<String, Any>()
content["name"] = accessor.name
content["value"] = value
if (isNotDefault) {
content["default"] = false
}
if (isDefaultProject) {
content["default_project"] = true
}
else {
hash?.let {
content["project"] = hash
}
}
logConfig(RECORDER_ID, componentName, content)
}
}
}
protected open fun logConfig(groupId: String, eventId: String, data: Map<String, Any>) {
FeatureUsageLogger.logState(groupId, eventId, data)
}
internal fun toHash(project: Project?): String? {
return project?.let {
return getProjectId(project)
}
}
}
| platform/configuration-store-impl/src/statistic/eventLog/FeatureUsageSettingsEvents.kt | 2462041890 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project nor the names of its contributors may
* 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.
*/
package org.hisp.dhis.android.core.data.dataset
import org.hisp.dhis.android.core.dataset.internal.SectionIndicatorLink
internal object SectionIndicatorLinkSamples {
fun getSectionIndicatorLink(): SectionIndicatorLink {
return SectionIndicatorLink.builder()
.id(1L)
.section("section")
.indicator("indicator")
.build()
}
}
| core/src/sharedTest/java/org/hisp/dhis/android/core/data/dataset/SectionIndicatorLinkSamples.kt | 296930040 |
package org.wikipedia.util
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
object ClipboardUtil {
@JvmStatic
fun setPlainText(context: Context, label: CharSequence?, text: CharSequence?) {
(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
.setPrimaryClip(ClipData.newPlainText(label, text))
}
}
| app/src/main/java/org/wikipedia/util/ClipboardUtil.kt | 1666329254 |
/*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.element.constructor
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml(name = "server")
class ServerConstructor(
@param:Attribute val name: String?,
@param:Element(name = "serverConfig") val config: ServerConfigConstructor?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ServerConstructor) return false
val that = other as ServerConstructor?
if (if (name != null) name != that!!.name else that!!.name != null) return false
return if (config != null) config == that.config else that.config == null
}
override fun hashCode(): Int {
var result = name?.hashCode() ?: 0
result = 31 * result + (config?.hashCode() ?: 0)
return result
}
}
| annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/constructor/ServerConstructor.kt | 3579696865 |
package com.ashish.movieguide.ui.widget
import android.content.Context
import android.support.v4.view.ViewCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.util.AttributeSet
import android.view.View
import java.util.ArrayList
/**
* Created by Ashish on Dec 27.
*/
class MultiSwipeRefreshLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SwipeRefreshLayout(context, attrs) {
var swipeableChildren = ArrayList<View>()
fun setSwipeableViews(vararg views: View) {
for (view in views) {
swipeableChildren.add(view)
}
}
override fun canChildScrollUp(): Boolean {
if (swipeableChildren.size > 0) {
swipeableChildren
.filter { it.isShown && !ViewCompat.canScrollVertically(it, -1) }
.forEach { return false }
}
return true
}
override fun onDetachedFromWindow() {
performCleanup()
super.onDetachedFromWindow()
}
private fun performCleanup() {
clearAnimation()
setOnRefreshListener(null)
}
} | app/src/main/kotlin/com/ashish/movieguide/ui/widget/MultiSwipeRefreshLayout.kt | 713575870 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project nor the names of its contributors may
* 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.
*/
package org.hisp.dhis.android.core.common.valuetype.validation.validators
import org.hisp.dhis.android.core.arch.helpers.Result
import org.hisp.dhis.android.core.common.valuetype.validation.failures.BooleanFailure
object BooleanValidator : ValueTypeValidator<BooleanFailure> {
override fun validate(value: String): Result<String, BooleanFailure> {
return when (value) {
"0" -> {
Result.Failure(BooleanFailure.ZeroIsNotFalseException)
}
"1" -> {
Result.Failure(BooleanFailure.OneIsNotTrueException)
}
"true", "false" -> {
Result.Success(value)
}
else -> {
Result.Failure(BooleanFailure.BooleanMalformedException)
}
}
}
}
| core/src/main/java/org/hisp/dhis/android/core/common/valuetype/validation/validators/BooleanValidator.kt | 2833999940 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project nor the names of its contributors may
* 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.
*/
package org.hisp.dhis.android.core.arch.db.adapters.enums.internal
import org.hisp.dhis.smscompression.SMSConsts
internal class SMSMetadataTypeColumnAdapter : EnumColumnAdapter<SMSConsts.MetadataType>() {
override fun getEnumClass(): Class<SMSConsts.MetadataType> {
return SMSConsts.MetadataType::class.java
}
}
| core/src/main/java/org/hisp/dhis/android/core/arch/db/adapters/enums/internal/SMSMetadataTypeColumnAdapter.kt | 1235538395 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.terminal
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.SystemInfo
import java.io.File
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty
/**
* @author traff
*/
@State(name = "TerminalProjectOptionsProvider", storages = [(Storage("terminal.xml"))])
class TerminalProjectOptionsProvider(val project: Project) : PersistentStateComponent<TerminalProjectOptionsProvider.State> {
private val myState = State()
override fun getState(): State? {
return myState
}
override fun loadState(state: State) {
myState.myStartingDirectory = state.myStartingDirectory
}
class State {
var myStartingDirectory: String? = null
}
var startingDirectory: String? by ValueWithDefault(State::myStartingDirectory, myState) { defaultStartingDirectory }
val defaultStartingDirectory: String?
get() {
var directory: String? = null
for (customizer in LocalTerminalCustomizer.EP_NAME.extensions) {
try {
if (directory == null) {
directory = customizer.getDefaultFolder(project)
}
}
catch (e: Exception) {
LOG.error("Exception during getting default folder", e)
}
}
return directory ?: currentProjectFolder()
}
private fun currentProjectFolder() = if (project.isDefault) null else project.guessProjectDir()?.canonicalPath
val defaultShellPath: String
get() {
val shell = System.getenv("SHELL")
if (shell != null && File(shell).canExecute()) {
return shell
}
if (SystemInfo.isUnix) {
if (File("/bin/bash").exists()) {
return "/bin/bash"
}
else {
return "/bin/sh"
}
}
else {
return "cmd.exe"
}
}
companion object {
private val LOG = Logger.getInstance(TerminalProjectOptionsProvider::class.java)
fun getInstance(project: Project): TerminalProjectOptionsProvider {
return ServiceManager.getService(project, TerminalProjectOptionsProvider::class.java)
}
}
}
// TODO: In Kotlin 1.1 it will be possible to pass references to instance properties. Until then we need 'state' argument as a receiver for
// to property to apply
class ValueWithDefault<S>(val prop: KMutableProperty1<S, String?>, val state: S, val default: () -> String?) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String? {
return if (prop.get(state) !== null) prop.get(state) else default()
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) {
prop.set(state, if (value == default() || value.isNullOrEmpty()) null else value)
}
}
| plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalProjectOptionsProvider.kt | 1888824754 |
// "Import" "true"
// ERROR: Unresolved reference: someTestFun
package functionimporttest
fun functionImportTest() {
<caret>someTestFun()
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/functionImport.before.Main.kt | 232584294 |
package klay.core
/**
* A bitmap fill pattern created by [Image.createPattern].
*/
abstract class Pattern protected constructor(
/** Whether this pattern repeats in the x-direction. */
val repeatX: Boolean,
/** Whether this pattern repeats in the y-direction. */
val repeatY: Boolean)
| src/main/kotlin/klay/core/Pattern.kt | 802741848 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.assertj.core.api
import org.assertj.core.internal.ComparatorBasedComparisonStrategy
import org.assertj.core.internal.Iterables
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
fun AbstractPathAssert<*>.hasChildren(vararg names: String) {
paths.assertIsDirectory(info, actual)
Iterables(ComparatorBasedComparisonStrategy(object : Comparator<Any> {
override fun compare(o1: Any, o2: Any): Int {
if (o1 is Path && o2 is Path) {
return o1.compareTo(o2)
}
else if (o1 is String && o2 is String) {
return o1.compareTo(o2)
}
else {
return if ((o1 as Path).endsWith(o2 as String)) 0 else -1
}
}
}))
.assertContainsOnly(info, Files.newDirectoryStream(actual).toList(), names)
}
| platform/testFramework/test-framework-java8/assertJ.kt | 2505317925 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.workspaceModel.storage.WorkspaceEntity
import it.unimi.dsi.fastutil.objects.Object2IntMap
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.concurrent.atomic.AtomicReference
/**
* This class fits the cases where there is a relatively small amount of classes (<50).
* The disadvantages are:
* - Two collections copies
*
* N.B. One of the approaches is to generate and assign ids to classes during the code generation.
*/
internal class ClassToIntConverter {
private val map: AtomicReference<Entry> = AtomicReference(Entry(newMap(), emptyArray()))
private class Entry(
val classToInt: Object2IntMap<Class<*>>,
val intToClass: Array<Class<*>?>,
)
fun getInt(clazz: Class<*>): Int {
while (true) {
val entry = map.get()
val result = entry.classToInt.getInt(clazz)
if (result != -1) return result
val classId = entry.classToInt.size
val newEntry = Entry(
newMap(entry.classToInt).also { it.put(clazz, classId) },
entry.intToClass.copyExtendAndPut(classId, clazz)
)
if (map.compareAndSet(entry, newEntry)) return classId
}
}
fun getClassOrDie(id: Int): Class<*> = map.get().intToClass[id] ?: error("Cannot find class by id: $id")
fun getMap(): Map<Class<*>, Int> = map.get().classToInt
fun fromMap(map: Map<Class<*>, Int>) {
val entry = Entry(
Object2IntOpenHashMap(map),
Array<Class<*>?>(map.values.maxOrNull() ?: 0) { null }.also { map.forEach { (clazz, index) -> it[index] = clazz } }
)
this.map.set(entry)
}
private fun newMap(oldMap: Object2IntMap<Class<*>>? = null): Object2IntOpenHashMap<Class<*>> {
val newMap = if (oldMap != null) Object2IntOpenHashMap(oldMap) else Object2IntOpenHashMap()
newMap.defaultReturnValue(-1)
return newMap
}
private inline fun <reified T> Array<T?>.copyExtendAndPut(id: Int, data: T): Array<T?> {
val thisSize = this.size
val res = Array(id + 1) { if (it < thisSize) this[it] else null }
res[id] = data
return res
}
companion object {
val INSTANCE = ClassToIntConverter()
}
}
internal fun Class<*>.toClassId(): Int = ClassToIntConverter.INSTANCE.getInt(this)
@Suppress("UNCHECKED_CAST")
internal inline fun <reified E> Int.findEntityClass(): Class<E> = ClassToIntConverter.INSTANCE.getClassOrDie(this) as Class<E>
@Suppress("UNCHECKED_CAST")
internal fun Int.findWorkspaceEntity(): Class<WorkspaceEntity> = ClassToIntConverter.INSTANCE.getClassOrDie(this) as Class<WorkspaceEntity>
| platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ClassToIntConverter.kt | 2665391976 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.icons.AllIcons
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollector
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollectorGroup
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.Disposer
import com.intellij.ui.GotItTooltip
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import javax.swing.JComponent
internal class ActionToolbarGotItTooltip(@NonNls private val id: String,
@Nls private val tooltipText: String,
disposable: Disposable,
private val toolbar: ActionToolbar,
private val actionComponentSelector: (ActionToolbar) -> JComponent?) : Activatable {
val tooltipDisposable = Disposer.newDisposable().also { Disposer.register(disposable, it) }
private var balloon: Balloon? = null
init {
UiNotifyConnector(toolbar.component, this).also { Disposer.register(tooltipDisposable, it) }
}
override fun showNotify() = showHint()
override fun hideNotify() = hideHint(false)
fun showHint() {
hideBalloon()
val component = actionComponentSelector(toolbar) ?: return
GotItTooltip(id, tooltipText, tooltipDisposable)
.setOnBalloonCreated { balloon = it }
.show(component, GotItTooltip.BOTTOM_MIDDLE)
}
private fun hideBalloon() {
balloon?.hide()
balloon = null
}
fun hideHint(dispose: Boolean) {
hideBalloon()
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
if (dispose) Disposer.dispose(tooltipDisposable)
}
}
internal val gearButtonOrToolbar: (ActionToolbar) -> JComponent = { toolbar -> toolbar.getGearButton() ?: toolbar.component }
internal val gearButton: (ActionToolbar) -> JComponent? = { toolbar -> toolbar.getGearButton() }
private fun ActionToolbar.getGearButton(): ActionButton? =
UIUtil.uiTraverser(component)
.filter(ActionButton::class.java)
.filter { it.icon == AllIcons.General.GearPlain }
.first()
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ActionToolbarGotItTooltip.kt | 3612165484 |
package com.github.hkokocin.androidkit.content
import android.annotation.SuppressLint
import android.content.SharedPreferences
import com.github.hkokocin.androidkit.AndroidKit
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.given
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.then
import org.junit.After
import org.junit.Before
import org.junit.Test
class SharedPreferencesKitTest {
val editor: SharedPreferences.Editor = mock {
given { it.putBoolean(any(), any()) }.willReturn(it)
given { it.putInt(any(), any()) }.willReturn(it)
given { it.putFloat(any(), any()) }.willReturn(it)
given { it.putLong(any(), any()) }.willReturn(it)
given { it.putString(any(), any()) }.willReturn(it)
given { it.putStringSet(any(), any()) }.willReturn(it)
}
@SuppressLint("CommitPrefEdits")
val preferences: SharedPreferences = mock {
given { it.edit() }.willReturn(editor)
}
val classToTest = object: SharedPreferencesKit{}
@Test
fun canApplyBoolean() {
classToTest.applyBoolean(preferences, "key", true)
inOrder(editor).apply {
verify(editor).putBoolean("key", true)
verify(editor).apply()
}
}
@Test
fun canApplyInt() {
classToTest.applyInt(preferences, "key", 1)
inOrder(editor).apply {
verify(editor).putInt("key", 1)
verify(editor).apply()
}
}
@Test
fun canApplyFloat() {
classToTest.applyFloat(preferences, "key", 1.0F)
inOrder(editor).apply {
verify(editor).putFloat("key", 1.0F)
verify(editor).apply()
}
}
@Test
fun canApplyLong() {
classToTest.applyLong(preferences, "key", 1L)
inOrder(editor).apply {
verify(editor).putLong("key", 1L)
verify(editor).apply()
}
}
@Test
fun canApplyString() {
classToTest.applyString(preferences, "key", "string")
inOrder(editor).apply {
verify(editor).putString("key", "string")
verify(editor).apply()
}
}
@Test
fun canApplyStringSet() {
classToTest.applyStringSet(preferences, "key", setOf("string"))
inOrder(editor).apply {
verify(editor).putStringSet("key", setOf("string"))
verify(editor).apply()
}
}
}
class SharedPreferencesExtensionsTest{
val kit: AndroidKit = mock()
val preferences: SharedPreferences = mock()
@Before
fun setUp() {
AndroidKit.instance = kit
}
@After
fun tearDown(){
AndroidKit.resetToDefault()
}
@Test
fun canApplyBoolean() {
preferences.applyBoolean("key", true)
then(kit).should().applyBoolean(preferences, "key", true)
}
@Test
fun canApplyInt() {
preferences.applyInt("key", 1)
then(kit).should().applyInt(preferences, "key", 1)
}
@Test
fun canapplyFloat() {
preferences.applyFloat("key", 1F)
then(kit).should().applyFloat(preferences, "key", 1F)
}
@Test
fun canapplyLong() {
preferences.applyLong("key", 1L)
then(kit).should().applyLong(preferences, "key", 1L)
}
@Test
fun canapplyString() {
preferences.applyString("key", "string")
then(kit).should().applyString(preferences, "key", "string")
}
@Test
fun canApplyStringSet() {
preferences.applyStringSet("key", setOf("string"))
then(kit).should().applyStringSet(preferences, "key", setOf("string"))
}
} | library/src/test/java/com/github/hkokocin/androidkit/content/SharedPreferencesKitTest.kt | 2237018692 |
/*
* Copyright 2016 Jasmine Villadarez
*
* 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.jv.practice.notes.presentation.views.activities
import android.support.v7.app.AppCompatActivity
import com.jv.practice.notes.App
import com.jv.practice.notes.presentation.internal.di.components.AppComponent
import com.jv.practice.notes.presentation.internal.di.modules.ActivityModule
abstract class BaseActivity : AppCompatActivity() {
protected fun getActivityModule(): ActivityModule {
return ActivityModule(this)
}
protected fun getApplicationComponent(): AppComponent {
return (application as App).applicationComponent
}
} | Notes/app/src/main/kotlin/com/jv/practice/notes/presentation/views/activities/BaseActivity.kt | 3466088336 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.codeInsight
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PlatformPatterns.psiFile
import com.intellij.patterns.StandardPatterns.string
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl
/**
* @author Vladislav.Soroka
*/
abstract class AbstractGradleCompletionContributor : CompletionContributor() {
protected fun findNamedArgumentValue(namedArgumentsOwner: GrNamedArgumentsOwner?, label: String): String? {
val namedArgument = namedArgumentsOwner?.findNamedArgument(label) ?: return null
return (namedArgument.expression as? GrLiteralImpl)?.value?.toString()
}
companion object {
val GRADLE_FILE_PATTERN: ElementPattern<PsiElement> = psiElement()
.inFile(psiFile().withName(string().endsWith('.' + GradleConstants.EXTENSION)))
}
}
| plugins/gradle/java/src/codeInsight/AbstractGradleCompletionContributor.kt | 4146099415 |
// 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.injection
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTreeUtil.getDeepestLast
import com.intellij.util.Consumer
import com.intellij.util.Processor
import org.intellij.plugins.intelliLang.Configuration
import org.intellij.plugins.intelliLang.inject.*
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.patterns.KotlinPatterns
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
@NonNls
val KOTLIN_SUPPORT_ID = "kotlin"
class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
override fun getId(): String = KOTLIN_SUPPORT_ID
override fun createAddActions(project: Project?, consumer: Consumer<in BaseInjection>?): Array<AnAction> {
return super.createAddActions(project, consumer).apply {
forEach {
it.templatePresentation.icon = KotlinFileType.INSTANCE.icon
}
}
}
override fun getPatternClasses() = arrayOf(KotlinPatterns::class.java)
override fun isApplicableTo(host: PsiLanguageInjectionHost?) = host is KtElement
override fun useDefaultInjector(host: PsiLanguageInjectionHost?): Boolean = false
override fun addInjectionInPlace(language: Language?, host: PsiLanguageInjectionHost?): Boolean {
if (language == null || host == null) return false
val configuration = Configuration.getProjectInstance(host.project).advancedConfiguration
if (!configuration.isSourceModificationAllowed) {
// It's not allowed to modify code without explicit permission. Postpone adding @Inject or comment till it granted.
host.putUserData(InjectLanguageAction.FIX_KEY, Processor { fixHost: PsiLanguageInjectionHost? ->
fixHost != null && addInjectionInstructionInCode(language, fixHost)
})
return false
}
if (!addInjectionInstructionInCode(language, host)) {
return false
}
TemporaryPlacesRegistry.getInstance(host.project).addHostWithUndo(host, InjectedLanguage.create(language.id))
return true
}
override fun removeInjectionInPlace(psiElement: PsiLanguageInjectionHost?): Boolean {
if (psiElement == null || psiElement !is KtElement) return false
val project = psiElement.getProject()
val injectInstructions = listOfNotNull(
findAnnotationInjection(psiElement),
findInjectionComment(psiElement)
)
TemporaryPlacesRegistry.getInstance(project).removeHostWithUndo(project, psiElement)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.remove.injection.in.code.instructions")) {
injectInstructions.forEach(PsiElement::delete)
}
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
}
fun findCommentInjection(host: KtElement): BaseInjection? {
return InjectorUtils.findCommentInjection(host, "", null)
}
private fun findInjectionComment(host: KtElement): PsiComment? {
val commentRef = Ref.create<PsiElement>(null)
InjectorUtils.findCommentInjection(host, "", commentRef) ?: return null
return commentRef.get() as? PsiComment
}
internal fun findAnnotationInjectionLanguageId(host: KtElement): InjectionInfo? =
findAnnotationInjection(host)?.let(::toInjectionInfo)
internal fun toInjectionInfo(annotationEntry: KtAnnotationEntry): InjectionInfo? {
val extractLanguageFromInjectAnnotation = extractLanguageFromInjectAnnotation(annotationEntry) ?: return null
val prefix = extractStringArgumentByName(annotationEntry, "prefix")
val suffix = extractStringArgumentByName(annotationEntry, "suffix")
return InjectionInfo(extractLanguageFromInjectAnnotation, prefix, suffix)
}
}
private fun extractStringArgumentByName(annotationEntry: KtAnnotationEntry, name: String): String? {
val namedArgument: ValueArgument =
annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null
return extractStringValue(namedArgument)
}
private fun extractLanguageFromInjectAnnotation(annotationEntry: KtAnnotationEntry): String? {
val firstArgument: ValueArgument = annotationEntry.valueArguments.firstOrNull() ?: return null
return extractStringValue(firstArgument)
}
private fun extractStringValue(valueArgument: ValueArgument): String? {
val firstStringArgument = valueArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return null
val firstStringEntry = firstStringArgument.entries.singleOrNull() ?: return null
return firstStringEntry.text
}
private fun findAnnotationInjection(host: KtElement): KtAnnotationEntry? {
val modifierListOwner = findElementToInjectWithAnnotation(host) ?: return null
val modifierList = modifierListOwner.modifierList ?: return null
// Host can't be before annotation
if (host.startOffset < modifierList.endOffset) return null
return modifierListOwner.findAnnotation(FqName(AnnotationUtil.LANGUAGE))
}
private fun canInjectWithAnnotation(host: PsiElement): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(host) ?: return false
val javaPsiFacade = JavaPsiFacade.getInstance(module.project)
return javaPsiFacade.findClass(AnnotationUtil.LANGUAGE, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) != null
}
private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? = PsiTreeUtil.getParentOfType(
host,
KtModifierListOwner::class.java,
false, /* strict */
KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */
)
private fun findElementToInjectWithComment(host: KtElement): KtExpression? {
val parentBlockExpression = PsiTreeUtil.getParentOfType(
host,
KtBlockExpression::class.java,
true, /* strict */
KtDeclaration::class.java /* Stop at */
) ?: return null
return parentBlockExpression.statements.firstOrNull { statement ->
PsiTreeUtil.isAncestor(statement, host, false) && checkIsValidPlaceForInjectionWithLineComment(statement, host)
}
}
private fun addInjectionInstructionInCode(language: Language, host: PsiLanguageInjectionHost): Boolean {
val ktHost = host as? KtElement ?: return false
val project = ktHost.project
// Find the place where injection can be stated with annotation or comment
val modifierListOwner = findElementToInjectWithAnnotation(ktHost)
if (modifierListOwner != null && canInjectWithAnnotation(ktHost)) {
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.annotation")) {
modifierListOwner.addAnnotation(FqName(AnnotationUtil.LANGUAGE), "\"${language.id}\"")
}
return true
}
// Find the place where injection can be done with one-line comment
val commentBeforeAnchor: PsiElement =
modifierListOwner?.firstNonCommentChild() ?: findElementToInjectWithComment(ktHost) ?: return false
val psiFactory = KtPsiFactory(project)
val injectComment = psiFactory.createComment("//language=" + language.id)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.comment")) {
commentBeforeAnchor.parent.addBefore(injectComment, commentBeforeAnchor)
}
return true
}
// Inspired with InjectorUtils.findCommentInjection()
private fun checkIsValidPlaceForInjectionWithLineComment(statement: KtExpression, host: KtElement): Boolean {
// make sure comment is close enough and ...
val statementStartOffset = statement.startOffset
val hostStart = host.startOffset
if (hostStart < statementStartOffset || hostStart - statementStartOffset > 120) {
return false
}
if (hostStart - statementStartOffset > 2) {
// ... there's no non-empty valid host in between comment and e2
if (prevWalker(host, statement).asSequence().takeWhile { it != null }.any {
it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text)
}
) return false
}
return true
}
private fun PsiElement.firstNonCommentChild(): PsiElement? =
firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull()
// Based on InjectorUtils.prevWalker
private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator<PsiElement?> {
return object : Iterator<PsiElement?> {
private var e: PsiElement? = element
override fun hasNext(): Boolean = true
override fun next(): PsiElement? {
val current = e
if (current == null || current === scope) return null
val prev = current.prevSibling
e = if (prev != null) {
getDeepestLast(prev)
} else {
val parent = current.parent
if (parent === scope || parent is PsiFile) null else parent
}
return e
}
}
}
| plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt | 1593809802 |
package org.moire.ultrasonic.api.subsonic.interceptors
import java.util.concurrent.TimeUnit.MILLISECONDS
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
internal const val SOCKET_READ_TIMEOUT_DOWNLOAD = 30 * 1000
// Allow 20 seconds extra timeout pear MB offset.
internal const val TIMEOUT_MILLIS_PER_OFFSET_BYTE = 0.02
/**
* Modifies request "Range" header to be according to HTTP standard.
*
* Also increases read timeout to allow server to transcode response and offset it.
*
* See [range rfc](https://tools.ietf.org/html/rfc7233).
*/
internal class RangeHeaderInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
val originalRequest = chain.request()
val headers = originalRequest.headers()
return if (headers.names().contains("Range")) {
val offsetValue = headers["Range"] ?: "0"
val offset = "bytes=$offsetValue-"
chain.withReadTimeout(getReadTimeout(offsetValue.toInt()), MILLISECONDS)
.proceed(
originalRequest.newBuilder()
.removeHeader("Range").addHeader("Range", offset)
.build()
)
} else {
chain.proceed(originalRequest)
}
}
// Set socket read timeout. Note: The timeout increases as the offset gets larger. This is
// to avoid the thrashing effect seen when offset is combined with transcoding/downsampling
// on the server. In that case, the server uses a long time before sending any data,
// causing the client to time out.
private fun getReadTimeout(offset: Int) =
(SOCKET_READ_TIMEOUT_DOWNLOAD + offset * TIMEOUT_MILLIS_PER_OFFSET_BYTE).toInt()
}
| core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/interceptors/RangeHeaderInterceptor.kt | 1320151622 |
package tripleklay.ui
import klay.core.Canvas
import klay.core.Font
import klay.core.Sound
import klay.core.TextBlock
import tripleklay.ui.Style.Binding
import tripleklay.util.EffectRenderer
import tripleklay.util.EffectRenderer.Gradient
import tripleklay.util.TextStyle
/**
* Defines style properties for interface elements. Some style properties are inherited, such that
* a property not specified in a leaf element will be inherited by the nearest parent for which the
* property is specified. Other style properties are not inherited, and a default value will be
* used in cases where a leaf element lacks a property. The documentation for each style property
* indicates whether or not it is inherited.
*/
abstract class Style<out V> protected constructor(
/** Indicates whether or not this style property is inherited. */
val inherited: Boolean) {
/** Defines element modes which can be used to modify an element's styles. */
enum class Mode(
/** Whether the element is enabled in this mode. */
val enabled: Boolean,
/** Whether the element is selected in this mode. */
val selected: Boolean) {
DEFAULT(true, false),
DISABLED(false, false),
SELECTED(true, true),
DISABLED_SELECTED(false, true)
}
/** Used to configure [Styles] instances. See [Styles.add]. */
class Binding<out V>(
/** The style being configured. */
val style: Style<V>,
/** The value to be bound for the style. */
val value: V)
/** Defines horizontal alignment choices. */
enum class HAlign {
LEFT {
override fun offset(size: Float, extent: Float): Float {
return 0f
}
},
RIGHT {
override fun offset(size: Float, extent: Float): Float {
return extent - size
}
},
CENTER {
override fun offset(size: Float, extent: Float): Float {
return (extent - size) / 2
}
};
abstract fun offset(size: Float, extent: Float): Float
}
/** Defines vertical alignment choices. */
enum class VAlign {
TOP {
override fun offset(size: Float, extent: Float): Float {
return 0f
}
},
BOTTOM {
override fun offset(size: Float, extent: Float): Float {
return extent - size
}
},
CENTER {
override fun offset(size: Float, extent: Float): Float {
return (extent - size) / 2
}
};
abstract fun offset(size: Float, extent: Float): Float
}
/** Defines icon position choices. */
enum class Pos {
LEFT, ABOVE, RIGHT, BELOW;
/** Tests if this position is left or right. */
fun horizontal(): Boolean {
return this == LEFT || this == RIGHT
}
}
/** Used to create text effects. */
interface EffectFactory {
/** Creates the effect renderer to be used by this factory. */
fun createEffectRenderer(elem: Element<*>): EffectRenderer
}
/** Defines supported text effects. */
enum class TextEffect : EffectFactory {
/** Outlines the text in the highlight color. */
PIXEL_OUTLINE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.PixelOutline(Styles.resolveStyle(elem, Style.HIGHLIGHT))
}
},
/** Outlines the text in the highlight color. */
VECTOR_OUTLINE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.VectorOutline(
Styles.resolveStyle(elem, Style.HIGHLIGHT),
Styles.resolveStyle(elem, Style.OUTLINE_WIDTH),
Styles.resolveStyle(elem, Style.OUTLINE_CAP),
Styles.resolveStyle(elem, Style.OUTLINE_JOIN))
}
},
/** Draws a shadow below and to the right of the text in the shadow color. */
SHADOW {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.Shadow(Styles.resolveStyle(elem, Style.SHADOW),
Styles.resolveStyle(elem, Style.SHADOW_X),
Styles.resolveStyle(elem, Style.SHADOW_Y))
}
},
/** Draws a gradient from the font color to the gradient color. */
GRADIENT {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return Gradient(Styles.resolveStyle(elem, Style.GRADIENT_COLOR),
Styles.resolveStyle(elem, Style.GRADIENT_TYPE))
}
},
/** No text effect. */
NONE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.NONE
}
}
}
/** Used to provide concise HAlign style declarations. */
class HAlignStyle internal constructor() : Style<HAlign>(false) {
val left = `is`(HAlign.LEFT)
val right = `is`(HAlign.RIGHT)
val center = `is`(HAlign.CENTER)
override fun getDefault(elem: Element<*>): HAlign {
return HAlign.CENTER
}
}
/** Used to provide concise VAlign style declarations. */
class VAlignStyle internal constructor() : Style<VAlign>(false) {
val top = `is`(VAlign.TOP)
val bottom = `is`(VAlign.BOTTOM)
val center = `is`(VAlign.CENTER)
override fun getDefault(elem: Element<*>): VAlign {
return VAlign.CENTER
}
}
/** Used to provide concise Pos style declarations. */
class PosStyle internal constructor() : Style<Pos>(false) {
val left = `is`(Pos.LEFT)
val above = `is`(Pos.ABOVE)
val right = `is`(Pos.RIGHT)
val below = `is`(Pos.BELOW)
override fun getDefault(elem: Element<*>): Pos {
return Pos.LEFT
}
}
/** Used to provide concise TextEffect style declarations. */
class TextEffectStyle internal constructor() : Style<EffectFactory>(true) {
val pixelOutline = `is`(TextEffect.PIXEL_OUTLINE)
val vectorOutline = `is`(TextEffect.VECTOR_OUTLINE)
val shadow = `is`(TextEffect.SHADOW)
val gradient = `is`(TextEffect.GRADIENT)
val none = `is`(TextEffect.NONE)
fun `is`(renderer: EffectRenderer): Binding<EffectFactory> {
return `is`(object : EffectFactory {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return renderer
}
})
}
override fun getDefault(elem: Element<*>): EffectFactory {
return TextEffect.NONE
}
}
class GradientTypeStyle internal constructor() : Style<Gradient.Type>(true) {
val bottom: Binding<Gradient.Type> = `is`(Gradient.Type.BOTTOM)
val top: Binding<Gradient.Type> = `is`(Gradient.Type.TOP)
val center: Binding<Gradient.Type> = `is`(Gradient.Type.CENTER)
override fun getDefault(elem: Element<*>): Gradient.Type {
return Gradient.Type.BOTTOM
}
}
/** A Boolean style, with convenient members for on and off bindings. */
class Flag(inherited: Boolean, private val _default: Boolean) : Style<Boolean>(inherited) {
val off = `is`(false)
val on = `is`(true)
override fun getDefault(mode: Element<*>): Boolean {
return _default
}
}
/**
* Returns the default value for this style for the supplied element.
*/
abstract fun getDefault(mode: Element<*>): V
companion object {
/** The foreground color for an element. Inherited. */
val COLOR: Style<Int> = object : Style<Int>(true) {
override fun getDefault(elem: Element<*>): Int {
return if (elem.isEnabled) 0xFF000000.toInt() else 0xFF666666.toInt()
}
}
/** The highlight color for an element. Inherited. */
val HIGHLIGHT: Style<Int> = object : Style<Int>(true) {
override fun getDefault(elem: Element<*>): Int {
return if (elem.isEnabled) 0xAAFFFFFF.toInt() else 0xAACCCCCC.toInt()
}
}
/** The shadow color for an element. Inherited. */
val SHADOW = newStyle(true, 0x55000000)
/** The shadow offset in pixels. Inherited. */
val SHADOW_X = newStyle(true, 2f)
/** The shadow offset in pixels. Inherited. */
val SHADOW_Y = newStyle(true, 2f)
/** The color of the gradient. Inherited. */
val GRADIENT_COLOR = newStyle(true, 0xFFC70000.toInt())
/** The type of gradient. Inherited. */
val GRADIENT_TYPE = GradientTypeStyle()
/** The stroke width of the outline, when using a vector outline. */
val OUTLINE_WIDTH = newStyle(true, 1f)
/** The line cap for the outline, when using a vector outline. */
val OUTLINE_CAP: Style<Canvas.LineCap> = newStyle(true, Canvas.LineCap.ROUND)
/** The line join for the outline, when using a vector outline. */
val OUTLINE_JOIN: Style<Canvas.LineJoin> = newStyle(true, Canvas.LineJoin.ROUND)
/** The horizontal alignment of an element. Not inherited. */
val HALIGN = HAlignStyle()
/** The vertical alignment of an element. Not inherited. */
val VALIGN = VAlignStyle()
/** The font used to render text. Inherited. */
val FONT = newStyle(true, Font("Helvetica", 16f))
/** Whether or not to allow text to wrap. When text cannot wrap and does not fit into the
* allowed space, it is truncated. Not inherited. */
val TEXT_WRAP = newFlag(false, false)
/** The effect to use when rendering text, if any. Inherited. */
val TEXT_EFFECT = TextEffectStyle()
/** Whether or not to underline text. Inherited. */
val UNDERLINE = newFlag(true, false)
/** Whether or not to automatically shrink a text widget's font size until it fits into the
* horizontal space it has been allotted. Cannot be used with [.TEXT_WRAP]. Not
* inherited. */
val AUTO_SHRINK = newFlag(false, false)
/** The background for an element. Not inherited. */
val BACKGROUND = newStyle(false, Background.blank())
/** The position relative to the text to render an icon for labels, buttons, etc. */
val ICON_POS = PosStyle()
/** The gap between the icon and text in labels, buttons, etc. */
val ICON_GAP = newStyle(false, 2)
/** If true, the icon is cuddled to the text, with extra space between icon and border, if
* false, the icon is placed next to the border with extra space between icon and label. */
val ICON_CUDDLE = newFlag(false, false)
/** The effect to apply to the icon. */
val ICON_EFFECT = newStyle(false, IconEffect.NONE)
/** The sound to be played when this element's action is triggered. */
val ACTION_SOUND = newStyle<Sound?>(false, null)
/**
* Creates a text style instance based on the supplied element's stylings.
*/
fun createTextStyle(elem: Element<*>): TextStyle {
return TextStyle(
Styles.resolveStyle(elem, Style.FONT),
Styles.resolveStyle(elem, Style.TEXT_EFFECT) !== TextEffect.PIXEL_OUTLINE,
Styles.resolveStyle(elem, Style.COLOR),
Styles.resolveStyle(elem, Style.TEXT_EFFECT).createEffectRenderer(elem),
Styles.resolveStyle(elem, Style.UNDERLINE))
}
/**
* Creates a style identifier with the supplied properties.
*/
fun <V> newStyle(inherited: Boolean, defaultValue: V): Style<V> {
return object : Style<V>(inherited) {
override fun getDefault(elem: Element<*>): V {
return defaultValue
}
}
}
/**
* Creates a boolean style identifier with the supplied properties.
*/
fun newFlag(inherited: Boolean, defaultValue: Boolean): Flag {
return Flag(inherited, defaultValue)
}
fun toAlignment(align: HAlign): TextBlock.Align {
when (align) {
Style.HAlign.LEFT -> return TextBlock.Align.LEFT
Style.HAlign.RIGHT -> return TextBlock.Align.RIGHT
Style.HAlign.CENTER -> return TextBlock.Align.CENTER
}
}
}
}
/**
* Returns a [Binding] with this style bound to the specified value.
* This is an extension function to support V's out variance.
*/
fun <V> Style<V>.`is`(value: V): Binding<V> {
return Binding(this, value)
}
| tripleklay/src/main/kotlin/tripleklay/ui/Style.kt | 3627351787 |
package com.github.michaelbull.result
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to
* current accumulator value and each element.
*/
public inline fun <T, R, E> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> Result<R, E>): Result<R, E> {
var accumulator = initial
for (element in this) {
accumulator = when (val result = operation(accumulator, element)) {
is Ok -> result.value
is Err -> return Err(result.error)
}
}
return Ok(accumulator)
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left to
* each element and current accumulator value.
*/
public inline fun <T, R, E> List<T>.foldRight(initial: R, operation: (T, acc: R) -> Result<R, E>): Result<R, E> {
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = when (val result = operation(iterator.previous(), accumulator)) {
is Ok -> result.value
is Err -> return Err(result.error)
}
}
}
return Ok(accumulator)
}
/**
* Combines a vararg of [Results][Result] into a single [Result] (holding a [List]).
*
* - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#combine)
*/
public fun <V, E> combine(vararg results: Result<V, E>): Result<List<V>, E> {
return results.asIterable().combine()
}
/**
* Combines an [Iterable] of [Results][Result] into a single [Result] (holding a [List]).
*
* - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#combine)
*/
public fun <V, E> Iterable<Result<V, E>>.combine(): Result<List<V>, E> {
return Ok(map {
when (it) {
is Ok -> it.value
is Err -> return it
}
})
}
/**
* Extracts from a vararg of [Results][Result] all the [Ok] elements. All the [Ok] elements are
* extracted in order.
*
* - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts)
*/
public fun <V, E> getAll(vararg results: Result<V, E>): List<V> {
return results.asIterable().getAll()
}
/**
* Extracts from an [Iterable] of [Results][Result] all the [Ok] elements. All the [Ok] elements
* are extracted in order.
*
* - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts)
*/
public fun <V, E> Iterable<Result<V, E>>.getAll(): List<V> {
return filterIsInstance<Ok<V>>().map { it.value }
}
/**
* Extracts from a vararg of [Results][Result] all the [Err] elements. All the [Err] elements are
* extracted in order.
*
* - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights)
*/
public fun <V, E> getAllErrors(vararg results: Result<V, E>): List<E> = results.asIterable().getAllErrors()
/**
* Extracts from an [Iterable] of [Results][Result] all the [Err] elements. All the [Err] elements
* are extracted in order.
*
* - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights)
*/
public fun <V, E> Iterable<Result<V, E>>.getAllErrors(): List<E> {
return filterIsInstance<Err<E>>().map { it.error }
}
/**
* Partitions a vararg of [Results][Result] into a [Pair] of [Lists][List]. All the [Ok] elements
* are extracted, in order, to the [first][Pair.first] value. Similarly the [Err] elements are
* extracted to the [Pair.second] value.
*
* - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers)
*/
public fun <V, E> partition(vararg results: Result<V, E>): Pair<List<V>, List<E>> {
return results.asIterable().partition()
}
/**
* Partitions an [Iterable] of [Results][Result] into a [Pair] of [Lists][List]. All the [Ok]
* elements are extracted, in order, to the [first][Pair.first] value. Similarly the [Err] elements
* are extracted to the [Pair.second] value.
*
* - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers)
*/
public fun <V, E> Iterable<Result<V, E>>.partition(): Pair<List<V>, List<E>> {
val values = mutableListOf<V>()
val errors = mutableListOf<E>()
forEach { result ->
when (result) {
is Ok -> values.add(result.value)
is Err -> errors.add(result.error)
}
}
return Pair(values, errors)
}
/**
* Returns a [Result<List<U>, E>][Result] containing the results of applying the given [transform]
* function to each element in the original collection, returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U> Iterable<V>.mapResult(
transform: (V) -> Result<U, E>
): Result<List<U>, E> {
return Ok(map { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Applies the given [transform] function to each element of the original collection and appends
* the results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U, C : MutableCollection<in U>> Iterable<V>.mapResultTo(
destination: C,
transform: (V) -> Result<U, E>
): Result<C, E> {
return Ok(mapTo(destination) { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing only the non-null results of applying the
* given [transform] function to each element in the original collection, returning early with the
* first [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any> Iterable<V>.mapResultNotNull(
transform: (V) -> Result<U, E>?
): Result<List<U>, E> {
return Ok(mapNotNull { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Applies the given [transform] function to each element in the original collection and appends
* only the non-null results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U : Any, C : MutableCollection<in U>> Iterable<V>.mapResultNotNullTo(
destination: C,
transform: (V) -> Result<U, E>?
): Result<C, E> {
return Ok(mapNotNullTo(destination) { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing the results of applying the given [transform]
* function to each element and its index in the original collection, returning early with the
* first [Err] if a transformation fails.
*/
public inline fun <V, E, U> Iterable<V>.mapResultIndexed(
transform: (index: Int, V) -> Result<U, E>
): Result<List<U>, E> {
return Ok(mapIndexed { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends the results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U, C : MutableCollection<in U>> Iterable<V>.mapResultIndexedTo(
destination: C,
transform: (index: Int, V) -> Result<U, E>
): Result<C, E> {
return Ok(mapIndexedTo(destination) { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing only the non-null results of applying the
* given [transform] function to each element and its index in the original collection, returning
* early with the first [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any> Iterable<V>.mapResultIndexedNotNull(
transform: (index: Int, V) -> Result<U, E>?
): Result<List<U>, E> {
return Ok(mapIndexedNotNull { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends only the non-null results to the given [destination], returning early with the first
* [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any, C : MutableCollection<in U>> Iterable<V>.mapResultIndexedNotNullTo(
destination: C,
transform: (index: Int, V) -> Result<U, E>?
): Result<C, E> {
return Ok(mapIndexedNotNullTo(destination) { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
| kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt | 3133650733 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package openxr
import org.lwjgl.generator.*
// Handle types
val XrInstance = XR_DEFINE_HANDLE("XrInstance")
val XrSession = XR_DEFINE_HANDLE("XrSession")
val XrSpace = XR_DEFINE_HANDLE("XrSpace")
val XrAction = XR_DEFINE_HANDLE("XrAction")
val XrSwapchain = XR_DEFINE_HANDLE("XrSwapchain")
val XrActionSet = XR_DEFINE_HANDLE("XrActionSet")
// Enum types
val XrResult = "XrResult".enumType
val XrStructureType = "XrStructureType".enumType
val XrFormFactor = "XrFormFactor".enumType
val XrViewConfigurationType = "XrViewConfigurationType".enumType
val XrEnvironmentBlendMode = "XrEnvironmentBlendMode".enumType
val XrReferenceSpaceType = "XrReferenceSpaceType".enumType
val XrActionType = "XrActionType".enumType
val XrEyeVisibility = "XrEyeVisibility".enumType
val XrSessionState = "XrSessionState".enumType
val XrObjectType = "XrObjectType".enumType
// Bitmask types
val XrInstanceCreateFlags = typedef(XrFlags64, "XrInstanceCreateFlags")
val XrSessionCreateFlags = typedef(XrFlags64, "XrSessionCreateFlags")
val XrSpaceVelocityFlags = typedef(XrFlags64, "XrSpaceVelocityFlags")
val XrSpaceLocationFlags = typedef(XrFlags64, "XrSpaceLocationFlags")
val XrSwapchainCreateFlags = typedef(XrFlags64, "XrSwapchainCreateFlags")
val XrSwapchainUsageFlags = typedef(XrFlags64, "XrSwapchainUsageFlags")
val XrCompositionLayerFlags = typedef(XrFlags64, "XrCompositionLayerFlags")
val XrViewStateFlags = typedef(XrFlags64, "XrViewStateFlags")
val XrInputSourceLocalizedNameFlags = typedef(XrFlags64, "XrInputSourceLocalizedNameFlags")
// Struct types
val XrApiLayerProperties = struct(Module.OPENXR, "XrApiLayerProperties", mutable = false) {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
Structure specifying layer properties.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_API_LAYER_PROPERTIES</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#EnumerateApiLayerProperties()
"""
Expression("#TYPE_API_LAYER_PROPERTIES")..XrStructureType("type", "the {@code XrStructureType} of this structure.").mutable()
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.").mutable()
charUTF8("layerName", "a string specifying the name of the API layer. Use this name in the ##XrInstanceCreateInfo{@code ::enabledApiLayerNames} array to enable this API layer for an instance.")["XR_MAX_API_LAYER_NAME_SIZE"]
XrVersion("specVersion", "the API version the API layer was written to, encoded as described in the <a target=\"_blank\" href=\"https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\\#api-version-numbers-and-semantics\">API Version Numbers and Semantics</a> section.")
uint32_t("layerVersion", "the version of this API layer. It is an integer, increasing with backward compatible changes.")
charUTF8("description", "a string providing additional details that <b>can</b> be used by the application to identify the API layer.")["XR_MAX_API_LAYER_DESCRIPTION_SIZE"]
}
val XrExtensionProperties = struct(Module.OPENXR, "XrExtensionProperties", mutable = false) {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
Returns properties of available instance extensions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EXTENSION_PROPERTIES</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#EnumerateInstanceExtensionProperties()
"""
Expression("#TYPE_EXTENSION_PROPERTIES")..XrStructureType("type", "the {@code XrStructureType} of this structure.").mutable()
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.").mutable()
charUTF8("extensionName", "a {@code NULL} terminated string specifying the name of the extension.")["XR_MAX_EXTENSION_NAME_SIZE"]
uint32_t("extensionVersion", "the version of this extension. It is an integer, incremented with backward compatible changes.")
}
val XrApplicationInfo = struct(Module.OPENXR, "XrApplicationInfo") {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
Structure specifying application info.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code applicationName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_APPLICATION_NAME_SIZE</li>
<li>{@code engineName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_ENGINE_NAME_SIZE</li>
</ul>
<div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
When using the OpenXR API to implement a reusable engine that will be used by many applications, {@code engineName} <b>should</b> be set to a unique string that identifies the engine, and {@code engineVersion} <b>should</b> encode a representation of the engine’s version. This way, all applications that share this engine version will provide the same {@code engineName} and {@code engineVersion} to the runtime. The engine <b>should</b> then enable individual applications to choose their specific {@code applicationName} and {@code applicationVersion}, enabling one application to be distinguished from another application.
When using the OpenXR API to implement an individual application without a shared engine, the input {@code engineName} <b>should</b> be left empty and {@code engineVersion} <b>should</b> be set to 0. The {@code applicationName} <b>should</b> then be filled in with a unique string that identifies the app and the {@code applicationVersion} <b>should</b> encode a representation of the application’s version.
</div>
<h5>See Also</h5>
##XrInstanceCreateInfo
"""
charUTF8("applicationName", "a non-empty string containing the name of the application.")["XR_MAX_APPLICATION_NAME_SIZE"]
uint32_t("applicationVersion", "an unsigned integer variable containing the developer-supplied version number of the application.")
charUTF8("engineName", "a string containing the name of the engine (if any) used to create the application. It may be empty to indicate no specified engine.")["XR_MAX_ENGINE_NAME_SIZE"]
uint32_t("engineVersion", "an unsigned integer variable containing the developer-supplied version number of the engine used to create the application. May be zero to indicate no specified engine.")
XrVersion("apiVersion", "the version of this API against which the application will run, encoded as described in the <a target=\"_blank\" href=\"https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\\#api-version-numbers-and-semantics\">API Version Numbers and Semantics</a> section. If the runtime does not support the requested {@code apiVersion} it <b>must</b> return #ERROR_API_VERSION_UNSUPPORTED.")
}
val XrInstanceCreateInfo = struct(Module.OPENXR, "XrInstanceCreateInfo") {
documentation =
"""
Structure specifying params of a newly created instance.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_INSTANCE_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrDebugUtilsMessengerCreateInfoEXT</li>
<li>{@code createFlags} <b>must</b> be 0</li>
<li>{@code applicationInfo} <b>must</b> be a valid ##XrApplicationInfo structure</li>
<li>If {@code enabledApiLayerCount} is not 0, {@code enabledApiLayerNames} <b>must</b> be a pointer to an array of {@code enabledApiLayerCount} null-terminated UTF-8 strings</li>
<li>If {@code enabledExtensionCount} is not 0, {@code enabledExtensionNames} <b>must</b> be a pointer to an array of {@code enabledExtensionCount} null-terminated UTF-8 strings</li>
</ul>
<h5>See Also</h5>
##XrApplicationInfo, #CreateInstance()
"""
Expression("#TYPE_INSTANCE_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrDebugUtilsMessengerCreateInfoEXT",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrInstanceCreateFlags("createFlags", "a bitmask of {@code XrInstanceCreateFlags} that identifies options that apply to the creation.")
XrApplicationInfo("applicationInfo", "an instance of ##XrApplicationInfo. This information helps runtimes recognize behavior inherent to classes of applications. ##XrApplicationInfo is defined in detail below.")
AutoSize("enabledApiLayerNames", optional = true)..uint32_t("enabledApiLayerCount", "the number of global API layers to enable.")
charUTF8.const.p.const.p("enabledApiLayerNames", "a pointer to an array of {@code enabledApiLayerCount} strings containing the names of API layers to enable for the created instance. See the <a target=\"_blank\" href=\"https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\\#api-layers-and-extensions\">API Layers And Extensions</a> section for further details.")
AutoSize("enabledExtensionNames", optional = true)..uint32_t("enabledExtensionCount", "the number of global extensions to enable.")
charUTF8.const.p.const.p("enabledExtensionNames", "a pointer to an array of {@code enabledExtensionCount} strings containing the names of extensions to enable.")
}
val XrInstanceProperties = struct(Module.OPENXR, "XrInstanceProperties", mutable = false) {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
Contains information about the instance.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_INSTANCE_PROPERTIES</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#GetInstanceProperties()
"""
Expression("#TYPE_INSTANCE_PROPERTIES")..XrStructureType("type", "the {@code XrStructureType} of this structure.").mutable()
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.").mutable()
XrVersion("runtimeVersion", "the runtime’s version (not necessarily related to an OpenXR API version), expressed in the format of #XR_MAKE_VERSION().")
charUTF8("runtimeName", "the name of the runtime.")["XR_MAX_RUNTIME_NAME_SIZE"]
}
val XrEventDataBuffer = struct(Module.OPENXR, "XrEventDataBuffer") {
documentation =
"""
Event buffer.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_BUFFER</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrEventDataBaseHeader, #PollEvent()
"""
Expression("#TYPE_EVENT_DATA_BUFFER")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
uint8_t("varying", "a fixed sized output buffer big enough to hold returned data elements for all specified event data types.")[4000]
}
val XrSystemGetInfo = struct(Module.OPENXR, "XrSystemGetInfo") {
documentation =
"""
Specifies desired attributes of the system.
<h5>Description</h5>
The ##XrSystemGetInfo structure specifies attributes about a system as desired by an application.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SYSTEM_GET_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code formFactor} <b>must</b> be a valid {@code XrFormFactor} value</li>
</ul>
<h5>See Also</h5>
#GetSystem()
"""
Expression("#TYPE_SYSTEM_GET_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrFormFactor("formFactor", "the {@code XrFormFactor} requested by the application.")
}
val XrSystemGraphicsProperties = struct(Module.OPENXR, "XrSystemGraphicsProperties") {
documentation =
"""
Graphics-related properties of a particular system.
<h5>See Also</h5>
##XrSystemProperties, ##XrSystemTrackingProperties, #GetSystem(), #GetSystemProperties()
"""
uint32_t("maxSwapchainImageHeight", "the maximum swapchain image pixel height supported by this system.")
uint32_t("maxSwapchainImageWidth", "the maximum swapchain image pixel width supported by this system.")
uint32_t("maxLayerCount", "the maximum number of composition layers supported by this system. The runtime <b>must</b> support at least #MIN_COMPOSITION_LAYERS_SUPPORTED layers.")
}
val XrSystemTrackingProperties = struct(Module.OPENXR, "XrSystemTrackingProperties") {
documentation =
"""
Tracking-related properties of a particular system.
<h5>See Also</h5>
##XrSystemGraphicsProperties, ##XrSystemProperties, #GetSystem(), #GetSystemProperties()
"""
XrBool32("orientationTracking", "set to #TRUE to indicate the system supports orientational tracking of the view pose(s), #FALSE otherwise.")
XrBool32("positionTracking", "set to #TRUE to indicate the system supports positional tracking of the view pose(s), #FALSE otherwise.")
}
val XrSystemProperties = struct(Module.OPENXR, "XrSystemProperties", mutable = false) {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
Properties of a particular system.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SYSTEM_PROPERTIES</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrRenderModelCapabilitiesRequestFB, ##XrSystemColorSpacePropertiesFB, ##XrSystemEyeGazeInteractionPropertiesEXT, ##XrSystemFacialTrackingPropertiesHTC, ##XrSystemFoveatedRenderingPropertiesVARJO, ##XrSystemHandTrackingMeshPropertiesMSFT, ##XrSystemHandTrackingPropertiesEXT, ##XrSystemKeyboardTrackingPropertiesFB, ##XrSystemMarkerTrackingPropertiesVARJO, ##XrSystemPassthroughPropertiesFB, ##XrSystemRenderModelPropertiesFB, ##XrSystemSpaceWarpPropertiesFB, ##XrSystemSpatialEntityPropertiesFB</li>
</ul>
<h5>See Also</h5>
##XrSystemGraphicsProperties, ##XrSystemTrackingProperties, #GetSystem(), #GetSystemProperties()
"""
Expression("#TYPE_SYSTEM_PROPERTIES")..XrStructureType("type", "the {@code XrStructureType} of this structure.").mutable()
PointerSetter(
"XrRenderModelCapabilitiesRequestFB", "XrSystemColorSpacePropertiesFB", "XrSystemEyeGazeInteractionPropertiesEXT", "XrSystemFacialTrackingPropertiesHTC", "XrSystemFoveatedRenderingPropertiesVARJO", "XrSystemHandTrackingMeshPropertiesMSFT", "XrSystemHandTrackingPropertiesEXT", "XrSystemKeyboardTrackingPropertiesFB", "XrSystemMarkerTrackingPropertiesVARJO", "XrSystemPassthroughPropertiesFB", "XrSystemRenderModelPropertiesFB", "XrSystemSpaceWarpPropertiesFB", "XrSystemSpatialEntityPropertiesFB",
prepend = true
)..nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.").mutable()
XrSystemId("systemId", "the {@code XrSystemId} identifying the system.")
uint32_t("vendorId", "a unique identifier for the vendor of the system.")
charUTF8("systemName", "a string containing the name of the system.")["XR_MAX_SYSTEM_NAME_SIZE"]
XrSystemGraphicsProperties("graphicsProperties", "an ##XrSystemGraphicsProperties structure specifying the system graphics properties.")
XrSystemTrackingProperties("trackingProperties", "an ##XrSystemTrackingProperties structure specifying system tracking properties.")
}
val XrSessionCreateInfo = struct(Module.OPENXR, "XrSessionCreateInfo") {
documentation =
"""
Creates a session.
<h5>Valid Usage</h5>
<ul>
<li>{@code systemId} <b>must</b> be a valid {@code XrSystemId} or #ERROR_SYSTEM_INVALID <b>must</b> be returned.</li>
<li>{@code next}, unless otherwise specified via an extension, <b>must</b> contain exactly one graphics API binding structure (a structure whose name begins with “XrGraphicsBinding”) or #ERROR_GRAPHICS_DEVICE_INVALID <b>must</b> be returned.</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SESSION_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrGraphicsBindingEGLMNDX, ##XrGraphicsBindingOpenGLWaylandKHR, ##XrGraphicsBindingOpenGLWin32KHR, ##XrGraphicsBindingOpenGLXcbKHR, ##XrGraphicsBindingOpenGLXlibKHR, ##XrGraphicsBindingVulkanKHR, ##XrHolographicWindowAttachmentMSFT, ##XrSessionCreateInfoOverlayEXTX</li>
<li>{@code createFlags} <b>must</b> be 0</li>
</ul>
<h5>See Also</h5>
#CreateSession()
"""
Expression("#TYPE_SESSION_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrGraphicsBindingEGLMNDX", "XrGraphicsBindingOpenGLWaylandKHR", "XrGraphicsBindingOpenGLWin32KHR", "XrGraphicsBindingOpenGLXcbKHR", "XrGraphicsBindingOpenGLXlibKHR", "XrGraphicsBindingVulkan2KHR", "XrGraphicsBindingVulkanKHR", "XrHolographicWindowAttachmentMSFT", "XrSessionCreateInfoOverlayEXTX",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR. Note that in most cases one graphics API extension specific struct needs to be in this next chain.")
XrSessionCreateFlags("createFlags", "identifies {@code XrSessionCreateFlags} that apply to the creation.")
XrSystemId("systemId", "the {@code XrSystemId} representing the system of devices to be used by this session.")
}
val XrVector3f = struct(Module.OPENXR, "XrVector3f") {
documentation =
"""
Three-dimensional vector.
<h5>Description</h5>
If used to represent physical distances (rather than e.g. velocity or angular velocity) and not otherwise specified, values <b>must</b> be in meters.
<h5>See Also</h5>
##XrCompositionLayerReprojectionPlaneOverrideMSFT, ##XrGeometryInstanceCreateInfoFB, ##XrGeometryInstanceTransformFB, ##XrHandCapsuleFB, ##XrHandJointVelocityEXT, ##XrHandMeshVertexMSFT, ##XrHandTrackingMeshFB, ##XrKeyboardTrackingDescriptionFB, ##XrPosef, ##XrQuaternionf, ##XrSceneMeshVertexBufferMSFT, ##XrSceneOrientedBoxBoundMSFT, ##XrSceneSphereBoundMSFT, ##XrSpaceVelocity, ##XrTriangleMeshCreateInfoFB, ##XrVector2f, ##XrVector4f, #TriangleMeshGetVertexBufferFB()
"""
float("x", "the x coordinate of the vector.")
float("y", "the y coordinate of the vector.")
float("z", "the z coordinate of the vector.")
}
val XrSpaceVelocity = struct(Module.OPENXR, "XrSpaceVelocity") {
documentation =
"""
Contains info about a space.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SPACE_VELOCITY</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code velocityFlags} <b>must</b> be 0 or a valid combination of {@code XrSpaceVelocityFlagBits} values</li>
</ul>
<h5>See Also</h5>
##XrSpaceLocation, ##XrVector3f, #LocateSpace()
"""
Expression("#TYPE_SPACE_VELOCITY")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrSpaceVelocityFlags("velocityFlags", "a bitfield, with bit masks defined in {@code XrSpaceVelocityFlagBits}, to indicate which members contain valid data. If none of the bits are set, no other fields in this structure <b>should</b> be considered to be valid or meaningful.")
XrVector3f("linearVelocity", "the relative linear velocity of the origin of #LocateSpace(){@code ::space} with respect to and expressed in the reference frame of #LocateSpace(){@code ::baseSpace}, in units of meters per second.")
XrVector3f("angularVelocity", "the relative angular velocity of #LocateSpace(){@code ::space} with respect to #LocateSpace(){@code ::baseSpace}. The vector’s direction is expressed in the reference frame of #LocateSpace(){@code ::baseSpace} and is parallel to the rotational axis of #LocateSpace(){@code ::space}. The vector’s magnitude is the relative angular speed of #LocateSpace(){@code ::space} in radians per second. The vector follows the right-hand rule for torque/rotation.")
}
val XrQuaternionf = struct(Module.OPENXR, "XrQuaternionf") {
documentation =
"""
Unit Quaternion.
<h5>See Also</h5>
##XrCompositionLayerCubeKHR, ##XrPosef, ##XrVector2f, ##XrVector3f, ##XrVector4f
"""
float("x", "the x coordinate of the quaternion.")
float("y", "the y coordinate of the quaternion.")
float("z", "the z coordinate of the quaternion.")
float("w", "the w coordinate of the quaternion.")
}
val XrPosef = struct(Module.OPENXR, "XrPosef") {
documentation =
"""
Location and orientation in a space.
<h5>Description</h5>
A runtime <b>must</b> return #ERROR_POSE_INVALID if the {@code orientation} norm deviates by more than 1% from unit length.
<h5>See Also</h5>
##XrActionSpaceCreateInfo, ##XrCompositionLayerCylinderKHR, ##XrCompositionLayerEquirect2KHR, ##XrCompositionLayerEquirectKHR, ##XrCompositionLayerProjectionView, ##XrCompositionLayerQuad, ##XrCompositionLayerSpaceWarpInfoFB, ##XrControllerModelNodeStateMSFT, ##XrEventDataReferenceSpaceChangePending, ##XrGeometryInstanceCreateInfoFB, ##XrGeometryInstanceTransformFB, ##XrHandJointLocationEXT, ##XrHandMeshSpaceCreateInfoMSFT, ##XrHandTrackingAimStateFB, ##XrHandTrackingMeshFB, ##XrMarkerSpaceCreateInfoVARJO, ##XrQuaternionf, ##XrReferenceSpaceCreateInfo, ##XrSceneComponentLocationMSFT, ##XrSceneFrustumBoundMSFT, ##XrSceneOrientedBoxBoundMSFT, ##XrSpaceLocation, ##XrSpatialAnchorCreateInfoFB, ##XrSpatialAnchorCreateInfoMSFT, ##XrSpatialAnchorSpaceCreateInfoMSFT, ##XrSpatialGraphNodeBindingPropertiesMSFT, ##XrSpatialGraphNodeSpaceCreateInfoMSFT, ##XrSpatialGraphStaticNodeBindingCreateInfoMSFT, ##XrVector2f, ##XrVector3f, ##XrVector4f, ##XrView, #SetInputDeviceLocationEXT()
"""
XrQuaternionf("orientation", "an ##XrQuaternionf representing the orientation within a space.")
XrVector3f("position", "an ##XrVector3f representing position within a space.")
}
val XrReferenceSpaceCreateInfo = struct(Module.OPENXR, "XrReferenceSpaceCreateInfo") {
documentation =
"""
Creation info for a reference space.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_REFERENCE_SPACE_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code referenceSpaceType} <b>must</b> be a valid {@code XrReferenceSpaceType} value</li>
</ul>
<h5>See Also</h5>
##XrPosef, #CreateReferenceSpace()
"""
Expression("#TYPE_REFERENCE_SPACE_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrReferenceSpaceType("referenceSpaceType", "the chosen {@code XrReferenceSpaceType}.")
XrPosef("poseInReferenceSpace", "an ##XrPosef defining the position and orientation of the new space’s origin within the natural reference frame of the reference space.")
}
val XrExtent2Df = struct(Module.OPENXR, "XrExtent2Df") {
documentation =
"""
Extent in two dimensions.
<h5>Description</h5>
This structure is used for component values that may be fractional (floating-point). If used to represent physical distances, values <b>must</b> be in meters.
The {@code width} and {@code height} value <b>must</b> be non-negative.
<h5>See Also</h5>
##XrCompositionLayerQuad, ##XrOffset2Df, ##XrRect2Df, ##XrScenePlaneMSFT, #GetMarkerSizeVARJO(), #GetReferenceSpaceBoundsRect()
"""
float("width", "the floating-point width of the extent.")
float("height", "the floating-point height of the extent.")
}
val XrActionSpaceCreateInfo = struct(Module.OPENXR, "XrActionSpaceCreateInfo") {
documentation =
"""
Creation info for an action space.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_SPACE_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code action} <b>must</b> be a valid {@code XrAction} handle</li>
</ul>
<h5>See Also</h5>
##XrPosef, #CreateActionSpace()
"""
Expression("#TYPE_ACTION_SPACE_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrAction("action", "a handle to a pose {@code XrAction} previously created with #CreateAction().")
XrPath("subactionPath", "#NULL_PATH or an {@code XrPath} that was specified when the action was created. If {@code subactionPath} is a valid path not specified when the action was created the runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED. If this parameter is set, the runtime <b>must</b> create a space that is relative to only that subaction’s pose binding.")
XrPosef("poseInActionSpace", "an ##XrPosef defining the position and orientation of the new space’s origin within the natural reference frame of the pose action.")
}
val XrSpaceLocation = struct(Module.OPENXR, "XrSpaceLocation") {
documentation =
"""
Contains info about a space.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SPACE_LOCATION</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrEyeGazeSampleTimeEXT, ##XrSpaceVelocity</li>
<li>{@code locationFlags} <b>must</b> be 0 or a valid combination of {@code XrSpaceLocationFlagBits} values</li>
</ul>
<h5>See Also</h5>
##XrPosef, ##XrSpaceVelocity, #LocateSpace()
"""
Expression("#TYPE_SPACE_LOCATION")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrEyeGazeSampleTimeEXT", "XrSpaceVelocity",
prepend = true
)..nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain, such as ##XrSpaceVelocity.")
XrSpaceLocationFlags("locationFlags", "a bitfield, with bit masks defined in {@code XrSpaceLocationFlagBits}, to indicate which members contain valid data. If none of the bits are set, no other fields in this structure <b>should</b> be considered to be valid or meaningful.")
XrPosef("pose", "an ##XrPosef defining the position and orientation of the origin of #LocateSpace(){@code ::space} within the reference frame of #LocateSpace(){@code ::baseSpace}.")
}
val XrViewConfigurationProperties = struct(Module.OPENXR, "XrViewConfigurationProperties") {
documentation =
"""
Detailed configuration properties for an XrViewConfigurationProperties.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_VIEW_CONFIGURATION_PROPERTIES</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code viewConfigurationType} <b>must</b> be a valid {@code XrViewConfigurationType} value</li>
</ul>
<h5>See Also</h5>
##XrViewConfigurationView, #GetViewConfigurationProperties()
"""
Expression("#TYPE_VIEW_CONFIGURATION_PROPERTIES")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrViewConfigurationType("viewConfigurationType", "the {@code XrViewConfigurationType} of the configuration.")
XrBool32("fovMutable", "indicates if the view field of view can be modified by the application.")
}
val XrViewConfigurationView = struct(Module.OPENXR, "XrViewConfigurationView") {
documentation =
"""
Individual view configuration.
<h5>Description</h5>
See ##XrSwapchainSubImage for more information about {@code imageRect} values, and ##XrSwapchainCreateInfo for more information about creating swapchains appropriately sized to support those {@code imageRect} values.
The array of ##XrViewConfigurationView returned by the runtime <b>must</b> adhere to the rules defined in <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#view_configuration_type">{@code XrViewConfigurationType}</a>, such as the count and association to the left and right eyes.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_VIEW_CONFIGURATION_VIEW</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrFoveatedViewConfigurationViewVARJO, ##XrViewConfigurationDepthRangeEXT, ##XrViewConfigurationViewFovEPIC</li>
</ul>
<h5>See Also</h5>
##XrViewConfigurationProperties, #EnumerateViewConfigurationViews()
"""
Expression("#TYPE_VIEW_CONFIGURATION_VIEW")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrFoveatedViewConfigurationViewVARJO", "XrViewConfigurationDepthRangeEXT", "XrViewConfigurationViewFovEPIC",
prepend = true
)..nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
uint32_t("recommendedImageRectWidth", "the optimal width of {@code imageRect} to use when rendering this view into a swapchain.")
uint32_t("maxImageRectWidth", "the maximum width of {@code imageRect} supported when rendering this view into a swapchain.")
uint32_t("recommendedImageRectHeight", "the optimal height of {@code imageRect} to use when rendering this view into a swapchain.")
uint32_t("maxImageRectHeight", "the maximum height of {@code imageRect} supported when rendering this view into a swapchain.")
uint32_t("recommendedSwapchainSampleCount", "the recommended number of sub-data element samples to create for each swapchain image that will be rendered into for this view.")
uint32_t("maxSwapchainSampleCount", "the maximum number of sub-data element samples supported for swapchain images that will be rendered into for this view.")
}
val XrSwapchainCreateInfo = struct(Module.OPENXR, "XrSwapchainCreateInfo") {
documentation =
"""
Creation info for a swapchain.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SWAPCHAIN_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrSecondaryViewConfigurationSwapchainCreateInfoMSFT, ##XrSwapchainCreateInfoFoveationFB, ##XrVulkanSwapchainCreateInfoMETA</li>
<li>{@code createFlags} <b>must</b> be 0 or a valid combination of {@code XrSwapchainCreateFlagBits} values</li>
<li>{@code usageFlags} <b>must</b> be 0 or a valid combination of {@code XrSwapchainUsageFlagBits} values</li>
</ul>
<h5>See Also</h5>
#CreateSession(), #CreateSwapchain(), #EnumerateSwapchainFormats()
"""
Expression("#TYPE_SWAPCHAIN_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrSecondaryViewConfigurationSwapchainCreateInfoMSFT", "XrSwapchainCreateInfoFoveationFB", "XrVulkanSwapchainCreateInfoMETA",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrSwapchainCreateFlags("createFlags", "a bitmask of {@code XrSwapchainCreateFlagBits} describing additional properties of the swapchain.")
XrSwapchainUsageFlags("usageFlags", "a bitmask of {@code XrSwapchainUsageFlagBits} describing the intended usage of the swapchain’s images. The usage flags define how the corresponding graphics API objects are created. A mismatch <b>may</b> result in swapchain images that do not support the application’s usage.")
int64_t("format", "a graphics API-specific texture format identifier. For example, if the graphics API specified in #CreateSession() is Vulkan, then this format is a Vulkan format such as {@code VK_FORMAT_R8G8B8A8_SRGB}. The format identifies the format that the runtime will interpret the texture as upon submission. Valid formats are indicated by #EnumerateSwapchainFormats().")
uint32_t("sampleCount", "the number of sub-data element samples in the image, <b>must</b> not be 0 or greater than the graphics API’s maximum limit.")
uint32_t("width", "the width of the image, <b>must</b> not be 0 or greater than the graphics API’s maximum limit.")
uint32_t("height", "the height of the image, <b>must</b> not be 0 or greater than the graphics API’s maximum limit.")
uint32_t("faceCount", "the number of faces, which can be either 6 (for cubemaps) or 1.")
uint32_t("arraySize", "the number of array layers in the image or 1 for a 2D image, <b>must</b> not be 0 or greater than the graphics API’s maximum limit.")
uint32_t("mipCount", "describes the number of levels of detail available for minified sampling of the image, <b>must</b> not be 0 or greater than the graphics API’s maximum limit.")
}
val XrSwapchainImageBaseHeader = struct(Module.OPENXR, "XrSwapchainImageBaseHeader") {
documentation =
"""
Image base header for a swapchain image.
<h5>Description</h5>
The ##XrSwapchainImageBaseHeader is a base structure that can be overridden by a graphics API-specific stext:XrSwapchainImage* child structure.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be one of the following XrStructureType values: #TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR, #TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR, #TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#EnumerateSwapchainImages()
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrSwapchainImageAcquireInfo = struct(Module.OPENXR, "XrSwapchainImageAcquireInfo") {
documentation =
"""
Describes a swapchain image acquisition.
<h5>Description</h5>
Because this structure only exists to support extension-specific structures, #AcquireSwapchainImage() will accept a {@code NULL} argument for {@code acquireInfo} for applications that are not using any relevant extensions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#AcquireSwapchainImage()
"""
Expression("#TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrSwapchainImageWaitInfo = struct(Module.OPENXR, "XrSwapchainImageWaitInfo") {
documentation =
"""
Describes a swapchain image wait operation.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SWAPCHAIN_IMAGE_WAIT_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#WaitSwapchainImage()
"""
Expression("#TYPE_SWAPCHAIN_IMAGE_WAIT_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrDuration("timeout", "indicates how many nanoseconds the call should block waiting for the image to become available for writing.")
}
val XrSwapchainImageReleaseInfo = struct(Module.OPENXR, "XrSwapchainImageReleaseInfo") {
documentation =
"""
Describes a swapchain image release.
<h5>Description</h5>
Because this structure only exists to support extension-specific structures, #ReleaseSwapchainImage() will accept a {@code NULL} argument for {@code releaseInfo} for applications that are not using any relevant extensions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#ReleaseSwapchainImage()
"""
Expression("#TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrSessionBeginInfo = struct(Module.OPENXR, "XrSessionBeginInfo") {
documentation =
"""
Struct containing session begin info.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SESSION_BEGIN_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrSecondaryViewConfigurationSessionBeginInfoMSFT</li>
<li>{@code primaryViewConfigurationType} <b>must</b> be a valid {@code XrViewConfigurationType} value</li>
</ul>
<h5>See Also</h5>
#BeginSession()
"""
Expression("#TYPE_SESSION_BEGIN_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrSecondaryViewConfigurationSessionBeginInfoMSFT",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrViewConfigurationType("primaryViewConfigurationType", "the {@code XrViewConfigurationType} to use during this session to provide images for the form factor’s primary displays.")
}
val XrFrameWaitInfo = struct(Module.OPENXR, "XrFrameWaitInfo") {
documentation =
"""
Wait frame information structure.
<h5>Description</h5>
Because this structure only exists to support extension-specific structures, #WaitFrame() <b>must</b> accept a {@code NULL} argument for {@code frameWaitInfo} for applications that are not using any relevant extensions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_FRAME_WAIT_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrFrameState, #WaitFrame()
"""
Expression("#TYPE_FRAME_WAIT_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrFrameState = struct(Module.OPENXR, "XrFrameState") {
documentation =
"""
Frame prediction structure.
<h5>Description</h5>
##XrFrameState describes the time at which the next frame will be displayed to the user. {@code predictedDisplayTime} <b>must</b> refer to the midpoint of the interval during which the frame is displayed. The runtime <b>may</b> report a different {@code predictedDisplayPeriod} from the hardware’s refresh cycle.
For any frame where {@code shouldRender} is #FALSE, the application <b>should</b> avoid heavy GPU work for that frame, for example by not rendering its layers. This typically happens when the application is transitioning into or out of a running session, or when some system UI is fully covering the application at the moment. As long as the session <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#session_running">is running</a>, the application <b>should</b> keep running the frame loop to maintain the frame synchronization to the runtime, even if this requires calling #EndFrame() with all layers omitted.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_FRAME_STATE</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrSecondaryViewConfigurationFrameStateMSFT</li>
</ul>
<h5>See Also</h5>
##XrFrameWaitInfo, #WaitFrame()
"""
Expression("#TYPE_FRAME_STATE")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrSecondaryViewConfigurationFrameStateMSFT",
prepend = true
)..nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrTime("predictedDisplayTime", "the anticipated display {@code XrTime} for the next application-generated frame.")
XrDuration("predictedDisplayPeriod", "the {@code XrDuration} of the display period for the next application-generated frame, for use in predicting display times beyond the next one.")
XrBool32("shouldRender", "#TRUE if the application <b>should</b> render its layers as normal and submit them to #EndFrame(). When this value is #FALSE, the application <b>should</b> avoid heavy GPU work where possible, for example by skipping layer rendering and then omitting those layers when calling #EndFrame().")
}
val XrFrameBeginInfo = struct(Module.OPENXR, "XrFrameBeginInfo") {
documentation =
"""
Begin frame information.
<h5>Description</h5>
Because this structure only exists to support extension-specific structures, #BeginFrame() will accept a {@code NULL} argument for {@code frameBeginInfo} for applications that are not using any relevant extensions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_FRAME_BEGIN_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#BeginFrame(), #WaitFrame()
"""
Expression("#TYPE_FRAME_BEGIN_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrCompositionLayerBaseHeader = struct(Module.OPENXR, "XrCompositionLayerBaseHeader") {
documentation =
"""
Composition layer base header.
<h5>Description</h5>
All composition layer structures begin with the elements described in the ##XrCompositionLayerBaseHeader. The ##XrCompositionLayerBaseHeader structure is not intended to be directly used, but forms a basis for defining current and future structures containing composition layer information. The ##XrFrameEndInfo structure contains an array of pointers to these polymorphic header structures. All composition layer type pointers <b>must</b> be type-castable as an ##XrCompositionLayerBaseHeader pointer.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be one of the following XrStructureType values: #TYPE_COMPOSITION_LAYER_CUBE_KHR, #TYPE_COMPOSITION_LAYER_CYLINDER_KHR, #TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR, #TYPE_COMPOSITION_LAYER_EQUIRECT_KHR, #TYPE_COMPOSITION_LAYER_PROJECTION, #TYPE_COMPOSITION_LAYER_QUAD</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrCompositionLayerAlphaBlendFB, ##XrCompositionLayerColorScaleBiasKHR, ##XrCompositionLayerImageLayoutFB, ##XrCompositionLayerPassthroughFB, ##XrCompositionLayerSecureContentFB, ##XrCompositionLayerSettingsFB</li>
<li>{@code layerFlags} <b>must</b> be 0 or a valid combination of {@code XrCompositionLayerFlagBits} values</li>
<li>{@code space} <b>must</b> be a valid {@code XrSpace} handle</li>
</ul>
<h5>See Also</h5>
##XrFrameEndInfo, ##XrSecondaryViewConfigurationLayerInfoMSFT, ##XrSwapchainSubImage
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
PointerSetter(
"XrCompositionLayerAlphaBlendFB", "XrCompositionLayerColorScaleBiasKHR", "XrCompositionLayerImageLayoutFB", "XrCompositionLayerPassthroughFB", "XrCompositionLayerSecureContentFB", "XrCompositionLayerSettingsFB",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrCompositionLayerFlags("layerFlags", "a bitmask of {@code XrCompositionLayerFlagBits} describing flags to apply to the layer.")
XrSpace("space", "the {@code XrSpace} in which the layer will be kept stable over time.")
}
val XrFrameEndInfo = struct(Module.OPENXR, "XrFrameEndInfo") {
documentation =
"""
End frame information.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_FRAME_END_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrSecondaryViewConfigurationFrameEndInfoMSFT</li>
<li>{@code environmentBlendMode} <b>must</b> be a valid {@code XrEnvironmentBlendMode} value</li>
<li>If {@code layerCount} is not 0, {@code layers} <b>must</b> be a pointer to an array of {@code layerCount} valid ##XrCompositionLayerBaseHeader-based structures. See also: ##XrCompositionLayerCubeKHR, ##XrCompositionLayerCylinderKHR, ##XrCompositionLayerEquirect2KHR, ##XrCompositionLayerEquirectKHR, ##XrCompositionLayerProjection, ##XrCompositionLayerQuad</li>
</ul>
<h5>See Also</h5>
##XrCompositionLayerBaseHeader, #EndFrame()
"""
Expression("#TYPE_FRAME_END_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrSecondaryViewConfigurationFrameEndInfoMSFT",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrTime("displayTime", "the {@code XrTime} at which this frame <b>should</b> be displayed.")
XrEnvironmentBlendMode("environmentBlendMode", "the {@code XrEnvironmentBlendMode} value representing the desired <a target=\"_blank\" href=\"https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\\#environment_blend_mode\">environment blend mode</a> for this frame.")
AutoSize("layers", optional = true)..uint32_t("layerCount", "the number of composition layers in this frame. The maximum supported layer count is identified by ##XrSystemGraphicsProperties::maxLayerCount. If layerCount is greater than the maximum supported layer count then #ERROR_LAYER_LIMIT_EXCEEDED <b>must</b> be returned.")
nullable..XrCompositionLayerBaseHeader.const.p.const.p("layers", "a pointer to an array of ##XrCompositionLayerBaseHeader pointers.")
}
val XrViewLocateInfo = struct(Module.OPENXR, "XrViewLocateInfo") {
documentation =
"""
Struct containing view locate information.
<h5>Description</h5>
The ##XrViewLocateInfo structure contains the display time and space used to locate the view ##XrView structures.
The runtime <b>must</b> return error #ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED if the given {@code viewConfigurationType} is not one of the supported type reported by #EnumerateViewConfigurations().
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_VIEW_LOCATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrViewLocateFoveatedRenderingVARJO</li>
<li>{@code viewConfigurationType} <b>must</b> be a valid {@code XrViewConfigurationType} value</li>
<li>{@code space} <b>must</b> be a valid {@code XrSpace} handle</li>
</ul>
<h5>See Also</h5>
##XrView, ##XrViewState, #LocateViews()
"""
Expression("#TYPE_VIEW_LOCATE_INFO")..XrStructureType("type", "")
PointerSetter(
"XrViewLocateFoveatedRenderingVARJO",
prepend = true
)..nullable..opaque_const_p("next", "")
XrViewConfigurationType("viewConfigurationType", "{@code XrViewConfigurationType} to query for.")
XrTime("displayTime", "the time for which the view poses are predicted.")
XrSpace("space", "the {@code XrSpace} in which the {@code pose} in each ##XrView is expressed.")
}
val XrViewState = struct(Module.OPENXR, "XrViewState") {
documentation =
"""
Struct containing additional view state.
<h5>Description</h5>
The ##XrViewState contains additional view state from #LocateViews() common to all views of the active view configuration.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_VIEW_STATE</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code viewStateFlags} <b>must</b> be 0 or a valid combination of {@code XrViewStateFlagBits} values</li>
</ul>
<h5>See Also</h5>
##XrView, #LocateViews()
"""
Expression("#TYPE_VIEW_STATE")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrViewStateFlags("viewStateFlags", "a bitmask of {@code XrViewStateFlagBits} indicating state for all views.")
}
val XrFovf = struct(Module.OPENXR, "XrFovf") {
documentation =
"""
Field of view.
<h5>Description</h5>
Angles to the right of the center and upwards from the center are positive, and angles to the left of the center and down from the center are negative. The total horizontal field of view is {@code angleRight} minus {@code angleLeft}, and the total vertical field of view is {@code angleUp} minus {@code angleDown}. For a symmetric FoV, {@code angleRight} and {@code angleUp} will have positive values, {@code angleLeft} will be -{@code angleRight}, and {@code angleDown} will be -{@code angleUp}.
The angles <b>must</b> be specified in radians, and <b>must</b> be between <code>-π/2</code> and <code>π/2</code> exclusively.
When {@code angleLeft} > {@code angleRight}, the content of the view <b>must</b> be flipped horizontally. When {@code angleDown} > {@code angleUp}, the content of the view <b>must</b> be flipped vertically.
<h5>See Also</h5>
##XrCompositionLayerProjectionView, ##XrSceneFrustumBoundMSFT, ##XrView, ##XrViewConfigurationViewFovEPIC
"""
float("angleLeft", "the angle of the left side of the field of view. For a symmetric field of view this value is negative.")
float("angleRight", "the angle of the right side of the field of view.")
float("angleUp", "the angle of the top part of the field of view.")
float("angleDown", "the angle of the bottom part of the field of view. For a symmetric field of view this value is negative.")
}
val XrView = struct(Module.OPENXR, "XrView") {
documentation =
"""
Struct containing view projection state.
<h5>Description</h5>
The ##XrView structure contains view pose and projection state necessary to render a single projection view in the view configuration.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_VIEW</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrFovf, ##XrPosef, ##XrViewLocateInfo, ##XrViewState, #LocateViews()
"""
Expression("#TYPE_VIEW")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrPosef("pose", "an ##XrPosef defining the location and orientation of the view in the {@code space} specified by the #LocateViews() function.")
XrFovf("fov", "the ##XrFovf for the four sides of the projection.")
}
val XrActionSetCreateInfo = struct(Module.OPENXR, "XrActionSetCreateInfo") {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
XrActionSet creation info.
<h5>Description</h5>
When multiple actions are bound to the same input source, the {@code priority} of each action set determines which bindings are suppressed. Runtimes <b>must</b> ignore input sources from action sets with a lower priority number if those specific input sources are also present in active actions within a higher priority action set. If multiple action sets with the same priority are bound to the same input source and that is the highest priority number, runtimes <b>must</b> process all those bindings at the same time.
Two actions are considered to be bound to the same input source if they use the same <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#semantic-path-input">identifier and optional location</a> path segments, even if they have different component segments.
When runtimes are ignoring bindings because of priority, they <b>must</b> treat the binding to that input source as though they do not exist. That means the {@code isActive} field <b>must</b> be #FALSE when retrieving action data, and that the runtime <b>must</b> not provide any visual, haptic, or other feedback related to the binding of that action to that input source. Other actions in the same action set which are bound to input sources that do not collide are not affected and are processed as normal.
If {@code actionSetName} or {@code localizedActionSetName} are empty strings, the runtime <b>must</b> return #ERROR_NAME_INVALID or #ERROR_LOCALIZED_NAME_INVALID respectively. If {@code actionSetName} or {@code localizedActionSetName} are duplicates of the corresponding field for any existing action set in the specified instance, the runtime <b>must</b> return #ERROR_NAME_DUPLICATED or #ERROR_LOCALIZED_NAME_DUPLICATED respectively. If the conflicting action set is destroyed, the conflicting field is no longer considered duplicated. If {@code actionSetName} contains characters which are not allowed in a single level of a <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#well-formed-path-strings">well-formed path string</a>, the runtime <b>must</b> return #ERROR_PATH_FORMAT_INVALID.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_SET_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code actionSetName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_ACTION_SET_NAME_SIZE</li>
<li>{@code localizedActionSetName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_LOCALIZED_ACTION_SET_NAME_SIZE</li>
</ul>
<h5>See Also</h5>
#CreateActionSet()
"""
Expression("#TYPE_ACTION_SET_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
charUTF8("actionSetName", "an array containing a {@code NULL} terminated non-empty string with the name of this action set.")["XR_MAX_ACTION_SET_NAME_SIZE"]
charUTF8("localizedActionSetName", "an array containing a {@code NULL} terminated {@code UTF}-8 string that can be presented to the user as a description of the action set. This string should be presented in the system’s current active locale.")["XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE"]
uint32_t("priority", "defines which action sets' actions are active on a given input source when actions on multiple active action sets are bound to the same input source. Larger priority numbers take precedence over smaller priority numbers.")
}
val XrActionCreateInfo = struct(Module.OPENXR, "XrActionCreateInfo") {
javaImport("static org.lwjgl.openxr.XR10.*")
documentation =
"""
XrAction creation info.
<h5>Description</h5>
Subaction paths are a mechanism that enables applications to use the same action name and handle on multiple devices. Applications can query action state using subaction paths that differentiate data coming from each device. This allows the runtime to group logically equivalent actions together in system UI. For instance, an application could create a single actionname:pick_up action with the pathname:/user/hand/left and pathname:/user/hand/right subaction paths and use the subaction paths to independently query the state of actionname:pick_up_with_left_hand and actionname:pick_up_with_right_hand.
Applications <b>can</b> create actions with or without the {@code subactionPaths} set to a list of paths. If this list of paths is omitted (i.e. {@code subactionPaths} is set to {@code NULL}, and {@code countSubactionPaths} is set to 0), the application is opting out of filtering action results by subaction paths and any call to get action data must also omit subaction paths.
If {@code subactionPaths} is specified and any of the following conditions are not satisfied, the runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED:
<ul>
<li>
Each path provided is one of:
<ul>
<li>pathname:/user/head</li>
<li>pathname:/user/hand/left</li>
<li>pathname:/user/hand/right</li>
<li>pathname:/user/gamepad</li>
</ul>
</li>
<li>No path appears in the list more than once</li>
</ul>
Extensions <b>may</b> append additional top level user paths to the above list.
<div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
Earlier revisions of the spec mentioned pathname:/user but it could not be implemented as specified and was removed as errata.
</div>
The runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED in the following circumstances:
<ul>
<li>The application specified subaction paths at action creation and the application called {@code xrGetActionState*} or a haptic function with an empty subaction path array.</li>
<li>The application called {@code xrGetActionState*} or a haptic function with a subaction path that was not specified when the action was created.</li>
</ul>
If {@code actionName} or {@code localizedActionName} are empty strings, the runtime <b>must</b> return #ERROR_NAME_INVALID or #ERROR_LOCALIZED_NAME_INVALID respectively. If {@code actionName} or {@code localizedActionName} are duplicates of the corresponding field for any existing action in the specified action set, the runtime <b>must</b> return #ERROR_NAME_DUPLICATED or #ERROR_LOCALIZED_NAME_DUPLICATED respectively. If the conflicting action is destroyed, the conflicting field is no longer considered duplicated. If {@code actionName} contains characters which are not allowed in a single level of a <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#well-formed-path-strings">well-formed path string</a>, the runtime <b>must</b> return #ERROR_PATH_FORMAT_INVALID.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_CREATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code actionName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_ACTION_NAME_SIZE</li>
<li>{@code actionType} <b>must</b> be a valid {@code XrActionType} value</li>
<li>If {@code countSubactionPaths} is not 0, {@code subactionPaths} <b>must</b> be a pointer to an array of {@code countSubactionPaths} valid {@code XrPath} values</li>
<li>{@code localizedActionName} <b>must</b> be a null-terminated UTF-8 string whose length is less than or equal to #MAX_LOCALIZED_ACTION_NAME_SIZE</li>
</ul>
<h5>See Also</h5>
#CreateAction(), #CreateActionSet()
"""
Expression("#TYPE_ACTION_CREATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
charUTF8("actionName", "an array containing a {@code NULL} terminated string with the name of this action.")["XR_MAX_ACTION_NAME_SIZE"]
XrActionType("actionType", "the {@code XrActionType} of the action to be created.")
AutoSize("subactionPaths", optional = true)..uint32_t("countSubactionPaths", "the number of elements in the {@code subactionPaths} array. If {@code subactionPaths} is NULL, this parameter must be 0.")
nullable..XrPath.const.p("subactionPaths", "an array of {@code XrPath} or {@code NULL}. If this array is specified, it contains one or more subaction paths that the application intends to query action state for.")
charUTF8("localizedActionName", "an array containing a {@code NULL} terminated {@code UTF}-8 string that can be presented to the user as a description of the action. This string should be in the system’s current active locale.")["XR_MAX_LOCALIZED_ACTION_NAME_SIZE"]
}
val XrActionSuggestedBinding = struct(Module.OPENXR, "XrActionSuggestedBinding") {
documentation =
"""
Suggested binding for a single action.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code action} <b>must</b> be a valid {@code XrAction} handle</li>
</ul>
<h5>See Also</h5>
##XrInteractionProfileSuggestedBinding, #SuggestInteractionProfileBindings()
"""
XrAction("action", "the {@code XrAction} handle for an action")
XrPath("binding", "the {@code XrPath} of a binding for the action specified in {@code action}. This path is any top level user path plus input source path, for example pathname:/user/hand/right/input/trigger/click. See <a target=\"_blank\" href=\"https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\\#input-suggested-bindings\">suggested bindings</a> for more details.")
}
val XrInteractionProfileSuggestedBinding = struct(Module.OPENXR, "XrInteractionProfileSuggestedBinding") {
documentation =
"""
Suggested bindings for a interaction profile.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrBindingModificationsKHR</li>
<li>{@code suggestedBindings} <b>must</b> be a pointer to an array of {@code countSuggestedBindings} valid ##XrActionSuggestedBinding structures</li>
<li>The {@code countSuggestedBindings} parameter <b>must</b> be greater than 0</li>
</ul>
<h5>See Also</h5>
##XrActionSuggestedBinding, #SuggestInteractionProfileBindings()
"""
Expression("#TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrBindingModificationsKHR",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrPath("interactionProfile", "the {@code XrPath} of an interaction profile.")
AutoSize("suggestedBindings")..uint32_t("countSuggestedBindings", "the number of suggested bindings in the array pointed to by {@code suggestedBindings}.")
XrActionSuggestedBinding.const.p("suggestedBindings", "a pointer to an array of ##XrActionSuggestedBinding structures that define all of the application’s suggested bindings for the specified interaction profile.")
}
val XrSessionActionSetsAttachInfo = struct(Module.OPENXR, "XrSessionActionSetsAttachInfo") {
documentation =
"""
Information to attach action sets to a session.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_SESSION_ACTION_SETS_ATTACH_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code actionSets} <b>must</b> be a pointer to an array of {@code countActionSets} valid {@code XrActionSet} handles</li>
<li>The {@code countActionSets} parameter <b>must</b> be greater than 0</li>
</ul>
<h5>See Also</h5>
#AttachSessionActionSets()
"""
Expression("#TYPE_SESSION_ACTION_SETS_ATTACH_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
AutoSize("actionSets")..uint32_t("countActionSets", "an integer specifying the number of valid elements in the {@code actionSets} array.")
XrActionSet.const.p("actionSets", "a pointer to an array of one or more {@code XrActionSet} handles to be attached to the session.")
}
val XrInteractionProfileState = struct(Module.OPENXR, "XrInteractionProfileState") {
documentation =
"""
Receives active interaction profile for a top level path.
<h5>Description</h5>
The runtime <b>must</b> only include interaction profiles that the application has provided bindings for via #SuggestInteractionProfileBindings() or #NULL_PATH. If the runtime is rebinding an interaction profile provided by the application to a device that the application did not provide bindings for, it <b>must</b> return the interaction profile path that it is emulating. If the runtime is unable to provide input because it cannot emulate any of the application-provided interaction profiles, it <b>must</b> return #NULL_PATH.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_INTERACTION_PROFILE_STATE</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrActionSuggestedBinding, #GetCurrentInteractionProfile(), #SuggestInteractionProfileBindings()
"""
Expression("#TYPE_INTERACTION_PROFILE_STATE")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrPath("interactionProfile", "the {@code XrPath} of the interaction profile path for the {@code topLevelUserPath} used to retrieve this state, or #NULL_PATH if there is no active interaction profile at that top level user path.")
}
val XrActionStateGetInfo = struct(Module.OPENXR, "XrActionStateGetInfo") {
documentation =
"""
Information to get action state.
<h5>Description</h5>
See ##XrActionCreateInfo for a description of subaction paths, and the restrictions on their use.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_STATE_GET_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code action} <b>must</b> be a valid {@code XrAction} handle</li>
</ul>
<h5>See Also</h5>
#GetActionStateBoolean(), #GetActionStateFloat(), #GetActionStatePose(), #GetActionStateVector2f()
"""
Expression("#TYPE_ACTION_STATE_GET_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrAction("action", "the {@code XrAction} being queried.")
XrPath("subactionPath", "the subaction path {@code XrPath} to query data from, or #NULL_PATH to specify all subaction paths. If the subaction path is specified, it is one of the subaction paths that were specified when the action was created. If the subaction path was not specified when the action was created, the runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED. If this parameter is specified, the runtime <b>must</b> return data that originates only from the subaction paths specified.")
}
val XrActionStateBoolean = struct(Module.OPENXR, "XrActionStateBoolean") {
documentation =
"""
Boolean action state.
<h5>Description</h5>
When multiple input sources are bound to this action, the {@code currentState} follows <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#multiple_inputs">the previously defined rule to resolve ambiguity</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_STATE_BOOLEAN</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#GetActionStateBoolean()
"""
Expression("#TYPE_ACTION_STATE_BOOLEAN")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrBool32("currentState", "the current state of the action.")
XrBool32("changedSinceLastSync", "#TRUE if the value of {@code currentState} is different than it was before the most recent call to #SyncActions(). This parameter can be combined with {@code currentState} to detect rising and falling edges since the previous call to #SyncActions(). E.g. if both {@code changedSinceLastSync} and {@code currentState} are #TRUE then a rising edge (#FALSE to #TRUE) has taken place.")
XrTime("lastChangeTime", "the {@code XrTime} when this action’s value last changed.")
XrBool32("isActive", "#TRUE if and only if there exists an input source that is contributing to the current state of this action.")
}
val XrActionStateFloat = struct(Module.OPENXR, "XrActionStateFloat") {
documentation =
"""
Floating point action state.
<h5>Description</h5>
When multiple input sources are bound to this action, the {@code currentState} follows <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#multiple_inputs">the previously defined rule to resolve ambiguity</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_STATE_FLOAT</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#GetActionStateFloat()
"""
Expression("#TYPE_ACTION_STATE_FLOAT")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
float("currentState", "the current state of the Action.")
XrBool32("changedSinceLastSync", "#TRUE if the value of {@code currentState} is different than it was before the most recent call to #SyncActions().")
XrTime("lastChangeTime", "the {@code XrTime} in nanoseconds since this action’s value last changed.")
XrBool32("isActive", "#TRUE if and only if there exists an input source that is contributing to the current state of this action.")
}
val XrVector2f = struct(Module.OPENXR, "XrVector2f") {
documentation =
"""
Two-dimensional vector.
<h5>Description</h5>
If used to represent physical distances (rather than e.g. normalized direction) and not otherwise specified, values <b>must</b> be in meters.
<h5>See Also</h5>
##XrActionStateVector2f, ##XrBoundary2DFB, ##XrCompositionLayerEquirectKHR, ##XrHandTrackingMeshFB, ##XrPosef, ##XrQuaternionf, ##XrVector3f, ##XrVector4f, ##XrVisibilityMaskKHR, #SetInputDeviceStateVector2fEXT()
"""
float("x", "the x coordinate of the vector.")
float("y", "the y coordinate of the vector.")
}
val XrActionStateVector2f = struct(Module.OPENXR, "XrActionStateVector2f") {
documentation =
"""
2D float vector action state.
<h5>Description</h5>
When multiple input sources are bound to this action, the {@code currentState} follows <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#multiple_inputs">the previously defined rule to resolve ambiguity</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_STATE_VECTOR2F</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrVector2f, #GetActionStateVector2f()
"""
Expression("#TYPE_ACTION_STATE_VECTOR2F")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrVector2f("currentState", "the current ##XrVector2f state of the Action.")
XrBool32("changedSinceLastSync", "#TRUE if the value of {@code currentState} is different than it was before the most recent call to #SyncActions().")
XrTime("lastChangeTime", "the {@code XrTime} in nanoseconds since this action’s value last changed.")
XrBool32("isActive", "#TRUE if and only if there exists an input source that is contributing to the current state of this action.")
}
val XrActionStatePose = struct(Module.OPENXR, "XrActionStatePose") {
documentation =
"""
Pose action metadata.
<h5>Description</h5>
A pose action <b>must</b> not be bound to multiple input sources, according to <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#multiple_inputs">the previously defined rule</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTION_STATE_POSE</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#GetActionStatePose()
"""
Expression("#TYPE_ACTION_STATE_POSE")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrBool32("isActive", "#TRUE if and only if there exists an input source that is being tracked by this pose action.")
}
val XrActiveActionSet = struct(Module.OPENXR, "XrActiveActionSet") {
documentation =
"""
Describes an active action set.
<h5>Description</h5>
This structure defines a single active action set and subaction path combination. Applications <b>can</b> provide a list of these structures to the #SyncActions() function.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code actionSet} <b>must</b> be a valid {@code XrActionSet} handle</li>
</ul>
<h5>See Also</h5>
##XrActionsSyncInfo, #SyncActions()
"""
XrActionSet("actionSet", "the handle of the action set to activate.")
XrPath("subactionPath", "a subaction path that was declared when one or more actions in the action set was created or #NULL_PATH. If the application wants to activate the action set on more than one subaction path, it <b>can</b> include additional ##XrActiveActionSet structs with the other {@code subactionPath} values. Using #NULL_PATH as the value for {@code subactionPath}, acts as a wildcard for all subaction paths on the actions in the action set. If the subaction path was not specified on any of the actions in the actionSet when that action was created, the runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED.")
}
val XrActionsSyncInfo = struct(Module.OPENXR, "XrActionsSyncInfo") {
documentation =
"""
Information to sync actions.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_ACTIONS_SYNC_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>If {@code countActiveActionSets} is not 0, {@code activeActionSets} <b>must</b> be a pointer to an array of {@code countActiveActionSets} valid ##XrActiveActionSet structures</li>
</ul>
<h5>See Also</h5>
##XrActiveActionSet, #SyncActions()
"""
Expression("#TYPE_ACTIONS_SYNC_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
AutoSize("activeActionSets", optional = true)..uint32_t("countActiveActionSets", "an integer specifying the number of valid elements in the {@code activeActionSets} array.")
nullable..XrActiveActionSet.const.p("activeActionSets", "{@code NULL} or a pointer to an array of one or more ##XrActiveActionSet structures that should be synchronized.")
}
val XrBoundSourcesForActionEnumerateInfo = struct(Module.OPENXR, "XrBoundSourcesForActionEnumerateInfo") {
documentation =
"""
Information to query the bound input sources for an action.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code action} <b>must</b> be a valid {@code XrAction} handle</li>
</ul>
<h5>See Also</h5>
#EnumerateBoundSourcesForAction()
"""
Expression("#TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrAction("action", "the handle of the action to query.")
}
val XrInputSourceLocalizedNameGetInfo = struct(Module.OPENXR, "XrInputSourceLocalizedNameGetInfo") {
documentation =
"""
Information to query the bound input sources for an action.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code whichComponents} <b>must</b> be a valid combination of {@code XrInputSourceLocalizedNameFlagBits} values</li>
<li>{@code whichComponents} <b>must</b> not be 0</li>
</ul>
<h5>See Also</h5>
#EnumerateBoundSourcesForAction(), #GetInputSourceLocalizedName()
"""
Expression("#TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrPath("sourcePath", "")
XrInputSourceLocalizedNameFlags("whichComponents", "any set of flags from {@code XrInputSourceLocalizedNameFlagBits}.")
}
val XrHapticActionInfo = struct(Module.OPENXR, "XrHapticActionInfo") {
documentation =
"""
Information to output haptic feedback.
<h5>Description</h5>
See ##XrActionCreateInfo for a description of subaction paths, and the restrictions on their use.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_HAPTIC_ACTION_INFO</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code action} <b>must</b> be a valid {@code XrAction} handle</li>
</ul>
<h5>See Also</h5>
#ApplyHapticFeedback(), #StopHapticFeedback()
"""
Expression("#TYPE_HAPTIC_ACTION_INFO")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrAction("action", "the {@code XrAction} handle for the desired output haptic action.")
XrPath("subactionPath", "the subaction path {@code XrPath} of the device to send the haptic event to, or #NULL_PATH to specify all subaction paths. If the subaction path is specified, it is one of the subaction paths that were specified when the action was created. If the subaction path was not specified when the action was created, the runtime <b>must</b> return #ERROR_PATH_UNSUPPORTED. If this parameter is specified, the runtime <b>must</b> trigger the haptic events only on the device from the subaction path.")
}
val XrHapticBaseHeader = struct(Module.OPENXR, "XrHapticBaseHeader") {
documentation =
"""
Base header for haptic feedback.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_HAPTIC_VIBRATION</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrHapticVibration, ##XrInteractionProfileAnalogThresholdVALVE, ##XrInteractionProfileDpadBindingEXT, #ApplyHapticFeedback()
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val _XrBaseInStructure = struct(Module.OPENXR, "XrBaseInStructure")
val XrBaseInStructure = struct(Module.OPENXR, "XrBaseInStructure") {
documentation =
"""
Convenience type for iterating (read only).
<h5>Description</h5>
##XrBaseInStructure can be used to facilitate iterating through a read-only structure pointer chain.
<h5>See Also</h5>
##XrBaseInStructure, ##XrBaseOutStructure
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
_XrBaseInStructure.const.p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val _XrBaseOutStructure = struct(Module.OPENXR, "XrBaseOutStructure")
val XrBaseOutStructure = struct(Module.OPENXR, "XrBaseOutStructure") {
documentation =
"""
Convenience type for iterating (mutable).
<h5>Description</h5>
##XrBaseOutStructure can be used to facilitate iterating through a structure pointer chain that returns data back to the application.
<h5>See Also</h5>
##XrBaseInStructure, ##XrBaseOutStructure
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
_XrBaseOutStructure.p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrOffset2Di = struct(Module.OPENXR, "XrOffset2Di") {
documentation =
"""
Offset in two dimensions.
<h5>Description</h5>
This variant is for representing discrete values such as texels. For representing physical distances, the floating-point variant <b>must</b> be used instead.
<h5>See Also</h5>
##XrExtent2Di, ##XrRect2Di
"""
int32_t("x", "the integer offset in the x direction.")
int32_t("y", "the integer offset in the y direction.")
}
val XrExtent2Di = struct(Module.OPENXR, "XrExtent2Di") {
documentation =
"""
Extent in two dimensions.
<h5>Description</h5>
This variant is for representing discrete values such as texels. For representing physical distances, the floating-point variant <b>must</b> be used instead.
The {@code width} and {@code height} value <b>must</b> be non-negative.
<h5>See Also</h5>
##XrOffset2Di, ##XrRect2Di
"""
int32_t("width", "the integer width of the extent.")
int32_t("height", "the integer height of the extent.")
}
val XrRect2Di = struct(Module.OPENXR, "XrRect2Di") {
documentation =
"""
Rect in two dimensions.
<h5>Description</h5>
This variant is for representing discrete values such as texels. For representing physical distances, the floating-point variant <b>must</b> be used instead.
<h5>See Also</h5>
##XrExtent2Di, ##XrOffset2Di, ##XrSwapchainSubImage
"""
XrOffset2Di("offset", "the ##XrOffset2Di specifying the integer rectangle offset.")
XrExtent2Di("extent", "the ##XrExtent2Di specifying the integer rectangle extent.")
}
val XrSwapchainSubImage = struct(Module.OPENXR, "XrSwapchainSubImage") {
documentation =
"""
Composition layer data.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code swapchain} <b>must</b> be a valid {@code XrSwapchain} handle</li>
</ul>
<h5>See Also</h5>
##XrCompositionLayerCylinderKHR, ##XrCompositionLayerDepthInfoKHR, ##XrCompositionLayerEquirect2KHR, ##XrCompositionLayerEquirectKHR, ##XrCompositionLayerProjectionView, ##XrCompositionLayerQuad, ##XrCompositionLayerSpaceWarpInfoFB, ##XrFrameEndInfo, ##XrRect2Di
"""
XrSwapchain("swapchain", "the {@code XrSwapchain} to be displayed.")
XrRect2Di("imageRect", "an ##XrRect2Di representing the valid portion of the image to use, in pixels. It also implicitly defines the transform from normalized image coordinates into pixel coordinates. The coordinate origin depends on which graphics API is being used. See the graphics API extension details for more information on the coordinate origin definition. Note that the compositor <b>may</b> bleed in pixels from outside the bounds in some cases, for instance due to mipmapping.")
uint32_t("imageArrayIndex", "the image array index, with 0 meaning the first or only array element.")
}
val XrCompositionLayerProjectionView = struct(Module.OPENXR, "XrCompositionLayerProjectionView") {
documentation =
"""
Projection layer element.
<h5>Description</h5>
The count and order of view poses submitted with ##XrCompositionLayerProjection <b>must</b> be the same order as that returned by #LocateViews(). The ##XrCompositionLayerProjectionView{@code ::pose} and ##XrCompositionLayerProjectionView{@code ::fov} <b>should</b> almost always derive from ##XrView{@code ::pose} and ##XrView{@code ::fov} as found in the #LocateViews(){@code ::views} array. However, applications <b>may</b> submit an ##XrCompositionLayerProjectionView which has a different view or FOV than that from #LocateViews(). In this case, the runtime will map the view and FOV to the system display appropriately. In the case that two submitted views within a single layer overlap, they <b>must</b> be composited in view array order.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_COMPOSITION_LAYER_PROJECTION_VIEW</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrCompositionLayerDepthInfoKHR, ##XrCompositionLayerSpaceWarpInfoFB</li>
<li>{@code subImage} <b>must</b> be a valid ##XrSwapchainSubImage structure</li>
</ul>
<h5>See Also</h5>
##XrCompositionLayerProjection, ##XrFovf, ##XrPosef, ##XrSwapchainSubImage
"""
Expression("#TYPE_COMPOSITION_LAYER_PROJECTION_VIEW")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrCompositionLayerDepthInfoKHR", "XrCompositionLayerSpaceWarpInfoFB",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrPosef("pose", "an ##XrPosef defining the location and orientation of this projection element in the {@code space} of the corresponding ##XrCompositionLayerProjectionView.")
XrFovf("fov", "the ##XrFovf for this projection element.")
XrSwapchainSubImage("subImage", "the image layer ##XrSwapchainSubImage to use.")
}
val XrCompositionLayerProjection = struct(Module.OPENXR, "XrCompositionLayerProjection", parentStruct = XrCompositionLayerBaseHeader) {
documentation =
"""
Composition layer for projection.
<h5>Description</h5>
<div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
Because a runtime may reproject the layer over time, a projection layer should specify an {@code XrSpace} in which to maximize stability of the layer content. For example, a projection layer containing world-locked content should use an {@code XrSpace} which is also world-locked, such as the {@code LOCAL} or {@code STAGE} reference spaces. In the case that the projection layer should be head-locked, such as a heads up display, the {@code VIEW} reference space would provide the highest quality layer reprojection.
</div>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_COMPOSITION_LAYER_PROJECTION</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a>. See also: ##XrCompositionLayerDepthTestVARJO, ##XrCompositionLayerReprojectionInfoMSFT, ##XrCompositionLayerReprojectionPlaneOverrideMSFT</li>
<li>{@code layerFlags} <b>must</b> be 0 or a valid combination of {@code XrCompositionLayerFlagBits} values</li>
<li>{@code space} <b>must</b> be a valid {@code XrSpace} handle</li>
<li>{@code views} <b>must</b> be a pointer to an array of {@code viewCount} valid ##XrCompositionLayerProjectionView structures</li>
<li>The {@code viewCount} parameter <b>must</b> be greater than 0</li>
</ul>
<h5>See Also</h5>
##XrCompositionLayerBaseHeader, ##XrCompositionLayerProjectionView, ##XrSwapchainSubImage
"""
Expression("#TYPE_COMPOSITION_LAYER_PROJECTION")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
PointerSetter(
"XrCompositionLayerDepthTestVARJO", "XrCompositionLayerReprojectionInfoMSFT", "XrCompositionLayerReprojectionPlaneOverrideMSFT",
prepend = true
)..nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrCompositionLayerFlags("layerFlags", "a bitmask of {@code XrCompositionLayerFlagBits} describing flags to apply to the layer.")
XrSpace("space", "the {@code XrSpace} in which the {@code pose} of each ##XrCompositionLayerProjectionView is evaluated over time by the compositor.")
AutoSize("views")..uint32_t("viewCount", "the count of views in the {@code views} array. This <b>must</b> be equal to the number of view poses returned by #LocateViews().")
XrCompositionLayerProjectionView.const.p("views", "the array of type ##XrCompositionLayerProjectionView containing each projection layer view.")
}
val XrCompositionLayerQuad = struct(Module.OPENXR, "XrCompositionLayerQuad", parentStruct = XrCompositionLayerBaseHeader) {
documentation =
"""
Quad composition layer.
<h5>Description</h5>
The ##XrCompositionLayerQuad layer is useful for user interface elements or 2D content rendered into the virtual world. The layer’s ##XrSwapchainSubImage::swapchain image is applied to a quad in the virtual world space. Only front face of the quad surface is visible; the back face is not visible and <b>must</b> not be drawn by the runtime. A quad layer has no thickness; it is a two-dimensional object positioned and oriented in 3D space. The position of a quad refers to the center of the quad within the given {@code XrSpace}. The orientation of the quad refers to the orientation of the normal vector from the front face. The size of a quad refers to the quad’s size in the <code>x-y</code> plane of the given {@code XrSpace}’s coordinate system. A quad with a position of {0,0,0}, rotation of {0,0,0,1} (no rotation), and a size of {1,1} refers to a 1 meter x 1 meter quad centered at {0,0,0} with its front face normal vector coinciding with the +z axis.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_COMPOSITION_LAYER_QUAD</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code layerFlags} <b>must</b> be 0 or a valid combination of {@code XrCompositionLayerFlagBits} values</li>
<li>{@code space} <b>must</b> be a valid {@code XrSpace} handle</li>
<li>{@code eyeVisibility} <b>must</b> be a valid {@code XrEyeVisibility} value</li>
<li>{@code subImage} <b>must</b> be a valid ##XrSwapchainSubImage structure</li>
</ul>
<h5>See Also</h5>
##XrCompositionLayerBaseHeader, ##XrExtent2Df, ##XrPosef, ##XrSwapchainSubImage
"""
Expression("#TYPE_COMPOSITION_LAYER_QUAD")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrCompositionLayerFlags("layerFlags", "a bitmask of {@code XrCompositionLayerFlagBits} describing flags to apply to the layer.")
XrSpace("space", "the {@code XrSpace} in which the {@code pose} of the quad layer is evaluated over time.")
XrEyeVisibility("eyeVisibility", "the {@code XrEyeVisibility} for this layer.")
XrSwapchainSubImage("subImage", "the image layer ##XrSwapchainSubImage to use.")
XrPosef("pose", "an ##XrPosef defining the position and orientation of the quad in the reference frame of the {@code space}.")
XrExtent2Df("size", "the width and height of the quad in meters.")
}
val XrEventDataBaseHeader = struct(Module.OPENXR, "XrEventDataBaseHeader") {
documentation =
"""
Base header for an event.
<h5>Description</h5>
The ##XrEventDataBaseHeader is a generic structure used to identify the common event data elements.
Upon receipt, the ##XrEventDataBaseHeader pointer should be type-cast to a pointer of the appropriate event data based on the {@code type} parameter.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be one of the following XrStructureType values: #TYPE_EVENT_DATA_DISPLAY_REFRESH_RATE_CHANGED_FB, #TYPE_EVENT_DATA_EVENTS_LOST, #TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING, #TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED, #TYPE_EVENT_DATA_MAIN_SESSION_VISIBILITY_CHANGED_EXTX, #TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO, #TYPE_EVENT_DATA_PERF_SETTINGS_EXT, #TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING, #TYPE_EVENT_DATA_SESSION_STATE_CHANGED, #TYPE_EVENT_DATA_SPACE_ERASE_COMPLETE_FB, #TYPE_EVENT_DATA_SPACE_QUERY_COMPLETE_FB, #TYPE_EVENT_DATA_SPACE_QUERY_RESULTS_AVAILABLE_FB, #TYPE_EVENT_DATA_SPACE_SAVE_COMPLETE_FB, #TYPE_EVENT_DATA_SPACE_SET_STATUS_COMPLETE_FB, #TYPE_EVENT_DATA_SPATIAL_ANCHOR_CREATE_COMPLETE_FB, #TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR, #TYPE_EVENT_DATA_VIVE_TRACKER_CONNECTED_HTCX</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
#PollEvent()
"""
XrStructureType("type", "the {@code XrStructureType} of this structure. This base structure itself has no associated {@code XrStructureType} value.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
}
val XrEventDataEventsLost = struct(Module.OPENXR, "XrEventDataEventsLost", parentStruct = XrEventDataBaseHeader) {
documentation =
"""
Event indicating events were lost.
<h5>Description</h5>
Receiving the ##XrEventDataEventsLost event structure indicates that the event queue overflowed and some events were removed at the position within the queue at which this event was found.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_EVENTS_LOST</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrEventDataBaseHeader, #PollEvent()
"""
Expression("#TYPE_EVENT_DATA_EVENTS_LOST")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
uint32_t("lostEventCount", "the number of events which have overflowed since the last call to #PollEvent().")
}
val XrEventDataInstanceLossPending = struct(Module.OPENXR, "XrEventDataInstanceLossPending", parentStruct = XrEventDataBaseHeader) {
documentation =
"""
Event indicating instance loss will occur.
<h5>Description</h5>
After the application has destroyed all of its instances and their children and waited past the specified time, it may then re-try #CreateInstance() in a loop waiting for whatever maintenance the runtime is performing to complete. The runtime will return #ERROR_RUNTIME_UNAVAILABLE from #CreateInstance() as long as it is unable to create the instance. Once the runtime has returned and is able to continue, it <b>must</b> resume returning #SUCCESS from #CreateInstance() if valid data is passed in.
<h5>Member Descriptions</h5>
<ul>
<li>{@code type} is the {@code XrStructureType} of this structure.</li>
<li>{@code next} is {@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.</li>
<li>{@code lossTime} is the absolute time at which the indicated instance will be considered lost and become unusable.</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrEventDataBaseHeader, #PollEvent()
"""
Expression("#TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING")..XrStructureType("type", "")
nullable..opaque_const_p("next", "")
XrTime("lossTime", "")
}
val XrEventDataSessionStateChanged = struct(Module.OPENXR, "XrEventDataSessionStateChanged", parentStruct = XrEventDataBaseHeader) {
documentation =
"""
Event indicating session state changed.
<h5>Description</h5>
Receiving the ##XrEventDataSessionStateChanged event structure indicates that the application has changed lifecycle state.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_SESSION_STATE_CHANGED</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code state} <b>must</b> be a valid {@code XrSessionState} value</li>
</ul>
<h5>See Also</h5>
##XrEventDataBaseHeader, #PollEvent()
"""
Expression("#TYPE_EVENT_DATA_SESSION_STATE_CHANGED")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrSession("session", "the {@code XrSession} which has changed state.")
XrSessionState("state", "the current {@code XrSessionState} of the {@code session}.")
XrTime("time", "an {@code XrTime} which indicates the time of the state change.")
}
val XrEventDataReferenceSpaceChangePending = struct(Module.OPENXR, "XrEventDataReferenceSpaceChangePending", parentStruct = XrEventDataBaseHeader) {
documentation =
"""
Notifies the application that a reference space is changing.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code referenceSpaceType} <b>must</b> be a valid {@code XrReferenceSpaceType} value</li>
</ul>
<h5>See Also</h5>
##XrPosef, #CreateReferenceSpace()
"""
Expression("#TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrSession("session", "the {@code XrSession} for which the reference space is changing.")
XrReferenceSpaceType("referenceSpaceType", "the {@code XrReferenceSpaceType} that is changing.")
XrTime("changeTime", "the target {@code XrTime} after which #LocateSpace() or #LocateViews() will return values that respect this change.")
XrBool32("poseValid", "true if the runtime can determine the {@code pose} of the new space in the previous space before the change.")
XrPosef("poseInPreviousSpace", "an ##XrPosef defining the position and orientation of the new reference space’s natural origin within the natural reference frame of its previous space.")
}
val XrEventDataInteractionProfileChanged = struct(Module.OPENXR, "XrEventDataInteractionProfileChanged", parentStruct = XrEventDataBaseHeader) {
documentation =
"""
Notifies the application than the active interaction profile has changed.
<h5>Description</h5>
The ##XrEventDataInteractionProfileChanged event is sent to the application to notify it that the active input form factor for one or more top level user paths has changed. This event <b>must</b> only be sent for interaction profiles that the application indicated its support for via #SuggestInteractionProfileBindings(). This event <b>must</b> only be sent for running sessions.
The application <b>can</b> call #GetCurrentInteractionProfile() if it wants to change its own behavior based on the active hardware.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
</ul>
<h5>See Also</h5>
#GetCurrentInteractionProfile(), #SuggestInteractionProfileBindings()
"""
Expression("#TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrSession("session", "the {@code XrSession} for which at least one of the interaction profiles for a top level path has changed.")
}
val XrHapticVibration = struct(Module.OPENXR, "XrHapticVibration", parentStruct = XrHapticBaseHeader) {
documentation =
"""
Base header for haptic feedback.
<h5>Description</h5>
The ##XrHapticVibration is used in calls to #ApplyHapticFeedback() that trigger actionname:vibration output actions.
The {@code duration}, and {@code frequency} parameters <b>may</b> be clamped to implementation-dependent ranges.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code type} <b>must</b> be #TYPE_HAPTIC_VIBRATION</li>
<li>{@code next} <b>must</b> be {@code NULL} or a valid pointer to the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#valid-usage-for-structure-pointer-chains">next structure in a structure chain</a></li>
</ul>
<h5>See Also</h5>
##XrHapticBaseHeader, #ApplyHapticFeedback()
"""
Expression("#TYPE_HAPTIC_VIBRATION")..XrStructureType("type", "the {@code XrStructureType} of this structure.")
nullable..opaque_const_p("next", "{@code NULL} or a pointer to the next structure in a structure chain. No such structures are defined in core OpenXR.")
XrDuration("duration", "the number of nanoseconds the vibration <b>should</b> last. If #MIN_HAPTIC_DURATION is specified, the runtime <b>must</b> produce a short haptics pulse of minimal supported duration for the haptic device.")
float("frequency", "the frequency of the vibration in Hz. If #FREQUENCY_UNSPECIFIED is specified, it is left to the runtime to decide the optimal frequency value to use.")
float("amplitude", "the amplitude of the vibration between <code>0.0</code> and <code>1.0</code>.")
}
val XrOffset2Df = struct(Module.OPENXR, "XrOffset2Df") {
documentation =
"""
Float offset in two dimensions.
<h5>Description</h5>
This structure is used for component values that may be fractional (floating-point). If used to represent physical distances, values <b>must</b> be in meters.
<h5>See Also</h5>
##XrExtent2Df, ##XrRect2Df
"""
float("x", "the floating-point offset in the x direction.")
float("y", "the floating-point offset in the y direction.")
}
val XrRect2Df = struct(Module.OPENXR, "XrRect2Df") {
documentation =
"""
Rect in two dimensions.
<h5>Description</h5>
This structure is used for component values that may be fractional (floating-point).
<h5>See Also</h5>
##XrExtent2Df, ##XrOffset2Df, #GetSpaceBoundingBox2DFB()
"""
XrOffset2Df("offset", "the ##XrOffset2Df specifying the rectangle offset.")
XrExtent2Df("extent", "the ##XrExtent2Df specifying the rectangle extent.")
}
val XrVector4f = struct(Module.OPENXR, "XrVector4f") {
documentation =
"""
Four-dimensional vector.
<h5>Description</h5>
If used to represent physical distances, {@code x}, {@code y}, and {@code z} values <b>must</b> be in meters.
<h5>See Also</h5>
##XrHandTrackingMeshFB, ##XrPosef, ##XrQuaternionf, ##XrVector2f, ##XrVector3f
"""
float("x", "the x coordinate of the vector.")
float("y", "the y coordinate of the vector.")
float("z", "the z coordinate of the vector.")
float("w", "the w coordinate of the vector.")
}
val XrColor4f = struct(Module.OPENXR, "XrColor4f") {
documentation =
"""
Color Vector.
<h5>Description</h5>
Unless otherwise specified, colors are encoded as linear (not with sRGB nor other gamma compression) values with individual components being in the range of 0.0 through 1.0, and without the RGB components being premultiplied by the alpha component.
If color encoding is specified as being premultiplied by the alpha component, the RGB components are set to zero if the alpha component is zero.
<h5>See Also</h5>
##XrCompositionLayerColorScaleBiasKHR, ##XrPassthroughColorMapMonoToRgbaFB, ##XrPassthroughStyleFB, ##XrSwapchainStateSamplerOpenGLESFB, ##XrSwapchainStateSamplerVulkanFB
"""
float("r", "the red component of the color.")
float("g", "the green component of the color.")
float("b", "the blue component of the color.")
float("a", "the alpha component of the color.")
} | modules/lwjgl/openxr/src/templates/kotlin/openxr/XRTypes.kt | 4180163867 |
package com.swmansion.common
interface GestureHandlerStateManager {
fun setGestureHandlerState(handlerTag: Int, newState: Int)
}
| android/src/main/java/com/swmansion/common/GestureHandlerStateManager.kt | 3822145023 |
package com.gorakgarak.anpr.parser
import org.xmlpull.v1.XmlPullParser
import android.util.Xml
import org.opencv.core.CvType
import org.opencv.core.Mat
import org.xmlpull.v1.XmlPullParserException
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* Created by kohry on 2017-10-22.
*/
object GorakgarakXMLParser {
private val namespace: String? = null
@Throws(XmlPullParserException::class, IOException::class)
fun parse(inputStream: InputStream, trainingDataTagName: String): Pair<Mat, Mat> {
try {
val parser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(inputStream, null)
parser.nextTag()
parser.require(XmlPullParser.START_TAG, namespace, "opencv_storage")
return Pair(readFeed(parser, trainingDataTagName), readFeed(parser, "classes"))
} finally {
inputStream.close()
}
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readFeed(parser: XmlPullParser, tagName:String): Mat {
var mat = Mat() //you have to initialize opencv first, before loading this.
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val name = parser.name
// Starts by looking for the entry tag
if (name == tagName) {
mat = readEntry(parser, tagName)
break
} else {
skip(parser)
}
}
return mat
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readEntry(parser: XmlPullParser, entryName: String): Mat {
parser.require(XmlPullParser.START_TAG, namespace, entryName)
var rows = 0
var cols = 0
var dt = ""
var data = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val name = parser.name
when (name) {
"rows" -> rows = readNode(parser, "rows").toInt()
"cols" -> cols = readNode(parser, "cols").toInt()
"dt" -> dt = readNode(parser, "dt")
"data" -> { data = readNode(parser, "data") }
else -> skip(parser)
}
}
var imageType = CvType.CV_32F
if (dt == "f") imageType = CvType.CV_32F else if(dt == "i") imageType = CvType.CV_32S
val mat = Mat(rows, cols, imageType)
val st = StringTokenizer(data)
(0 until rows).forEach { row ->
(0 until cols).forEach { col ->
if (dt == "f") mat.put(row, col, floatArrayOf(st.nextToken().toFloat()))
else if (dt == "i") mat.put(row, col, intArrayOf(st.nextToken().toInt()))
}
}
return mat
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readNode(parser: XmlPullParser, name: String): String {
parser.require(XmlPullParser.START_TAG, namespace, name)
val title = readText(parser)
parser.require(XmlPullParser.END_TAG, namespace, name)
return title
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readText(parser: XmlPullParser): String {
var result = ""
if (parser.next() == XmlPullParser.TEXT) {
result = parser.text
parser.nextTag()
}
return result
}
@Throws(XmlPullParserException::class, IOException::class)
private fun skip(parser: XmlPullParser) {
if (parser.eventType != XmlPullParser.START_TAG) {
throw IllegalStateException()
}
var depth = 1
while (depth != 0) {
when (parser.next()) {
XmlPullParser.END_TAG -> depth--
XmlPullParser.START_TAG -> depth++
}
}
}
} | app/src/main/java/com/gorakgarak/anpr/parser/GorakgarakXMLParser.kt | 827321168 |
package com.afzaln.awakedebug.data
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import com.afzaln.awakedebug.DebuggingType
import com.afzaln.awakedebug.AwakeDebugApp
import timber.log.Timber
private const val KEY_USB_DEBUG_ENABLED = "UsbDebugEnabled"
private const val KEY_WIFI_DEBUG_ENABLED = "WifiDebugEnabled"
private const val KEY_AWAKE_DEBUG_ENABLED = "AwakeDebugEnabled"
private const val KEY_AWAKE_DEBUG_ACTIVE = "AwakeDebugActive"
private const val KEY_DISPLAY_TIMEOUT = "DisplayTimeout"
/**
* Responsible for keeping user choices for
* Awake Debug setting and the last system
* display timeout, for restoring.
*
* Created by Dmytro Karataiev on 3/29/17.
*/
class Prefs(val app: AwakeDebugApp) {
private val preferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(app)
val enabledDebuggingTypes: List<DebuggingType>
get() {
return arrayListOf<DebuggingType>().apply {
if (usbDebugging) add(DebuggingType.USB)
if (wifiDebugging) add(DebuggingType.WIFI)
}
}
var usbDebugging: Boolean
get() {
val usbDebugging = preferences.getBoolean(KEY_USB_DEBUG_ENABLED, true)
Timber.d("$KEY_USB_DEBUG_ENABLED: %s", usbDebugging)
return usbDebugging
}
set(value) {
Timber.d("Setting $KEY_USB_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_USB_DEBUG_ENABLED, value).apply()
}
var wifiDebugging: Boolean
get() {
val usbDebugging = preferences.getBoolean(KEY_WIFI_DEBUG_ENABLED, true)
Timber.d("$KEY_WIFI_DEBUG_ENABLED: %s", usbDebugging)
return usbDebugging
}
set(value) {
Timber.d("Setting $KEY_WIFI_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_WIFI_DEBUG_ENABLED, value).apply()
}
var awakeDebug: Boolean
get() {
val awakeDebugEnabled = preferences.getBoolean(KEY_AWAKE_DEBUG_ENABLED, false)
Timber.d("$KEY_AWAKE_DEBUG_ENABLED: %s", awakeDebugEnabled)
return awakeDebugEnabled
}
set(value) {
Timber.d("Setting $KEY_AWAKE_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_AWAKE_DEBUG_ENABLED, value).apply()
}
var awakeDebugActive: Boolean
get() {
val awakeDebugActive = preferences.getBoolean(KEY_AWAKE_DEBUG_ACTIVE, false)
Timber.d("$KEY_AWAKE_DEBUG_ACTIVE: %s", awakeDebugActive)
return awakeDebugActive
}
set(value) {
Timber.d("Setting $KEY_AWAKE_DEBUG_ACTIVE: %s", value)
preferences.edit().putBoolean(KEY_AWAKE_DEBUG_ACTIVE, value).apply()
}
var savedTimeout: Int
get() {
return preferences.getInt(KEY_DISPLAY_TIMEOUT, 60000)
}
set(value) {
Timber.d("Setting $KEY_DISPLAY_TIMEOUT = %s", value)
preferences.edit().putInt(KEY_DISPLAY_TIMEOUT, value).apply()
}
}
| app/src/main/java/com/afzaln/awakedebug/data/Prefs.kt | 1835162747 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
// ResultListList.kt
object RESTFUL_SERVICES : Response() {
override val url = "http://localhost:8080/restful/services"
override val str = """
{
"value": [
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"simple.SimpleObjectMenu\"",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Simple Objects"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.FixtureScriptsDefault\"",
"href": "http://localhost:8080/restful/services/causewayApplib.FixtureScriptsDefault",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.LayoutServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.MetaModelServicesMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.MetaModelServicesMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.SwaggerServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.SwaggerServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.TranslationServicePoMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.TranslationServicePoMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.HsqlDbManagerMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.HsqlDbManagerMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.ConfigurationServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.ConfigurationServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Configuration Service Menu"
}
],
"extensions": {},
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/services",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/list\""
},
{
"rel": "up",
"href": "http://localhost:8080/restful/",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}
]
}"""
}
| incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/RESTFUL_SERVICES.kt | 1594586658 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.api
import com.intellij.collaboration.api.graphql.CachingGraphQLQueryLoader
import com.intellij.collaboration.api.graphql.GraphQLApiClient
import com.intellij.collaboration.api.graphql.GraphQLDataSerializer
import com.intellij.collaboration.api.httpclient.HttpClientFactory
import com.intellij.collaboration.api.httpclient.HttpRequestConfigurer
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
class GitLabApi(override val clientFactory: HttpClientFactory,
override val requestConfigurer: HttpRequestConfigurer) : GraphQLApiClient() {
@Suppress("SSBasedInspection")
override val logger: Logger = LOG
override val gqlQueryLoader: CachingGraphQLQueryLoader = GitLabGQLQueryLoader
override val gqlSerializer: GraphQLDataSerializer = GitLabGQLDataSerializer
companion object {
private val LOG = logger<GitLabApi>()
}
} | plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/GitLabApi.kt | 2992645211 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.fir.codeInsight.tooling
import org.jetbrains.kotlin.idea.base.codeInsight.tooling.AbstractGenericTestIconProvider
import org.jetbrains.kotlin.idea.base.codeInsight.tooling.AbstractNativeIdePlatformKindTooling
import org.jetbrains.kotlin.idea.base.lineMarkers.run.KotlinMainFunctionDetector
import org.jetbrains.kotlin.idea.base.platforms.StableModuleNameProvider
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import javax.swing.Icon
class FirNativeIdePlatformKindTooling : AbstractNativeIdePlatformKindTooling() {
override val testIconProvider: AbstractGenericTestIconProvider
get() = SymbolBasedGenericTestIconProvider
override fun acceptsAsEntryPoint(function: KtFunction): Boolean {
return function is KtNamedFunction
&& KotlinMainFunctionDetector.getInstance().isMain(function)
&& super.acceptsAsEntryPoint(function)
}
override fun getTestIcon(declaration: KtNamedDeclaration, allowSlowOperations: Boolean): Icon? {
if (!allowSlowOperations) {
return null
}
val testContainerElement = testIconProvider.getTestContainerElement(declaration) ?: return null
if (testIconProvider.isKotlinTestDeclaration(testContainerElement)) {
return null
}
val module = declaration.module ?: return null
val moduleName = StableModuleNameProvider.getInstance(module.project).getStableModuleName(module)
return getTestIcon(declaration, moduleName)
}
} | plugins/kotlin/base/fir/code-insight/src/org/jetbrains/kotlin/idea/base/fir/codeInsight/tooling/FirNativeIdePlatformKindTooling.kt | 1726524818 |
package main.lib
class Greeting {
companion object {
private fun getGreeting(name: String): String {
return "Hello $name!"
}
fun getGreetings(names: Array<String>): Array<String> {
return Array(names.size) { i -> getGreeting(names.get(i)) }
}
}
}
| examples/kotlin/simple_project/main/lib/Greeting.kt | 1313351445 |
package com.github.vhromada.catalog.web.connector.entity
/**
* A class represents episode.
*
* @author Vladimir Hromada
*/
data class Episode(
/**
* UUID
*/
val uuid: String,
/**
* Number of episode
*/
val number: Int,
/**
* Name
*/
val name: String,
/**
* Length
*/
val length: Int,
/**
* Formatted length
*/
val formattedLength: String,
/**
* Note
*/
val note: String?
)
| web/src/main/kotlin/com/github/vhromada/catalog/web/connector/entity/Episode.kt | 1121721168 |
package org.stepic.droid.core.presenters
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineDataSet
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import org.stepic.droid.adaptive.ui.adapters.AdaptiveWeeksAdapter
import org.stepic.droid.adaptive.util.ExpHelper
import org.stepic.droid.core.presenters.contracts.AdaptiveProgressView
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.CourseId
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.storage.operations.DatabaseFacade
import javax.inject.Inject
class AdaptiveProgressPresenter
@Inject
constructor (
@CourseId
private val courseId: Long,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler,
private val databaseFacade: DatabaseFacade
) : PresenterBase<AdaptiveProgressView>() {
private val adapter = AdaptiveWeeksAdapter()
private val compositeDisposable = CompositeDisposable()
init {
compositeDisposable.add(
Single.fromCallable { databaseFacade.getExpForCourse(courseId) }
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe({
adapter.setHeaderLevelAndTotal(ExpHelper.getCurrentLevel(it), it)
}, {})
)
compositeDisposable.add(
Single.fromCallable { databaseFacade.getExpForWeeks(courseId) }
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe(adapter::addAll, {})
)
compositeDisposable.add(
Single.fromCallable { databaseFacade.getExpForLast7Days(courseId) }
.map {
Pair(LineDataSet(it.mapIndexed { index, l -> Entry(index.toFloat(), l.toFloat()) }, ""), it.sum())
}
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe({
adapter.setHeaderChart(it.first, it.second)
}, {})
)
}
override fun attachView(view: AdaptiveProgressView) {
super.attachView(view)
view.onWeeksAdapter(adapter)
}
fun destroy() {
compositeDisposable.dispose()
}
} | app/src/main/java/org/stepic/droid/core/presenters/AdaptiveProgressPresenter.kt | 2435673176 |
package io.customerly.demoapp
import android.app.Application
import android.graphics.Color
import io.customerly.Customerly
/**
* Created by Gianni on 09/07/18.
* Project: Customerly-KAndroid-SDK
*/
@Suppress("unused")
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
Customerly.configure(application = this, customerlyAppId = CUSTOMERLY_APP_ID, widgetColorInt = Color.RED)
}
companion object {
const val CUSTOMERLY_APP_ID = ""//TODO
}
} | demoapp/src/main/java/io/customerly/demoapp/MyApp.kt | 757054313 |
package io.github.ranolp.kubo.general.objects
import io.github.ranolp.kubo.general.error.CannotDeleteError
import io.github.ranolp.kubo.general.error.NotOwnerError
import io.github.ranolp.kubo.general.side.Sided
interface Chat : Sided {
val title: String?
val users: List<User>
fun sendMessage(message: String)
fun history(): History
fun leave(): Boolean
@Throws(NotOwnerError::class, CannotDeleteError::class) fun delete()
} | Kubo-api/src/main/kotlin/io/github/ranolp/kubo/general/objects/Chat.kt | 2037056408 |
package com.aemtools.analysis.htl.callchain.elements.virtual
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.java.ArrayJavaTypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.java.IterableJavaTypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.java.MapJavaTypeDescriptor
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
/**
* Virtual call chain element interface.
* Represents call chain that has no physical presentation
* inside PSI
* @author Dmytro Troynikov
*/
interface VirtualCallChainElement {
/**
* Name of current call chain element.
*/
val name: String
/**
* Type descriptor of current call chain element.
*/
val type: TypeDescriptor
/**
* Previous virtual call chain element from current call chain.
*/
val previous: VirtualCallChainElement?
/**
* Convert current virtual call chain element into [LookupElement].
*
* @return lookup element
*/
fun toLookupElement(): LookupElement
}
| aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/elements/virtual/VirtualCallChainElement.kt | 3459851786 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.intellij.codeWithMe.ClientId
import com.intellij.diagnostic.ThreadDumper
import com.intellij.icons.AllIcons
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.command.CommandEvent
import com.intellij.openapi.command.CommandListener
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.ContentInfo
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.TrackerContent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.commit.isNonModalCommit
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Future
import java.util.function.Supplier
class LineStatusTrackerManager(private val project: Project) : LineStatusTrackerManagerI, Disposable {
private val LOCK = Any()
private var isDisposed = false
private val trackers = HashMap<Document, TrackerData>()
private val forcedDocuments = HashMap<Document, Multiset<Any>>()
private val eventDispatcher = EventDispatcher.create(Listener::class.java)
private var partialChangeListsEnabled: Boolean = false
private val documentsInDefaultChangeList = HashSet<Document>()
private var clmFreezeCounter: Int = 0
private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>()
private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>()
private val loader = MyBaseRevisionLoader()
companion object {
private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java)
@JvmStatic
fun getInstance(project: Project): LineStatusTrackerManagerI = project.service()
@JvmStatic
fun getInstanceImpl(project: Project): LineStatusTrackerManager {
return getInstance(project) as LineStatusTrackerManager
}
}
class MyStartupActivity : VcsStartupActivity {
override fun runActivity(project: Project) {
LineStatusTrackerManager.getInstanceImpl(project).startListenForEditors()
}
override fun getOrder(): Int = VcsInitObject.OTHER_INITIALIZATION.order
}
private fun startListenForEditors() {
val busConnection = project.messageBus.connect()
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener())
busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener())
busConnection.subscribe(CommandListener.TOPIC, MyCommandListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
busConnection.subscribe(ChangeListAvailabilityListener.TOPIC, MyChangeListAvailabilityListener())
ApplicationManager.getApplication().messageBus.connect(this)
.subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener())
LocalLineStatusTrackerProvider.EP_NAME.addChangeListener(Runnable { updateTrackingSettings() }, this)
updatePartialChangeListsAvailability()
runInEdt {
if (project.isDisposed) return@runInEdt
ApplicationManager.getApplication().addApplicationListener(MyApplicationListener(), this)
FileStatusManager.getInstance(project).addFileStatusListener(MyFileStatusListener(), this)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(MyDocumentListener(), this)
MyEditorFactoryListener().install(this)
onEverythingChanged()
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
override fun dispose() {
isDisposed = true
Disposer.dispose(loader)
synchronized(LOCK) {
for ((document, multiset) in forcedDocuments) {
for (requester in multiset.elementSet()) {
warn("Tracker is being held on dispose by $requester", document)
}
}
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? {
synchronized(LOCK) {
return trackers[document]?.tracker
}
}
override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return null
return getLineStatusTracker(document)
}
@RequiresEdt
override fun requestTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) {
warn("Tracker is being requested after dispose by $requester", document)
return
}
val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() }
multiset.add(requester)
if (trackers[document] == null) {
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
switchTracker(virtualFile, document)
}
}
}
@RequiresEdt
override fun releaseTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val multiset = forcedDocuments[document]
if (multiset == null || !multiset.contains(requester)) {
warn("Tracker release underflow by $requester", document)
return
}
multiset.remove(requester)
if (multiset.isEmpty()) {
forcedDocuments.remove(document)
checkIfTrackerCanBeReleased(document)
}
}
}
override fun invokeAfterUpdate(task: Runnable) {
loader.addAfterUpdateRunnable(task)
}
fun getTrackers(): List<LineStatusTracker<*>> {
synchronized(LOCK) {
return trackers.values.map { it.tracker }
}
}
fun addTrackerListener(listener: Listener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
open class ListenerAdapter : Listener
interface Listener : EventListener {
fun onTrackerAdded(tracker: LineStatusTracker<*>) {
}
fun onTrackerRemoved(tracker: LineStatusTracker<*>) {
}
}
@RequiresEdt
private fun checkIfTrackerCanBeReleased(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
if (forcedDocuments.containsKey(document)) return
if (data.tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = data.tracker.hasPartialState()
if (hasPartialChanges) {
log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile)
return
}
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile)
if (data.tracker.hasPendingPartialState() ||
fileStatesAwaitingRefresh.containsKey(data.tracker.virtualFile)) {
log("checkIfTrackerCanBeReleased - has pending state", data.tracker.virtualFile)
return
}
}
}
releaseTracker(document)
}
}
@RequiresEdt
private fun onEverythingChanged() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) return
log("onEverythingChanged", null)
val files = HashSet<VirtualFile>()
for (data in trackers.values) {
files.add(data.tracker.virtualFile)
}
for (document in forcedDocuments.keys) {
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null) files.add(file)
}
for (file in files) {
onFileChanged(file)
}
}
}
@RequiresEdt
private fun onFileChanged(virtualFile: VirtualFile) {
val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile) ?: return
synchronized(LOCK) {
if (isDisposed) return
log("onFileChanged", virtualFile)
val tracker = trackers[document]?.tracker
if (tracker != null || forcedDocuments.containsKey(document)) {
switchTracker(virtualFile, document, refreshExisting = true)
}
}
}
private fun registerTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = VcsUtil.getFilePath(tracker.virtualFile)
if (data.clmFilePath != null) {
LOG.error("[registerTrackerInCLM] tracker already registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(filePath, tracker)
data.clmFilePath = filePath
}
private fun unregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = data.clmFilePath
if (filePath == null) {
LOG.error("[unregisterTrackerInCLM] tracker is not registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(filePath, tracker)
data.clmFilePath = null
val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (filePath != actualFilePath) {
LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath")
}
}
private fun reregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val oldFilePath = data.clmFilePath
val newFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (oldFilePath == null) {
LOG.error("[reregisterTrackerInCLM] tracker is not registered")
return
}
if (oldFilePath != newFilePath) {
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(oldFilePath, tracker)
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(newFilePath, tracker)
data.clmFilePath = newFilePath
}
}
private fun canCreateTrackerFor(virtualFile: VirtualFile?): Boolean {
if (isDisposed) return false
if (virtualFile == null || virtualFile is LightVirtualFile) return false
if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false
return true
}
override fun arePartialChangelistsEnabled(): Boolean = partialChangeListsEnabled
override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean {
if (!partialChangeListsEnabled) return false
val vcs = VcsUtil.getVcsFor(project, virtualFile)
return vcs != null && vcs.arePartialChangelistsSupported()
}
private fun switchTracker(virtualFile: VirtualFile, document: Document,
refreshExisting: Boolean = false) {
val provider = getTrackerProvider(virtualFile)
val oldTracker = trackers[document]?.tracker
if (oldTracker != null && provider != null && provider.isMyTracker(oldTracker)) {
if (refreshExisting) {
refreshTracker(oldTracker, provider)
}
}
else {
releaseTracker(document)
if (provider != null) installTracker(virtualFile, document, provider)
}
}
private fun installTracker(virtualFile: VirtualFile, document: Document,
provider: LocalLineStatusTrackerProvider): LocalLineStatusTracker<*>? {
if (isDisposed) return null
if (trackers[document] != null) return null
val tracker = provider.createTracker(project, virtualFile) ?: return null
tracker.mode = getTrackingMode()
val data = TrackerData(tracker)
val replacedData = trackers.put(document, data)
LOG.assertTrue(replacedData == null)
registerTrackerInCLM(data)
refreshTracker(tracker, provider)
eventDispatcher.multicaster.onTrackerAdded(tracker)
if (clmFreezeCounter > 0) {
tracker.freeze()
}
log("Tracker installed", virtualFile)
return tracker
}
private fun getTrackerProvider(virtualFile: VirtualFile): LocalLineStatusTrackerProvider? {
if (!canCreateTrackerFor(virtualFile)) return null
val customTracker = LocalLineStatusTrackerProvider.EP_NAME.findFirstSafe { it.isTrackedFile(project, virtualFile) }
if (customTracker != null) return customTracker
return listOf(ChangelistsLocalStatusTrackerProvider, DefaultLocalStatusTrackerProvider).find { it.isTrackedFile(project, virtualFile) }
}
@RequiresEdt
private fun releaseTracker(document: Document) {
val data = trackers.remove(document) ?: return
eventDispatcher.multicaster.onTrackerRemoved(data.tracker)
unregisterTrackerInCLM(data)
data.tracker.release()
log("Tracker released", data.tracker.virtualFile)
}
private fun updatePartialChangeListsAvailability() {
partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS &&
ChangeListManager.getInstance(project).areChangeListsEnabled()
}
private fun updateTrackingSettings() {
synchronized(LOCK) {
if (isDisposed) return
val mode = getTrackingMode()
for (data in trackers.values) {
data.tracker.mode = mode
}
}
onEverythingChanged()
}
private fun getTrackingMode(): LocalLineStatusTracker.Mode {
val settings = VcsApplicationSettings.getInstance()
return LocalLineStatusTracker.Mode(settings.SHOW_LST_GUTTER_MARKERS,
settings.SHOW_LST_ERROR_STRIPE_MARKERS,
settings.SHOW_WHITESPACES_IN_LST)
}
@RequiresEdt
private fun refreshTracker(tracker: LocalLineStatusTracker<*>,
provider: LocalLineStatusTrackerProvider) {
if (isDisposed) return
if (provider !is LineStatusTrackerContentLoader) return
loader.scheduleRefresh(RefreshRequest(tracker.document, provider))
log("Refresh queued", tracker.virtualFile)
}
private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() {
fun hasRequestFor(document: Document): Boolean {
return hasRequest { it.document == document }
}
override fun loadRequest(request: RefreshRequest): Result<RefreshData> {
if (isDisposed) return Result.Canceled()
val document = request.document
val virtualFile = FileDocumentManager.getInstance().getFile(document)
val loader = request.loader
log("Loading started", virtualFile)
if (virtualFile == null || !virtualFile.isValid) {
log("Loading error: virtual file is not valid", virtualFile)
return Result.Error()
}
if (!canCreateTrackerFor(virtualFile) || !loader.isTrackedFile(project, virtualFile)) {
log("Loading error: virtual file is not a tracked file", virtualFile)
return Result.Error()
}
val newContentInfo = loader.getContentInfo(project, virtualFile)
if (newContentInfo == null) {
log("Loading error: base revision not found", virtualFile)
return Result.Error()
}
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading cancelled: tracker not found", virtualFile)
return Result.Canceled()
}
if (!loader.shouldBeUpdated(data.contentInfo, newContentInfo)) {
log("Loading cancelled: no need to update", virtualFile)
return Result.Canceled()
}
}
val content = loader.loadContent(project, newContentInfo)
if (content == null) {
log("Loading error: provider failure", virtualFile)
return Result.Error()
}
log("Loading successful", virtualFile)
return Result.Success(RefreshData(content, newContentInfo))
}
@RequiresEdt
override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) {
val document = request.document
when (result) {
is Result.Canceled -> handleCanceled(document)
is Result.Error -> handleError(request, document)
is Result.Success -> handleSuccess(request, document, result.data)
}
checkIfTrackerCanBeReleased(document)
}
private fun handleCanceled(document: Document) {
restorePendingTrackerState(document)
}
private fun handleError(request: RefreshRequest, document: Document) {
synchronized(LOCK) {
val loader = request.loader
val data = trackers[document] ?: return
val tracker = data.tracker
if (loader.isMyTracker(tracker)) {
loader.handleLoadingError(tracker)
}
data.contentInfo = null
}
}
private fun handleSuccess(request: RefreshRequest, document: Document, refreshData: RefreshData) {
val virtualFile = FileDocumentManager.getInstance().getFile(document)!!
val loader = request.loader
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading finished: tracker already released", virtualFile)
return
}
if (!loader.shouldBeUpdated(data.contentInfo, refreshData.contentInfo)) {
log("Loading finished: no need to update", virtualFile)
return
}
data.contentInfo = refreshData.contentInfo
tracker = data.tracker
}
if (loader.isMyTracker(tracker)) {
loader.setLoadedContent(tracker, refreshData.content)
log("Loading finished: success", virtualFile)
}
else {
log("Loading finished: wrong tracker. tracker: $tracker, loader: $loader", virtualFile)
}
restorePendingTrackerState(document)
}
private fun restorePendingTrackerState(document: Document) {
val tracker = getLineStatusTracker(document)
if (tracker is ChangelistsLocalLineStatusTracker) {
val virtualFile = tracker.virtualFile
val state = synchronized(LOCK) {
fileStatesAwaitingRefresh.remove(virtualFile) ?: return
}
val success = tracker.restoreState(state)
log("Pending state restored. success - $success", virtualFile)
}
}
}
/**
* We can speedup initial content loading if it was already loaded by someone.
* We do not set 'contentInfo' here to ensure, that following refresh will fix potential inconsistency.
*/
@RequiresEdt
@ApiStatus.Internal
fun offerTrackerContent(document: Document, text: CharSequence) {
try {
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null || data.contentInfo != null) return
tracker = data.tracker
}
if (tracker is LocalLineStatusTrackerImpl<*>) {
ClientId.withClientId(ClientId.localId) {
tracker.setBaseRevision(text)
log("Offered content", tracker.virtualFile)
}
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
private inner class MyFileStatusListener : FileStatusListener {
override fun fileStatusesChanged() {
onEverythingChanged()
}
override fun fileStatusChanged(virtualFile: VirtualFile) {
onFileChanged(virtualFile)
}
}
private inner class MyEditorFactoryListener : EditorFactoryListener {
fun install(disposable: Disposable) {
val editorFactory = EditorFactory.getInstance()
for (editor in editorFactory.allEditors) {
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
editorFactory.addEditorFactoryListener(this, disposable)
}
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
releaseTrackerFor(editor.document, editor)
}
}
private fun isTrackedEditor(editor: Editor): Boolean {
// can't filter out "!isInLocalFileSystem" files, custom VcsBaseContentProvider can handle them
if (FileDocumentManager.getInstance().getFile(editor.document) == null) {
return false
}
return editor.project == null || editor.project == project
}
}
private inner class MyVirtualFileListener : BulkFileListener {
override fun before(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFileDeleteEvent -> handleFileDeletion(event.file)
}
}
}
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> when {
VirtualFile.PROP_ENCODING == event.propertyName -> onFileChanged(event.file)
event.isRename -> handleFileMovement(event.file)
}
is VFileMoveEvent -> handleFileMovement(event.file)
}
}
}
private fun handleFileMovement(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
reregisterTrackerInCLM(data)
}
}
}
private fun handleFileDeletion(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
releaseTracker(data.tracker.document)
}
}
}
private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) {
if (file.isDirectory) {
val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) }
for (data in affected) {
action(data)
}
}
else {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return
val data = trackers[document] ?: return
action(data)
}
}
}
private inner class MyDocumentListener : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread
if (!partialChangeListsEnabled || project.isDisposed) return
val document = event.document
if (documentsInDefaultChangeList.contains(document)) return
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
if (getLineStatusTracker(document) != null) return
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) return
val changeList = ChangeListManager.getInstance(project).getChangeList(virtualFile)
val inAnotherChangelist = changeList != null && !ActiveChangeListTracker.getInstance(project).isActiveChangeList(changeList)
if (inAnotherChangelist) {
log("Tracker install from DocumentListener: ", virtualFile)
val tracker = synchronized(LOCK) {
installTracker(virtualFile, document, provider)
}
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.replayChangesFromDocumentEvents(listOf(event))
}
}
else {
documentsInDefaultChangeList.add(document)
}
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
documentsInDefaultChangeList.clear()
synchronized(LOCK) {
val documents = trackers.values.map { it.tracker.document }
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
}
private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener {
override fun settingsUpdated() {
updatePartialChangeListsAvailability()
updateTrackingSettings()
}
}
private inner class MyChangeListListener : ChangeListAdapter() {
override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) {
runInEdt(ModalityState.any()) {
if (project.isDisposed) return@runInEdt
expireInactiveRangesDamagedNotifications()
EditorFactory.getInstance().allEditors
.forEach { if (it is EditorEx) it.gutterComponentEx.repaint() }
}
}
}
private inner class MyChangeListAvailabilityListener : ChangeListAvailabilityListener {
override fun onBefore() {
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
val fileStates = LineStatusTrackerManager.getInstanceImpl(project).collectPartiallyChangedFilesStates()
if (fileStates.isNotEmpty()) {
PartialLineStatusTrackerManagerState.saveCurrentState(project, fileStates)
}
}
}
override fun onAfter() {
updatePartialChangeListsAvailability()
onEverythingChanged()
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
}
private inner class MyCommandListener : CommandListener {
override fun commandFinished(event: CommandEvent) {
if (!partialChangeListsEnabled) return
if (CommandProcessor.getInstance().currentCommand == null &&
!filesWithDamagedInactiveRanges.isEmpty()) {
showInactiveRangesDamagedNotification()
}
}
}
class CheckinFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
val project = panel.project
return object : CheckinHandler() {
override fun checkinSuccessful() {
resetExcludedFromCommit()
}
override fun checkinFailed(exception: MutableList<VcsException>?) {
resetExcludedFromCommit()
}
private fun resetExcludedFromCommit() {
runInEdt {
// TODO Move this to SingleChangeListCommitWorkflow
if (!project.isDisposed && !panel.isNonModalCommit) getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
}
}
}
}
private inner class MyFreezeListener : VcsFreezingProcess.Listener {
override fun onFreeze() {
runReadAction {
synchronized(LOCK) {
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.freeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
clmFreezeCounter++
}
}
}
override fun onUnfreeze() {
runInEdt(ModalityState.any()) {
synchronized(LOCK) {
clmFreezeCounter--
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.unfreeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
}
}
}
private class TrackerData(val tracker: LocalLineStatusTracker<*>,
var contentInfo: ContentInfo? = null,
var clmFilePath: FilePath? = null)
private class RefreshRequest(val document: Document, val loader: LineStatusTrackerContentLoader) {
override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document
override fun hashCode(): Int = document.hashCode()
override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown") // NON-NLS
}
private class RefreshData(val content: TrackerContent,
val contentInfo: ContentInfo)
private fun log(@NonNls message: String, file: VirtualFile?) {
if (LOG.isDebugEnabled) {
if (file != null) {
LOG.debug(message + "; file: " + file.path)
}
else {
LOG.debug(message)
}
}
}
private fun warn(@NonNls message: String, document: Document?) {
val file = document?.let { FileDocumentManager.getInstance().getFile(it) }
warn(message, file)
}
private fun warn(@NonNls message: String, file: VirtualFile?) {
if (file != null) {
LOG.warn(message + "; file: " + file.path)
}
else {
LOG.warn(message)
}
}
@RequiresEdt
fun resetExcludedFromCommitMarkers() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val documents = mutableListOf<Document>()
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.resetExcludedFromCommitMarkers()
documents.add(tracker.document)
}
}
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>()
synchronized(LOCK) {
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = tracker.affectedChangeListsIds.size > 1
if (hasPartialChanges) {
result.add(tracker.storeTrackerState())
}
}
}
}
return result
}
@RequiresEdt
internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) {
runWriteAction {
synchronized(LOCK) {
if (isDisposed) return@runWriteAction
for (state in trackerStates) {
val virtualFile = state.virtualFile
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) continue
switchTracker(virtualFile, document)
val tracker = trackers[document]?.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) continue
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("State restoration scheduled", virtualFile)
}
else {
val success = tracker.restoreState(state)
log("State restored. success - $success", virtualFile)
}
}
loader.addAfterUpdateRunnable(Runnable {
synchronized(LOCK) {
log("State restoration finished", null)
fileStatesAwaitingRefresh.clear()
}
})
}
}
onEverythingChanged()
}
@RequiresEdt
internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) {
ApplicationManager.getApplication().assertIsWriteThread()
if (filesWithDamagedInactiveRanges.contains(virtualFile) || virtualFile == FileEditorManagerEx.getInstanceEx(project).currentFile) {
return
}
filesWithDamagedInactiveRanges.add(virtualFile)
}
private fun showInactiveRangesDamagedNotification() {
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
val lastNotification = currentNotifications.lastOrNull { !it.isExpired }
if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles)
currentNotifications.forEach { it.expire() }
val files = filesWithDamagedInactiveRanges.toSet()
filesWithDamagedInactiveRanges.clear()
InactiveRangesDamagedNotification(project, files).notify(project)
}
@RequiresEdt
private fun expireInactiveRangesDamagedNotifications() {
filesWithDamagedInactiveRanges.clear()
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
currentNotifications.forEach { it.expire() }
}
private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>)
: Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId,
AllIcons.Toolwindows.ToolWindowChanges,
null,
null,
VcsBundle.message("lst.inactive.ranges.damaged.notification"),
NotificationType.INFORMATION,
null) {
init {
addAction(NotificationAction.createSimple(
Supplier { VcsBundle.message("action.NotificationAction.InactiveRangesDamagedNotification.text.view.changes") },
Runnable {
val defaultList = ChangeListManager.getInstance(project).defaultChangeList
val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) }
val window = getToolWindowFor(project, LOCAL_CHANGES)
window?.activate { ChangesViewManager.getInstance(project).selectChanges(changes) }
expire()
}))
}
}
@TestOnly
fun waitUntilBaseContentsLoaded() {
assert(ApplicationManager.getApplication().isUnitTestMode)
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
val semaphore = Semaphore()
semaphore.down()
loader.addAfterUpdateRunnable(Runnable {
semaphore.up()
})
val start = System.currentTimeMillis()
while (true) {
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
if (semaphore.waitFor(10)) {
return
}
if (System.currentTimeMillis() - start > 10000) {
loader.dumpInternalState()
System.err.println(ThreadDumper.dumpThreadsToString())
throw IllegalStateException("Couldn't await base contents") // NON-NLS
}
}
}
@TestOnly
fun releaseAllTrackers() {
synchronized(LOCK) {
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
}
/**
* Single threaded queue with the following properties:
* - Ignores duplicated requests (the first queued is used).
* - Allows to check whether request is scheduled or is waiting for completion.
* - Notifies callbacks when queue is exhausted.
*/
private abstract class SingleThreadLoader<Request, T> : Disposable {
private val LOG = Logger.getInstance(SingleThreadLoader::class.java)
private val LOCK: Any = Any()
private val taskQueue = ArrayDeque<Request>()
private val waitingForRefresh = HashSet<Request>()
private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>()
private var isScheduled: Boolean = false
private var isDisposed: Boolean = false
private var lastFuture: Future<*>? = null
@RequiresBackgroundThread
protected abstract fun loadRequest(request: Request): Result<T>
@RequiresEdt
protected abstract fun handleResult(request: Request, result: Result<T>)
@RequiresEdt
fun scheduleRefresh(request: Request) {
if (isDisposed) return
synchronized(LOCK) {
if (taskQueue.contains(request)) return
taskQueue.add(request)
schedule()
}
}
@RequiresEdt
override fun dispose() {
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
isDisposed = true
taskQueue.clear()
waitingForRefresh.clear()
lastFuture?.cancel(true)
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
executeCallbacks(callbacksWaitingUpdateCompletion)
}
@RequiresEdt
protected fun hasRequest(condition: (Request) -> Boolean): Boolean {
synchronized(LOCK) {
return taskQueue.any(condition) ||
waitingForRefresh.any(condition)
}
}
@CalledInAny
fun addAfterUpdateRunnable(task: Runnable) {
val updateScheduled = putRunnableIfUpdateScheduled(task)
if (updateScheduled) return
runInEdt(ModalityState.any()) {
if (!putRunnableIfUpdateScheduled(task)) {
task.run()
}
}
}
private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean {
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false
callbacksWaitingUpdateCompletion.add(task)
return true
}
}
private fun schedule() {
if (isDisposed) return
synchronized(LOCK) {
if (isScheduled) return
if (taskQueue.isEmpty()) return
isScheduled = true
lastFuture = ApplicationManager.getApplication().executeOnPooledThread {
ClientId.withClientId(ClientId.localId) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable {
handleRequests()
})
}
}
}
}
private fun handleRequests() {
while (true) {
val request = synchronized(LOCK) {
val request = taskQueue.poll()
if (isDisposed || request == null) {
isScheduled = false
return
}
waitingForRefresh.add(request)
return@synchronized request
}
handleSingleRequest(request)
}
}
private fun handleSingleRequest(request: Request) {
val result: Result<T> = try {
loadRequest(request)
}
catch (e: ProcessCanceledException) {
Result.Canceled()
}
catch (e: Throwable) {
LOG.error(e)
Result.Error()
}
runInEdt(ModalityState.any()) {
try {
synchronized(LOCK) {
waitingForRefresh.remove(request)
}
handleResult(request, result)
}
finally {
notifyTrackerRefreshed()
}
}
}
@RequiresEdt
private fun notifyTrackerRefreshed() {
if (isDisposed) return
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) {
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
}
executeCallbacks(callbacks)
}
@RequiresEdt
private fun executeCallbacks(callbacks: List<Runnable>) {
for (callback in callbacks) {
try {
callback.run()
}
catch (e: ProcessCanceledException) {
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
@TestOnly
fun dumpInternalState() {
synchronized(LOCK) {
LOG.debug("isScheduled - $isScheduled")
LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}")
taskQueue.forEach {
LOG.debug("pending task: ${it}")
}
waitingForRefresh.forEach {
LOG.debug("waiting refresh: ${it}")
}
}
}
}
private sealed class Result<T> {
class Success<T>(val data: T) : Result<T>()
class Canceled<T> : Result<T>()
class Error<T> : Result<T>()
}
private object ChangelistsLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled(file)) return false
if (!super.isTrackedFile(project, file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status != FileStatus.MODIFIED &&
status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE &&
status != FileStatus.NOT_CHANGED) return false
val change = ChangeListManager.getInstance(project).getChange(file)
return change == null ||
change.javaClass == Change::class.java &&
(change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) &&
change.afterRevision is CurrentContentRevision
}
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is ChangelistsLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return ChangelistsLocalLineStatusTracker.createTracker(project, document, file)
}
}
private object DefaultLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is SimpleLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return SimpleLocalLineStatusTracker.createTracker(project, document, file)
}
}
private abstract class BaseRevisionStatusTrackerContentLoader : LineStatusTrackerContentLoader {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!VcsFileStatusProvider.getInstance(project).isSupported(file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status == FileStatus.ADDED ||
status == FileStatus.DELETED ||
status == FileStatus.UNKNOWN ||
status == FileStatus.IGNORED) {
return false
}
return true
}
override fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? {
val baseContent = VcsFileStatusProvider.getInstance(project).getBaseRevision(file) ?: return null
return BaseRevisionContentInfo(baseContent, file.charset)
}
override fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean {
newInfo as BaseRevisionContentInfo
return oldInfo == null ||
oldInfo !is BaseRevisionContentInfo ||
oldInfo.baseContent.revisionNumber != newInfo.baseContent.revisionNumber ||
oldInfo.baseContent.revisionNumber == VcsRevisionNumber.NULL ||
oldInfo.charset != newInfo.charset
}
override fun loadContent(project: Project, info: ContentInfo): BaseRevisionContent? {
info as BaseRevisionContentInfo
val lastUpToDateContent = info.baseContent.loadContent() ?: return null
val correctedText = StringUtil.convertLineSeparators(lastUpToDateContent)
return BaseRevisionContent(correctedText)
}
override fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) {
tracker as LocalLineStatusTrackerImpl<*>
content as BaseRevisionContent
tracker.setBaseRevision(content.text)
}
override fun handleLoadingError(tracker: LocalLineStatusTracker<*>) {
tracker as LocalLineStatusTrackerImpl<*>
tracker.dropBaseRevision()
}
private class BaseRevisionContentInfo(val baseContent: VcsBaseContentProvider.BaseContent, val charset: Charset) : ContentInfo
private class BaseRevisionContent(val text: CharSequence) : TrackerContent
}
interface LocalLineStatusTrackerProvider {
fun isTrackedFile(project: Project, file: VirtualFile): Boolean
fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean
fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>?
companion object {
val EP_NAME: ExtensionPointName<LocalLineStatusTrackerProvider> =
ExtensionPointName.create("com.intellij.openapi.vcs.impl.LocalLineStatusTrackerProvider")
}
}
interface LineStatusTrackerContentLoader : LocalLineStatusTrackerProvider {
fun getContentInfo(project: Project, file: VirtualFile): ContentInfo?
fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean
fun loadContent(project: Project, info: ContentInfo): TrackerContent?
fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent)
fun handleLoadingError(tracker: LocalLineStatusTracker<*>)
interface ContentInfo
interface TrackerContent
} | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt | 504572620 |
package com.devslopes.datafrost1997.gitterchat.Controller
import android.content.*
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout
import com.devslopes.datafrost1997.gitterchat.Adapters.MessageAdapter
import com.devslopes.datafrost1997.gitterchat.Model.Channel
import com.devslopes.datafrost1997.gitterchat.Model.Message
import com.devslopes.datafrost1997.gitterchat.R
import com.devslopes.datafrost1997.gitterchat.R.id.*
import com.devslopes.datafrost1997.gitterchat.Services.AuthService
import com.devslopes.datafrost1997.gitterchat.Services.MessageService
import com.devslopes.datafrost1997.gitterchat.Services.UserDataService
import com.devslopes.datafrost1997.gitterchat.Utilities.BROADCAST_USER_DATA_CHANGE
import com.devslopes.datafrost1997.gitterchat.Utilities.SOCKET_URL
import io.socket.client.IO
import io.socket.emitter.Emitter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.nav_header_main.*
class MainActivity : AppCompatActivity() {
val socket = IO.socket(SOCKET_URL)
lateinit var channelAdapter: ArrayAdapter<Channel>
lateinit var messageAdapter: MessageAdapter
var selectedChannel: Channel? = null
private fun setupAdapters() {
channelAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, MessageService.channels)
channel_list.adapter = channelAdapter
messageAdapter = MessageAdapter(this,MessageService.messages)
messageListView.adapter = messageAdapter
val layoutManager = LinearLayoutManager(this)
messageListView.layoutManager = layoutManager
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
socket.connect()
socket.on("channelCreated", onNewChannel)
socket.on("messageCreated", onNewMessage)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
setupAdapters()
LocalBroadcastManager.getInstance(this).registerReceiver(userDataChangeReceiver,
IntentFilter(BROADCAST_USER_DATA_CHANGE))
channel_list.setOnItemClickListener { _, _, i, _ ->
selectedChannel = MessageService.channels[i]
drawer_layout.closeDrawer(GravityCompat.START)
updateWithChanel()
}
if (App.prefs.isLoggedIn) {
AuthService.findUserByEmail(this) {}
}
}
override fun onDestroy() {
socket.disconnect()
LocalBroadcastManager.getInstance(this).unregisterReceiver(userDataChangeReceiver)
super.onDestroy()
}
private val userDataChangeReceiver = object: BroadcastReceiver () {
override fun onReceive(context: Context, intent: Intent?) {
if (App.prefs.isLoggedIn) {
userNameNavHeader.text = UserDataService.name
userEmailNavHeader.text = UserDataService.email
val resourceId = resources.getIdentifier(UserDataService.avatarName, "drawable",
packageName)
userImageNavHeader.setImageResource(resourceId)
userImageNavHeader.setBackgroundColor(UserDataService.returnAvatarColor(UserDataService.avatarColor))
loginBtnNavHeader.text = "Logout"
MessageService.getChannels { complete ->
if(complete) {
if (MessageService.channels.count()>0) {
selectedChannel = MessageService.channels[0]
channelAdapter.notifyDataSetChanged()
updateWithChanel()
}
}
}
}
}
}
fun updateWithChanel() {
mainChannelName.text = "#${selectedChannel?.name}"
if (selectedChannel != null) {
MessageService.getMessages(selectedChannel!!.id) { complete ->
if (complete) {
// for (message in MessageService.messages) {
// println(message.message)
// }
messageAdapter.notifyDataSetChanged()
if (messageAdapter.itemCount > 0) {
messageListView.smoothScrollToPosition(messageAdapter.itemCount - 1)
}
}
}
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
fun loginBtnNavClicked(view: View) {
if (App.prefs.isLoggedIn) {
// log out
UserDataService.logout()
channelAdapter.notifyDataSetChanged()
messageAdapter.notifyDataSetChanged()
userNameNavHeader.text = ""
userEmailNavHeader.text = ""
userImageNavHeader.setImageResource(R.drawable.profiledefault)
userImageNavHeader.setBackgroundColor(Color.TRANSPARENT)
loginBtnNavHeader.text = "Login"
mainChannelName.text = "Please Log In"
} else {
val loginIntent = Intent(this, loginActivity::class.java)
startActivity(loginIntent)
}
}
fun addChannelClicked(view: View) {
if(App.prefs.isLoggedIn) {
val builder = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.add_channel_dialog,null)
builder.setView(dialogView)
.setPositiveButton("Add") { _, _ ->
val nameTextField = dialogView.findViewById<EditText>(R.id.addChannelNameTxt)
val descTextField = dialogView.findViewById<EditText>(R.id.addChannelDescTxt)
val channelName = nameTextField.text.toString()
val channelDesc = descTextField.text.toString()
socket.emit("newChannel", channelName, channelDesc)
}
.setNegativeButton("Cancel") { _, _ ->
}
.show()
}
}
private val onNewChannel = Emitter.Listener { args ->
// println(args[0] as String)
if(App.prefs.isLoggedIn){
runOnUiThread {
val channelName = args[0] as String
val channelDescription = args[1] as String
val channelId = args[2] as String
val newChannel = Channel(channelName, channelDescription, channelId)
MessageService.channels.add(newChannel)
channelAdapter.notifyDataSetChanged()
}
}
}
private val onNewMessage = Emitter.Listener { args ->
if(App.prefs.isLoggedIn) {
runOnUiThread {
val channelId = args[2] as String
if(channelId == selectedChannel?.id) {
val msgBody = args[0] as String
val userName = args[3] as String
val userAvatar = args[4] as String
val userAvatarColor = args[5] as String
val id = args[6] as String
val timeStamp = args[7] as String
val newMessage = Message(msgBody, userName, channelId, userAvatar, userAvatarColor, id, timeStamp)
MessageService.messages.add(newMessage)
messageAdapter.notifyDataSetChanged()
messageListView.smoothScrollToPosition(messageAdapter.itemCount - 1)
}
}
}
}
fun sendMesgBtnClicked(view: View) {
if (App.prefs.isLoggedIn && messageTextField.text.isNotEmpty() && selectedChannel != null) {
val userId = UserDataService.id
val channelId = selectedChannel!!.id
socket.emit("newMessage", messageTextField.text.toString(), userId, channelId,
UserDataService.name, UserDataService.avatarName, UserDataService.avatarColor)
messageTextField.text.clear()
hideKeyboard()
}
}
fun hideKeyboard () {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText) {
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
}
| app/src/main/java/com/devslopes/datafrost1997/gitterchat/Controller/MainActivity.kt | 782619759 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.externalComponents.UpdatableExternalComponent
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.util.BuildNumber
class UpdateChain internal constructor(val chain: List<BuildNumber>, val size: String?)
class CheckForUpdateResult {
val state: UpdateStrategy.State
val newBuild: BuildInfo?
val updatedChannel: UpdateChannel?
val patches: UpdateChain?
val error: Exception?
internal constructor(newBuild: BuildInfo?, updatedChannel: UpdateChannel?, patches: UpdateChain?) {
this.state = UpdateStrategy.State.LOADED
this.newBuild = newBuild
this.updatedChannel = updatedChannel
this.patches = patches
this.error = null
}
internal constructor(state: UpdateStrategy.State, error: Exception?) {
this.state = state
this.newBuild = null
this.updatedChannel = null
this.patches = null
this.error = error
}
}
/**
* [enabled] - new versions of enabled plugins compatible with the specified build
*
* [disabled] - new versions of disabled plugins compatible with the specified build
*
* [incompatible] - plugins that would become incompatible and don't have updates compatible with the specified build
*/
data class PluginUpdates(
val enabled: Collection<PluginDownloader>,
val disabled: Collection<PluginDownloader>,
val incompatible: Collection<IdeaPluginDescriptor>,
)
data class ExternalUpdate(
val source: ExternalComponentSource,
val components: Collection<UpdatableExternalComponent>
)
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckResults.kt | 2414791960 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.util
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import kotlin.reflect.KClass
abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() {
constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } })
private val builder = StringBuilder()
var level = 0
private set
override fun visitElement(element: PsiElement) {
val charSequence = render(element)
if (charSequence != null) {
builder.append(" ".repeat(level))
builder.append(charSequence)
builder.appendln()
}
val shouldIndent = shouldIndent(element)
if (shouldIndent) level++
element.acceptChildren(this)
if (shouldIndent) level--
}
protected abstract fun render(element: PsiElement): CharSequence?
val result: String
get() = builder.toString()
} | uast/uast-common/src/org/jetbrains/uast/util/IndentedPrintingVisitor.kt | 1992276602 |
/*
* Copyright (C) 2019 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 okio
actual sealed interface BufferedSource : Source {
actual val buffer: Buffer
actual fun exhausted(): Boolean
actual fun require(byteCount: Long)
actual fun request(byteCount: Long): Boolean
actual fun readByte(): Byte
actual fun readShort(): Short
actual fun readShortLe(): Short
actual fun readInt(): Int
actual fun readIntLe(): Int
actual fun readLong(): Long
actual fun readLongLe(): Long
actual fun readDecimalLong(): Long
actual fun readHexadecimalUnsignedLong(): Long
actual fun skip(byteCount: Long)
actual fun readByteString(): ByteString
actual fun readByteString(byteCount: Long): ByteString
actual fun select(options: Options): Int
actual fun readByteArray(): ByteArray
actual fun readByteArray(byteCount: Long): ByteArray
actual fun read(sink: ByteArray): Int
actual fun readFully(sink: ByteArray)
actual fun read(sink: ByteArray, offset: Int, byteCount: Int): Int
actual fun readFully(sink: Buffer, byteCount: Long)
actual fun readAll(sink: Sink): Long
actual fun readUtf8(): String
actual fun readUtf8(byteCount: Long): String
actual fun readUtf8Line(): String?
actual fun readUtf8LineStrict(): String
actual fun readUtf8LineStrict(limit: Long): String
actual fun readUtf8CodePoint(): Int
actual fun indexOf(b: Byte): Long
actual fun indexOf(b: Byte, fromIndex: Long): Long
actual fun indexOf(b: Byte, fromIndex: Long, toIndex: Long): Long
actual fun indexOf(bytes: ByteString): Long
actual fun indexOf(bytes: ByteString, fromIndex: Long): Long
actual fun indexOfElement(targetBytes: ByteString): Long
actual fun indexOfElement(targetBytes: ByteString, fromIndex: Long): Long
actual fun rangeEquals(offset: Long, bytes: ByteString): Boolean
actual fun rangeEquals(offset: Long, bytes: ByteString, bytesOffset: Int, byteCount: Int): Boolean
actual fun peek(): BufferedSource
}
| okio/src/nonJvmMain/kotlin/okio/BufferedSource.kt | 1576155441 |
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto.rest.model.crypto
class SendToDeviceBody {
// `Any` should implement SendToDeviceObject, but we cannot use interface here because of Gson serialization
@JvmField
var messages: Map<String, Map<String, Any>>? = null
} | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/rest/model/crypto/SendToDeviceBody.kt | 3969353971 |
/* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.zipstep
import kotlinx.serialization.Required
import kotlinx.serialization.Serializable
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.model.enums.CompressionLevel
import net.lingala.zip4j.model.enums.CompressionMethod
@Serializable
data class ZipStepSettings(
@Required var compressionMethod: CompressionMethod = CompressionMethod.DEFLATE,
@Required var compressionLevel: CompressionLevel = CompressionLevel.NORMAL,
@Required var readHiddenFiles: Boolean = true,
@Required var readHiddenFolders: Boolean = true,
@Required var writeExtendedLocalFileHeader: Boolean = true,
@Required var fileComment: String = "",
@Required var symbolicLinkAction: ZipParameters.SymbolicLinkAction = ZipParameters.SymbolicLinkAction.INCLUDE_LINKED_FILE_ONLY,
@Required var unixMode: Boolean = false
)
| zipstep/src/main/kotlin/com/deflatedpickle/quiver/zipstep/ZipStepSettings.kt | 1222703240 |
/*
* (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component
import com.faendir.acra.ui.ext.booleanProperty
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.HasComponents
import com.vaadin.flow.component.HasSize
import com.vaadin.flow.component.HasStyle
import com.vaadin.flow.component.Tag
import com.vaadin.flow.component.dependency.JsModule
import com.vaadin.flow.component.littemplate.LitTemplate
/**
* @author lukas
* @since 18.10.18
*/
@Tag("acrarium-card")
@JsModule("./elements/card.ts")
class Card() : LitTemplate(), HasSize, HasStyle, HasComponents, HasSlottedComponents<Card.Slot> {
constructor(vararg components: Component) : this() {
add(*components)
}
fun setHeader(vararg components: Component) {
add(Slot.HEADER, *components)
}
var allowCollapse by booleanProperty("canCollapse")
var isCollapsed by booleanProperty("isCollapsed")
var dividerEnabled by booleanProperty("divider")
fun setHeaderColor(textColor: String?, backgroundColor: String?) {
style["--acrarium-card-header-text-color"] = textColor
style["--acrarium-card-header-color"] = backgroundColor
}
fun removeContent() {
children.filter { it.element.getAttribute("slot") == null }.forEach { this.remove(it) }
}
fun hasContent() = children.anyMatch { it.element.getAttribute("slot") == null }
enum class Slot : HasSlottedComponents.Slot {
HEADER
}
} | acrarium/src/main/kotlin/com/faendir/acra/ui/component/Card.kt | 328188497 |
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.drm.egl
import org.freedesktop.jaccall.Pointer
import org.westford.compositor.core.GlRenderer
import org.westford.compositor.core.OutputFactory
import org.westford.compositor.core.OutputGeometry
import org.westford.compositor.core.OutputMode
import org.westford.compositor.drm.DrmOutput
import org.westford.compositor.drm.DrmPlatform
import org.westford.compositor.protocol.WlOutput
import org.westford.compositor.protocol.WlOutputFactory
import org.westford.launch.LifeCycleSignals
import org.westford.launch.Privileges
import org.westford.nativ.libEGL.EglCreatePlatformWindowSurfaceEXT
import org.westford.nativ.libEGL.EglGetPlatformDisplayEXT
import org.westford.nativ.libEGL.LibEGL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_BACK_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CLIENT_APIS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CONTEXT_CLIENT_VERSION
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_EXTENSIONS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NONE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_CONTEXT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_DISPLAY
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_PLATFORM_GBM_KHR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_RENDER_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VENDOR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VERSION
import org.westford.nativ.libGLESv2.LibGLESv2
import org.westford.nativ.libgbm.Libgbm
import java.lang.String.format
import java.util.*
import java.util.logging.Logger
import javax.inject.Inject
class DrmEglPlatformFactory @Inject internal constructor(private val wlOutputFactory: WlOutputFactory,
private val outputFactory: OutputFactory,
private val privateDrmEglPlatformFactory: PrivateDrmEglPlatformFactory,
private val libgbm: Libgbm,
private val gbmBoFactory: GbmBoFactory,
private val libEGL: LibEGL,
private val libGLESv2: LibGLESv2,
private val drmPlatform: DrmPlatform,
private val drmEglOutputFactory: DrmEglOutputFactory,
private val glRenderer: GlRenderer,
private val lifeCycleSignals: LifeCycleSignals,
private val privileges: Privileges) {
fun create(): DrmEglPlatform {
val gbmDevice = this.libgbm.gbm_create_device(this.drmPlatform.drmFd)
val eglDisplay = createEglDisplay(gbmDevice)
val eglExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_EXTENSIONS)).get()
val eglClientApis = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_CLIENT_APIS)).get()
val eglVendor = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VENDOR)).get()
val eglVersion = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VERSION)).get()
LOGGER.info(format("Creating DRM EGL output:\n" + "\tEGL client apis: %s\n" + "\tEGL vendor: %s\n" + "\tEGL version: %s\n" + "\tEGL extensions: %s",
eglClientApis,
eglVendor,
eglVersion,
eglExtensions))
val eglConfig = this.glRenderer.eglConfig(eglDisplay,
eglExtensions)
val eglContext = createEglContext(eglDisplay,
eglConfig)
val drmOutputs = this.drmPlatform.renderOutputs
val drmEglRenderOutputs = ArrayList<DrmEglOutput>(drmOutputs.size)
val wlOutputs = ArrayList<WlOutput>(drmEglRenderOutputs.size)
drmOutputs.forEach {
drmEglRenderOutputs.add(createDrmEglRenderOutput(it,
gbmDevice,
eglDisplay,
eglContext,
eglConfig))
}
drmEglRenderOutputs.forEach {
wlOutputs.add(createWlOutput(it))
}
this.lifeCycleSignals.activateSignal.connect {
this.privileges.setDrmMaster(this.drmPlatform.drmFd)
wlOutputs.forEach {
val drmEglOutput = it.output.renderOutput as DrmEglOutput
drmEglOutput.setDefaultMode()
drmEglOutput.enable(it)
}
}
this.lifeCycleSignals.deactivateSignal.connect {
drmEglRenderOutputs.forEach {
it.disable()
}
this.privileges.dropDrmMaster(this.drmPlatform.drmFd)
}
return this.privateDrmEglPlatformFactory.create(gbmDevice,
eglDisplay,
eglContext,
eglExtensions,
wlOutputs)
}
private fun createWlOutput(drmEglOutput: DrmEglOutput): WlOutput {
val drmOutput = drmEglOutput.drmOutput
val drmModeConnector = drmOutput.drmModeConnector
val drmModeModeInfo = drmOutput.mode
val fallBackDpi = 96
var mmWidth = drmModeConnector.mmWidth
val hdisplay = drmOutput.mode.hdisplay
if (mmWidth == 0) {
mmWidth = (hdisplay * 25.4 / fallBackDpi).toInt()
}
var mmHeight = drmModeConnector.mmHeight
val vdisplay = drmOutput.mode.vdisplay
if (mmHeight == 0) {
mmHeight = (vdisplay * 25.4 / fallBackDpi).toInt()
}
//TODO gather more geo & drmModeModeInfo info
val outputGeometry = OutputGeometry(physicalWidth = mmWidth,
physicalHeight = mmHeight,
make = "unknown",
model = "unknown",
x = 0,
y = 0,
subpixel = drmModeConnector.drmModeSubPixel,
transform = 0)
val outputMode = OutputMode(width = hdisplay.toInt(),
height = vdisplay.toInt(),
refresh = drmOutput.mode.vrefresh,
flags = drmModeModeInfo.flags)
//FIXME deduce an output name from the drm connector
return this.wlOutputFactory.create(this.outputFactory.create(drmEglOutput,
"fixme",
outputGeometry,
outputMode))
}
private fun createEglDisplay(gbmDevice: Long): Long {
val noDisplayExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(EGL_NO_DISPLAY,
EGL_EXTENSIONS))
if (noDisplayExtensions.address == 0L) {
throw RuntimeException("Could not query egl extensions.")
}
val extensions = noDisplayExtensions.get()
if (!extensions.contains("EGL_MESA_platform_gbm")) {
throw RuntimeException("Required extension EGL_MESA_platform_gbm not available.")
}
val eglGetPlatformDisplayEXT = Pointer.wrap<EglGetPlatformDisplayEXT>(EglGetPlatformDisplayEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglGetPlatformDisplayEXT").address))
val eglDisplay = eglGetPlatformDisplayEXT.get()(EGL_PLATFORM_GBM_KHR,
gbmDevice,
0L)
if (eglDisplay == 0L) {
throw RuntimeException("eglGetDisplay() failed")
}
if (this.libEGL.eglInitialize(eglDisplay,
0L,
0L) == 0) {
throw RuntimeException("eglInitialize() failed")
}
return eglDisplay
}
private fun createEglContext(eglDisplay: Long,
config: Long): Long {
val eglContextAttribs = Pointer.nref(//@formatter:off
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
//@formatter:on
)
val context = this.libEGL.eglCreateContext(eglDisplay,
config,
EGL_NO_CONTEXT,
eglContextAttribs.address)
if (context == 0L) {
throw RuntimeException("eglCreateContext() failed")
}
return context
}
private fun createDrmEglRenderOutput(drmOutput: DrmOutput,
gbmDevice: Long,
eglDisplay: Long,
eglContext: Long,
eglConfig: Long): DrmEglOutput {
val drmModeModeInfo = drmOutput.mode
//TODO test if format is supported (gbm_device_is_format_supported)?
val gbmSurface = this.libgbm.gbm_surface_create(gbmDevice,
drmModeModeInfo.hdisplay.toInt(),
drmModeModeInfo.vdisplay.toInt(),
Libgbm.GBM_FORMAT_XRGB8888,
Libgbm.GBM_BO_USE_SCANOUT or Libgbm.GBM_BO_USE_RENDERING)
if (gbmSurface == 0L) {
throw RuntimeException("failed to create gbm surface")
}
val eglSurface = createEglSurface(eglDisplay,
eglConfig,
gbmSurface)
this.libEGL.eglMakeCurrent(eglDisplay,
eglSurface,
eglSurface,
eglContext)
this.libGLESv2.glClearColor(1.0f,
1.0f,
1.0f,
1.0f)
this.libGLESv2.glClear(LibGLESv2.GL_COLOR_BUFFER_BIT)
this.libEGL.eglSwapBuffers(eglDisplay,
eglSurface)
val gbmBo = this.gbmBoFactory.create(gbmSurface)
val drmEglRenderOutput = this.drmEglOutputFactory.create(this.drmPlatform.drmFd,
gbmDevice,
gbmBo,
gbmSurface,
drmOutput,
eglSurface,
eglContext,
eglDisplay)
drmEglRenderOutput.setDefaultMode()
return drmEglRenderOutput
}
private fun createEglSurface(eglDisplay: Long,
config: Long,
gbmSurface: Long): Long {
val eglSurfaceAttribs = Pointer.nref(EGL_RENDER_BUFFER,
EGL_BACK_BUFFER,
EGL_NONE)
val eglGetPlatformDisplayEXT = Pointer.wrap<EglCreatePlatformWindowSurfaceEXT>(EglCreatePlatformWindowSurfaceEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglCreatePlatformWindowSurfaceEXT").address))
val eglSurface = eglGetPlatformDisplayEXT.get()(eglDisplay,
config,
gbmSurface,
eglSurfaceAttribs.address)
if (eglSurface == 0L) {
throw RuntimeException("eglCreateWindowSurface() failed")
}
return eglSurface
}
companion object {
private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
}
}
| compositor/src/main/kotlin/org/westford/compositor/drm/egl/DrmEglPlatformFactory.kt | 3174638690 |
package pl.edu.amu.wmi.erykandroidcommon.di
import android.app.Application
import android.content.Context
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.google.gson.Gson
import dagger.Component
import pl.edu.amu.wmi.erykandroidcommon.base.BaseActivity
import pl.edu.amu.wmi.erykandroidcommon.service.PicassoCache
import pl.edu.amu.wmi.erykandroidcommon.verify.FormVerificationManager
import javax.inject.Singleton
/**
* @author Eryk Mariankowski <eryk.mariankowski></eryk.mariankowski>@247.codes> on 21.10.17.
*/
@Singleton
@Component(modules = [CommonApplicationModule::class])
interface CommonApplicationComponent {
fun provideContext(): Context
fun picassoCache(): PicassoCache
fun gson(): Gson
fun application(): Application
fun commonApplication(): CommonApplication
fun provideSharedPreferences(): RxSharedPreferences
fun inject(baseActivity: BaseActivity)
fun inject(baseActivity: FormVerificationManager)
}
| src/main/java/pl/edu/amu/wmi/erykandroidcommon/di/CommonApplicationComponent.kt | 615528102 |
// 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.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.util.ui.JBUI
import net.miginfocom.swing.MigLayout
import java.awt.*
import java.beans.PropertyChangeListener
import java.util.ArrayList
import javax.swing.*
class DialogHeader(val window: Window) : CustomHeader(window) {
private val titleLabel = JLabel().apply {
border = LABEL_BORDER
}
private val titleChangeListener = PropertyChangeListener{
titleLabel.text = getTitle()
}
init {
layout = MigLayout("novisualpadding, ins 0, fillx, gap 0", "[min!][][pref!]")
titleLabel.text = getTitle()
productIcon.border = JBUI.Borders.empty(0, H, 0, H)
add(productIcon)
add(titleLabel, "wmin 0, left")
add(buttonPanes.getView(), "top, wmin pref")
}
override fun installListeners() {
super.installListeners()
window.addPropertyChangeListener("title", titleChangeListener)
}
override fun uninstallListeners() {
super.uninstallListeners()
window.removePropertyChangeListener(titleChangeListener)
}
override fun createButtonsPane(): CustomFrameTitleButtons = CustomFrameTitleButtons.create(myCloseAction)
override fun updateActive() {
titleLabel.foreground = if (myActive) UIManager.getColor("Panel.foreground") else UIManager.getColor("Label.disabledForeground")
super.updateActive()
}
override fun windowStateChanged() {
super.windowStateChanged()
titleLabel.text = getTitle()
}
override fun addNotify() {
super.addNotify()
titleLabel.text = getTitle()
}
private fun getTitle(): String? {
when (window) {
is Dialog -> return window.title
else -> return ""
}
}
override fun getHitTestSpots(): List<RelativeRectangle> {
val hitTestSpots = ArrayList<RelativeRectangle>()
hitTestSpots.add(RelativeRectangle(productIcon))
hitTestSpots.add(RelativeRectangle(buttonPanes.getView()))
return hitTestSpots
}
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/DialogHeader.kt | 3776744559 |
// 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.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.actions.getContextCommitWorkflowHandler
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.vcs.commit.CommitWorkflowHandler
abstract class BaseCommitExecutorAction : DumbAwareAction() {
init {
isEnabledInModalContext = true
}
override fun update(e: AnActionEvent) {
val workflowHandler = e.getContextCommitWorkflowHandler()
val executor = getCommitExecutor(workflowHandler)
e.presentation.isVisible = workflowHandler != null && executor != null
e.presentation.isEnabled = workflowHandler != null && executor != null && workflowHandler.isExecutorEnabled(executor)
}
override fun actionPerformed(e: AnActionEvent) {
val workflowHandler = e.getContextCommitWorkflowHandler()!!
val executor = getCommitExecutor(workflowHandler)!!
workflowHandler.execute(executor)
}
protected open val executorId: String = ""
protected open fun getCommitExecutor(handler: CommitWorkflowHandler?) = handler?.getExecutor(executorId)
companion object {
fun AnActionEvent.getAmendCommitModePrefix(): String {
val isAmend = getContextCommitWorkflowHandler()?.amendCommitHandler?.isAmendCommitMode == true
return if (isAmend) "Amend " else ""
}
}
}
internal class DefaultCommitExecutorAction(private val executor: CommitExecutor) : BaseCommitExecutorAction() {
init {
templatePresentation.text = executor.actionText
}
override fun getCommitExecutor(handler: CommitWorkflowHandler?): CommitExecutor? = executor
} | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BaseCommitExecutorAction.kt | 546383635 |
package net.vixiv.instant.search.engine
import net.vixiv.instant.R
import net.vixiv.instant.constant.Constants
/**
* The StartPage mobile search engine.
*/
class StartPageMobileSearch : BaseSearchEngine(
"file:///android_asset/startpage.png",
Constants.STARTPAGE_MOBILE_SEARCH,
R.string.search_engine_startpage_mobile
)
| app/src/main/java/net/vixiv/instant/search/engine/StartPageMobileSearch.kt | 3153619866 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.BalloonBuilder
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.util.function.Consumer
import java.util.function.Predicate
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.event.HyperlinkListener
/**
* If you want to register a toolwindow, which will be enabled during the dumb mode, please use [ToolWindowManager]'s
* registration methods which have 'canWorkInDumbMode' parameter.
*/
abstract class ToolWindowManager {
companion object {
@JvmStatic
fun getInstance(project: Project): ToolWindowManager = project.getService(ToolWindowManager::class.java)
}
abstract val focusManager: IdeFocusManager
abstract fun canShowNotification(toolWindowId: String): Boolean
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String, component: JComponent, anchor: ToolWindowAnchor): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, component = component, anchor = anchor, canCloseContent = false, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun registerToolWindow(id: String,
component: JComponent,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, component = component, anchor = anchor, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String, canCloseContent: Boolean, anchor: ToolWindowAnchor): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
secondary: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, sideTool = secondary, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean,
secondary: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, sideTool = secondary, canCloseContent = canCloseContent, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
abstract fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow
/**
* does nothing if tool window with specified isn't registered.
*/
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
abstract fun unregisterToolWindow(id: String)
abstract fun activateEditorComponent()
/**
* @return `true` if and only if editor component is active.
*/
abstract val isEditorComponentActive: Boolean
/**
* @return array of `id`s of all registered tool windows.
*/
abstract val toolWindowIds: Array<String>
abstract val toolWindowIdSet: Set<String>
/**
* @return `ID` of currently active tool window or `null` if there is no active
* tool window.
*/
abstract val activeToolWindowId: String?
/**
* @return `ID` of tool window that was activated last time.
*/
abstract val lastActiveToolWindowId: String?
/**
* @return registered tool window with specified `id`. If there is no registered
* tool window with specified `id` then the method returns `null`.
* @see ToolWindowId
*/
abstract fun getToolWindow(@NonNls id: String?): ToolWindow?
/**
* Puts specified runnable to the tail of current command queue.
*/
abstract fun invokeLater(runnable: Runnable)
abstract fun notifyByBalloon(toolWindowId: String, type: MessageType, @NlsContexts.NotificationContent htmlBody: String)
fun notifyByBalloon(toolWindowId: String,
type: MessageType,
@NlsContexts.PopupContent htmlBody: String,
icon: Icon?,
listener: HyperlinkListener?) {
notifyByBalloon(ToolWindowBalloonShowOptions(toolWindowId = toolWindowId, type = type, htmlBody = htmlBody, icon = icon, listener = listener))
}
abstract fun notifyByBalloon(options: ToolWindowBalloonShowOptions)
abstract fun getToolWindowBalloon(id: String): Balloon?
abstract fun isMaximized(window: ToolWindow): Boolean
abstract fun setMaximized(window: ToolWindow, maximized: Boolean)
/*
* Returns visual representation of tool window location
* @see AllIcons.Actions#MoveToBottomLeft ... com.intellij.icons.AllIcons.Actions#MoveToWindow icon set
*/
open fun getLocationIcon(id: String, fallbackIcon: Icon): Icon = fallbackIcon
abstract fun getLastActiveToolWindow(condition: Predicate<in JComponent>?): ToolWindow?
}
data class ToolWindowBalloonShowOptions(val toolWindowId: String,
val type: MessageType,
@NlsContexts.PopupContent val htmlBody: String,
val icon: Icon? = null,
val listener: HyperlinkListener? = null,
val balloonCustomizer: Consumer<BalloonBuilder>? = null) | platform/platform-api/src/com/intellij/openapi/wm/ToolWindowManager.kt | 1280547025 |
package com.intellij.workspace.api
import com.google.common.hash.Funnel
import com.google.common.hash.HashCode
import com.google.common.hash.Hasher
import com.intellij.openapi.util.text.StringUtil
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.util.*
class DebuggingHasher: Hasher {
private val sb = StringBuilder()
override fun putByte(b: Byte): Hasher {
sb.appendln("BYTE: $b")
return this
}
override fun putDouble(d: Double): Hasher {
sb.appendln("DOUBLE: $d")
return this
}
override fun putLong(l: Long): Hasher {
sb.appendln("LONG: $l")
return this
}
override fun putInt(i: Int): Hasher {
sb.appendln("INT: $i")
return this
}
override fun putBytes(bytes: ByteArray): Hasher {
sb.appendln("BYTES: ${StringUtil.toHexString(bytes)}")
return this
}
override fun putBytes(bytes: ByteArray, off: Int, len: Int): Hasher {
sb.appendln("BYTES RANGE: ${StringUtil.toHexString(Arrays.copyOfRange(bytes, off, off + len))}")
return this
}
override fun putBytes(bytes: ByteBuffer): Hasher {
sb.appendln("BYTES BUFFER: ${StringUtil.toHexString(bytes.array())}")
return this
}
override fun putUnencodedChars(charSequence: CharSequence): Hasher {
sb.appendln("CHARS: $charSequence")
return this
}
override fun putBoolean(b: Boolean): Hasher {
sb.appendln("BOOLEAN: $b")
return this
}
override fun <T : Any?> putObject(instance: T, funnel: Funnel<in T>): Hasher = throw UnsupportedOperationException()
override fun putShort(s: Short): Hasher {
sb.appendln("SHORT: $s")
return this
}
override fun putChar(c: Char): Hasher {
sb.appendln("CHAR: $c")
return this
}
override fun putFloat(f: Float): Hasher {
sb.appendln("FLOAT: $f")
return this
}
override fun hash(): HashCode = HashCode.fromBytes(sb.toString().toByteArray())
override fun putString(charSequence: CharSequence, charset: Charset): Hasher {
sb.appendln("STRING: $charSequence as ${charset.name()}")
return this
}
} | platform/workspaceModel-core-tests/test/com/intellij/workspace/api/DebuggingHasher.kt | 2246333813 |
// 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.ide.ui
import com.intellij.navigation.LocationPresentation.DEFAULT_LOCATION_PREFIX
import com.intellij.navigation.LocationPresentation.DEFAULT_LOCATION_SUFFIX
import com.intellij.navigation.TargetPopupPresentation
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.SimpleTextAttributes.*
import com.intellij.ui.speedSearch.SearchAwareRenderer
import com.intellij.ui.speedSearch.SpeedSearchUtil.appendColoredFragmentForMatcher
import com.intellij.util.text.MatcherHolder
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus.Experimental
import javax.swing.JList
@Experimental
abstract class TargetPresentationMainRenderer<T> : ColoredListCellRenderer<T>(), SearchAwareRenderer<T> {
protected abstract fun getPresentation(value: T): TargetPopupPresentation?
final override fun getItemSearchString(item: T): String? = getPresentation(item)?.presentableText
final override fun customizeCellRenderer(list: JList<out T>, value: T, index: Int, selected: Boolean, hasFocus: Boolean) {
val presentation = getPresentation(value) ?: run {
append("Invalid", ERROR_ATTRIBUTES)
return
}
val attributes = presentation.presentableAttributes
val bgColor = attributes?.backgroundColor ?: UIUtil.getListBackground()
icon = presentation.icon
background = if (selected) UIUtil.getListSelectionBackground(hasFocus) else bgColor
val nameAttributes = attributes?.let(::fromTextAttributes)
?: SimpleTextAttributes(STYLE_PLAIN, list.foreground)
val matcher = MatcherHolder.getAssociatedMatcher(list)
appendColoredFragmentForMatcher(presentation.presentableText, this, nameAttributes, matcher, bgColor, selected)
presentation.locationText?.let { locationText ->
val locationAttributes = presentation.locationAttributes?.let {
merge(defaultLocationAttributes, fromTextAttributes(it))
} ?: defaultLocationAttributes
append(DEFAULT_LOCATION_PREFIX, defaultLocationAttributes)
append("in ", defaultLocationAttributes)
append(locationText, locationAttributes)
append(DEFAULT_LOCATION_SUFFIX, defaultLocationAttributes)
}
}
companion object {
private val defaultLocationAttributes = SimpleTextAttributes(STYLE_PLAIN, JBColor.GRAY)
}
}
| platform/lang-impl/src/com/intellij/ide/ui/TargetPresentationMainRenderer.kt | 4115772285 |
// 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.testGuiFramework.fixtures
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.testGuiFramework.impl.findComponent
import com.intellij.ui.components.labels.ActionLink
import org.fest.swing.core.MouseButton
import org.fest.swing.core.MouseClickInfo
import org.fest.swing.core.Robot
import org.fest.swing.driver.ComponentDriver
import org.fest.swing.driver.JComponentDriver
import java.awt.Component
import java.awt.Container
import java.awt.Point
class ActionLinkFixture constructor(robot: Robot, target: ActionLink) : JComponentFixture<ActionLinkFixture, ActionLink>(
ActionLinkFixture::class.java, robot, target) {
init {
replaceDriverWith(ActionLinkDriver(robot))
}
internal class ActionLinkDriver(robot: Robot) : JComponentDriver<ActionLink>(robot) {
override fun click(c: ActionLink) {
clickActionLinkText(c, MouseButton.LEFT_BUTTON, 1)
}
override fun click(c: ActionLink, button: MouseButton) {
clickActionLinkText(c, button, 1)
}
override fun click(c: ActionLink, mouseClickInfo: MouseClickInfo) {
clickActionLinkText(c, mouseClickInfo.button(), mouseClickInfo.times())
}
override fun doubleClick(c: ActionLink) {
clickActionLinkText(c, MouseButton.LEFT_BUTTON, 2)
}
override fun rightClick(c: ActionLink) {
clickActionLinkText(c, MouseButton.RIGHT_BUTTON, 2)
}
override fun click(c: ActionLink, button: MouseButton, times: Int) {
clickActionLinkText(c, button, times)
}
override fun click(c: ActionLink, where: Point) {
click(c, where, MouseButton.LEFT_BUTTON, 1)
}
private fun clickActionLinkText(c: Component, mouseButton: MouseButton, times: Int) {
assert(c is ActionLink)
val textRectangleCenter = (c as ActionLink).textRectangleCenter
click(c, textRectangleCenter, mouseButton, times)
}
private fun click(c: Component, where: Point, mouseButton: MouseButton, times: Int) {
ComponentDriver.checkInEdtEnabledAndShowing(c)
this.robot.click(c, where, mouseButton, times)
}
}
companion object {
fun findByActionId(actionId: String, robot: Robot, container: Container?): ActionLinkFixture {
val actionLink = robot.findComponent(container, ActionLink::class.java) {
if (it.isVisible && it.isShowing)
actionId == ActionManager.getInstance().getId(it.action)
else
false
}
return ActionLinkFixture(robot, actionLink)
}
fun actionLinkFixtureByName(actionName: String, robot: Robot, container: Container): ActionLinkFixture {
val actionLink = robot.findComponent(container, ActionLink::class.java) {
if (it.isVisible && it.isShowing) {
it.text == actionName
}
else false
}
return ActionLinkFixture(robot, actionLink)
}
}
}
| platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/ActionLinkFixture.kt | 2220326244 |
// FILE: 1.kt
package test
class A {
val param = "start"
var result = "fail"
var addParam = "_additional_"
inline fun inlineFun(arg: String, crossinline f: (String) -> Unit) {
{
f(arg + addParam)
}()
}
fun box(): String {
inlineFun("1") { c ->
{
inlineFun("2") { a ->
{
result = param + c + a
}()
}
}()
}
return if (result == "start1_additional_2_additional_") "OK" else "fail: $result"
}
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
fun box(): String {
return A().box()
}
| backend.native/tests/external/codegen/boxInline/anonymousObject/properRecapturingInClass/lambdaChain_3.kt | 2962415904 |
package nl.mpcjanssen.simpletask
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import nl.mpcjanssen.simpletask.remote.FileStore
import org.json.JSONObject
import java.io.File
object QueryStore {
const val TAG = "QueryStore"
fun importFilters(importFile: File) {
FileStore.readFile(importFile) { contents ->
val jsonFilters = JSONObject(contents)
jsonFilters.keys().forEach { name ->
val json = jsonFilters.getJSONObject(name)
val newQuery = Query(json, luaModule = "mainui")
save(newQuery, name)
}
}
}
fun exportFilters(exportFile: File) {
val json = TodoApplication.config.savedQueriesJSONString
FileStore.writeFile(exportFile, json)
}
fun ids() : List<String> {
return TodoApplication.config.savedQueries.map { it.name }
}
fun get(id: String): NamedQuery {
return TodoApplication.config.savedQueries.first { it.name == id }
}
fun save(query: Query, name: String) {
val queries = TodoApplication.config.savedQueries.toMutableList()
queries.add(NamedQuery(name,query))
TodoApplication.config.savedQueries = queries
}
fun delete(id: String) {
val newQueries = TodoApplication.config.savedQueries.filterNot { it.name == id }
TodoApplication.config.savedQueries = newQueries
}
fun rename(squery: NamedQuery, newName: String) {
val queries = TodoApplication.config.savedQueries.toMutableList()
val idx = queries.indexOf(squery)
if (idx != -1 ) {
queries[idx] = NamedQuery(newName, squery.query)
}
TodoApplication.config.savedQueries = queries
}
}
object LegacyQueryStore {
private const val ID_PREFIX: String = "filter_"
const val TAG = "QueryStore"
fun ids() : List<String> {
val prefsPath = "../shared_prefs"
val prefsXml = File(TodoApplication.app.filesDir, "$prefsPath/")
return if (prefsXml.exists() && prefsXml.isDirectory) {
val ids = prefsXml.listFiles { _, name -> name.startsWith(ID_PREFIX) }
?.map { it.relativeTo(prefsXml).name }
?.map { it -> it.substringBeforeLast(".xml") } ?: emptyList()
Log.d(TAG, "Saved applyFilter ids: $ids")
ids
} else {
Log.w(TAG, "No pref_xml folder ${prefsXml.path}")
emptyList()
}
}
fun get(id: String): NamedQuery {
val prefs = prefs(id)
return NamedQuery.initFromPrefs(prefs, "mainui", id)
}
private fun prefs(id: String): SharedPreferences {
return TodoApplication.app.getSharedPreferences(id, Context.MODE_PRIVATE)
}
fun delete(id: String) {
val prefsPath = "../shared_prefs"
val prefsXml = File(TodoApplication.app.filesDir, "$prefsPath/$id.xml")
val deleted = prefsXml.delete()
if (!deleted) {
Log.w(TAG, "Failed to delete saved query: $id")
}
}
}
| app/src/main/java/nl/mpcjanssen/simpletask/QueryStore.kt | 2099869 |
import Main.Companion.set
fun test() {
42[42, ""] = 3
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/fromCompanion/operators/set/Implicit.kt | 297540954 |
package b
import a.*
fun bar() {
test()
}
| plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveFunctionToPackage/before/b/onDemandImport.kt | 346473379 |
// 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.internal.statistics
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import kotlin.test.assertEquals
import kotlin.test.assertTrue
object StatisticsTestEventValidator {
fun assertLogEventIsValid(json: JsonObject, isState: Boolean, vararg dataOptions: String) {
assertTrue(json.get("time").isJsonPrimitive)
assertTrue(json.get("session").isJsonPrimitive)
assertTrue(isValid(json.get("session").asString))
assertTrue(json.get("bucket").isJsonPrimitive)
assertTrue(isValid(json.get("bucket").asString))
assertTrue(json.get("build").isJsonPrimitive)
assertTrue(isValid(json.get("build").asString))
assertTrue(json.get("group").isJsonObject)
assertTrue(json.getAsJsonObject("group").get("id").isJsonPrimitive)
assertTrue(json.getAsJsonObject("group").get("version").isJsonPrimitive)
assertTrue(isValid(json.getAsJsonObject("group").get("id").asString))
assertTrue(isValid(json.getAsJsonObject("group").get("version").asString))
assertTrue(json.get("event").isJsonObject)
assertTrue(json.getAsJsonObject("event").get("id").isJsonPrimitive)
assertEquals(isState, json.getAsJsonObject("event").has("state"))
if (isState) {
assertTrue(json.getAsJsonObject("event").get("state").asBoolean)
}
assertEquals(!isState, json.getAsJsonObject("event").has("count"))
if (!isState) {
assertTrue(json.getAsJsonObject("event").get("count").asJsonPrimitive.isNumber)
}
assertTrue(json.getAsJsonObject("event").get("data").isJsonObject)
assertTrue(isValid(json.getAsJsonObject("event").get("id").asString))
val obj = json.getAsJsonObject("event").get("data").asJsonObject
validateJsonObject(dataOptions, obj)
}
private fun validateJsonObject(dataOptions: Array<out String>, obj: JsonObject) {
for (option in dataOptions) {
assertTrue(isValid(option))
when (val jsonElement = obj.get(option)) {
is JsonPrimitive -> assertTrue(isValid(jsonElement.asString))
is JsonArray -> {
for (dataPart in jsonElement) {
if (dataPart is JsonObject) {
validateJsonObject(dataPart.keySet().toTypedArray(), dataPart)
}
else {
assertTrue(isValid(dataPart.asString))
}
}
}
is JsonObject -> {
validateJsonObject(jsonElement.keySet().toTypedArray(), jsonElement)
}
}
}
}
fun isValid(str : String) : Boolean {
val noTabsOrLineSeparators = str.indexOf("\r") == -1 && str.indexOf("\n") == -1 && str.indexOf("\t") == -1
val noQuotes = str.indexOf("\"") == -1
return noTabsOrLineSeparators && noQuotes && str.matches("[\\p{ASCII}]*".toRegex())
}
} | platform/platform-tests/testSrc/com/intellij/internal/statistics/StatisticsTestEventValidator.kt | 3487090541 |
// 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.wizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.util.NlsContexts
/**
* Describes fork in steps' tree in new project wizard.
* Appends control and logic to switch UI from different vertical wizard steps,
* and applies data from steps which are selected when wizard's finish button is pressed.
* Steps can form tree structure, i.e. direct or indirect child of multistep can be multistep.
*
* @see NewProjectWizardStep
*/
interface NewProjectWizardMultiStepFactory<P : NewProjectWizardStep> {
/**
* Name of step and label that should be used in multistep switcher.
*/
val name: @NlsContexts.Label String
/**
* The ordinal the steps are sorted by
*/
@JvmDefault
val ordinal: Int
get() = Int.MAX_VALUE
/**
* Disabled steps will be excluded from multistep switcher.
*
* @param context is context of wizard where created step will be displayed
* Use [WizardContext.isCreatingNewProject] to filter factory if that cannot create new module.
*/
fun isEnabled(context: WizardContext): Boolean = true
/**
* Creates new project wizard step with parent step.
* Parent is needed to transfer data from parents into children steps.
*/
fun createStep(parent: P): NewProjectWizardStep
} | platform/platform-impl/src/com/intellij/ide/wizard/NewProjectWizardMultiStepFactory.kt | 3378480455 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader
open class GHGQLPagedListLoader<T>(progressManager: ProgressManager,
private val loader: SimpleGHGQLPagesLoader<T>)
: GHListLoaderBase<T>(progressManager) {
override fun canLoadMore() = !loading && (loader.hasNext || error != null)
override fun doLoadMore(indicator: ProgressIndicator, update: Boolean) = loader.loadNext(indicator, update)
override fun reset() {
loader.reset()
super.reset()
}
}
| plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHGQLPagedListLoader.kt | 2750733185 |
package com.virtlink.editorservices.structureoutline
import com.virtlink.editorservices.ScopeNames
import com.virtlink.editorservices.Span
import com.virtlink.editorservices.symbols.ISymbol
import java.io.Serializable
/**
* A node in the structure outline.
*/
interface IStructureOutlineElement : Serializable {
// /**
// * Gets the symbol this node refers to.
// */
// val symbol: ISymbol
val label: String
val nameSpan: Span?
val scopes: ScopeNames
val isLeaf: Boolean?
} | aesi/src/main/kotlin/com/virtlink/editorservices/structureoutline/IStructureOutlineElement.kt | 1139442239 |
/*
The MIT License (MIT)
FTL-Compiler Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.frontend.lexer
import com.thomas.needham.ftl.utils.SourceFile
/**
* Class to represent a location within a source file
* @author Thomas Needham
*/
class Span {
/**
* The SourceFile that this span is contained in
* @see SourceFile
*/
val file: SourceFile
/**
* The Line that this span starts on
*/
val beginLine: Int
/**
* The Column that this span starts on
*/
val beginColumn: Int
/**
* The Line that this span ends on
*/
val endLine: Int
/**
* The Column that this span ends on
*/
val endColumn: Int
/**
* Constructor for Span
* @param sourceFile The SourceFile that this span is contained in
* @param beginLine The Line that this span starts on
* @param beginColumn The Column that this span starts on
* @param endLine The Line that this span ends on Leave blank if unknown
* @param endColumn The Column that this span ends on Leave blank if unknown
* @see SourceFile
*/
constructor(sourceFile: SourceFile, beginLine: Int, beginColumn: Int, endLine: Int = -1, endColumn: Int = -1) {
this.file = sourceFile
this.beginLine = beginLine
this.beginColumn = beginColumn
this.endLine = endLine
this.endColumn = endColumn
}
/**
* Function to get the beginning location of this span
* @return A string which represents the beginning of this span
*/
fun getBeginPosition(): String {
return "Line: ${beginLine}, Column: ${beginColumn}"
}
/**
* Function to get the ending location of this span
* @return A string which represents the end of this span
*/
fun getEndPosition(): String {
return "Line: ${endLine}, Column: ${endColumn}"
}
/**
* Function to get a string which represents this span
* @return A string that represents this span
*/
override fun toString(): String {
return "${file.file.name}: ${getBeginPosition()} To ${getEndPosition()}"
}
}
| src/main/kotlin/com/thomas/needham/ftl/frontend/lexer/Span.kt | 294766917 |
/*
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.packagesearch.http
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.castSafelyTo
import com.intellij.util.io.HttpRequests
import kotlinx.coroutines.suspendCancellableCoroutine
import org.jetbrains.idea.reposearch.DependencySearchBundle
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class HttpWrapper {
private val logger = Logger.getInstance(HttpWrapper::class.java)
private val cache = ConcurrentHashMap<String, String>()
internal suspend fun requestString(
url: String,
acceptContentType: String,
timeoutInSeconds: Int = 10,
headers: List<Pair<String, String>>,
useCache: Boolean = false,
verbose: Boolean = true
): String = suspendCancellableCoroutine { cont ->
try {
val cacheKey = getCacheKey(url, acceptContentType, timeoutInSeconds, headers)
if (useCache) {
cache[cacheKey]?.let { cont.resume(it) }
}
val builder = HttpRequests.request(url)
.productNameAsUserAgent()
.accept(acceptContentType)
.connectTimeout(timeoutInSeconds * 1000)
.readTimeout(timeoutInSeconds * 1000)
.tuner { connection ->
headers.forEach {
connection.setRequestProperty(it.first, it.second)
}
}
builder.connect { request ->
val statusCode = request.connection.castSafelyTo<HttpURLConnection>()?.responseCode ?: -1
val responseText = request.connection.getInputStream().use { it.readBytes { cont.isCancelled }.toString(Charsets.UTF_8) }
if (cont.isCancelled) return@connect
if (statusCode != HttpURLConnection.HTTP_OK && verbose) {
logger.trace(
"""
|
|<-- HTTP GET $url
| Accept: $acceptContentType
|${headers.joinToString("\n") { " ${it.first}: ${it.second}" }}
|
|--> RESPONSE HTTP $statusCode
|$responseText
|
""".trimMargin()
)
}
when {
responseText.isEmpty() -> cont.resumeWithException(EmptyBodyException())
else -> cont.resume(responseText).also { if (useCache) cache[cacheKey] = responseText }
}
}
}
catch (t: Throwable) {
cont.resumeWithException(t)
}
}
private fun getCacheKey(
url: String,
acceptContentType: String,
timeoutInSeconds: Int,
headers: List<Pair<String, String>>
) = (listOf(url, acceptContentType, timeoutInSeconds) + headers.map { it.toString() }).joinToString(":")
private fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE, cancellationRequested: () -> Boolean): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
while (bytes >= 0 && !cancellationRequested()) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = read(buffer)
}
return bytesCopied
}
private fun InputStream.readBytes(cancellationRequested: () -> Boolean): ByteArray {
val buffer = ByteArrayOutputStream(maxOf(DEFAULT_BUFFER_SIZE, this.available()))
copyTo(buffer, cancellationRequested = cancellationRequested)
return buffer.toByteArray()
}
}
internal class EmptyBodyException : RuntimeException(
DependencySearchBundle.message("reposearch.search.client.response.body.is.empty")
) | plugins/repository-search/src/main/kotlin/org/jetbrains/idea/packagesearch/http/HttpWrapper.kt | 2755456879 |
package foo
class MemberEnd {
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/callableReferences/nestedToTopLevel/after/foo/MemberEnd.kt | 2575910250 |
// WITH_RUNTIME
val x = hashSetOf("abc").<caret>let {
it.forEach {
println(it)
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/letToRun/nestedLambda.kt | 4291819034 |
open class A<T, C, D<T>>
class B : A<Int, Long, List<Int>>(<caret>)
// SET_TRUE: ALIGN_MULTILINE_METHOD_BRACKETS
// IGNORE_FORMATTER
// KT-39459 | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyArgumentInCallByReferenceInSuperTypeWithTypeArguments2.kt | 1811334680 |
// 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.debugger.coroutine.data
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ReadAction
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.sun.jdi.Location
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinVariableNameFinder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeCoroutineStackFrameProxy
import org.jetbrains.kotlin.idea.debugger.safeLocation
import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame
/**
* Coroutine exit frame represented by a stack frames
* invokeSuspend():-1
* resumeWith()
*
*/
class CoroutinePreflightFrame(
val coroutineInfoData: CoroutineInfoData,
val frame: StackFrameProxyImpl,
val threadPreCoroutineFrames: List<StackFrameProxyImpl>,
val mode: SuspendExitMode,
firstFrameVariables: List<JavaValue> = coroutineInfoData.topFrameVariables()
) : CoroutineStackFrame(frame, null, firstFrameVariables) {
override fun isInLibraryContent() = false
override fun isSynthetic() = false
}
class CreationCoroutineStackFrame(
frame: StackFrameProxyImpl,
sourcePosition: XSourcePosition?,
val first: Boolean,
location: Location? = frame.safeLocation()
) : CoroutineStackFrame(frame, sourcePosition, emptyList(), false, location), XDebuggerFramesList.ItemWithSeparatorAbove {
override fun getCaptionAboveOf() =
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace")
override fun hasSeparatorAbove() =
first
}
open class CoroutineStackFrame(
frame: StackFrameProxyImpl,
private val position: XSourcePosition?,
private val spilledVariables: List<JavaValue> = emptyList(),
private val includeFrameVariables: Boolean = true,
location: Location? = frame.safeLocation(),
) : KotlinStackFrame(safeCoroutineStackFrameProxy(location, spilledVariables, frame)) {
init {
descriptor.updateRepresentation(null, DescriptorLabelListener.DUMMY_LISTENER)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val frame = other as? JavaStackFrame ?: return false
return descriptor.frameProxy == frame.descriptor.frameProxy
}
override fun hashCode(): Int {
return descriptor.frameProxy.hashCode()
}
override fun buildVariablesThreadAction(debuggerContext: DebuggerContextImpl, children: XValueChildrenList, node: XCompositeNode) {
if (includeFrameVariables || spilledVariables.isEmpty()) {
super.buildVariablesThreadAction(debuggerContext, children, node)
val debugProcess = debuggerContext.debugProcess ?: return
addOptimisedVariables(debugProcess, children)
} else {
// ignore original frame variables
for (variable in spilledVariables) {
children.add(variable)
}
}
}
private fun addOptimisedVariables(debugProcess: DebugProcessImpl, children: XValueChildrenList) {
val visibleVariableNames by lazy { children.getUniqueNames() }
for (variable in spilledVariables) {
val name = variable.name
if (name !in visibleVariableNames) {
children.add(variable)
visibleVariableNames.add(name)
}
}
val declaredVariableNames = findVisibleVariableNames(debugProcess)
for (name in declaredVariableNames) {
if (name !in visibleVariableNames) {
children.add(createOptimisedVariableMessageNode(name))
}
}
}
private fun createOptimisedVariableMessageNode(name: String) =
createMessageNode(
KotlinDebuggerCoroutinesBundle.message("optimised.variable.message", "\'$name\'"),
AllIcons.General.Information
)
private fun XValueChildrenList.getUniqueNames(): MutableSet<String> {
val names = mutableSetOf<String>()
for (i in 0 until size()) {
names.add(getName(i))
}
return names
}
private fun findVisibleVariableNames(debugProcess: DebugProcessImpl): List<String> {
val location = stackFrameProxy.safeLocation() ?: return emptyList()
return ReadAction.nonBlocking<List<String>> {
KotlinVariableNameFinder(debugProcess)
.findVisibleVariableNames(location)
}.executeSynchronously()
}
override fun getSourcePosition() =
position ?: super.getSourcePosition()
}
| plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrames.kt | 3218079558 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.merge
import com.intellij.diff.DiffEditorTitleCustomizer
import com.intellij.dvcs.repo.Repository
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk.br
import com.intellij.openapi.util.text.HtmlChunk.text
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser
import com.intellij.openapi.vcs.changes.ui.ChangeListViewerDialog
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBLabel
import com.intellij.util.Consumer
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.impl.VcsCommitMetadataImpl
import com.intellij.vcs.log.ui.details.MultipleCommitInfoDialog
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.GitBranch
import git4idea.GitRevisionNumber
import git4idea.GitUtil.*
import git4idea.GitVcs
import git4idea.changes.GitChangeUtils
import git4idea.history.GitCommitRequirements
import git4idea.history.GitHistoryUtils
import git4idea.history.GitLogUtil
import git4idea.history.GitLogUtil.readFullDetails
import git4idea.history.GitLogUtil.readFullDetailsForHashes
import git4idea.i18n.GitBundle
import git4idea.i18n.GitBundleExtensions.html
import git4idea.rebase.GitRebaseUtils
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import org.jetbrains.annotations.Nls
import javax.swing.JPanel
internal open class GitDefaultMergeDialogCustomizer(
private val project: Project
) : MergeDialogCustomizer() {
override fun getMultipleFileMergeDescription(files: MutableCollection<VirtualFile>): String {
val repos = getRepositoriesForFiles(project, files)
.ifEmpty { getRepositories(project).filter { it.stagingAreaHolder.allConflicts.isNotEmpty() } }
val mergeBranches = repos.mapNotNull { resolveMergeBranch(it)?.presentable }.toSet()
if (mergeBranches.isNotEmpty()) {
val currentBranches = getCurrentBranchNameSet(repos)
return html(
"merge.dialog.description.merge.label.text",
mergeBranches.size, text(getFirstBranch(mergeBranches)).bold(),
currentBranches.size, text(getFirstBranch(currentBranches)).bold()
)
}
val rebaseOntoBranches = repos.mapNotNull { resolveRebaseOntoBranch(it) }
if (rebaseOntoBranches.isNotEmpty()) {
val singleCurrentBranch = getSingleCurrentBranchName(repos)
val singleOntoBranch = rebaseOntoBranches.toSet().singleOrNull()
return getDescriptionForRebase(singleCurrentBranch, singleOntoBranch?.branchName, singleOntoBranch?.hash)
}
val cherryPickCommitDetails = repos.mapNotNull { loadCherryPickCommitDetails(it) }
if (cherryPickCommitDetails.isNotEmpty()) {
val singleCherryPick = cherryPickCommitDetails.distinctBy { it.authorName + it.commitMessage }.singleOrNull()
return html(
"merge.dialog.description.cherry.pick.label.text",
cherryPickCommitDetails.size, text(cherryPickCommitDetails.single().shortHash).code(),
(singleCherryPick != null).toInt(),
text(singleCherryPick?.authorName ?: ""),
HtmlBuilder().append(br()).append(text(singleCherryPick?.commitMessage ?: "").code())
)
}
return super.getMultipleFileMergeDescription(files)
}
override fun getTitleCustomizerList(file: FilePath): DiffEditorTitleCustomizerList {
val repository = GitRepositoryManager.getInstance(project).getRepositoryForFileQuick(file) ?: return DEFAULT_CUSTOMIZER_LIST
return when (repository.state) {
Repository.State.MERGING -> getMergeTitleCustomizerList(repository, file)
Repository.State.REBASING -> getRebaseTitleCustomizerList(repository, file)
Repository.State.GRAFTING -> getCherryPickTitleCustomizerList(repository, file)
else -> DEFAULT_CUSTOMIZER_LIST
}
}
private fun getCherryPickTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val cherryPickHead = tryResolveRef(repository, CHERRY_PICK_HEAD) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
CHERRY_PICK_HEAD,
HEAD
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
GitBundle.message("merge.dialog.diff.left.title.cherry.pick.label.text"),
repository,
file,
Pair(mergeBase, HEAD)
)
val rightTitleCustomizer = getTitleWithCommitDetailsCustomizer(
html("merge.dialog.diff.right.title.cherry.pick.label.text", cherryPickHead.toShortString()),
repository,
file,
cherryPickHead.asString()
)
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
@NlsSafe
private fun getFirstBranch(branches: Collection<String>): String = branches.first()
private fun getMergeTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val currentBranchHash = getHead(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val currentBranchPresentable = repository.currentBranchName ?: currentBranchHash.toShortString()
val mergeBranch = resolveMergeBranch(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBranchHash = mergeBranch.hash
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
currentBranchHash.asString(),
mergeBranchHash.asString()
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
html("merge.dialog.diff.title.changes.from.branch.label.text", text(currentBranchPresentable).bold()),
repository,
file,
Pair(mergeBase, currentBranchHash.asString())
)
val rightTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
html("merge.dialog.diff.title.changes.from.branch.label.text", text(mergeBranch.presentable).bold()),
repository,
file,
Pair(mergeBase, mergeBranchHash.asString())
)
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
private fun getRebaseTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val currentBranchHash = getHead(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val rebasingBranchPresentable = repository.currentBranchName ?: currentBranchHash.toShortString()
val upstreamBranch = resolveRebaseOntoBranch(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val upstreamBranchHash = upstreamBranch.hash
val rebaseHead = tryResolveRef(repository, REBASE_HEAD) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
REBASE_HEAD,
upstreamBranchHash.asString()
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitle = html(
"merge.dialog.diff.left.title.rebase.label.text",
rebaseHead.toShortString(),
text(rebasingBranchPresentable).bold()
)
val leftTitleCustomizer = getTitleWithCommitDetailsCustomizer(leftTitle, repository, file, rebaseHead.asString())
val rightTitle =
if (upstreamBranch.branchName != null) {
html("merge.dialog.diff.right.title.rebase.with.branch.label.text", text(upstreamBranch.branchName).bold())
}
else {
html("merge.dialog.diff.right.title.rebase.without.branch.label.text")
}
val rightTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(rightTitle, repository, file, Pair(mergeBase, HEAD))
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
private fun loadCherryPickCommitDetails(repository: GitRepository): CherryPickDetails? {
val cherryPickHead = tryResolveRef(repository, CHERRY_PICK_HEAD) ?: return null
val shortDetails = GitLogUtil.collectMetadata(project, GitVcs.getInstance(project), repository.root,
listOf(cherryPickHead.asString()))
val result = shortDetails.singleOrNull() ?: return null
return CherryPickDetails(cherryPickHead.toShortString(), result.author.name, result.subject)
}
private data class CherryPickDetails(@NlsSafe val shortHash: String, @NlsSafe val authorName: String, @NlsSafe val commitMessage: String)
}
internal fun getDescriptionForRebase(@NlsSafe rebasingBranch: String?, @NlsSafe baseBranch: String?, baseHash: Hash?): String =
when {
baseBranch != null -> html(
"merge.dialog.description.rebase.with.onto.branch.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold(),
text(baseBranch).bold(),
(baseHash != null).toInt(), baseHash?.toShortString() ?: ""
)
baseHash != null -> html(
"merge.dialog.description.rebase.with.hash.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold(),
text(baseHash.toShortString()).bold()
)
else -> html(
"merge.dialog.description.rebase.without.onto.info.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold()
)
}
internal fun getDefaultLeftPanelTitleForBranch(@NlsSafe branchName: String): String =
html("merge.dialog.diff.left.title.default.branch.label.text", text(branchName).bold())
internal fun getDefaultRightPanelTitleForBranch(@NlsSafe branchName: String?, baseHash: Hash?): String =
when {
branchName != null -> html(
"merge.dialog.diff.right.title.default.with.onto.branch.label.text",
text(branchName).bold(),
(baseHash != null).toInt(), baseHash?.toShortString() ?: ""
)
baseHash != null -> html(
"merge.dialog.diff.right.title.default.with.hash.label.text",
text(baseHash.toShortString()).bold()
)
else -> GitBundle.message("merge.dialog.diff.right.title.default.without.onto.info.label.text")
}
@NlsSafe
private fun resolveMergeBranchOrCherryPick(repository: GitRepository): String? {
val mergeBranch = resolveMergeBranch(repository)
if (mergeBranch != null) return mergeBranch.presentable
val rebaseOntoBranch = resolveRebaseOntoBranch(repository)
if (rebaseOntoBranch != null) return rebaseOntoBranch.presentable
val cherryHead = tryResolveRef(repository, CHERRY_PICK_HEAD)
if (cherryHead != null) return "cherry-pick"
return null
}
private fun resolveMergeBranch(repository: GitRepository): RefInfo? {
val mergeHead = tryResolveRef(repository, MERGE_HEAD) ?: return null
return resolveBranchName(repository, mergeHead)
}
private fun resolveRebaseOntoBranch(repository: GitRepository): RefInfo? {
val ontoHash = GitRebaseUtils.getOntoHash(repository.project, repository.root) ?: return null
val repo = GitRepositoryManager.getInstance(repository.project).getRepositoryForRoot(repository.root) ?: return null
return resolveBranchName(repo, ontoHash)
}
private fun resolveBranchName(repository: GitRepository, hash: Hash): RefInfo {
var branches: Collection<GitBranch> = repository.branches.findLocalBranchesByHash(hash)
if (branches.isEmpty()) branches = repository.branches.findRemoteBranchesByHash(hash)
return RefInfo(hash, branches.singleOrNull()?.name)
}
private fun tryResolveRef(repository: GitRepository, @NlsSafe ref: String): Hash? {
try {
val revision = GitRevisionNumber.resolve(repository.project, repository.root, ref)
return HashImpl.build(revision.asString())
}
catch (e: VcsException) {
return null
}
}
@NlsSafe
internal fun getSingleMergeBranchName(roots: Collection<GitRepository>): String? = getMergeBranchNameSet(roots).singleOrNull()
private fun getMergeBranchNameSet(roots: Collection<GitRepository>): Set<@NlsSafe String> = roots.mapNotNull { repo ->
resolveMergeBranchOrCherryPick(repo)
}.toSet()
@NlsSafe
internal fun getSingleCurrentBranchName(roots: Collection<GitRepository>): String? = getCurrentBranchNameSet(roots).singleOrNull()
private fun getCurrentBranchNameSet(roots: Collection<GitRepository>): Set<@NlsSafe String> = roots.asSequence().mapNotNull { repo ->
repo.currentBranchName ?: repo.currentRevision?.let { VcsLogUtil.getShortHash(it) }
}.toSet()
internal fun getTitleWithCommitDetailsCustomizer(
@Nls title: String,
repository: GitRepository,
file: FilePath,
@NlsSafe commit: String
) = DiffEditorTitleCustomizer {
getTitleWithShowDetailsAction(title) {
val dlg = ChangeListViewerDialog(repository.project)
dlg.loadChangesInBackground {
val changeList = GitChangeUtils.getRevisionChanges(
repository.project,
repository.root,
commit,
true,
false,
false
)
ChangeListViewerDialog.ChangelistData(changeList, file)
}
dlg.title = StringUtil.stripHtml(title, false)
dlg.isModal = true
dlg.show()
}
}
internal fun getTitleWithCommitsRangeDetailsCustomizer(
@NlsContexts.Label title: String,
repository: GitRepository,
file: FilePath,
range: Pair<@NlsSafe String, @NlsSafe String>
) = DiffEditorTitleCustomizer {
getTitleWithShowDetailsAction(title) {
val details = mutableListOf<VcsCommitMetadata>()
val filteredCommits = HashSet<VcsCommitMetadata>()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
readFullDetails(
repository.project,
repository.root,
Consumer { commit ->
val commitMetadata = VcsCommitMetadataImpl(
commit.id, commit.parents, commit.commitTime, commit.root, commit.subject,
commit.author, commit.fullMessage, commit.committer, commit.authorTime)
if (commit.affectedPaths.contains(file)) {
filteredCommits.add(commitMetadata)
}
details.add(commitMetadata)
},
"${range.first}..${range.second}")
},
GitBundle.message("merge.dialog.customizer.collecting.details.progress"),
true,
repository.project)
val dlg = MergeConflictMultipleCommitInfoDialog(repository.project, repository.root, details, filteredCommits)
dlg.title = StringUtil.stripHtml(title, false)
dlg.show()
}
}
internal fun getTitleWithShowDetailsAction(@Nls title: String, action: () -> Unit): JPanel =
BorderLayoutPanel()
.addToCenter(JBLabel(title).setCopyable(true))
.addToRight(ActionLink(GitBundle.message("merge.dialog.customizer.show.details.link.label")) { action() })
private fun Boolean.toInt() = if (this) 1 else 0
private class MergeConflictMultipleCommitInfoDialog(
private val project: Project,
private val root: VirtualFile,
commits: List<VcsCommitMetadata>,
private val filteredCommits: Set<VcsCommitMetadata>
) : MultipleCommitInfoDialog(project, commits) {
init {
filterCommitsByConflictingFile()
}
@Throws(VcsException::class)
override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> {
val changes = mutableListOf<Change>()
readFullDetailsForHashes(project, root, commits.map { commit -> commit.id.asString() }, GitCommitRequirements.DEFAULT) { gitCommit ->
changes.addAll(gitCommit.changes)
}
return CommittedChangesTreeBrowser.zipChanges(changes)
}
private fun filterCommitsByConflictingFile() {
setFilter { commit -> filteredCommits.contains(commit) }
}
override fun createSouthAdditionalPanel(): JPanel {
val checkbox = JBCheckBox(GitBundle.message("merge.dialog.customizer.filter.by.conflicted.file.checkbox"), true)
checkbox.addItemListener {
if (checkbox.isSelected) {
filterCommitsByConflictingFile()
}
else {
resetFilter()
}
}
return BorderLayoutPanel().addToCenter(checkbox)
}
}
private data class RefInfo(val hash: Hash, @NlsSafe val branchName: String?) {
@NlsSafe
val presentable: String = branchName ?: hash.toShortString()
} | plugins/git4idea/src/git4idea/merge/GitDefaultMergeDialogCustomizer.kt | 3510139266 |
fun test() {
val a = 44;<caret> val b = 42;
}
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER | plugins/kotlin/idea/tests/testData/indentationOnNewline/Semicolon2.kt | 4133915053 |
package io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2
import io.github.feelfreelinux.wykopmobilny.api.filters.OWMContentFilter
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkResponse
import io.github.feelfreelinux.wykopmobilny.utils.api.stripImageCompression
import io.github.feelfreelinux.wykopmobilny.utils.textview.removeHtml
import io.github.feelfreelinux.wykopmobilny.utils.toPrettyDate
class LinkMapper {
companion object {
fun map(value: LinkResponse, owmContentFilter: OWMContentFilter) =
owmContentFilter.filterLink(
Link(
value.id,
value.title?.removeHtml() ?: "",
value.description?.removeHtml() ?: "",
value.tags,
value.sourceUrl,
value.voteCount,
value.buryCount,
mutableListOf(),
value.commentsCount,
value.relatedCount,
if (value.author != null) AuthorMapper.map(value.author) else null,
value.date,
value.preview?.stripImageCompression(),
value.plus18,
value.canVote,
value.isHot,
value.status,
value.userVote,
value.userFavorite ?: false,
value.app,
false,
false
)
)
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/mapper/apiv2/LinkMapper.kt | 2135544664 |
package frameInlineFunCallInsideInlineFun
class A {
inline fun inlineFun(s: (Int) -> Unit) {
val element = 1.0
s(1)
}
val prop = 1
}
class B {
inline fun foo(s: (Int) -> Unit) {
val element = 2
val a = A()
// STEP_INTO: 1
// STEP_OVER: 1
//Breakpoint!
a.inlineFun {
val e = element
}
s(1)
}
}
class C {
fun bar() {
val element = 1f
B().foo {
val e = element
}
}
}
fun main(args: Array<String>) {
C().bar()
}
// PRINT_FRAME
// EXPRESSION: element
// RESULT: 1.0: D
// EXPRESSION: this.prop
// RESULT: 1: I
| plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameInlineFunCallInsideInlineFun.kt | 1197031493 |
package torille.fi.lurkforreddit.subreddit
import dagger.Module
import dagger.Provides
import torille.fi.lurkforreddit.data.models.view.Subreddit
import torille.fi.lurkforreddit.di.scope.ActivityScoped
@Module
abstract class SubredditModule {
@Module
companion object {
@JvmStatic
@Provides
@ActivityScoped
fun provideSubreddit(subredditActivity: SubredditActivity): Subreddit {
return subredditActivity.intent.getParcelableExtra(SubredditFragment.ARGUMENT_SUBREDDIT)
}
}
} | app/src/main/java/torille/fi/lurkforreddit/subreddit/SubredditModule.kt | 2515002845 |
// DISABLE-ERRORS
class A(i: Int, j: Int) {
constructor(i: Int) : this(i, 2) {
a = 1
}
val a<caret>: Int
} | plugins/kotlin/idea/tests/testData/intentions/joinDeclarationAndAssignment/deleteConstructorBlock2.kt | 952971391 |
package test
interface С
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/sealedClassesAddImplements/С.kt | 3207954273 |
package bolone
import alraune.*
import aplight.GelNew
import bolone.rp.OrderFields
import pieces100.*
import vgrechka.*
import java.sql.Timestamp
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KMutableProperty1
val boConfig get() = alConfig.bolone!!
class BoloneConfig(
val frontTSOutDir: String,
val distDir: String)
abstract class Field {
var error by place<String?>()
}
class TextField : Field() {
var value by place<String>()
companion object {
fun make(value: String, error: String?) = TextField().also {
it.value = value
it.error = error
}
fun noError(value: String) = make(value, null)
}
fun intValue() = value.toInt()
}
class DateTimeValidationRange(minHoursFromNow: Int = 4, calendarMinOffsetHours: Int = 1) {
val min = TimePile.hoursFromRealNow_ms(minHoursFromNow.toLong())
val minToShowInCalendar = TimePile.plusHours_ms(min, calendarMinOffsetHours.toLong())
val max = System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000
fun toFrontCalendarRange() = BoFrontFuns.JSLongRange(
min = JSLong(minToShowInCalendar),
max = JSLong(max))
}
class BiddingParamsDateValidationRanges {
val workDeadlineShownToWritersDuringBidding = DateTimeValidationRange()
val closeBiddingReminderTime = DateTimeValidationRange()
}
fun orderDeadlineRange() = DateTimeValidationRange()
fun bucketNameForSite(site: AlSite): String {
return bucketNameForSite(BoSite.from(site))
}
fun bucketNameForSite(site: BoSite): String {
return site.name
}
enum class BoSite {
Customer, Writer, Admin;
companion object {
fun from(x: AlSite) = when (x) {
AlSite.BoloneCustomer -> Customer
AlSite.BoloneWriter -> Writer
AlSite.BoloneAdmin -> Admin
else -> wtf(x.name)
}
}
}
fun nextOrderFileID() = dbNextSequenceValue(AlConst.orderFileIdSequence)
@GelNew class ReminderJobParams {
var time by place<Timestamp>()
var jobUUID by place<String>()
var taskUUID by place<String>()
fun deleteJobAndTaskIfExists() {
AlGlobal.jobManager.removeIfExists(jobUUID)
dbDeleteTaskByUuid(taskUUID)
}
fun createJob() {
// TODO:vgrechka .....
// AlGlobal.jobManager.add(jobUuid = order.data.bidding!!.closeBiddingReminderJobUUID, job = CloseBiddingReminderJob(order))
}
}
| alraune/alraune/src/main/java/bolone/bolone-package-1.kt | 1685835923 |
package com.github.kerubistan.kerub.data.ispn
import com.github.kerubistan.kerub.data.EventListener
import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import org.infinispan.Cache
import java.util.UUID
class VirtualStorageDeviceDynamicDaoImpl(cache: Cache<UUID, VirtualStorageDeviceDynamic>, eventListener: EventListener)
: IspnDaoBase<VirtualStorageDeviceDynamic, UUID>(cache, eventListener), VirtualStorageDeviceDynamicDao | src/main/kotlin/com/github/kerubistan/kerub/data/ispn/VirtualStorageDeviceDynamicDaoImpl.kt | 3898963932 |
package org.jetbrains.haskell.debugger
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.openapi.fileTypes.FileType
import org.jetbrains.haskell.fileType.HaskellFileType
import org.jetbrains.haskell.fileType.HaskellFile
import org.jetbrains.haskell.HaskellViewProvider
import com.intellij.psi.impl.PsiManagerImpl
import com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.haskell.fileType.HaskellFileViewProviderFactory
import com.intellij.psi.PsiFileFactory
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.psi.impl.source.PsiExpressionCodeFragmentImpl
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.EvaluationMode
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory
import com.intellij.psi.PsiDocumentManager
class HaskellDebuggerEditorsProvider : XDebuggerEditorsProvider() {
override fun createDocument(project: Project,
text: String,
sourcePosition: XSourcePosition?,
mode: EvaluationMode): Document {
if(sourcePosition != null) {
val hsPsiFile = PsiFileFactory.getInstance(project)!!.createFileFromText(sourcePosition.file.name,
HaskellFileType.INSTANCE,
text)
val hsDocument = PsiDocumentManager.getInstance(project)!!.getDocument(hsPsiFile)
if(hsDocument != null) {
return hsDocument
}
}
return EditorFactory.getInstance()!!.createDocument(text)
}
override fun getFileType(): FileType = HaskellFileType.INSTANCE
} | plugin/src/org/jetbrains/haskell/debugger/HaskellDebuggerEditorsProvider.kt | 1660121764 |
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon.*
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.geometry.Side
import javafx.scene.paint.Color
import tornadofx.*
class ListMenuTestApp : App(ListMenuTest::class)
class ListMenuTest : View("ListMenu Test") {
val listmenu = listmenu(theme = "blue") {
addMenuItems()
activeItem = items.first()
maxHeight = Double.MAX_VALUE
}
override val root = borderpane {
setPrefSize(650.0, 500.0)
top {
vbox(10) {
label(title).style { fontSize = 3.em }
hbox(10) {
alignment = Pos.CENTER
label("Orientation")
combobox(listmenu.orientationProperty, Orientation.values().toList())
label("Icon Position")
combobox(listmenu.iconPositionProperty, values = Side.values().toList())
label("Theme")
combobox(listmenu.themeProperty, values = listOf("none", "blue"))
checkbox("Icons Only") {
selectedProperty().onChange {
with(listmenu) {
items.clear()
if (it) {
iconOnlyMenuItems()
} else {
addMenuItems()
}
}
}
}
}
label(stringBinding(listmenu.activeItemProperty) { "Currently selected: ${value?.text}" }) {
style { textFill = Color.RED }
}
style {
alignment = Pos.CENTER
}
}
}
center = listmenu
style {
backgroundColor += Color.WHITE
}
paddingAll = 20
}
private fun ListMenu.iconOnlyMenuItems() {
item(graphic = icon(USER))
item(graphic = icon(SUITCASE))
item(graphic = icon(COG))
}
private fun ListMenu.addMenuItems() {
item("Contacts", icon(USER))
item("Projects", icon(SUITCASE))
item("Settings", icon(COG))
}
private fun icon(icon: FontAwesomeIcon) = FontAwesomeIconView(icon).apply { glyphSize = 20 }
} | src/test/kotlin/tornadofx/testapps/ListMenuTest.kt | 1008147239 |
/*
* 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
package androidx.compose.ui.unit
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.util.packInts
import androidx.compose.ui.util.unpackInt1
import androidx.compose.ui.util.unpackInt2
/**
* Constructs an [IntSize] from width and height [Int] values.
*/
@Stable
fun IntSize(width: Int, height: Int): IntSize = IntSize(packInts(width, height))
/**
* A two-dimensional size class used for measuring in [Int] pixels.
*/
@Immutable
@kotlin.jvm.JvmInline
value class IntSize internal constructor(@PublishedApi internal val packedValue: Long) {
/**
* The horizontal aspect of the size in [Int] pixels.
*/
@Stable
val width: Int
get() = unpackInt1(packedValue)
/**
* The vertical aspect of the size in [Int] pixels.
*/
@Stable
val height: Int
get() = unpackInt2(packedValue)
@Stable
inline operator fun component1(): Int = width
@Stable
inline operator fun component2(): Int = height
/**
* Returns an IntSize scaled by multiplying [width] and [height] by [other]
*/
@Stable
operator fun times(other: Int): IntSize =
IntSize(width = width * other, height = height * other)
/**
* Returns an IntSize scaled by dividing [width] and [height] by [other]
*/
@Stable
operator fun div(other: Int): IntSize =
IntSize(width = width / other, height = height / other)
@Stable
override fun toString(): String = "$width x $height"
companion object {
/**
* IntSize with a zero (0) width and height.
*/
val Zero = IntSize(0L)
}
}
/**
* Returns an [IntSize] with [size]'s [IntSize.width] and [IntSize.height]
* multiplied by [this].
*/
@Stable
operator fun Int.times(size: IntSize) = size * this
/**
* Convert a [IntSize] to a [IntRect].
*/
@Stable
fun IntSize.toIntRect(): IntRect {
return IntRect(IntOffset.Zero, this)
}
/**
* Returns the [IntOffset] of the center of the rect from the point of [0, 0]
* with this [IntSize].
*/
@Stable
val IntSize.center: IntOffset
get() = IntOffset(width / 2, height / 2)
// temporary while PxSize is transitioned to Size
@Stable
fun IntSize.toSize() = Size(width.toFloat(), height.toFloat()) | compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/IntSize.kt | 2553945870 |
package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.searcheverywhere.ClassSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.psi.PsiNamedElement
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
@IntellijInternalApi
class SearchEverywhereClassFeaturesProvider : SearchEverywhereElementFeaturesProvider(ClassSearchEverywhereContributor::class.java) {
companion object {
val IS_DEPRECATED = EventFields.Boolean("isDeprecated")
}
override fun getFeaturesDeclarations(): List<EventField<*>> {
return arrayListOf<EventField<*>>(IS_DEPRECATED)
}
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val item = SearchEverywherePsiElementFeaturesProvider.getPsiElement(element) ?: return emptyList()
val data = arrayListOf<EventPair<*>>()
ReadAction.run<Nothing> {
(item as? PsiNamedElement)?.name?.let { elementName ->
data.addAll(getNameMatchingFeatures(elementName, searchQuery))
}
}
val presentation = (element as? PSIPresentationBgRendererWrapper.PsiItemWithPresentation)?.presentation
data.putIfValueNotNull(IS_DEPRECATED, isDeprecated(presentation))
return data
}
private fun isDeprecated(presentation: TargetPresentation?): Boolean? {
if (presentation == null) {
return null
}
val effectType = presentation.presentableTextAttributes?.effectType ?: return false
return effectType == EffectType.STRIKEOUT
}
}
| plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereClassFeaturesProvider.kt | 1912523627 |
// 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.refactoring.detector
import com.intellij.DynamicBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.PropertyKey
import java.util.function.Supplier
class RefactoringDetectorBundle : DynamicBundle(BUNDLE) {
companion object {
const val BUNDLE = "messages.RefactoringDetectorBundle"
private val INSTANCE = RefactoringDetectorBundle()
@JvmStatic
fun message(key: @PropertyKey(resourceBundle = BUNDLE) String, vararg params: Any): @Nls String {
return INSTANCE.getMessage(key, *params)
}
@JvmStatic
fun messagePointer(key: @PropertyKey(resourceBundle = BUNDLE) String, vararg params: Any): Supplier<@Nls String> {
return INSTANCE.getLazyMessage(key, *params)
}
}
}
| plugins/refactoring-detector/src/com/intellij/refactoring/detector/RefactoringDetectorBundle.kt | 2917182917 |
package training.featuresSuggester.listeners
import com.intellij.openapi.project.Project
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XDebugSessionListener
import com.intellij.xdebugger.XDebuggerManagerListener
import training.featuresSuggester.SuggestingUtils.handleAction
import training.featuresSuggester.actions.Action
import training.featuresSuggester.actions.DebugProcessStartedAction
import training.featuresSuggester.actions.DebugProcessStoppedAction
class DebuggerListener(val project: Project) : XDebuggerManagerListener {
private var curSessionListener: XDebugSessionListener? = null
override fun processStarted(debugProcess: XDebugProcess) {
handleDebugAction(::DebugProcessStartedAction)
}
override fun processStopped(debugProcess: XDebugProcess) {
handleDebugAction(::DebugProcessStoppedAction)
}
private fun <T : Action> handleDebugAction(actionConstructor: (Project, Long) -> T) {
handleAction(
project,
actionConstructor(project, System.currentTimeMillis())
)
}
override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) {
if (previousSession != null && curSessionListener != null) {
previousSession.removeSessionListener(curSessionListener!!)
curSessionListener = null
}
if (currentSession != null) {
curSessionListener = DebugSessionListener(currentSession)
currentSession.addSessionListener(curSessionListener!!)
}
}
}
| plugins/ide-features-trainer/src/training/featuresSuggester/listeners/DebuggerListener.kt | 3962933555 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.configurationStore.ComponentSerializationUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.impl.libraries.UnknownLibraryKind
import com.intellij.openapi.roots.libraries.LibraryKindRegistry
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl.Companion.toLibraryRootType
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.FileContainerDescription
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.JarDirectoryDescription
import com.intellij.workspaceModel.ide.toExternalSource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryPropertiesEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot
import java.io.StringReader
class LibraryStateSnapshot(
val libraryEntity: LibraryEntity,
val storage: EntityStorage,
val libraryTable: LibraryTable,
val parentDisposable: Disposable) {
private val roots = collectFiles(libraryEntity)
private val excludedRootsContainer = if (libraryEntity.excludedRoots.isNotEmpty()) {
FileContainerDescription(libraryEntity.excludedRoots.map { it.url }, emptyList())
}
else null
private val kindProperties by lazy {
val customProperties = libraryEntity.libraryProperties
val k = customProperties?.libraryType?.let {
LibraryKindRegistry.getInstance().findKindById(it) ?: UnknownLibraryKind.getOrCreate(it)
} as? PersistentLibraryKind<*>
val p = loadProperties(k, customProperties)
k to p
}
val kind: PersistentLibraryKind<*>?
get() = kindProperties.first
val properties: LibraryProperties<*>?
get() = kindProperties.second
private fun loadProperties(kind: PersistentLibraryKind<*>?, customProperties: LibraryPropertiesEntity?): LibraryProperties<*>? {
if (kind == null) return null
val properties = kind.createDefaultProperties()
val propertiesElement = customProperties?.propertiesXmlTag
if (propertiesElement == null) return properties
ComponentSerializationUtil.loadComponentState(properties, JDOMUtil.load(StringReader(propertiesElement)))
return properties
}
val name: String?
get() = LibraryNameGenerator.getLegacyLibraryName(libraryEntity.symbolicId)
val module: Module?
get() = (libraryTable as? ModuleLibraryTableBridge)?.module
fun getFiles(rootType: OrderRootType): Array<VirtualFile> {
return roots[rootType.toLibraryRootType()]?.getFiles() ?: VirtualFile.EMPTY_ARRAY
}
fun getUrls(rootType: OrderRootType): Array<String> = roots[rootType.toLibraryRootType()]?.getUrls() ?: ArrayUtil.EMPTY_STRING_ARRAY
val excludedRootUrls: Array<String>
get() = excludedRootsContainer?.getUrls() ?: ArrayUtil.EMPTY_STRING_ARRAY
val excludedRoots: Array<VirtualFile>
get() = excludedRootsContainer?.getFiles() ?: VirtualFile.EMPTY_ARRAY
fun isValid(url: String, rootType: OrderRootType): Boolean {
return roots[rootType.toLibraryRootType()]
?.findByUrl(url)?.isValid ?: false
}
fun getInvalidRootUrls(type: OrderRootType): List<String> {
return roots[type.toLibraryRootType()]?.getList()?.filterNot { it.isValid }?.map { it.url } ?: emptyList()
}
fun isJarDirectory(url: String) = isJarDirectory(url, OrderRootType.CLASSES)
fun isJarDirectory(url: String, rootType: OrderRootType): Boolean {
return roots[rootType.toLibraryRootType()]?.isJarDirectory(url) ?: false
}
val externalSource: ProjectModelExternalSource?
get() = (libraryEntity.entitySource as? JpsImportedEntitySource)?.toExternalSource()
companion object {
fun collectFiles(libraryEntity: LibraryEntity): Map<Any, FileContainerDescription> = libraryEntity.roots.groupBy { it.type }.mapValues { (_, roots) ->
val urls = roots.filter { it.inclusionOptions == LibraryRoot.InclusionOptions.ROOT_ITSELF }.map { it.url }
val jarDirs = roots
.filter { it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF }
.map {
JarDirectoryDescription(it.url, it.inclusionOptions == LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY)
}
FileContainerDescription(urls, jarDirs)
}
}
}
| platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryStateSnapshot.kt | 2383789924 |
// WITH_RUNTIME
// INTENTION_TEXT: "Remove return@label"
fun foo() {
listOf(1,2,3).find label@{
return@label <caret>true
}
} | plugins/kotlin/idea/tests/testData/intentions/removeLabeledReturnInLambda/labeledLambda.kt | 4134382284 |
// 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
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionSorter
import com.intellij.codeInsight.completion.CompletionUtil
import com.intellij.codeInsight.completion.impl.CamelHumpMatcher
import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.registry.Registry
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ProcessingContext
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.project.ModuleOrigin
import org.jetbrains.kotlin.idea.caches.project.OriginCapability
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getResolveScope
import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.platform.isMultiPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class CompletionSessionConfiguration(
val useBetterPrefixMatcherForNonImportedClasses: Boolean,
val nonAccessibleDeclarations: Boolean,
val javaGettersAndSetters: Boolean,
val javaClassesNotToBeUsed: Boolean,
val staticMembers: Boolean,
val dataClassComponentFunctions: Boolean
)
fun CompletionSessionConfiguration(parameters: CompletionParameters) = CompletionSessionConfiguration(
useBetterPrefixMatcherForNonImportedClasses = parameters.invocationCount < 2,
nonAccessibleDeclarations = parameters.invocationCount >= 2,
javaGettersAndSetters = parameters.invocationCount >= 2,
javaClassesNotToBeUsed = parameters.invocationCount >= 2,
staticMembers = parameters.invocationCount >= 2,
dataClassComponentFunctions = parameters.invocationCount >= 2
)
abstract class CompletionSession(
protected val configuration: CompletionSessionConfiguration,
originalParameters: CompletionParameters,
resultSet: CompletionResultSet
) {
init {
CompletionBenchmarkSink.instance.onCompletionStarted(this)
}
protected val parameters = run {
val fixedPosition = addParamTypesIfNeeded(originalParameters.position)
originalParameters.withPosition(fixedPosition, fixedPosition.textOffset)
}
protected val toFromOriginalFileMapper = ToFromOriginalFileMapper.create(this.parameters)
protected val position = this.parameters.position
protected val file = position.containingFile as KtFile
protected val resolutionFacade = file.getResolutionFacade()
protected val moduleDescriptor = resolutionFacade.moduleDescriptor
protected val project = position.project
protected val isJvmModule = TargetPlatformDetector.getPlatform(originalParameters.originalFile as KtFile).isJvm()
protected val isDebuggerContext = file is KtCodeFragment
protected val nameExpression: KtSimpleNameExpression?
protected val expression: KtExpression?
init {
val reference = (position.parent as? KtSimpleNameExpression)?.mainReference
if (reference != null) {
if (reference.expression is KtLabelReferenceExpression) {
this.nameExpression = null
this.expression = reference.expression.parent.parent as? KtExpressionWithLabel
} else {
this.nameExpression = reference.expression
this.expression = nameExpression
}
} else {
this.nameExpression = null
this.expression = null
}
}
protected val bindingContext = CompletionBindingContextProvider.getInstance(project).getBindingContext(position, resolutionFacade)
protected val inDescriptor = position.getResolutionScope(bindingContext, resolutionFacade).ownerDescriptor
private val kotlinIdentifierStartPattern = StandardPatterns.character().javaIdentifierStart().andNot(singleCharPattern('$'))
private val kotlinIdentifierPartPattern = StandardPatterns.character().javaIdentifierPart().andNot(singleCharPattern('$'))
protected val prefix = CompletionUtil.findIdentifierPrefix(
originalParameters.position.containingFile,
originalParameters.offset,
kotlinIdentifierPartPattern or singleCharPattern('@'),
kotlinIdentifierStartPattern
)!!
protected val prefixMatcher = CamelHumpMatcher(prefix)
protected val descriptorNameFilter: (String) -> Boolean = prefixMatcher.asStringNameFilter()
protected val isVisibleFilter: (DeclarationDescriptor) -> Boolean =
{ isVisibleDescriptor(it, completeNonAccessible = configuration.nonAccessibleDeclarations) }
protected val isVisibleFilterCheckAlways: (DeclarationDescriptor) -> Boolean =
{ isVisibleDescriptor(it, completeNonAccessible = false) }
protected val referenceVariantsHelper = ReferenceVariantsHelper(
bindingContext,
resolutionFacade,
moduleDescriptor,
isVisibleFilter,
NotPropertiesService.getNotProperties(position)
)
protected val callTypeAndReceiver =
if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression)
protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression, callTypeAndReceiver) }
protected val basicLookupElementFactory =
BasicLookupElementFactory(project, InsertHandlerProvider(callTypeAndReceiver.callType) { expectedInfos })
// LookupElementsCollector instantiation is deferred because virtual call to createSorter uses data from derived classes
protected val collector: LookupElementsCollector by lazy(LazyThreadSafetyMode.NONE) {
LookupElementsCollector(
{ CompletionBenchmarkSink.instance.onFlush(this) },
prefixMatcher, originalParameters, resultSet,
createSorter(), (file as? KtCodeFragment)?.extraCompletionFilter,
moduleDescriptor.platform.isMultiPlatform()
)
}
protected val searchScope: GlobalSearchScope =
getResolveScope(originalParameters.originalFile as KtFile)
protected fun indicesHelper(mayIncludeInaccessible: Boolean): KotlinIndicesHelper {
val filter = if (mayIncludeInaccessible) isVisibleFilter else isVisibleFilterCheckAlways
return KotlinIndicesHelper(
resolutionFacade,
searchScope,
filter,
filterOutPrivate = !mayIncludeInaccessible,
declarationTranslator = { toFromOriginalFileMapper.toSyntheticFile(it) },
file = file
)
}
private fun isVisibleDescriptor(descriptor: DeclarationDescriptor, completeNonAccessible: Boolean): Boolean {
if (!configuration.javaClassesNotToBeUsed && descriptor is ClassDescriptor) {
if (descriptor.importableFqName?.let(::isJavaClassNotToBeUsedInKotlin) == true) return false
}
if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false
if (descriptor is DeclarationDescriptorWithVisibility) {
val visible = descriptor.isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade)
if (visible) return true
return completeNonAccessible && (!descriptor.isFromLibrary() || isDebuggerContext)
}
if (descriptor.isExcludedFromAutoImport(project, file)) return false
return true
}
private fun DeclarationDescriptor.isFromLibrary(): Boolean {
if (module.getCapability(OriginCapability) == ModuleOrigin.LIBRARY) return true
if (this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return overriddenDescriptors.all { it.isFromLibrary() }
}
return false
}
private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean {
val owner = typeParameter.containingDeclaration
var parent: DeclarationDescriptor? = inDescriptor
while (parent != null) {
if (parent == owner) return true
if (parent is ClassDescriptor && !parent.isInner) return false
parent = parent.containingDeclaration
}
return true
}
protected fun flushToResultSet() {
collector.flushToResultSet()
}
fun complete(): Boolean {
return try {
_complete().also {
CompletionBenchmarkSink.instance.onCompletionEnded(this, false)
}
} catch (pce: ProcessCanceledException) {
CompletionBenchmarkSink.instance.onCompletionEnded(this, true)
throw pce
}
}
private fun _complete(): Boolean {
// we restart completion when prefix becomes "get" or "set" to ensure that properties get lower priority comparing to get/set functions (see KT-12299)
val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("get or set prefix") {
override fun accepts(prefix: String, context: ProcessingContext?) = prefix == "get" || prefix == "set"
})
collector.restartCompletionOnPrefixChange(prefixPattern)
val statisticsContext = calcContextForStatisticsInfo()
if (statisticsContext != null) {
collector.addLookupElementPostProcessor { lookupElement ->
// we should put data into the original element because of DecoratorCompletionStatistician
lookupElement.putUserDataDeep(STATISTICS_INFO_CONTEXT_KEY, statisticsContext)
lookupElement
}
}
doComplete()
flushToResultSet()
return !collector.isResultEmpty
}
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
collector.addLookupElementPostProcessor(processor)
}
protected abstract fun doComplete()
protected abstract val descriptorKindFilter: DescriptorKindFilter?
protected abstract val expectedInfos: Collection<ExpectedInfo>
protected val importableFqNameClassifier = ImportableFqNameClassifier(file)
protected open fun createSorter(): CompletionSorter {
var sorter = CompletionSorter.defaultSorter(parameters, prefixMatcher)!!
sorter = sorter.weighBefore(
"stats", DeprecatedWeigher, PriorityWeigher, PreferGetSetMethodsToPropertyWeigher,
NotImportedWeigher(importableFqNameClassifier),
NotImportedStaticMemberWeigher(importableFqNameClassifier),
KindWeigher, CallableWeigher
)
sorter = sorter.weighAfter("stats", VariableOrFunctionWeigher, ImportedWeigher(importableFqNameClassifier))
val preferContextElementsWeigher = PreferContextElementsWeigher(inDescriptor)
sorter =
if (callTypeAndReceiver is CallTypeAndReceiver.SUPER_MEMBERS) { // for completion after "super." strictly prefer the current member
sorter.weighBefore("kotlin.deprecated", preferContextElementsWeigher)
} else {
sorter.weighBefore("kotlin.proximity", preferContextElementsWeigher)
}
sorter = sorter.weighBefore("middleMatching", PreferMatchingItemWeigher)
// we insert one more RealPrefixMatchingWeigher because one inserted in default sorter is placed in a bad position (after "stats")
sorter = sorter.weighAfter("lift.shorter", RealPrefixMatchingWeigher())
sorter = sorter.weighAfter("kotlin.proximity", ByNameAlphabeticalWeigher, PreferLessParametersWeigher)
sorter = sorter.weighBefore("prefix", KotlinUnwantedLookupElementWeigher)
sorter = if (expectedInfos.all { it.fuzzyType?.type?.isUnit() == true }) {
sorter.weighBefore("prefix", PreferDslMembers)
} else {
sorter.weighAfter("kotlin.preferContextElements", PreferDslMembers)
}
return sorter
}
protected fun calcContextForStatisticsInfo(): String? {
if (expectedInfos.isEmpty()) return null
var context = expectedInfos
.mapNotNull { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName }
.distinct()
.singleOrNull()
?.let { "expectedType=$it" }
if (context == null) {
context = expectedInfos
.mapNotNull { it.expectedName }
.distinct()
.singleOrNull()
?.let { "expectedName=$it" }
}
return context
}
protected val referenceVariantsCollector = if (nameExpression != null) {
ReferenceVariantsCollector(
referenceVariantsHelper, indicesHelper(true), prefixMatcher,
nameExpression, callTypeAndReceiver, resolutionFacade, bindingContext,
importableFqNameClassifier, configuration
)
} else {
null
}
protected fun ReferenceVariants.excludeNonInitializedVariable(): ReferenceVariants {
return ReferenceVariants(referenceVariantsHelper.excludeNonInitializedVariable(imported, position), notImportedExtensions)
}
protected fun referenceVariantsWithSingleFunctionTypeParameter(): ReferenceVariants? {
val variants = referenceVariantsCollector?.allCollected ?: return null
val filter = { descriptor: DeclarationDescriptor ->
descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(descriptor)
}
return ReferenceVariants(variants.imported.filter(filter), variants.notImportedExtensions.filter(filter))
}
protected fun getRuntimeReceiverTypeReferenceVariants(lookupElementFactory: LookupElementFactory): Pair<ReferenceVariants, LookupElementFactory>? {
val evaluator = file.getCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) ?: return null
val referenceVariants = referenceVariantsCollector?.allCollected ?: return null
val explicitReceiver = callTypeAndReceiver.receiver as? KtExpression ?: return null
val type = bindingContext.getType(explicitReceiver) ?: return null
if (!TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)) return null
val runtimeType = evaluator(explicitReceiver)
if (runtimeType == null || runtimeType == type) return null
val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType, bindingContext)
val (variants, notImportedExtensions) = ReferenceVariantsCollector(
referenceVariantsHelper, indicesHelper(true), prefixMatcher,
nameExpression!!, callTypeAndReceiver, resolutionFacade, bindingContext,
importableFqNameClassifier, configuration, runtimeReceiver = expressionReceiver
).collectReferenceVariants(descriptorKindFilter!!)
val filteredVariants = filterVariantsForRuntimeReceiverType(variants, referenceVariants.imported)
val filteredNotImportedExtensions =
filterVariantsForRuntimeReceiverType(notImportedExtensions, referenceVariants.notImportedExtensions)
val runtimeVariants = ReferenceVariants(filteredVariants, filteredNotImportedExtensions)
return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType, 0))))
}
private fun <TDescriptor : DeclarationDescriptor> filterVariantsForRuntimeReceiverType(
runtimeVariants: Collection<TDescriptor>,
baseVariants: Collection<TDescriptor>
): Collection<TDescriptor> {
val baseVariantsByName = baseVariants.groupBy { it.name }
val result = ArrayList<TDescriptor>()
for (variant in runtimeVariants) {
val candidates = baseVariantsByName[variant.name]
if (candidates == null || candidates.none { compareDescriptors(project, variant, it) }) {
result.add(variant)
}
}
return result
}
protected open fun shouldCompleteTopLevelCallablesFromIndex(): Boolean {
if (nameExpression == null) return false
if ((descriptorKindFilter?.kindMask ?: 0).and(DescriptorKindFilter.CALLABLES_MASK) == 0) return false
if (callTypeAndReceiver is CallTypeAndReceiver.IMPORT_DIRECTIVE) return false
return callTypeAndReceiver.receiver == null
}
protected fun processTopLevelCallables(processor: (CallableDescriptor) -> Unit) {
val shadowedFilter = ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, nameExpression!!, callTypeAndReceiver)
?.createNonImportedDeclarationsFilter<CallableDescriptor>(referenceVariantsCollector!!.allCollected.imported)
indicesHelper(true).processTopLevelCallables({ prefixMatcher.prefixMatches(it) }) {
if (shadowedFilter != null) {
shadowedFilter(listOf(it)).singleOrNull()?.let(processor)
} else {
processor(it)
}
}
}
protected fun withCollectRequiredContextVariableTypes(action: (LookupElementFactory) -> Unit): Collection<FuzzyType> {
val provider = CollectRequiredTypesContextVariablesProvider()
val lookupElementFactory = createLookupElementFactory(provider)
action(lookupElementFactory)
return provider.requiredTypes
}
protected fun withContextVariablesProvider(contextVariablesProvider: ContextVariablesProvider, action: (LookupElementFactory) -> Unit) {
val lookupElementFactory = createLookupElementFactory(contextVariablesProvider)
action(lookupElementFactory)
}
protected open fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory {
return LookupElementFactory(
basicLookupElementFactory, receiverTypes,
callTypeAndReceiver.callType, inDescriptor, contextVariablesProvider
)
}
protected fun detectReceiverTypes(
bindingContext: BindingContext,
nameExpression: KtSimpleNameExpression,
callTypeAndReceiver: CallTypeAndReceiver<*, *>
): List<ReceiverType>? {
var receiverTypes = callTypeAndReceiver.receiverTypesWithIndex(
bindingContext, nameExpression, moduleDescriptor, resolutionFacade,
stableSmartCastsOnly = true, /* we don't include smart cast receiver types for "unstable" receiver value to mark members grayed */
withImplicitReceiversWhenExplicitPresent = true
)
if (callTypeAndReceiver is CallTypeAndReceiver.SAFE || isDebuggerContext) {
receiverTypes = receiverTypes?.map { ReceiverType(it.type.makeNotNullable(), it.receiverIndex) }
}
return receiverTypes
}
}
| plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt | 2861044896 |
// 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.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.MayBeConstantInspection.Status.*
import org.jetbrains.kotlin.idea.quickfix.AddConstModifierFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.propertyVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.constants.ErrorValue
import org.jetbrains.kotlin.resolve.constants.NullValue
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.constants.evaluate.isStandaloneOnlyConstant
import org.jetbrains.kotlin.resolve.jvm.annotations.hasJvmFieldAnnotation
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class MayBeConstantInspection : AbstractKotlinInspection() {
enum class Status {
NONE,
MIGHT_BE_CONST,
MIGHT_BE_CONST_ERRONEOUS,
JVM_FIELD_MIGHT_BE_CONST,
JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER,
JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return propertyVisitor { property ->
when (val status = property.getStatus()) {
NONE, JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER,
MIGHT_BE_CONST_ERRONEOUS, JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS -> return@propertyVisitor
MIGHT_BE_CONST, JVM_FIELD_MIGHT_BE_CONST -> {
holder.registerProblem(
property.nameIdentifier ?: property,
if (status == JVM_FIELD_MIGHT_BE_CONST)
KotlinBundle.message("const.might.be.used.instead.of.jvmfield")
else
KotlinBundle.message("might.be.const"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(AddConstModifierFix(property), property.containingFile)
)
}
}
}
}
companion object {
fun KtProperty.getStatus(): Status {
if (isLocal || isVar || getter != null ||
hasModifier(KtTokens.CONST_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) || hasActualModifier()
) {
return NONE
}
val containingClassOrObject = this.containingClassOrObject
if (!isTopLevel && containingClassOrObject !is KtObjectDeclaration) return NONE
if (containingClassOrObject?.isObjectLiteral() == true) return NONE
val initializer = initializer
// For some reason constant evaluation does not work for property.analyze()
val context = (initializer ?: this).analyze(BodyResolveMode.PARTIAL)
val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? VariableDescriptor ?: return NONE
val type = propertyDescriptor.type
if (!KotlinBuiltIns.isPrimitiveType(type) && !KotlinBuiltIns.isString(type)) return NONE
val withJvmField = propertyDescriptor.hasJvmFieldAnnotation()
if (annotationEntries.isNotEmpty() && !withJvmField) return NONE
return when {
initializer != null -> {
val compileTimeConstant = ConstantExpressionEvaluator.getConstant(
initializer, context
) ?: return NONE
val erroneousConstant = compileTimeConstant.usesNonConstValAsConstant
compileTimeConstant.toConstantValue(propertyDescriptor.type).takeIf {
!it.isStandaloneOnlyConstant() && it !is NullValue && it !is ErrorValue
} ?: return NONE
when {
withJvmField ->
if (erroneousConstant) JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS
else JVM_FIELD_MIGHT_BE_CONST
else ->
if (erroneousConstant) MIGHT_BE_CONST_ERRONEOUS
else MIGHT_BE_CONST
}
}
withJvmField -> JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER
else -> NONE
}
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MayBeConstantInspection.kt | 388547536 |
package org.penella.index.bstree
import org.penella.index.IndexType
import org.penella.messages.IndexResultSet
import org.penella.structures.triples.HashTriple
import org.penella.structures.triples.TripleType
/**
* 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.
*
* Created by alisle on 11/29/16.
*/
class ObjectBSTreeIndex() : BSTreeIndex(IndexType.O) {
override fun add(triple: HashTriple) = addTriple(triple.hashObj, triple.hashSubject, triple.hashProperty)
override fun get(first: TripleType, second: TripleType, firstValue: Long, secondValue: Long) : IndexResultSet = throw InvalidIndexRequest()
override fun get(first: TripleType, value: Long ) : IndexResultSet = if(first == TripleType.OBJECT) getResults(value) else throw IncorrectIndexRequest()
}
| src/main/java/org/penella/index/bstree/ObjectBSTreeIndex.kt | 1310277939 |
package com.maly.domain.event
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
/**
* @author Aleksander Brzozowski
*/
interface EventRepository: JpaRepository<Event, Long>, JpaSpecificationExecutor<Event> | src/main/kotlin/com/maly/domain/event/EventRepository.kt | 745428649 |
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.openapi.util.NlsSafe
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
sealed class PackageScope(open val scopeName: String) : Comparable<PackageScope> {
@get:Nls
abstract val displayName: String
override fun compareTo(other: PackageScope): Int = scopeName.compareTo(other.scopeName)
object Missing : PackageScope("") {
@Nls
override val displayName = PackageSearchBundle.message("packagesearch.ui.missingScope")
@NonNls
override fun toString() = "[Missing scope]"
}
data class Named(@NlsSafe override val scopeName: String) : PackageScope(scopeName) {
init {
require(scopeName.isNotBlank()) { "A Named scope name cannot be blank." }
}
@Nls
override val displayName = scopeName
@NonNls
override fun toString() = scopeName
}
companion object {
fun from(rawScope: String?): PackageScope {
if (rawScope.isNullOrBlank()) return Missing
return Named(rawScope.trim())
}
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageScope.kt | 644363035 |
open class Foo
class Bar : Foo()
val foo = Foo()
val bar = Bar()
val o : Any = ""
fun f(p1 : Foo, p2 : Bar, p3 : String, p4 : Foo?) {
var a : Foo
a = <caret>
}
fun f1() : Foo{}
fun f2() : Bar{}
fun f3() : String{}
// EXIST: foo
// EXIST: bar
// ABSENT: o
// EXIST: p1
// EXIST: p2
// ABSENT: p3
// ABSENT: { lookupString:"p4", itemText:"p4" }
// EXIST: { lookupString:"p4", itemText:"!! p4" }
// EXIST: { lookupString:"p4", itemText:"?: p4" }
// EXIST: f1
// EXIST: f2
// ABSENT: f3
// EXIST: { lookupString:"Foo", itemText:"Foo", tailText: "() (<root>)" }
| plugins/kotlin/completion/tests/testData/smart/EmptyPrefix.kt | 3595376991 |
// "Assign to property" "false"
// ACTION: Converts the assignment statement to an expression
// ACTION: Do not show return expression hints
// ERROR: Val cannot be reassigned
class Test {
val foo = 1
fun test(foo: Int) {
<caret>foo = foo
}
} | plugins/kotlin/idea/tests/testData/quickfix/assignToProperty/valProperty.kt | 3068669891 |
package com.zeroami.commonlib.mvp
import android.os.Bundle
import com.zeroami.commonlib.utils.LL
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
/**
* BasePresenter,实现MvpPresenter,完成Presenter的通用操作
*
* @author Zeroami
*/
abstract class LBasePresenter<V : LMvpView>(view: V) : LMvpPresenter<V>, LRxSupport {
protected lateinit var mvpView: V
private set
private lateinit var emptyMvpView: V // 一个空实现的MvpView,避免V和P解除绑定时P持有的V的MvpView引用为空导致空指针
private val compositeDisposable: CompositeDisposable by lazy { CompositeDisposable() }
init {
attachView(view)
createEmptyMvpView()
}
/**
* 关联完成调用
*/
protected open fun onViewAttached() {}
/**
* 解除关联完成调用
*/
protected open fun onViewDetached() {}
override fun doViewInitialized() {}
override fun handleExtras(extras: Bundle) {}
override fun subscribeEvent() {}
override fun attachView(view: V) {
mvpView = view
onViewAttached()
}
override fun detachView() {
mvpView = emptyMvpView
compositeDisposable.clear()
onViewDetached()
}
override fun addDisposable(disposable: Disposable) {
compositeDisposable.add(disposable)
}
/**
* 创建空实现的MvpView
*/
@Suppress("UNCHECKED_CAST")
private fun createEmptyMvpView() {
emptyMvpView = Proxy.newProxyInstance(javaClass.classLoader, mvpView.javaClass.interfaces, object : InvocationHandler {
@Throws(Throwable::class)
override fun invoke(o: Any?, method: Method?, args: Array<Any>?): Any? {
LL.i("EmptyMvpView的%s方法被调用", method?.name ?: "")
if (method?.declaringClass == Any::class.java) {
return method.invoke(this, *args!!)
}
return null
}
}) as V
}
}
| commonlib/src/main/java/com/zeroami/commonlib/mvp/LBasePresenter.kt | 436033732 |
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.SearchTextField
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.Subscription
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import java.awt.Dimension
import java.awt.event.KeyEvent
class PackagesSmartSearchField(
searchFieldFocus: Flow<Unit>,
project: Project
) : SearchTextField(false) {
init {
@Suppress("MagicNumber") // Swing dimension constants
PackageSearchUI.setHeight(this, height = 25)
@Suppress("MagicNumber") // Swing dimension constants
minimumSize = Dimension(100.scaled(), minimumSize.height)
textEditor.setTextToTriggerEmptyTextStatus(PackageSearchBundle.message("packagesearch.search.hint"))
textEditor.emptyText.isShowAboveCenter = true
PackageSearchUI.overrideKeyStroke(textEditor, "shift ENTER", this::transferFocusBackward)
searchFieldFocus
.onEach { withContext(Dispatchers.EDT) { requestFocus() } }
.launchIn(project.lifecycleScope)
}
/**
* Trying to navigate to the first element in the brief list
* @return true in case of success; false if the list is empty
*/
var goToTable: () -> Boolean = { false }
var fieldClearedListener: (() -> Unit)? = null
private val listeners = mutableSetOf<(KeyEvent) -> Unit>()
fun registerOnKeyPressedListener(action: (KeyEvent) -> Unit): Subscription {
listeners.add(action)
return Subscription { listeners.remove(action) }
}
override fun preprocessEventForTextField(e: KeyEvent?): Boolean {
e?.let { keyEvent -> listeners.forEach { listener -> listener(keyEvent) } }
if (e?.keyCode == KeyEvent.VK_DOWN || e?.keyCode == KeyEvent.VK_PAGE_DOWN) {
goToTable() // trying to navigate to the list instead of "show history"
e.consume() // suppress default "show history" logic anyway
return true
}
return super.preprocessEventForTextField(e)
}
override fun getBackground() = PackageSearchUI.HeaderBackgroundColor
override fun onFocusLost() {
super.onFocusLost()
addCurrentTextToHistory()
}
override fun onFieldCleared() {
super.onFieldCleared()
fieldClearedListener?.invoke()
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesSmartSearchField.kt | 1804353095 |
fun foo(bar: Int) {
bar >= 0 && bar <= 10<caret>
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/gteqlteq.kt | 365670228 |
package servers
import com.onyx.application.impl.WebDatabaseServer
import com.onyx.persistence.IManagedEntity
import entities.SimpleEntity
/**
* Created by timothy.osborn on 4/1/15.
*/
class SampleDatabaseServer(databaseLocation: String) : WebDatabaseServer(databaseLocation) {
companion object {
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
@Throws(Exception::class)
@JvmStatic fun main(args: Array<String>) {
val server1 = SampleDatabaseServer("C:/Sandbox/Onyx/Tests/server.oxd")
server1.port = 8080
server1.webServicePort = 8082
server1.start()
val simpleEntity = SimpleEntity()
simpleEntity.name = "Test Name"
simpleEntity.simpleId = "ASDF"
server1.persistenceManager.saveEntity<IManagedEntity>(simpleEntity)
server1.join()
println("Started")
}
}
}
| onyx-database-tests/src/main/kotlin/servers/SampleDatabaseServer.kt | 1227332603 |
// 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.formatter.trailingComma
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespace
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.utils.addToStdlib.cast
object TrailingCommaHelper {
fun findInvalidCommas(commaOwner: KtElement): List<PsiElement> = commaOwner.firstChild
?.siblings(withItself = false)
?.filter { it.isComma }
?.filter {
it.prevLeaf(true)?.isLineBreak() == true || it.leafIgnoringWhitespace(false) != it.leafIgnoringWhitespaceAndComments(false)
}?.toList().orEmpty()
fun trailingCommaExistsOrCanExist(psiElement: PsiElement, settings: CodeStyleSettings): Boolean =
TrailingCommaContext.create(psiElement).commaExistsOrMayExist(settings.kotlinCustomSettings)
fun trailingCommaExists(commaOwner: KtElement): Boolean = when (commaOwner) {
is KtFunctionLiteral -> commaOwner.valueParameterList?.trailingComma != null
is KtWhenEntry -> commaOwner.trailingComma != null
is KtDestructuringDeclaration -> commaOwner.trailingComma != null
else -> trailingCommaOrLastElement(commaOwner)?.isComma == true
}
fun trailingCommaOrLastElement(commaOwner: KtElement): PsiElement? {
val lastChild = commaOwner.lastSignificantChild ?: return null
val withSelf = when (PsiUtil.getElementType(lastChild)) {
KtTokens.COMMA -> return lastChild
in RIGHT_BARRIERS -> false
else -> true
}
return lastChild.getPrevSiblingIgnoringWhitespaceAndComments(withSelf)?.takeIf {
PsiUtil.getElementType(it) !in LEFT_BARRIERS
}?.takeIfIsNotError()
}
/**
* @return true if [commaOwner] has a trailing comma and hasn't a line break before the first or after the last element
*/
fun lineBreakIsMissing(commaOwner: KtElement): Boolean {
if (!trailingCommaExists(commaOwner)) return false
val first = elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) return true
val last = elementAfterLastElement(commaOwner)
return last?.prevLeaf(true)?.isLineBreak() == false
}
fun elementBeforeFirstElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.lBrace else commaOwner.leftParenthesis
}
is KtWhenEntry -> commaOwner.parent.cast<KtWhenExpression>().openBrace
is KtDestructuringDeclaration -> commaOwner.lPar
else -> commaOwner.firstChild?.takeIfIsNotError()
}
fun elementAfterLastElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.arrow else commaOwner.rightParenthesis
}
is KtWhenEntry -> commaOwner.arrow
is KtDestructuringDeclaration -> commaOwner.rPar
else -> commaOwner.lastChild?.takeIfIsNotError()
}
private fun PsiElement.takeIfIsNotError(): PsiElement? = takeIf { !PsiTreeUtil.hasErrorElements(it) }
private val RIGHT_BARRIERS = TokenSet.create(KtTokens.RBRACKET, KtTokens.RPAR, KtTokens.RBRACE, KtTokens.GT, KtTokens.ARROW)
private val LEFT_BARRIERS = TokenSet.create(KtTokens.LBRACKET, KtTokens.LPAR, KtTokens.LBRACE, KtTokens.LT)
private val PsiElement.lastSignificantChild: PsiElement?
get() = when (this) {
is KtWhenEntry -> arrow
is KtDestructuringDeclaration -> rPar
else -> lastChild
}
} | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaHelper.kt | 542057332 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.util.ArrayUtil
import java.io.File
import java.net.URI
import java.nio.file.Path
abstract class BrowserLauncher {
companion object {
@JvmStatic
val instance: BrowserLauncher
get() = ApplicationManager.getApplication().getService(BrowserLauncher::class.java)
}
abstract fun open(url: String)
abstract fun browse(file: File)
abstract fun browse(file: Path)
fun browse(uri: URI): Unit = browse(uri.toString(), null, null)
fun browse(url: String, browser: WebBrowser?): Unit = browse(url, browser, null)
abstract fun browse(url: String, browser: WebBrowser? = null, project: Project? = null)
abstract fun browseUsingPath(url: String?,
browserPath: String? = null,
browser: WebBrowser? = null,
project: Project? = null,
openInNewWindow: Boolean = false,
additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY): Boolean
} | platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncher.kt | 3158535120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.