repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gradle/gradle | .teamcity/src/main/kotlin/configurations/FunctionalTest.kt | 2 | 2764 | package configurations
import common.functionalTestExtraParameters
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildSteps
import model.CIBuildModel
import model.Stage
import model.StageName
import model.TestCoverage
const val functionalTestTag = "FunctionalTest"
class FunctionalTest(
model: CIBuildModel,
id: String,
name: String,
description: String,
val testCoverage: TestCoverage,
stage: Stage,
enableTestDistribution: Boolean,
subprojects: List<String> = listOf(),
extraParameters: String = "",
extraBuildSteps: BuildSteps.() -> Unit = {},
preBuildSteps: BuildSteps.() -> Unit = {}
) : BaseGradleBuildType(stage = stage, init = {
this.name = name
this.description = description
this.id(id)
val testTasks = getTestTaskName(testCoverage, subprojects)
applyTestDefaults(
model, this, testTasks,
dependsOnQuickFeedbackLinux = !testCoverage.withoutDependencies && stage.stageName > StageName.PULL_REQUEST_FEEDBACK,
os = testCoverage.os,
buildJvm = testCoverage.buildJvm,
arch = testCoverage.arch,
extraParameters = (
listOf(functionalTestExtraParameters(functionalTestTag, testCoverage.os, testCoverage.arch, testCoverage.testJvmVersion.major.toString(), testCoverage.vendor.name)) +
(if (enableTestDistribution) "-DenableTestDistribution=%enableTestDistribution% -DtestDistributionPartitionSizeInSeconds=%testDistributionPartitionSizeInSeconds%" else "") +
"-PflakyTests=${determineFlakyTestStrategy(stage)}" +
extraParameters
).filter { it.isNotBlank() }.joinToString(separator = " "),
timeout = testCoverage.testType.timeout,
extraSteps = extraBuildSteps,
preSteps = preBuildSteps
)
failureConditions {
// JavaExecDebugIntegrationTest.debug session fails without debugger might cause JVM crash
// Some soak tests produce OOM exceptions
// There are also random worker crashes for some tests.
// We have test-retry to handle the crash in tests
javaCrash = false
}
})
private fun determineFlakyTestStrategy(stage: Stage): String {
val stageName = StageName.values().first { it.stageName == stage.stageName.stageName }
// See gradlebuild.basics.FlakyTestStrategy
return if (stageName < StageName.READY_FOR_RELEASE) "exclude" else "include"
}
fun getTestTaskName(testCoverage: TestCoverage, subprojects: List<String>): String {
val testTaskName = "${testCoverage.testType.name}Test"
return when {
subprojects.isEmpty() -> {
testTaskName
}
else -> {
subprojects.joinToString(" ") { "$it:$testTaskName" }
}
}
}
| apache-2.0 | a04cb2eea4f2015a6ba5208849f85b4a | 36.863014 | 189 | 0.695007 | 4.806957 | false | true | false | false |
Takhion/android-extras-delegates | library/src/main/java/me/eugeniomarletti/extras/bundle/base/Array.kt | 1 | 3771 | @file:Suppress("NOTHING_TO_INLINE")
package me.eugeniomarletti.extras.bundle.base
import android.os.Parcelable
import me.eugeniomarletti.extras.bundle.BundleExtra
inline fun BundleExtra.ParcelableArray(name: String? = null, customPrefix: String? = null) =
ParcelableArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.ParcelableArray(defaultValue: Array<Parcelable?>, name: String? = null, customPrefix: String? = null) =
ParcelableArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.CharSequenceArray(name: String? = null, customPrefix: String? = null) =
CharSequenceArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.CharSequenceArray(defaultValue: Array<CharSequence?>, name: String? = null, customPrefix: String? = null) =
CharSequenceArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.StringArray(name: String? = null, customPrefix: String? = null) =
StringArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.StringArray(defaultValue: Array<String?>, name: String? = null, customPrefix: String? = null) =
StringArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.ByteArray(name: String? = null, customPrefix: String? = null) =
ByteArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.ByteArray(defaultValue: ByteArray, name: String? = null, customPrefix: String? = null) =
ByteArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.CharArray(name: String? = null, customPrefix: String? = null) =
CharArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.CharArray(defaultValue: CharArray, name: String? = null, customPrefix: String? = null) =
CharArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.IntArray(name: String? = null, customPrefix: String? = null) =
IntArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.IntArray(defaultValue: IntArray, name: String? = null, customPrefix: String? = null) =
IntArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.ShortArray(name: String? = null, customPrefix: String? = null) =
ShortArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.ShortArray(defaultValue: ShortArray, name: String? = null, customPrefix: String? = null) =
ShortArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.LongArray(name: String? = null, customPrefix: String? = null) =
LongArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.LongArray(defaultValue: LongArray, name: String? = null, customPrefix: String? = null) =
LongArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.DoubleArray(name: String? = null, customPrefix: String? = null) =
DoubleArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.DoubleArray(defaultValue: DoubleArray, name: String? = null, customPrefix: String? = null) =
DoubleArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.FloatArray(name: String? = null, customPrefix: String? = null) =
FloatArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.FloatArray(defaultValue: FloatArray, name: String? = null, customPrefix: String? = null) =
FloatArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun BundleExtra.BooleanArray(name: String? = null, customPrefix: String? = null) =
BooleanArray({ it }, { it }, name, customPrefix)
inline fun BundleExtra.BooleanArray(defaultValue: BooleanArray, name: String? = null, customPrefix: String? = null) =
BooleanArray({ it ?: defaultValue }, { it }, name, customPrefix)
| mit | 1b751a12741484ca69c27eda12307045 | 51.375 | 130 | 0.710422 | 4.19 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKChatChannelMuteTable.kt | 1 | 5874 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.database.table
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel
import com.rpkit.chat.bukkit.database.create
import com.rpkit.chat.bukkit.database.jooq.Tables.RPKIT_CHAT_CHANNEL_MUTE
import com.rpkit.chat.bukkit.mute.RPKChatChannelMute
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileId
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level.SEVERE
/**
* Represents the chat channel mute table
*/
class RPKChatChannelMuteTable(private val database: Database, private val plugin: RPKChatBukkit) : Table {
private data class MinecraftProfileChatChannelCacheKey(
val minecraftProfileId: Int,
val chatChannelName: String
)
private val cache = if (plugin.config.getBoolean("caching.rpkit_chat_channel_mute.minecraft_profile_id.enabled")) {
database.cacheManager.createCache(
"rpk-chat-bukkit.rpkit_chat_channel_mute.minecraft_profile_id",
MinecraftProfileChatChannelCacheKey::class.java,
RPKChatChannelMute::class.java,
plugin.config.getLong("caching.rpkit_chat_channel_mute.minecraft_profile_id.size")
)
} else {
null
}
fun insert(entity: RPKChatChannelMute): CompletableFuture<Void> {
val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null)
val chatChannelName = entity.chatChannel.name
return runAsync {
database.create
.insertInto(
RPKIT_CHAT_CHANNEL_MUTE,
RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID,
RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME
)
.values(
minecraftProfileId.value,
chatChannelName.value
)
.execute()
cache?.set(MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value), entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to insert chat channel mute", exception)
throw exception
}
}
fun get(minecraftProfile: RPKMinecraftProfile, chatChannel: RPKChatChannel): CompletableFuture<RPKChatChannelMute?> {
val minecraftProfileId = minecraftProfile.id ?: return CompletableFuture.completedFuture(null)
val chatChannelName = chatChannel.name
val cacheKey = MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value)
if (cache?.containsKey(cacheKey) == true) {
return CompletableFuture.completedFuture(cache[cacheKey])
}
return CompletableFuture.supplyAsync {
database.create
.select(
RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID,
RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME
)
.from(RPKIT_CHAT_CHANNEL_MUTE)
.where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.and(RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME.eq(chatChannelName.value))
.fetchOne() ?: return@supplyAsync null
val chatChannelMute = RPKChatChannelMute(
minecraftProfile,
chatChannel
)
cache?.set(cacheKey, chatChannelMute)
return@supplyAsync chatChannelMute
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get chat channel mute", exception)
throw exception
}
}
fun delete(entity: RPKChatChannelMute): CompletableFuture<Void> {
val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null)
val chatChannelName = entity.chatChannel.name
val cacheKey = MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value)
return runAsync {
database.create
.deleteFrom(RPKIT_CHAT_CHANNEL_MUTE)
.where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.and(RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME.eq(chatChannelName.value))
.execute()
cache?.remove(cacheKey)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete chat channel mute", exception)
throw exception
}
}
fun delete(minecraftProfileId: RPKMinecraftProfileId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_CHAT_CHANNEL_MUTE)
.where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.execute()
cache?.removeMatching { it.minecraftProfile.id?.value == minecraftProfileId.value }
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete chat channel mutes for Minecraft profile id", exception)
throw exception
}
}
| apache-2.0 | 0e415f7ae9f676ce8ee3e3a7489e4980 | 43.5 | 121 | 0.677903 | 4.973751 | false | false | false | false |
ajordens/clouddriver | clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/flow/seekers/SagaCommandCompletedEventSeeker.kt | 3 | 2137 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.saga.flow.seekers
import com.netflix.spinnaker.clouddriver.saga.SagaCommandCompleted
import com.netflix.spinnaker.clouddriver.saga.flow.SagaFlow
import com.netflix.spinnaker.clouddriver.saga.flow.Seeker
import com.netflix.spinnaker.clouddriver.saga.flow.convertActionStepToCommandName
import com.netflix.spinnaker.clouddriver.saga.models.Saga
import org.slf4j.LoggerFactory
/**
* Seeks the [SagaFlowIterator] index to the next command following a [SagaCommandCompleted] event.
*/
internal class SagaCommandCompletedEventSeeker : Seeker {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
override fun invoke(currentIndex: Int, steps: List<SagaFlow.Step>, saga: Saga): Int? {
val completionEvents = saga.getEvents().filterIsInstance<SagaCommandCompleted>()
if (completionEvents.isEmpty()) {
// If there are no completion events, we don't need to seek at all.
return null
}
val lastCompletedCommand = completionEvents.last().command
val step = steps
.filterIsInstance<SagaFlow.ActionStep>()
.find { convertActionStepToCommandName(it) == lastCompletedCommand }
if (step == null) {
// Not the end of the world if this seeker doesn't find a correlated step, but it's definitely an error case
log.error("Could not find step associated with last completed command ($lastCompletedCommand)")
return null
}
return (steps.indexOf(step) + 1).also {
log.debug("Suggesting to seek index to $it")
}
}
}
| apache-2.0 | 1971254dd283e1505d185b0d6f14a424 | 38.574074 | 114 | 0.745438 | 4.240079 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TristeRealidadeCommand.kt | 1 | 8561 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.common.utils.image.JVMImage
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.api.commands.CommandException
import net.perfectdreams.loritta.morenitta.api.entities.User
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.DiscordUser
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda.JDAUser
import net.perfectdreams.loritta.morenitta.utils.*
import net.perfectdreams.loritta.morenitta.utils.locale.Gender
import net.perfectdreams.loritta.morenitta.utils.locale.PersonalPronoun
import java.awt.*
import java.awt.image.BufferedImage
class TristeRealidadeCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("sadreality", "tristerealidade"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
companion object {
private const val LOCALE_PREFIX = "commands.command"
}
override fun command() = create {
needsToUploadFiles = true
localizedDescription("$LOCALE_PREFIX.tristerealidade.description")
executesDiscord {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, this.locale, "sadreality")
val context = this
var x = 0
var y = 0
val base = BufferedImage(384, 256, BufferedImage.TYPE_INT_ARGB) // Iremos criar uma imagem 384x256 (tamanho do template)
val baseGraph = base.graphics.enableFontAntiAliasing()
val users = mutableListOf<User>()
val user1 = context.user(0)
val user2 = context.user(1)
val user3 = context.user(2)
val user4 = context.user(3)
val user5 = context.user(4)
val user6 = context.user(5)
if (user1 != null) users.add(user1)
if (user2 != null) users.add(user2)
if (user3 != null) users.add(user3)
if (user4 != null) users.add(user4)
if (user5 != null) users.add(user5)
if (user6 != null) users.add(user6)
val members = context.guild.members.filter { !it.user.isBot}.toMutableList()
while (6 > users.size) {
val member = if (members.isNotEmpty()) {
members[LorittaBot.RANDOM.nextInt(members.size)]
} else {
throw CommandException("Não existem membros suficientes para fazer uma triste realidade, sorry ;w;", Constants.ERROR)
}
users.add(JDAUser(member.user))
members.remove(member)
}
var lovedGender = Gender.UNKNOWN
val firstUser = users[0]
if (firstUser is DiscordUser) {
lovedGender = loritta.pudding.transaction {
val profile = loritta.getLorittaProfile(firstUser.id)
profile?.settings?.gender ?: Gender.UNKNOWN
}
}
if (lovedGender == Gender.UNKNOWN)
lovedGender = Gender.FEMALE
var aux = 0
while (6 > aux) {
val member = users[0]
if (member is JDAUser) {
val avatarImg = (
LorittaUtils.downloadImage(
loritta,
member.getEffectiveAvatarUrl(ImageFormat.PNG, 128)
) ?: LorittaUtils.downloadImage(loritta, member.handle.defaultAvatarUrl))!!
.getScaledInstance(128, 128, Image.SCALE_SMOOTH)
baseGraph.drawImage(avatarImg, x, y, null)
baseGraph.font = Constants.MINECRAFTIA.deriveFont(Font.PLAIN, 8f)
baseGraph.color = Color.BLACK
baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 12)
baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 14)
baseGraph.drawString(member.name + "#" + member.handle.discriminator, x, y + 13)
baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 2, y + 13)
baseGraph.color = Color.WHITE
baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 13)
baseGraph.font = ArtsyJoyLoriConstants.BEBAS_NEUE.deriveFont(22f)
var gender = Gender.UNKNOWN
gender = loritta.pudding.transaction {
val profile = loritta.getLorittaProfile(firstUser.id)
profile?.settings?.gender ?: Gender.UNKNOWN
}
if (gender == Gender.UNKNOWN)
gender = Gender.MALE
if (aux == 0)
gender = lovedGender
// If we use '0', '1', '2' in the YAML, Crowdin may think that's an array, and that's no good
val slot = when (aux) {
0 -> "theGuyYouLike"
1 -> "theFather"
2 -> "theBrother"
3 -> "theFirstLover"
4 -> "theBestFriend"
5 -> "you"
else -> throw RuntimeException("Invalid slot $aux")
}
drawCentralizedTextOutlined(
baseGraph,
locale["$LOCALE_PREFIX.tristerealidade.slot.$slot.${gender.name}", lovedGender.getPossessivePronoun(locale, PersonalPronoun.THIRD_PERSON, member.name)],
Rectangle(x, y + 80, 128, 42),
Color.WHITE,
Color.BLACK,
2
)
x += 128
if (x > 256) {
x = 0
y = 128
}
}
aux++
users.removeAt(0)
}
context.sendImage(JVMImage(base), "sad_reality.png", context.getUserMention(true))
}
}
private fun drawCentralizedTextOutlined(graphics: Graphics, text: String, rectangle: Rectangle, fontColor: Color, strokeColor: Color, strokeSize: Int) {
val font = graphics.font
graphics.font = font
val fontMetrics = graphics.fontMetrics
val lines = mutableListOf<String>()
val split = text.split(" ")
var x = 0
var currentLine = StringBuilder()
for (string in split) {
val stringWidth = fontMetrics.stringWidth("$string ")
val newX = x + stringWidth
if (newX >= rectangle.width) {
var endResult = currentLine.toString().trim()
if (endResult.isEmpty()) { // okay wtf
// Se o texto é grande demais e o conteúdo atual está vazio... bem... substitua o endResult pela string atual
endResult = string
lines.add(endResult)
x = 0
continue
}
lines.add(endResult)
currentLine = StringBuilder()
currentLine.append(' ')
currentLine.append(string)
x = fontMetrics.stringWidth("$string ")
} else {
currentLine.append(' ')
currentLine.append(string)
x = newX
}
}
lines.add(currentLine.toString().trim())
val skipHeight = fontMetrics.ascent
var y = (rectangle.height / 2) - ((skipHeight - 4) * (lines.size - 1))
for (line in lines) {
graphics.color = strokeColor
for (strokeX in rectangle.x - strokeSize .. rectangle.x + strokeSize) {
for (strokeY in rectangle.y + y - strokeSize .. rectangle.y + y + strokeSize) {
ImageUtils.drawCenteredStringEmoji(loritta, graphics, line, Rectangle(strokeX, strokeY, rectangle.width, 24), font)
}
}
graphics.color = fontColor
ImageUtils.drawCenteredStringEmoji(loritta, graphics, line, Rectangle(rectangle.x, rectangle.y + y, rectangle.width, 24), font)
y += skipHeight
}
}
} | agpl-3.0 | dceee6d51ade090c0ea343695f7decbf | 41.577114 | 196 | 0.548323 | 4.812711 | false | false | false | false |
sniffy/sniffy | sniffy-test/sniffy-kotest/src/main/kotlin/io/sniffy/test/kotest/usage/SniffyExtension.kt | 1 | 1570 | package io.sniffy.test.kotest.usage
import io.kotest.core.extensions.TestCaseExtension
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.sniffy.Sniffy
import io.sniffy.SniffyAssertionError
import io.sniffy.Spy
import io.sniffy.Threads
import io.sniffy.configuration.SniffyConfiguration
import io.sniffy.socket.TcpConnections
import io.sniffy.sql.SqlQueries
/**
* @since 3.1.7
*/
open class SniffyExtension(expectation: Spy.Expectation? = null) : TestCaseExtension {
private val spy: Spy<*> = Sniffy.spy<Spy<*>>()
init {
expectation.let {
spy.expect(it)
}
SniffyConfiguration.INSTANCE.isMonitorJdbc = true
SniffyConfiguration.INSTANCE.isMonitorSocket = true
SniffyConfiguration.INSTANCE.isMonitorNio = true
Sniffy.initialize()
}
fun expect(expectation: Spy.Expectation): SniffyExtension {
spy.expect(expectation)
return this
}
override suspend fun intercept(testCase: TestCase, execute: suspend (TestCase) -> TestResult): TestResult {
val testResult = execute.invoke(testCase)
try {
spy.verify()
} catch (e: SniffyAssertionError) {
return TestResult.failure(duration = testResult.duration, e = e)
}
return testResult
}
}
class NoSocketsAllowedExtension(threads: Threads = Threads.ANY) : SniffyExtension(TcpConnections.none().threads(threads))
class NoSqlExtension(threads: Threads = Threads.ANY) : SniffyExtension(SqlQueries.noneQueries().threads(threads))
| mit | 31f2e728a2924dd938f9203eac782e38 | 29.784314 | 121 | 0.711465 | 4.266304 | false | true | false | false |
vanniktech/Emoji | emoji-facebook/src/commonMain/kotlin/com/vanniktech/emoji/facebook/FacebookEmoji.kt | 1 | 2409 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić 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
*
* 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.vanniktech.emoji.facebook
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.IgnoredOnParcel
import com.vanniktech.emoji.Parcelable
import com.vanniktech.emoji.Parcelize
@Parcelize internal class FacebookEmoji internal constructor(
override val unicode: String,
override val shortcodes: List<String>,
internal val x: Int,
internal val y: Int,
override val isDuplicate: Boolean,
override val variants: List<FacebookEmoji> = emptyList(),
private var parent: FacebookEmoji? = null,
) : Emoji, Parcelable {
@IgnoredOnParcel override val base by lazy(LazyThreadSafetyMode.NONE) {
var result = this
while (result.parent != null) {
result = result.parent!!
}
result
}
init {
@Suppress("LeakingThis")
for (variant in variants) {
variant.parent = this
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FacebookEmoji
if (unicode != other.unicode) return false
if (shortcodes != other.shortcodes) return false
if (x != other.x) return false
if (y != other.y) return false
if (isDuplicate != other.isDuplicate) return false
if (variants != other.variants) return false
return true
}
override fun hashCode(): Int {
var result = unicode.hashCode()
result = 31 * result + shortcodes.hashCode()
result = 31 * result + x
result = 31 * result + y
result = 31 * result + isDuplicate.hashCode()
result = 31 * result + variants.hashCode()
return result
}
override fun toString(): String {
return "FacebookEmoji(unicode='$unicode', shortcodes=$shortcodes, x=$x, y=$y, isDuplicate=$isDuplicate, variants=$variants)"
}
}
| apache-2.0 | cfa7bb1343a851f153ea3973f5125130 | 30.25974 | 128 | 0.701288 | 4.25265 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/codec/vpx/VpxUtils.kt | 1 | 3488 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.codec.vpx
class VpxUtils {
companion object {
/**
* The bitmask for the TL0PICIDX field.
*/
const val TL0PICIDX_MASK = 0xff
/**
* The bitmask for the extended picture id field.
*/
const val EXTENDED_PICTURE_ID_MASK = 0x7fff
/**
* Returns the delta between two VP8/VP9 extended picture IDs, taking into account
* rollover. This will return the 'shortest' delta between the two
* picture IDs in the form of the number you'd add to b to get a. e.g.:
* getExtendedPictureIdDelta(1, 10) -> -9 (10 + -9 = 1)
* getExtendedPictureIdDelta(1, 32760) -> 9 (32760 + 9 = 1)
* @return the delta between two extended picture IDs (modulo 2^15).
*/
@JvmStatic
fun getExtendedPictureIdDelta(a: Int, b: Int): Int {
val diff = a - b
return when {
diff < -(1 shl 14) -> diff + (1 shl 15)
diff > (1 shl 14) -> diff - (1 shl 15)
else -> diff
}
}
/**
* Apply a delta to a given extended picture ID and return the result (taking
* rollover into account)
* @param start the starting extended picture ID
* @param delta the delta to be applied
* @return the extended picture ID resulting from doing "start + delta"
*/
@JvmStatic
fun applyExtendedPictureIdDelta(start: Int, delta: Int): Int =
(start + delta) and EXTENDED_PICTURE_ID_MASK
/**
* Returns the delta between two VP8/VP9 Tl0PicIdx values, taking into account
* rollover. This will return the 'shortest' delta between the two
* picture IDs in the form of the number you'd add to b to get a. e.g.:
* getTl0PicIdxDelta(1, 10) -> -9 (10 + -9 = 1)
* getTl0PicIdxDelta(1, 250) -> 7 (250 + 7 = 1)
*
* If either value is -1 (meaning tl0picidx not found) return 0.
* @return the delta between two extended picture IDs (modulo 2^8).
*/
@JvmStatic
fun getTl0PicIdxDelta(a: Int, b: Int): Int {
if (a < 0 || b < 0) return 0
val diff = a - b
return when {
diff < -(1 shl 7) -> diff + (1 shl 8)
diff > (1 shl 7) -> diff - (1 shl 8)
else -> diff
}
}
/**
* Apply a delta to a given Tl0PidIcx and return the result (taking
* rollover into account)
* @param start the starting Tl0PicIdx
* @param delta the delta to be applied
* @return the Tl0PicIdx resulting from doing "start + delta"
*/
@JvmStatic
fun applyTl0PicIdxDelta(start: Int, delta: Int): Int =
(start + delta) and TL0PICIDX_MASK
}
}
| apache-2.0 | 2fd54d687e168d5fb9bc7d3fd2f9d794 | 36.913043 | 90 | 0.572821 | 4.046404 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/SsrcAssociationStore.kt | 1 | 3579 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.util
import org.jitsi.nlj.rtp.SsrcAssociationType
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.NodeStatsProducer
import java.util.concurrent.CopyOnWriteArrayList
typealias SsrcAssociationHandler = (SsrcAssociation) -> Unit
class SsrcAssociationStore(
private val name: String = "SSRC Associations"
) : NodeStatsProducer {
private val ssrcAssociations: MutableList<SsrcAssociation> = CopyOnWriteArrayList()
/**
* The SSRC associations indexed by the primary SSRC. Since an SSRC may have
* multiple secondary SSRC mappings, the primary SSRC maps to a list of its
* SSRC associations
*/
private var ssrcAssociationsByPrimarySsrc = mapOf<Long, List<SsrcAssociation>>()
private var ssrcAssociationsBySecondarySsrc = mapOf<Long, SsrcAssociation>()
private val handlers: MutableList<SsrcAssociationHandler> = CopyOnWriteArrayList()
/**
* Each time an association is added, we want to invoke the handlers
* and each time a handler is added, want to invoke it with all existing
* associations. In order to make each of those operations a single,
* atomic operation, we use this lock to synchronize them.
*/
private val lock = Any()
fun addAssociation(ssrcAssociation: SsrcAssociation) {
synchronized(lock) {
ssrcAssociations.add(ssrcAssociation)
rebuildMaps()
handlers.forEach { it(ssrcAssociation) }
}
}
private fun rebuildMaps() {
ssrcAssociationsByPrimarySsrc = ssrcAssociations.groupBy(SsrcAssociation::primarySsrc)
ssrcAssociationsBySecondarySsrc = ssrcAssociations.associateBy(SsrcAssociation::secondarySsrc)
}
fun getPrimarySsrc(secondarySsrc: Long): Long? =
ssrcAssociationsBySecondarySsrc[secondarySsrc]?.primarySsrc
fun getSecondarySsrc(primarySsrc: Long, associationType: SsrcAssociationType): Long? =
ssrcAssociationsByPrimarySsrc[primarySsrc]?.find { it.type == associationType }?.secondarySsrc
/**
* When an SSRC has no associations at all (audio, for example), we consider it a
* 'primary' SSRC. So to perform this check we assume the given SSRC has been
* signalled and simply verify that it's *not* signaled as a secondary SSRC.
* Note that this may mean there is a slight window before the SSRC associations are
* processed during which we return true for an SSRC which will later be denoted
* as a secondary ssrc.
*/
fun isPrimarySsrc(ssrc: Long): Boolean {
return !ssrcAssociationsBySecondarySsrc.containsKey(ssrc)
}
fun onAssociation(handler: (SsrcAssociation) -> Unit) {
synchronized(lock) {
handlers.add(handler)
ssrcAssociations.forEach(handler)
}
}
override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock(name).apply {
addString("SSRC associations", ssrcAssociations.toString())
}
}
| apache-2.0 | 4ffd36c395a84b940b89df1c4fa5f88e | 39.213483 | 102 | 0.719754 | 4.759309 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/ui/screens/GameListScreen.kt | 1 | 44442 | package com.github.emulio.ui.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction
import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.Scaling
import com.badlogic.gdx.utils.Timer
import com.github.emulio.Emulio
import com.github.emulio.exceptions.ProcessCreationException
import com.github.emulio.model.Game
import com.github.emulio.model.Platform
import com.github.emulio.model.RomsMode
import com.github.emulio.model.RomsNaming
import com.github.emulio.model.config.DummyInputConfig
import com.github.emulio.model.config.InputConfig
import com.github.emulio.model.theme.*
import com.github.emulio.process.ProcessLauncher
import com.github.emulio.ui.input.InputListener
import com.github.emulio.ui.input.InputManager
import com.github.emulio.ui.screens.dialogs.InfoDialog
import com.github.emulio.ui.screens.keyboard.VirtualKeyboardDialog
import com.github.emulio.utils.DateHelper
import com.github.emulio.utils.translate
import mu.KotlinLogging
import java.io.File
import java.util.Stack
class GameListScreen(
emulio: Emulio,
val platform: Platform) : EmulioScreen(emulio), InputListener {
val logger = KotlinLogging.logger { }
private val inputController: InputManager = InputManager(this, emulio, stage)
private val interpolation = Interpolation.fade
private lateinit var items: List<Item>
private var selectedListItem: Item? = null
private lateinit var listView: GameList
private lateinit var listScrollPane: ScrollPane
private lateinit var descriptionScrollPane: ScrollPane
private lateinit var gameImage: Image
private lateinit var gameReleaseDate: TextField
private lateinit var gameDescription: Label
private lateinit var gamePlayCount: TextField
private lateinit var gameLastPlayed: TextField
private lateinit var gamePlayers: TextField
private lateinit var gameGenre: TextField
private lateinit var gamePublisher: TextField
private lateinit var gameDeveloper: TextField
private lateinit var root: Group
private lateinit var logo: Image
private lateinit var imageView: ViewImage
private lateinit var ratingImages: RatingImages
private lateinit var lastOpenedFolder: File
private var lastTimer: Timer.Task? = null
private var lastSequenceAction: SequenceAction? = null
private val folderStack = Stack<File>()
init {
Gdx.input.inputProcessor = inputController
prepareGamesList(emulio, findGames(emulio), true)
}
private fun prepareGamesList(emulio: Emulio,
games: List<Game>,
rootFolder: Boolean = false,
overrideFolder: File? = null) {
logger.info { "Preparing game list. (emulio instance: $emulio, games size: ${games.size}, folder: $rootFolder, override: $overrideFolder)" }
if (platform.romsMode == RomsMode.NORMAL) {
prepareGameListExpanded(games, rootFolder, overrideFolder)
} else if (platform.romsMode == RomsMode.FLAT) {
prepareGameListFlat(games)
}
initGUI()
selectedListItem = items.first()
updateGameSelected()
}
private fun prepareGameListFlat(games: List<Game>) {
games.forEach {
it.displayName = fetchGameName(it)
}
val sorted = games.sortedBy {
it.displayName!!.toLowerCase()
}
this.items = sorted.map {
GameItem(it)
}
}
private fun fetchGameName(it: Game): String {
if (it.displayName != null) {
return it.displayName!!
}
if (platform.romsNaming == RomsNaming.FOLDER) {
return it.path.parentFile.name
}
if (platform.romsNaming == RomsNaming.FIRST_FOLDER) {
val root = platform.romsPath
val path = findFirstPath(root, it.path)
return path.name
}
return it.displayName ?: it.name ?: it.path.name
}
private fun findFirstPath(rootFolder: File, path: File): File {
if (path.parentFile == rootFolder) {
return path
}
return findFirstPath(rootFolder, path.parentFile)
}
private fun prepareGameListExpanded(games: List<Game>, rootFolder: Boolean, overrideFolder: File?) {
logger.debug { "getting all absolute paths" }
val absolutePaths = games.map { it.path.parentFile.absoluteFile }
.toSortedSet(Comparator { file1, file2 -> file1.absolutePath.compareTo(file2.absolutePath) })
logger.debug { "filtering games" }
val filteredGames = if ((rootFolder && absolutePaths.size > 1) || overrideFolder != null) { // roms are coming from more than one main directory (subFolders)
val rootPath = overrideFolder ?: platform.romsPath
lastOpenedFolder = rootPath
val mergedGames = mutableListOf<Game>()
val folders = rootPath.listFiles()?.filter { it.isDirectory && !it.isHidden } ?: emptyList()
items = folders.map {
PathItem(it.name, it)
}.sortedBy {
it.displayName
}.filter { pathItem ->
val folder = pathItem.path
val found = games.find { game ->
val path = game.path
path.nameWithoutExtension == folder.nameWithoutExtension &&
path.parentFile.absolutePath == folder.absolutePath
}
if (found != null) {
mergedGames.add(found)
false
} else {
true
}
}
games.filter { game ->
game.path.parentFile.absolutePath == rootPath.absolutePath
} + mergedGames
} else {
items = emptyList()
games
}
val supportedExtensions = platform.romsExtensions
val gamesMap = mutableMapOf<String, Game>()
filteredGames.forEach { game ->
val nameWithoutExtension = game.path.nameWithoutExtension
val gameFound: Game? = gamesMap[nameWithoutExtension]
if (gameFound != null) {
if (gameFound.path.name != nameWithoutExtension) {
if (!gamesMap.containsKey(nameWithoutExtension)) {
gamesMap[nameWithoutExtension] = game
game.displayName = nameWithoutExtension
}
} else if (gameFound.path.name == nameWithoutExtension) {
val idxFound = supportedExtensions.indexOf(gameFound.path.extension)
val idxGame = supportedExtensions.indexOf(game.path.extension)
if (idxGame < idxFound) {
val key = game.name!!
gamesMap[nameWithoutExtension] = game
game.displayName = key
}
}
} else {
val key = game.name ?: game.path.name
game.displayName = key
if (!gamesMap.containsKey(nameWithoutExtension)) {
gamesMap[nameWithoutExtension] = game
}
}
}
logger.debug { "rootFolder: $rootFolder" }
val folders = if (folderStack.isEmpty()) {
items
} else {
listOf(PathUpItem) + items
}
this.items = folders + gamesMap.values.map {
it.displayName = fetchGameName(it)
it
}.sortedBy {
it.displayName!!.toLowerCase()
}.map {
GameItem(it)
}
}
private fun findGames(emulio: Emulio, customFilter: ((Game) -> Boolean)? = null): List<Game> {
return if (customFilter == null) {
emulio.games!![platform]?.toList() ?: emptyList()
} else {
(emulio.games!![platform]?.toList() ?: emptyList()).filter(customFilter)
}
}
private fun isBasicViewOnly(): Boolean {
return items.filterIsInstance<GameItem>().map { it.game }.none { it.id != null || it.description != null || it.image != null }
}
private var guiReady: Boolean = false
private fun initGUI() {
stage.clear()
val theme = emulio.theme[platform]!!
val basicViewOnly = isBasicViewOnly()
val view = theme.findView(if (basicViewOnly) "basic" else "detailed")!!
buildCommonComponents(view)
if (basicViewOnly) {
buildBasicView(view)
} else {
buildDetailedView(view)
}
}
override fun onScreenLoad() {
logger.debug { "onScreenLoad" }
guiReady = true
if (items.size > 1) {
listView.selectedIndex = 0
selectedListItem = items[0]
updateGameSelected()
}
}
private fun buildBasicView(basicView: View) {
gameListView = basicView.findViewItem("gamelist") as TextList
buildListScrollPane { buildListView() }
}
private var lastSelectedIndex: Int = -1
private fun buildListScrollPane(builder: () -> GameList) {
listView = builder()
listView.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val newIndex = listView.selectedIndex
if (lastSelectedIndex == newIndex) {
onConfirmButton(DummyInputConfig)
return
}
selectedListItem = items[newIndex]
updateGameSelected()
lastSelectedIndex = listView.selectedIndex
}
})
listScrollPane = ScrollPane(listView, ScrollPane.ScrollPaneStyle()).apply {
setFlickScroll(true)
setScrollBarPositions(false, true)
setScrollingDisabled(true, false)
setSmoothScrolling(true)
isTransform = true
setSize(gameListView)
setPosition(gameListView)
}
stage.addActor(listScrollPane)
}
private fun buildCommonComponents(view: View) {
val backgroundView = view.findViewItem("background") as ViewImage?
if (backgroundView != null) {
stage.addActor(buildImage(backgroundView).apply {
setScaling(Scaling.stretch)
setPosition(0f, 0f)
setSize(screenWidth, screenHeight)
})
} else {
val lightGrayTexture = createColorTexture(0xc5c6c7FF.toInt())
stage.addActor(Image(lightGrayTexture).apply {
setFillParent(true)
})
}
val footer = view.findViewItem("footer") as ViewImage?
val imgFooter: Image?
if (footer != null) {
imgFooter = buildImage(footer, Scaling.stretch)
stage.addActor(imgFooter)
} else {
imgFooter = null
}
val header = view.findViewItem("header") as ViewImage?
if (header != null) {
stage.addActor(buildImage(header, Scaling.stretch))
}
initRoot()
initLogoSmall()
val systemName1 = view.findViewItem("system_name_1")?.let { it as Text }
if (systemName1 != null) {
stage.addActor(buildTextField(systemName1))
}
val systemName2 = view.findViewItem("system_name_2")?.let { it as Text }
if (systemName2 != null) {
stage.addActor(buildTextField(systemName2))
}
val logo = view.findViewItem("logo") as ViewImage?
if (logo != null) {
val platformImage = buildImage(logo, Scaling.fit)
stage.addActor(platformImage)
}
val footerHeight: Float
val footerY: Float
if (imgFooter != null) {
footerHeight = imgFooter.height
footerY = imgFooter.y
} else {
footerHeight = 10f
footerY = 10f
}
initHelpHuds(footerY, footerHeight, HelpItems(
txtSelect = "Options".translate().toUpperCase(),
txtOptions = "Menu".translate().toUpperCase(),
txtCancel = "Back".translate().toUpperCase(),
txtConfirm = "Launch".translate().toUpperCase(),
txtLeftRight = "System".translate().toUpperCase(),
txtUpDown = "Choose".translate().toUpperCase(),
alpha = 0.9f,
txtColor = Color(0x666666FF)
))
}
private lateinit var gameListView: TextList
private fun buildDetailedView(detailedView: View) {
val descriptionView = detailedView.findViewItem("md_description") as Text?
if (descriptionView != null) {
gameDescription = buildLabel(descriptionView)
gameDescription.setWrap(true)
descriptionScrollPane = ScrollPane(gameDescription, ScrollPane.ScrollPaneStyle()).apply {
setFlickScroll(true)
setScrollBarPositions(false, true)
setSmoothScrolling(true)
setForceScroll(false, true)
isTransform = true
setSize(descriptionView)
setPosition(descriptionView)
}
stage.addActor(descriptionScrollPane)
}
gameListView = detailedView.findViewItem("gamelist") as TextList
buildListScrollPane { buildListView() }
val imageView = detailedView.findViewItem("md_image") as ViewImage?
if (imageView != null) {
gameImage = buildImage(imageView)
stage.addActor(gameImage)
this.imageView = imageView
}
val lbRating = buildLabel(detailedView, "md_lbl_rating", "Rating:")
buildLabel(detailedView, "md_lbl_releasedate", "Released:")
buildLabel(detailedView, "md_lbl_developer", "Developer:")
buildLabel(detailedView, "md_lbl_publisher", "Publisher:")
buildLabel(detailedView, "md_lbl_genre", "Genre:")
buildLabel(detailedView, "md_lbl_players", "Players:")
buildLabel(detailedView, "md_lbl_lastplayed", "Last played:")
buildLabel(detailedView, "md_lbl_playcount", "Times played:")
val playCountView = detailedView.findViewItem("md_playcount") as Text?
if (playCountView != null) {
gamePlayCount = buildTextField(playCountView)
stage.addActor(gamePlayCount)
}
val lastPlayedView = detailedView.findViewItem("md_lastplayed") as Text?
if (lastPlayedView != null) {
gameLastPlayed = buildTextField(lastPlayedView)
stage.addActor(gameLastPlayed)
}
val playersView = detailedView.findViewItem("md_players") as Text?
if (playersView != null) {
gamePlayers = buildTextField(playersView)
stage.addActor(gamePlayers)
}
val genreView = detailedView.findViewItem("md_genre") as Text?
if (genreView != null) {
gameGenre = buildTextField(genreView)
stage.addActor(gameGenre)
}
val publisherView = detailedView.findViewItem("md_publisher") as Text?
if (publisherView != null) {
gamePublisher = buildTextField(publisherView)
stage.addActor(gamePublisher)
}
val developerView = detailedView.findViewItem("md_developer") as Text?
if (developerView != null) {
gameDeveloper = buildTextField(developerView)
stage.addActor(gameDeveloper)
}
val releaseDateView = detailedView.findViewItem("md_releasedate") as Text?
if (releaseDateView != null) {
gameReleaseDate = buildTextField(releaseDateView)
stage.addActor(gameReleaseDate)
}
val ratingView = detailedView.findViewItem("md_rating") as Rating?
if (ratingView != null) {
buildRatingImages(ratingView, lbRating!!)
}
}
data class RatingImages(
val ratingImg1: Image,
val ratingImg2: Image,
val ratingImg3: Image,
val ratingImg4: Image,
val ratingImg5: Image,
val ratingUnFilledTexture: Texture,
val ratingFilledTexture: Texture,
val ratingColor: Color
)
private fun buildRatingImages(ratingView: Rating, lbRating: Label) {
val ratingTexture = buildTexture("images/resources/star_unfilled_128_128.png")
val ratingFilledTexture = buildTexture("images/resources/star_filled_128_128.png")
val ratingWidth = lbRating.height
val ratingHeight = lbRating.height
val ratingImg1 = Image(ratingTexture).apply {
setSize(ratingWidth, ratingHeight)
val (viewX, viewY) = getPosition(ratingView)
x = viewX
y = viewY + 6f
}
stage.addActor(ratingImg1)
val ratingImg2 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg1.x + ratingImg1.width, ratingImg1.y)
stage.addActor(ratingImg2)
val ratingImg3 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg2.x + ratingImg2.width, ratingImg1.y)
stage.addActor(ratingImg3)
val ratingImg4 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg3.x + ratingImg3.width, ratingImg1.y)
stage.addActor(ratingImg4)
val ratingImg5 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg4.x + ratingImg4.width, ratingImg1.y)
stage.addActor(ratingImg5)
val color = getColor(ratingView.color)
ratingImages = RatingImages(
ratingImg1,
ratingImg2,
ratingImg3,
ratingImg4,
ratingImg5,
ratingTexture,
ratingFilledTexture,
color
)
}
private fun buildLabel(detailedView: View, viewName: String, viewText: String): Label? {
val lbView = detailedView.findViewItem(viewName) as Text?
if (lbView != null) {
val lbl = buildLabel(lbView).apply {
setText(viewText)
}
stage.addActor(lbl)
return lbl
}
return null
}
private fun buildImage(image: ViewImage, scaling: Scaling = Scaling.fit, imagePath: File? = image.path): Image {
val texture = if (imagePath != null) {
Texture(FileHandle(imagePath), true)
} else {
val size = getSize(image)
createColorTexture(0xFFCC00FF.toInt(), size.first.toInt(), size.second.toInt())
}
texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap)
return Image(texture).apply {
setScaling(scaling)
setSize(image)
setPosition(image)
setOrigin(image)
setAlign(Align.left)
isVisible = imagePath != null
}
}
private fun buildTextField(textView: Text): TextField {
val text = if (textView.forceUpperCase) {
textView.text?.toUpperCase() ?: ""
} else {
textView.text ?: ""
}
val color = getColor(textView.textColor ?: textView.color)
return TextField(text, TextField.TextFieldStyle().apply {
font = getFont(getFontPath(textView), getFontSize(textView.fontSize), color)
fontColor = color
}).apply {
alignment = when(textView.alignment) {
TextAlignment.LEFT -> Align.left
TextAlignment.RIGHT -> Align.right
TextAlignment.CENTER -> Align.center
TextAlignment.JUSTIFY -> Align.left //TODO
}
setSize(textView)
setPosition(textView)
}
}
private fun buildLabel(textView: Text): Label {
val text = if (textView.forceUpperCase) {
textView.text?.toUpperCase() ?: ""
} else {
textView.text ?: ""
}
val lbColor = getColor(textView.textColor ?: textView.color)
val font = getFont(getFontPath(textView), getFontSize(textView.fontSize))
return Label(text, Label.LabelStyle(font, lbColor)).apply {
setAlignment(Align.topLeft)
setSize(textView)
setPosition(textView)
color = lbColor
}
}
private fun buildListView(): GameList {
return buildGameListView(gameListView, items)
}
class GameList(style: ListStyle?) : com.badlogic.gdx.scenes.scene2d.ui.List<Item>(style) {
override fun drawItem(batch: Batch, font: BitmapFont, index: Int, item: Item, x1: Float, y: Float, width: Float): GlyphLayout {
return drawText(item, x1, font, batch, y, width)
}
private fun drawText(item: Item, x1: Float, font: BitmapFont, batch: Batch, y: Float, width: Float): GlyphLayout {
val text = textOf(item)
val x = x1 + 5
return font.draw(batch, text, x, y, 0, text.length, width, Align.left, false, "...")
}
private fun drawWithIcon(item: Item, x1: Float, font: BitmapFont, batch: Batch, y: Float, width: Float): GlyphLayout {
val text = textOf(item)
val image = iconOf(item)
val x = x1 + 5
val lineHeight = font.lineHeight
val imgWidth = lineHeight - (lineHeight / 15)
val imgHeight = lineHeight - (lineHeight / 15)
val offsetY = (lineHeight / 5)
batch.draw(image, x, y - imgHeight + offsetY, imgWidth, imgHeight)
return font.draw(batch, text, x + imgWidth + 5, y, 0, text.length, width, Align.left, false, "...")
}
private fun iconOf(item: Item): Texture {
return when (item) {
is PathUpItem -> {
Texture("images/icons/folder-up.png")
}
is PathItem -> {
Texture("images/icons/folder.png")
}
is GameItem -> {
val extension = item.game.path.extension
if (setOf("7z", "zip", "rar", "ace", "jar", "tar", "gz", "bz2").contains(extension)) {
Texture("images/icons/file-rom-archive.png")
} else {
Texture("images/icons/file-rom-file.png")
}
}
else -> {
error("Invalid state")
}
}
}
private fun textOf(item: Item): String {
if (items.filter { it.displayName == item.displayName }.size > 1) {
return item.path.name
}
return item.displayName
}
}
private fun buildGameListView(gameListView: TextList, listItems: List<Item>): GameList {
return GameList(com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle().apply {
fontColorUnselected = getColor(gameListView.primaryColor)
fontColorSelected = getColor(gameListView.selectedColor)
font = getFont(getFontPath(gameListView), getFontSize(gameListView.fontSize))
val selectorTexture = createColorTexture(Integer.parseInt(gameListView.selectorColor + "FF", 16))
selection = TextureRegionDrawable(TextureRegion(selectorTexture))
}).apply {
setSize(gameListView)
listItems.forEach { listItem ->
items.add(listItem)
}
}
}
private fun Widget.setOrigin(viewItem: ViewItem) {
if (viewItem.originX != null && viewItem.originY != null) {
val originX = viewItem.originX!!
val originY = viewItem.originY!!
val offsetX = if (originX == 0f) {
0f
} else {
width * originX
}
val offsetY = when (originY) {
0f -> 0f
1f -> height
else -> height * (1f - viewItem.originY!!)
}
setOrigin(offsetX, offsetY)
x += offsetX
y += offsetY
}
}
private fun getSize(viewItem: ViewItem): Pair<Float, Float> {
var width = if (viewItem.sizeX != null) {
screenWidth * viewItem.sizeX!!
} else {
200f
}
var height = if (viewItem.sizeY != null) {
screenHeight * viewItem.sizeY!!
} else {
200f
}
if (viewItem.maxSizeX != null) {
width = width.coerceAtLeast(screenWidth * viewItem.maxSizeX!!)
}
if (viewItem.maxSizeY != null) {
height = height.coerceAtLeast(screenHeight * viewItem.maxSizeY!!)
}
return Pair(width, height)
}
private fun Actor.setSize(viewItem: ViewItem) {
var width = if (viewItem.sizeX != null) {
screenWidth * viewItem.sizeX!!
} else {
this.width
}
var height = if (viewItem.sizeY != null) {
screenHeight * viewItem.sizeY!!
} else {
this.height
}
if (viewItem.maxSizeX != null) {
width = width.coerceAtMost(screenWidth * viewItem.maxSizeX!!)
}
if (viewItem.maxSizeY != null) {
height = height.coerceAtMost(screenHeight * viewItem.maxSizeY!!)
}
setSize(width, height)
}
private fun Actor.setPosition(view: ViewItem) {
val (x, y) = getPosition(view)
setPosition(x, y)
}
private fun Actor.getPosition(view: ViewItem): Pair<Float, Float> {
val x = screenWidth * view.positionX!!
val y = (screenHeight * (1f - view.positionY!!)) - height
return Pair(x, y)
}
private fun getFontPath(textView: Text): FileHandle {
return if (textView.fontPath != null) {
FileHandle(textView.fontPath!!.absolutePath)
} else{
Gdx.files.internal("fonts/RopaSans-Regular.ttf")
}
}
private fun getFontSize(fontSize: Float?): Int {
return if (fontSize == null) {
90
} else {
(fontSize * screenHeight).toInt()
}
}
private fun initRoot() {
root = Group().apply {
width = screenWidth
height = screenHeight
x = 0f
y = 0f
}
stage.addActor(root)
}
private fun initLogoSmall() {
logo = Image(Texture("images/logo-small.png")).apply {
x = screenWidth
y = (height / 2) - 5f
addAction(Actions.moveTo(screenWidth - width - 15f, y, 0.5f, interpolation))
}
root.addActor(logo)
}
override fun hide() {
}
override fun render(delta: Float) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act(Gdx.graphics.deltaTime.coerceAtMost(1 / 30f))
stage.draw()
inputController.update(delta)
}
override fun pause() {
}
override fun resume() {
}
override fun resize(width: Int, height: Int) {
}
override fun release() {
inputController.dispose()
}
private fun launchGame() {
if (listView.selectedIndex == -1) {
error("No game was selected")
}
val selectedListItem = selectedListItem!!
if (selectedListItem is PathItem) {
return
}
check(selectedListItem is GameItem)
val path = selectedListItem.game.path
logger.info { "launchGame: ${path.name}" }
val command = platform.runCommand.map {
when {
it.contains("%ROM_RAW%") ->
it.replace("%ROM_RAW%", path.absolutePath)
it.contains("%ROM%") ->
it.replace("%ROM%", path.absolutePath) //TODO check EmulationStation documentation
it.contains("%BASENAME%") ->
it.replace("%BASENAME%", path.nameWithoutExtension)
else -> it
}
}
emulio.options.minimizeApplication()
try {
ProcessLauncher.executeProcess(command.toTypedArray())
} catch (ex: ProcessCreationException) {
showErrorDialog("There was a problem launching this game. Check your config".translate())
}
emulio.options.restoreApplication()
}
private fun selectNext(amount: Int = 1) {
val nextIndex = listView.selectedIndex + amount
if (amount < 0) {
if (nextIndex < 0) {
listView.selectedIndex = listView.items.size + amount
} else {
listView.selectedIndex = nextIndex
}
}
if (amount > 0) {
if (nextIndex >= listView.items.size) {
listView.selectedIndex = 0
} else {
listView.selectedIndex = nextIndex
}
}
val list = items
selectedListItem = list[listView.selectedIndex]
updateGameSelected()
checkVisible(nextIndex)
}
private fun updateGameSelected() {
lastTimer?.cancel()
lastSequenceAction?.reset()
val selectedListItem = selectedListItem
logger.debug { if (selectedListItem != null) { "updateGameSelected [${selectedListItem.displayName}] [${selectedListItem.path.name}]" } else { "no game" } }
if (isBasicViewOnly()) {
logger.trace { "basic view only, ignore update game selected" }
return
}
if (selectedListItem == null || selectedListItem is PathItem) {
logger.trace { "no selected list item, clearing info" }
clearDetailedView()
return
}
check(selectedListItem is GameItem)
val game = selectedListItem.game
val hasImage = game.image != null && game.image.isFile
val texture = if (hasImage) {
Texture(FileHandle(game.image), true)
} else {
Texture(0, 0, Pixmap.Format.RGB888)
}
texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap)
gameImage.drawable = TextureRegionDrawable(TextureRegion(texture))
gameImage.isVisible = hasImage
gameReleaseDate.text = safeValue(if (game.releaseDate != null) {
DateHelper.format(game.releaseDate)
} else {
null
})
gameDeveloper.text = safeValue(game.developer)
gamePlayCount.text = "0"
gameLastPlayed.text = "Never"
gamePlayers.text = safeValue(game.players)
gameGenre.text = safeValue(game.genre)
gamePublisher.text = safeValue(game.publisher)
gameDeveloper.text = safeValue(game.developer)
descriptionScrollPane.scrollY = 0f
gameDescription.setText(safeValue(game.description, ""))
val gameRating = game.rating
if (gameRating != null) {
val rating = game.rating
ratingImages.apply {
ratingImg1.drawable = if (rating > 0.05) {
TextureRegionDrawable(TextureRegion(ratingFilledTexture))
} else {
TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
}
ratingImg2.drawable = if (rating > 0.25) {
TextureRegionDrawable(TextureRegion(ratingFilledTexture))
} else {
TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
}
ratingImg3.drawable = if (rating > 0.45) {
TextureRegionDrawable(TextureRegion(ratingFilledTexture))
} else {
TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
}
ratingImg4.drawable = if (rating > 0.65) {
TextureRegionDrawable(TextureRegion(ratingFilledTexture))
} else {
TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
}
ratingImg5.drawable = if (rating > 0.90) {
TextureRegionDrawable(TextureRegion(ratingFilledTexture))
} else {
TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
}
ratingImg1.color = ratingColor
ratingImg2.color = ratingColor
ratingImg3.color = ratingColor
ratingImg4.color = ratingColor
ratingImg5.color = ratingColor
}
} else {
ratingImages.apply {
ratingImg1.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
ratingImg2.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
ratingImg3.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
ratingImg4.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
ratingImg5.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture))
ratingImg1.color = ratingColor
ratingImg2.color = ratingColor
ratingImg3.color = ratingColor
ratingImg4.color = ratingColor
ratingImg5.color = ratingColor
}
}
animateDescription()
}
private fun clearDetailedView() {
gameImage.isVisible = false
ratingImages.apply {
ratingImg1.color = Color.CLEAR
ratingImg2.color = Color.CLEAR
ratingImg3.color = Color.CLEAR
ratingImg4.color = Color.CLEAR
ratingImg5.color = Color.CLEAR
}
gameDeveloper.text = ""
gamePlayCount.text = ""
gameLastPlayed.text = ""
gamePlayers.text = ""
gameGenre.text = ""
gamePublisher.text = ""
gameDeveloper.text = ""
gameReleaseDate.text = ""
gameDescription.setText("")
}
private fun animateDescription() {
lastTimer = Timer.schedule(object : Timer.Task() {
override fun run() {
if (gameDescription.height <= descriptionScrollPane.height) {
return
}
val scrollAmount = gameDescription.height - descriptionScrollPane.height
val actionTime = scrollAmount * 0.05f
val sequenceAction = SequenceAction(
ScrollByAction(0f, scrollAmount, actionTime),
Actions.delay(2f),
ScrollByAction(0f, -scrollAmount, actionTime)
)
lastSequenceAction = sequenceAction
descriptionScrollPane.addAction(sequenceAction)
}
}, 2.5f)
}
private fun safeValue(string: String?, defaultText: String = "Unknown"): String {
return string?.trim() ?: defaultText
}
private fun checkVisible(index: Int) {
val itemHeight = listView.itemHeight
val selectionY = index * itemHeight
val selectionY2 = selectionY + itemHeight
val minItemsVisible = itemHeight * 5
val itemsPerView = listScrollPane.height / itemHeight
val gamesList = items
if (listView.selectedIndex > (gamesList.size - itemsPerView)) {
listScrollPane.scrollY = listView.height - listScrollPane.height
return
}
if (listView.selectedIndex == 0) {
listScrollPane.scrollY = 0f
return
}
if ((selectionY2 + minItemsVisible) > listScrollPane.height) {
listScrollPane.scrollY = (selectionY2 - listScrollPane.height) + minItemsVisible
}
val minScrollY = (selectionY - minItemsVisible).coerceAtLeast(0f)
if (minScrollY < listScrollPane.scrollY) {
listScrollPane.scrollY = minScrollY
}
}
override fun buildImage(imgPath: String, imgWidth: Float, imgHeight: Float, x: Float, y: Float): Image {
return buildImage(buildTexture(imgPath), imgWidth, imgHeight, x, y)
}
private fun buildImage(texture: Texture, imgWidth: Float, imgHeight: Float, x: Float, y: Float): Image {
val imgButtonStart = Image(texture)
imgButtonStart.setSize(imgWidth, imgHeight)
imgButtonStart.x = x
imgButtonStart.y = y
return imgButtonStart
}
private fun buildTexture(imgPath: String): Texture {
return Texture(Gdx.files.internal(imgPath), true).apply {
setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap)
}
}
override fun onConfirmButton(input: InputConfig) {
updateHelp()
if (!guiReady) return
val selectedListItem = selectedListItem ?: return
when (selectedListItem) {
is PathUpItem -> {
goUpDir()
}
is PathItem -> {
val selectedFolder = selectedListItem.path
folderStack.push(selectedFolder.parentFile)
val found = findGames(emulio) { game ->
game.path.parentFile == selectedFolder
}
val hasSubFolders = selectedFolder.listFiles()!!.any { it.isDirectory }
if (found.isEmpty() && !hasSubFolders) {
showInfoDialog("No games found in this folder.")
folderStack.pop()
return
}
reloadGameListOnFolder(selectedFolder)
listView.selectedIndex = 0
this.selectedListItem = items[0]
}
else -> {
launchGame()
}
}
}
private fun reloadGameListOnFolder(folder: File) {
prepareGamesList(emulio, findGames(emulio), false, folder)
}
override fun onCancelButton(input: InputConfig) {
updateHelp()
if (!guiReady) return
if (folderStack.isEmpty()) {
switchScreen(PlatformsScreen(emulio, platform))
} else {
goUpDir()
}
}
private fun goUpDir() {
val lastOpenedFolder = lastOpenedFolder
reloadGameListOnFolder(folderStack.pop())
val index = 0.coerceAtLeast(
items.indexOf(
items.find { it.path.absolutePath == lastOpenedFolder.absolutePath }
)
)
listView.selectedIndex = index
selectedListItem = items[index]
}
override fun onUpButton(input: InputConfig) {
updateHelp()
if (!guiReady) return
selectNext(-1)
}
override fun onDownButton(input: InputConfig) {
updateHelp()
logger.debug { "onDownButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
selectNext()
}
override fun onLeftButton(input: InputConfig) {
updateHelp()
logger.debug { "onLeftButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
val platforms = emulio.platforms
val index = platforms.indexOf(platform)
val previousPlatform = if (index > 0) {
index - 1
} else {
platforms.size - 1
}
switchScreen(GameListScreen(emulio, platforms[previousPlatform]))
}
override fun onRightButton(input: InputConfig) {
updateHelp()
logger.debug { "onRightButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
val platforms = emulio.platforms
val index = platforms.indexOf(platform)
val previousPlatform = if (index > platforms.size - 2) {
0
} else {
index + 1
}
switchScreen(GameListScreen(emulio, platforms[previousPlatform]))
}
override fun onFindButton(input: InputConfig) {
updateHelp()
logger.debug { "onFindButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
VirtualKeyboardDialog("Search", "Message", emulio, stage) { text ->
handleSearch(filterByText(text))
}.show(stage)
}
override fun onOptionsButton(input: InputConfig) {
updateHelp()
Gdx.app.postRunnable {
showMainMenu {
GameListScreen(emulio, platform)
}
}
}
override fun onSelectButton(input: InputConfig) {
updateHelp()
logger.debug { "onSelectButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
Gdx.app.postRunnable {
showOptionsMenu { response ->
val searchDialogText = response.searchDialogText
val jumpToLetter = response.jumpToLetter
if (searchDialogText != null) {
handleSearch(filterByText(searchDialogText))
} else if (jumpToLetter != null) {
handleSearch(filterByLetter(jumpToLetter))
}
}
}
}
private fun filterByLetter(jumpToLetter: Char): (Game) -> Boolean {
return { game ->
val displayName = game.displayName
val name = game.name
val containsName = name?.toLowerCase()?.startsWith(jumpToLetter.toLowerCase()) ?: false
val containsDisplayName = displayName?.toLowerCase()?.startsWith(jumpToLetter.toLowerCase()) ?: false
containsName || containsDisplayName
}
}
private fun filterByText(searchDialogText: String): (Game) -> Boolean {
return { game ->
val displayName = game.displayName
val name = game.name
val containsName = name?.toLowerCase()?.contains(searchDialogText) ?: false
val containsDisplayName = displayName?.toLowerCase()?.contains(searchDialogText) ?: false
containsName || containsDisplayName
}
}
private fun handleSearch(customFilter: ((Game) -> Boolean)?) {
val gamesFound = findGames(emulio, customFilter)
if (gamesFound.isNotEmpty()) {
stage.actors.clear()
prepareGamesList(emulio, gamesFound)
selectNext(1)
} else {
Gdx.app.postRunnable {
InfoDialog(
"No games found".translate(),
"No games found, please change your criteria.".translate(),
emulio).show(stage)
}
}
}
override fun onPageUpButton(input: InputConfig) {
updateHelp()
logger.debug { "onPageUpButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
selectNext(-10)
}
override fun onPageDownButton(input: InputConfig) {
updateHelp()
logger.debug { "onPageDownButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" }
if (!guiReady) return
selectNext(10)
}
override fun onExitButton(input: InputConfig) {
updateHelp()
if (!guiReady) return
showCloseDialog()
}
}
class ScrollByAction(private val endScrollX: Float, private val endScrollY: Float, duration: Float) : TemporalAction(duration) {
private lateinit var scrollPane: ScrollPane
private var startScrollX: Float = -1f
private var startScrollY: Float = -1f
override fun begin() {
scrollPane = target as ScrollPane
startScrollX = scrollPane.scrollX
startScrollY = scrollPane.scrollY
}
override fun update(percent: Float) {
scrollPane.scrollX = startScrollX + (endScrollX - startScrollX) * percent
scrollPane.scrollY = startScrollY + (endScrollY - startScrollY) * percent
}
}
open class Item(val displayName: String, val path: File)
class GameItem(val game: Game) : Item(game.displayName ?: game.name ?: game.path.name, game.path)
open class PathItem(displayName: String, path: File) : Item(displayName, path)
object PathUpItem : PathItem("..", File("up file")) | gpl-3.0 | 0fd312a44cea246318193c89ff9b67db | 31.322182 | 165 | 0.59815 | 4.852806 | false | false | false | false |
SimonMarquis/FCM-toolbox | app/src/main/java/fr/smarquis/fcm/data/db/AppDatabase.kt | 1 | 1628 | package fr.smarquis.fcm.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import fr.smarquis.fcm.data.db.AppDatabase.MapConverter
import fr.smarquis.fcm.data.db.AppDatabase.PayloadConverter
import fr.smarquis.fcm.data.model.Message
import fr.smarquis.fcm.data.model.Payload
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
@Database(entities = [Message::class], version = 1)
@TypeConverters(value = [MapConverter::class, PayloadConverter::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun dao(): MessageDao
object PayloadConverter : KoinComponent {
private val moshi by inject<Moshi>()
private val adapter = moshi.adapter(Payload::class.java)
@TypeConverter
@JvmStatic
fun fromJson(data: String): Payload? = adapter.fromJson(data)
@TypeConverter
@JvmStatic
fun toJson(payload: Payload?): String = adapter.toJson(payload)
}
object MapConverter : KoinComponent {
private val moshi by inject<Moshi>()
private val adapter = moshi.adapter<Map<String, String>>(Types.newParameterizedType(Map::class.java, String::class.java, String::class.java))
@TypeConverter
@JvmStatic
fun stringToMap(data: String): Map<String, String> = adapter.fromJson(data).orEmpty()
@TypeConverter
@JvmStatic
fun mapToString(map: Map<String, String>?): String = adapter.toJson(map)
}
}
| apache-2.0 | 889fb9c0d6d8598aedc6635066f8a355 | 28.6 | 149 | 0.72113 | 4.318302 | false | false | false | false |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/AudioActivity.kt | 1 | 2973 | package com.jiangkang.ktools
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.OnInitListener
import android.text.TextUtils
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.jiangkang.annotations.Safe
import com.jiangkang.ktools.audio.VoiceBroadcastReceiver
import com.jiangkang.ktools.databinding.ActivityAudioBinding
import com.jiangkang.tools.utils.ToastUtils
import java.util.*
/**
* @author jiangkang
*/
class AudioActivity : AppCompatActivity() {
private lateinit var binding:ActivityAudioBinding
private val etTextContent: EditText by lazy { findViewById<EditText>(R.id.et_text_content) }
private var onInitListener: OnInitListener? = null
private var speech: TextToSpeech? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAudioBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnTextToSpeech.setOnClickListener {
onBtnTextToSpeechClicked()
}
binding.btnPlaySingleSound.setOnClickListener {
onBtnPlaySingleSoundClicked()
}
binding.btnPlayMultiSounds.setOnClickListener {
onBtnPlayMultiSoundsClicked()
}
}
override fun onDestroy() {
super.onDestroy()
if (speech != null) {
speech!!.shutdown()
}
}
private fun onBtnTextToSpeechClicked() {
onInitListener = OnInitListener { status ->
if (status == TextToSpeech.SUCCESS) {
val result = speech!!.setLanguage(Locale.ENGLISH)
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
ToastUtils.showShortToast("语言不支持")
} else {
var content = "This is a default voice"
if (!TextUtils.isEmpty(etTextContent.text.toString())) {
content = etTextContent.text.toString()
}
speech!!.speak(content, TextToSpeech.QUEUE_FLUSH, null, null)
}
}
}
speech = TextToSpeech(this, onInitListener)
}
@Safe
fun onBtnPlaySingleSoundClicked() {
val player = MediaPlayer.create(this, R.raw.tts_success)
player.start()
}
private fun onBtnPlayMultiSoundsClicked() {
sendBroadcast(Intent(this, VoiceBroadcastReceiver::class.java))
}
companion object {
fun launch(context: Context, bundle: Bundle?) {
val intent = Intent(context, AudioActivity::class.java)
if (bundle != null) {
intent.putExtras(bundle)
}
context.startActivity(intent)
}
}
}
| mit | 159ae81a0740ff3ab9f10c8a3e05f7fe | 30.860215 | 96 | 0.643604 | 4.963149 | false | false | false | false |
Dreamersoul/FastHub | app/src/main/java/com/fastaccess/provider/theme/ThemeEngine.kt | 1 | 15804 | package com.fastaccess.provider.theme
import android.app.Activity
import android.app.ActivityManager
import android.graphics.BitmapFactory
import android.support.annotation.StyleRes
import com.danielstone.materialaboutlibrary.MaterialAboutActivity
import com.fastaccess.R
import com.fastaccess.helper.Logger
import com.fastaccess.helper.PrefGetter
import com.fastaccess.helper.ViewHelper
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.modules.login.LoginActivity
import com.fastaccess.ui.modules.login.chooser.LoginChooserActivity
import com.fastaccess.ui.modules.main.donation.DonateActivity
import com.fastaccess.ui.modules.reviews.changes.ReviewChangesActivity
/**
* Created by Kosh on 07 Jun 2017, 6:52 PM
*/
object ThemeEngine {
fun apply(activity: BaseActivity<*, *>) {
if (hasTheme(activity)) {
return
}
val themeMode = PrefGetter.getThemeType(activity)
val themeColor = PrefGetter.getThemeColor(activity)
activity.setTheme(getTheme(themeMode, themeColor))
setTaskDescription(activity)
applyNavBarColor(activity)
}
private fun applyNavBarColor(activity: Activity) {
if (!PrefGetter.isNavBarTintingDisabled() && PrefGetter.getThemeType() != PrefGetter.LIGHT) {
activity.window.navigationBarColor = ViewHelper.getPrimaryColor(activity)
}
}
fun applyForAbout(activity: MaterialAboutActivity) {
val themeMode = PrefGetter.getThemeType(activity)
when (themeMode) {
PrefGetter.LIGHT -> activity.setTheme(R.style.AppTheme_AboutActivity_Light)
PrefGetter.DARK -> activity.setTheme(R.style.AppTheme_AboutActivity_Dark)
PrefGetter.AMLOD -> activity.setTheme(R.style.AppTheme_AboutActivity_Amlod)
PrefGetter.MID_NIGHT_BLUE -> activity.setTheme(R.style.AppTheme_AboutActivity_MidNightBlue)
PrefGetter.BLUISH -> activity.setTheme(R.style.AppTheme_AboutActivity_Bluish)
}
setTaskDescription(activity)
}
fun applyDialogTheme(activity: BaseActivity<*, *>) {
val themeMode = PrefGetter.getThemeType(activity)
val themeColor = PrefGetter.getThemeColor(activity)
activity.setTheme(getDialogTheme(themeMode, themeColor))
setTaskDescription(activity)
}
@StyleRes fun getTheme(themeMode: Int, themeColor: Int): Int {
Logger.e(themeMode, themeColor)
// I wish if I could simplify this :'( too many cases for the love of god.
when (themeMode) {
PrefGetter.LIGHT -> when (themeColor) {
PrefGetter.RED -> return R.style.ThemeLight_Red
PrefGetter.PINK -> return R.style.ThemeLight_Pink
PrefGetter.PURPLE -> return R.style.ThemeLight_Purple
PrefGetter.DEEP_PURPLE -> return R.style.ThemeLight_DeepPurple
PrefGetter.INDIGO -> return R.style.ThemeLight_Indigo
PrefGetter.BLUE -> return R.style.ThemeLight
PrefGetter.LIGHT_BLUE -> return R.style.ThemeLight_LightBlue
PrefGetter.CYAN -> return R.style.ThemeLight_Cyan
PrefGetter.TEAL -> return R.style.ThemeLight_Teal
PrefGetter.GREEN -> return R.style.ThemeLight_Green
PrefGetter.LIGHT_GREEN -> return R.style.ThemeLight_LightGreen
PrefGetter.LIME -> return R.style.ThemeLight_Lime
PrefGetter.YELLOW -> return R.style.ThemeLight_Yellow
PrefGetter.AMBER -> return R.style.ThemeLight_Amber
PrefGetter.ORANGE -> return R.style.ThemeLight_Orange
PrefGetter.DEEP_ORANGE -> return R.style.ThemeLight_DeepOrange
else -> return R.style.ThemeLight
}
PrefGetter.DARK -> when (themeColor) {
PrefGetter.RED -> return R.style.ThemeDark_Red
PrefGetter.PINK -> return R.style.ThemeDark_Pink
PrefGetter.PURPLE -> return R.style.ThemeDark_Purple
PrefGetter.DEEP_PURPLE -> return R.style.ThemeDark_DeepPurple
PrefGetter.INDIGO -> return R.style.ThemeDark_Indigo
PrefGetter.BLUE -> return R.style.ThemeDark
PrefGetter.LIGHT_BLUE -> return R.style.ThemeDark_LightBlue
PrefGetter.CYAN -> return R.style.ThemeDark_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeDark_Green
PrefGetter.LIGHT_GREEN -> return R.style.ThemeDark_LightGreen
PrefGetter.LIME -> return R.style.ThemeDark_Lime
PrefGetter.YELLOW -> return R.style.ThemeDark_Yellow
PrefGetter.AMBER -> return R.style.ThemeDark_Amber
PrefGetter.ORANGE -> return R.style.ThemeDark_Orange
PrefGetter.DEEP_ORANGE -> return R.style.ThemeDark_DeepOrange
else -> return R.style.ThemeDark
}
PrefGetter.AMLOD -> when (themeColor) {
PrefGetter.RED -> return R.style.ThemeAmlod_Red
PrefGetter.PINK -> return R.style.ThemeAmlod_Pink
PrefGetter.PURPLE -> return R.style.ThemeAmlod_Purple
PrefGetter.DEEP_PURPLE -> return R.style.ThemeAmlod_DeepPurple
PrefGetter.INDIGO -> return R.style.ThemeAmlod_Indigo
PrefGetter.BLUE -> return R.style.ThemeAmlod
PrefGetter.LIGHT_BLUE -> return R.style.ThemeAmlod_LightBlue
PrefGetter.CYAN -> return R.style.ThemeAmlod_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeAmlod_Green
PrefGetter.LIGHT_GREEN -> return R.style.ThemeAmlod_LightGreen
PrefGetter.LIME -> return R.style.ThemeAmlod_Lime
PrefGetter.YELLOW -> return R.style.ThemeAmlod_Yellow
PrefGetter.AMBER -> return R.style.ThemeAmlod_Amber
PrefGetter.ORANGE -> return R.style.ThemeAmlod_Orange
PrefGetter.DEEP_ORANGE -> return R.style.ThemeAmlod_DeepOrange
else -> return R.style.ThemeAmlod
}
PrefGetter.MID_NIGHT_BLUE -> when (themeColor) {
PrefGetter.RED -> return R.style.ThemeMidNighBlue_Red
PrefGetter.PINK -> return R.style.ThemeMidNighBlue_Pink
PrefGetter.PURPLE -> return R.style.ThemeMidNighBlue_Purple
PrefGetter.DEEP_PURPLE -> return R.style.ThemeMidNighBlue_DeepPurple
PrefGetter.INDIGO -> return R.style.ThemeMidNighBlue_Indigo
PrefGetter.BLUE -> return R.style.ThemeMidNighBlue
PrefGetter.LIGHT_BLUE -> return R.style.ThemeMidNighBlue_LightBlue
PrefGetter.CYAN -> return R.style.ThemeMidNighBlue_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeMidNighBlue_Green
PrefGetter.LIGHT_GREEN -> return R.style.ThemeMidNighBlue_LightGreen
PrefGetter.LIME -> return R.style.ThemeMidNighBlue_Lime
PrefGetter.YELLOW -> return R.style.ThemeMidNighBlue_Yellow
PrefGetter.AMBER -> return R.style.ThemeMidNighBlue_Amber
PrefGetter.ORANGE -> return R.style.ThemeMidNighBlue_Orange
PrefGetter.DEEP_ORANGE -> return R.style.ThemeMidNighBlue_DeepOrange
else -> return R.style.ThemeMidNighBlue
}
PrefGetter.BLUISH -> when (themeColor) {
PrefGetter.RED -> return R.style.ThemeBluish_Red
PrefGetter.PINK -> return R.style.ThemeBluish_Pink
PrefGetter.PURPLE -> return R.style.ThemeBluish_Purple
PrefGetter.DEEP_PURPLE -> return R.style.ThemeBluish_DeepPurple
PrefGetter.INDIGO -> return R.style.ThemeBluish_Indigo
PrefGetter.BLUE -> return R.style.ThemeBluish
PrefGetter.LIGHT_BLUE -> return R.style.ThemeBluish_LightBlue
PrefGetter.CYAN -> return R.style.ThemeBluish_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeBluish_Green
PrefGetter.LIGHT_GREEN -> return R.style.ThemeBluish_LightGreen
PrefGetter.LIME -> return R.style.ThemeBluish_Lime
PrefGetter.YELLOW -> return R.style.ThemeBluish_Yellow
PrefGetter.AMBER -> return R.style.ThemeBluish_Amber
PrefGetter.ORANGE -> return R.style.ThemeBluish_Orange
PrefGetter.DEEP_ORANGE -> return R.style.ThemeBluish_DeepOrange
else -> return R.style.ThemeBluish
}
}
return R.style.ThemeLight
}
@StyleRes fun getDialogTheme(themeMode: Int, themeColor: Int): Int {
when (themeMode) {
PrefGetter.LIGHT -> when (themeColor) {
PrefGetter.RED -> return R.style.DialogThemeLight_Red
PrefGetter.PINK -> return R.style.DialogThemeLight_Pink
PrefGetter.PURPLE -> return R.style.DialogThemeLight_Purple
PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeLight_DeepPurple
PrefGetter.INDIGO -> return R.style.DialogThemeLight_Indigo
PrefGetter.BLUE -> return R.style.DialogThemeLight
PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeLight_LightBlue
PrefGetter.CYAN -> return R.style.DialogThemeLight_Cyan
PrefGetter.TEAL -> return R.style.DialogThemeLight_Teal
PrefGetter.GREEN -> return R.style.DialogThemeLight_Green
PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeLight_LightGreen
PrefGetter.LIME -> return R.style.DialogThemeLight_Lime
PrefGetter.YELLOW -> return R.style.DialogThemeLight_Yellow
PrefGetter.AMBER -> return R.style.DialogThemeLight_Amber
PrefGetter.ORANGE -> return R.style.DialogThemeLight_Orange
PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeLight_DeepOrange
else -> return R.style.DialogThemeLight
}
PrefGetter.DARK -> when (themeColor) {
PrefGetter.RED -> return R.style.DialogThemeDark_Red
PrefGetter.PINK -> return R.style.DialogThemeDark_Pink
PrefGetter.PURPLE -> return R.style.DialogThemeDark_Purple
PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeDark_DeepPurple
PrefGetter.INDIGO -> return R.style.DialogThemeDark_Indigo
PrefGetter.BLUE -> return R.style.DialogThemeDark
PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeDark_LightBlue
PrefGetter.CYAN -> return R.style.DialogThemeDark_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeDark_Green
PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeDark_LightGreen
PrefGetter.LIME -> return R.style.DialogThemeDark_Lime
PrefGetter.YELLOW -> return R.style.DialogThemeDark_Yellow
PrefGetter.AMBER -> return R.style.DialogThemeDark_Amber
PrefGetter.ORANGE -> return R.style.DialogThemeDark_Orange
PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeDark_DeepOrange
else -> return R.style.DialogThemeDark
}
PrefGetter.AMLOD -> when (themeColor) {
PrefGetter.RED -> return R.style.DialogThemeAmlod_Red
PrefGetter.PINK -> return R.style.DialogThemeAmlod_Pink
PrefGetter.PURPLE -> return R.style.DialogThemeAmlod_Purple
PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeAmlod_DeepPurple
PrefGetter.INDIGO -> return R.style.DialogThemeAmlod_Indigo
PrefGetter.BLUE -> return R.style.DialogThemeAmlod
PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeAmlod_LightBlue
PrefGetter.CYAN -> return R.style.DialogThemeAmlod_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeAmlod_Green
PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeAmlod_LightGreen
PrefGetter.LIME -> return R.style.DialogThemeAmlod_Lime
PrefGetter.YELLOW -> return R.style.DialogThemeAmlod_Yellow
PrefGetter.AMBER -> return R.style.DialogThemeAmlod_Amber
PrefGetter.ORANGE -> return R.style.DialogThemeAmlod_Orange
PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeAmlod_DeepOrange
else -> return R.style.DialogThemeAmlod
}
PrefGetter.MID_NIGHT_BLUE -> when (themeColor) {
PrefGetter.RED -> return R.style.DialogThemeLight_Red
PrefGetter.PINK -> return R.style.DialogThemeLight_Pink
PrefGetter.PURPLE -> return R.style.DialogThemeLight_Purple
PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeLight_DeepPurple
PrefGetter.INDIGO -> return R.style.DialogThemeLight_Indigo
PrefGetter.BLUE -> return R.style.DialogThemeLight
PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeLight_LightBlue
PrefGetter.CYAN -> return R.style.DialogThemeLight_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeLight_Green
PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeLight_LightGreen
PrefGetter.LIME -> return R.style.DialogThemeLight_Lime
PrefGetter.YELLOW -> return R.style.DialogThemeLight_Yellow
PrefGetter.AMBER -> return R.style.DialogThemeLight_Amber
PrefGetter.ORANGE -> return R.style.DialogThemeLight_Orange
PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeLight_DeepOrange
else -> return R.style.DialogThemeLight
}
PrefGetter.BLUISH -> when (themeColor) {
PrefGetter.RED -> return R.style.DialogThemeBluish_Red
PrefGetter.PINK -> return R.style.DialogThemeBluish_Pink
PrefGetter.PURPLE -> return R.style.DialogThemeBluish_Purple
PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeBluish_DeepPurple
PrefGetter.INDIGO -> return R.style.DialogThemeBluish_Indigo
PrefGetter.BLUE -> return R.style.DialogThemeBluish
PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeBluish_LightBlue
PrefGetter.CYAN -> return R.style.DialogThemeBluish_Cyan
PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeBluish_Green
PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeBluish_LightGreen
PrefGetter.LIME -> return R.style.DialogThemeBluish_Lime
PrefGetter.YELLOW -> return R.style.DialogThemeBluish_Yellow
PrefGetter.AMBER -> return R.style.DialogThemeBluish_Amber
PrefGetter.ORANGE -> return R.style.DialogThemeBluish_Orange
PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeBluish_DeepOrange
else -> return R.style.DialogThemeBluish
}
}
return R.style.DialogThemeLight
}
private fun setTaskDescription(activity: Activity) {
activity.setTaskDescription(ActivityManager.TaskDescription(activity.getString(R.string.app_name),
BitmapFactory.decodeResource(activity.resources, R.mipmap.ic_launcher), ViewHelper.getPrimaryColor(activity)))
}
private fun hasTheme(activity: BaseActivity<*, *>) = (activity is LoginChooserActivity || activity is LoginActivity ||
activity is DonateActivity || activity is ReviewChangesActivity)
} | gpl-3.0 | 019f04fb0b28fefcdcf55dfdb5f04d21 | 59.095057 | 126 | 0.650215 | 5.310484 | false | false | false | false |
stephanenicolas/toothpick | ktp/src/test/kotlin/toothpick/ktp/TestRuntime.kt | 1 | 7968 | /*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.ktp
import javax.inject.Named
import javax.inject.Provider
import javax.inject.Qualifier
import org.amshove.kluent.When
import org.amshove.kluent.calling
import org.amshove.kluent.itReturns
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldNotBeNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import toothpick.InjectConstructor
import toothpick.Lazy
import toothpick.ktp.delegate.inject
import toothpick.ktp.delegate.lazy
import toothpick.ktp.delegate.provider
import toothpick.ktp.extension.getInstance
import toothpick.ktp.extension.getLazy
import toothpick.ktp.extension.getProvider
import toothpick.testing.ToothPickExtension
class TestRuntime {
@JvmField
@RegisterExtension
val toothpickExtension = ToothPickExtension(this, "Foo")
@JvmField
@RegisterExtension
val mockitoExtension = MockitoExtension()
@Mock
lateinit var dependency: Dependency
@Mock
@field:Named("name")
lateinit var namedDependency: Dependency
@Mock
@field:QualifierName
lateinit var qualifierDependency: Dependency
@Test
fun `field injection should inject mocks when they are defined`() {
// GIVEN
When calling dependency.num() itReturns 2
When calling namedDependency.num() itReturns 3
When calling qualifierDependency.num() itReturns 4
// WHEN
val entryPoint = EntryPoint()
// THEN
assertDependencies(entryPoint, 2, 3, 4)
}
@Test
fun `constructor injection by getInstance should inject dependencies when they are defined`() {
// GIVEN
When calling dependency.num() itReturns 2
When calling namedDependency.num() itReturns 3
When calling qualifierDependency.num() itReturns 4
// WHEN
val nonEntryPoint: NonEntryPoint = KTP.openScope("Foo").getInstance()
// THEN
assertDependencies(nonEntryPoint, 2, 3, 4)
}
@Test
fun `constructor injection byLazy should inject dependencies when they are defined`() {
// GIVEN
When calling dependency.num() itReturns 2
When calling namedDependency.num() itReturns 3
When calling qualifierDependency.num() itReturns 4
// WHEN
val nonEntryPoint: Lazy<NonEntryPoint> = KTP.openScope("Foo").getLazy()
// THEN
assertDependencies(nonEntryPoint.get(), 2, 3, 4)
}
@Test
fun `constructor injection by provider should inject dependencies when they are defined`() {
// GIVEN
When calling dependency.num() itReturns 2
When calling namedDependency.num() itReturns 3
When calling qualifierDependency.num() itReturns 4
// WHEN
val nonEntryPoint: Provider<NonEntryPoint> = KTP.openScope("Foo").getProvider()
// THEN
assertDependencies(nonEntryPoint.get(), 2, 3, 4)
}
private fun assertDependencies(
nonEntryPoint: NonEntryPoint,
dependencyValue: Int,
namedDependencyValue: Int,
qualifierDependencyValue: Int
) {
nonEntryPoint.shouldNotBeNull()
nonEntryPoint.dependency.shouldNotBeNull()
nonEntryPoint.lazyDependency.shouldNotBeNull()
nonEntryPoint.providerDependency.shouldNotBeNull()
nonEntryPoint.namedDependency.shouldNotBeNull()
nonEntryPoint.namedLazyDependency.shouldNotBeNull()
nonEntryPoint.namedProviderDependency.shouldNotBeNull()
nonEntryPoint.qualifierDependency.shouldNotBeNull()
nonEntryPoint.qualifierLazyDependency.shouldNotBeNull()
nonEntryPoint.qualifierProviderDependency.shouldNotBeNull()
nonEntryPoint.dependency.num() shouldEqual dependencyValue
nonEntryPoint.lazyDependency.get().num() shouldEqual dependencyValue
nonEntryPoint.providerDependency.get().num() shouldEqual dependencyValue
nonEntryPoint.namedDependency.num() shouldEqual namedDependencyValue
nonEntryPoint.namedLazyDependency.get().num() shouldEqual namedDependencyValue
nonEntryPoint.namedProviderDependency.get().num() shouldEqual namedDependencyValue
nonEntryPoint.qualifierDependency.num() shouldEqual qualifierDependencyValue
nonEntryPoint.qualifierLazyDependency.get().num() shouldEqual qualifierDependencyValue
nonEntryPoint.qualifierProviderDependency.get().num() shouldEqual qualifierDependencyValue
}
private fun assertDependencies(
entryPoint: EntryPoint,
dependencyValue: Int,
namedDependencyValue: Int,
qualifierDependencyValue: Int
) {
entryPoint.shouldNotBeNull()
entryPoint.dependency.shouldNotBeNull()
entryPoint.lazyDependency.shouldNotBeNull()
entryPoint.providerDependency.shouldNotBeNull()
entryPoint.namedDependency.shouldNotBeNull()
entryPoint.namedLazyDependency.shouldNotBeNull()
entryPoint.namedProviderDependency.shouldNotBeNull()
entryPoint.qualifierDependency.shouldNotBeNull()
entryPoint.qualifierLazyDependency.shouldNotBeNull()
entryPoint.qualifierProviderDependency.shouldNotBeNull()
entryPoint.dependency.num() shouldEqual dependencyValue
entryPoint.lazyDependency.num() shouldEqual dependencyValue
entryPoint.providerDependency.num() shouldEqual dependencyValue
entryPoint.namedDependency.num() shouldEqual namedDependencyValue
entryPoint.namedLazyDependency.num() shouldEqual namedDependencyValue
entryPoint.namedProviderDependency.num() shouldEqual namedDependencyValue
entryPoint.qualifierDependency.num() shouldEqual qualifierDependencyValue
entryPoint.qualifierLazyDependency.num() shouldEqual qualifierDependencyValue
}
class EntryPoint {
val dependency: Dependency by inject()
val lazyDependency: Dependency by lazy()
val providerDependency: Dependency by provider()
val namedDependency: Dependency by inject("name")
val namedLazyDependency: Dependency by lazy("name")
val namedProviderDependency: Dependency by provider("name")
val qualifierDependency: Dependency by inject(QualifierName::class)
val qualifierLazyDependency: Dependency by lazy(QualifierName::class)
val qualifierProviderDependency: Dependency by provider(QualifierName::class)
init {
KTP.openScope("Foo").inject(this)
}
}
@InjectConstructor
class NonEntryPoint(
val dependency: Dependency,
val lazyDependency: Lazy<Dependency>,
val providerDependency: Provider<Dependency>,
@Named("name") val namedDependency: Dependency,
@Named("name") val namedLazyDependency: Lazy<Dependency>,
@Named("name") val namedProviderDependency: Provider<Dependency>,
@QualifierName val qualifierDependency: Dependency,
@QualifierName val qualifierLazyDependency: Lazy<Dependency>,
@QualifierName val qualifierProviderDependency: Provider<Dependency>
)
// open for mocking
open class Dependency {
open fun num(): Int {
return 1
}
}
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class QualifierName
}
| apache-2.0 | dc68cbe3c8ccd2a39bedeb72e885310d | 36.942857 | 99 | 0.72992 | 5.639066 | false | false | false | false |
square/leakcanary | leakcanary-android-release/src/main/java/leakcanary/ProcessInfo.kt | 2 | 4016 | package leakcanary
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.ActivityManager.MemoryInfo
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.os.Build.VERSION.SDK_INT
import android.os.Process
import android.os.SystemClock
import android.system.Os
import android.system.OsConstants
import java.io.File
import java.io.FileReader
import leakcanary.ProcessInfo.AvailableRam.BelowThreshold
import leakcanary.ProcessInfo.AvailableRam.LowRamDevice
import leakcanary.ProcessInfo.AvailableRam.Memory
interface ProcessInfo {
val isImportanceBackground: Boolean
val elapsedMillisSinceStart: Long
fun availableDiskSpaceBytes(path: File): Long
sealed class AvailableRam {
object LowRamDevice : AvailableRam()
object BelowThreshold : AvailableRam()
class Memory(val bytes: Long) : AvailableRam()
}
fun availableRam(context: Context): AvailableRam
@SuppressLint("NewApi")
object Real : ProcessInfo {
private val memoryOutState = RunningAppProcessInfo()
private val memoryInfo = MemoryInfo()
private val processStartUptimeMillis by lazy {
Process.getStartUptimeMillis()
}
private val processForkRealtimeMillis by lazy {
readProcessForkRealtimeMillis()
}
override val isImportanceBackground: Boolean
get() {
ActivityManager.getMyMemoryState(memoryOutState)
return memoryOutState.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND
}
override val elapsedMillisSinceStart: Long
get() = if (SDK_INT >= 24) {
SystemClock.uptimeMillis() - processStartUptimeMillis
} else {
SystemClock.elapsedRealtime() - processForkRealtimeMillis
}
@SuppressLint("UsableSpace")
override fun availableDiskSpaceBytes(path: File) = path.usableSpace
override fun availableRam(context: Context): AvailableRam {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
if (SDK_INT >= 19 && activityManager.isLowRamDevice) {
return LowRamDevice
} else {
activityManager.getMemoryInfo(memoryInfo)
return if (memoryInfo.lowMemory || memoryInfo.availMem <= memoryInfo.threshold) {
BelowThreshold
} else {
val systemAvailableMemory = memoryInfo.availMem - memoryInfo.threshold
val runtime = Runtime.getRuntime()
val appUsedMemory = runtime.totalMemory() - runtime.freeMemory()
val appAvailableMemory = runtime.maxMemory() - appUsedMemory
val availableMemory = systemAvailableMemory.coerceAtMost(appAvailableMemory)
Memory(availableMemory)
}
}
}
/**
* See https://dev.to/pyricau/android-vitals-when-did-my-app-start-24p4#process-fork-time
*/
private fun readProcessForkRealtimeMillis(): Long {
val myPid = Process.myPid()
val ticksAtProcessStart = readProcessStartTicks(myPid)
val ticksPerSecond = if (SDK_INT >= 21) {
Os.sysconf(OsConstants._SC_CLK_TCK)
} else {
val tckConstant = try {
Class.forName("android.system.OsConstants").getField("_SC_CLK_TCK").getInt(null)
} catch (e: ClassNotFoundException) {
Class.forName("libcore.io.OsConstants").getField("_SC_CLK_TCK").getInt(null)
}
val os = Class.forName("libcore.io.Libcore").getField("os").get(null)!!
os::class.java.getMethod("sysconf", Integer.TYPE).invoke(os, tckConstant) as Long
}
return ticksAtProcessStart * 1000 / ticksPerSecond
}
// Benchmarked (with Jetpack Benchmark) on Pixel 3 running
// Android 10. Median time: 0.13ms
private fun readProcessStartTicks(pid: Int): Long {
val path = "/proc/$pid/stat"
val stat = FileReader(path).buffered().use { reader ->
reader.readLine()
}
val fields = stat.substringAfter(") ")
.split(' ')
return fields[19].toLong()
}
}
}
| apache-2.0 | ec607e453b7ff9deedbd8047622aeb18 | 32.466667 | 97 | 0.704183 | 4.568828 | false | false | false | false |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/presentation/ui/settings/fragments/SettingsSecurityFragment.kt | 1 | 11772 | /**
* ownCloud Android client application
*
* @author Juan Carlos Garrote Gascón
*
* Copyright (C) 2022 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.ui.settings.fragments
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.preference.CheckBoxPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen
import com.owncloud.android.R
import com.owncloud.android.extensions.avoidScreenshotsIfNeeded
import com.owncloud.android.extensions.showMessageInSnackbar
import com.owncloud.android.presentation.ui.security.BiometricActivity
import com.owncloud.android.presentation.ui.security.BiometricManager
import com.owncloud.android.presentation.ui.security.LockTimeout
import com.owncloud.android.presentation.ui.security.PREFERENCE_LOCK_TIMEOUT
import com.owncloud.android.presentation.ui.security.PatternActivity
import com.owncloud.android.presentation.ui.security.passcode.PassCodeActivity
import com.owncloud.android.presentation.ui.settings.fragments.SettingsFragment.Companion.removePreferenceFromScreen
import com.owncloud.android.presentation.viewmodels.settings.SettingsSecurityViewModel
import com.owncloud.android.utils.DocumentProviderUtils.Companion.notifyDocumentProviderRoots
import org.koin.androidx.viewmodel.ext.android.viewModel
class SettingsSecurityFragment : PreferenceFragmentCompat() {
// ViewModel
private val securityViewModel by viewModel<SettingsSecurityViewModel>()
private var screenSecurity: PreferenceScreen? = null
private var prefPasscode: CheckBoxPreference? = null
private var prefPattern: CheckBoxPreference? = null
private var prefBiometric: CheckBoxPreference? = null
private var prefLockApplication: ListPreference? = null
private var prefLockAccessDocumentProvider: CheckBoxPreference? = null
private var prefTouchesWithOtherVisibleWindows: CheckBoxPreference? = null
private val enablePasscodeLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
else {
prefPasscode?.isChecked = true
prefBiometric?.isChecked = securityViewModel.getBiometricsState()
// Allow to use biometric lock, lock delay and access from document provider since Passcode lock has been enabled
enableBiometricAndLockApplication()
}
}
private val disablePasscodeLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
else {
prefPasscode?.isChecked = false
// Do not allow to use biometric lock, lock delay nor access from document provider since Passcode lock has been disabled
disableBiometric()
prefLockApplication?.isEnabled = false
}
}
private val enablePatternLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
else {
prefPattern?.isChecked = true
prefBiometric?.isChecked = securityViewModel.getBiometricsState()
// Allow to use biometric lock, lock delay and access from document provider since Pattern lock has been enabled
enableBiometricAndLockApplication()
}
}
private val disablePatternLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult
else {
prefPattern?.isChecked = false
// Do not allow to use biometric lock, lock delay nor access from document provider since Pattern lock has been disabled
disableBiometric()
prefLockApplication?.isEnabled = false
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings_security, rootKey)
screenSecurity = findPreference(SCREEN_SECURITY)
prefPasscode = findPreference(PassCodeActivity.PREFERENCE_SET_PASSCODE)
prefPattern = findPreference(PatternActivity.PREFERENCE_SET_PATTERN)
prefBiometric = findPreference(BiometricActivity.PREFERENCE_SET_BIOMETRIC)
prefLockApplication = findPreference<ListPreference>(PREFERENCE_LOCK_TIMEOUT)?.apply {
entries = listOf(
getString(R.string.prefs_lock_application_entries_immediately),
getString(R.string.prefs_lock_application_entries_1minute),
getString(R.string.prefs_lock_application_entries_5minutes),
getString(R.string.prefs_lock_application_entries_30minutes)
).toTypedArray()
entryValues = listOf(
LockTimeout.IMMEDIATELY.name,
LockTimeout.ONE_MINUTE.name,
LockTimeout.FIVE_MINUTES.name,
LockTimeout.THIRTY_MINUTES.name
).toTypedArray()
isEnabled = !securityViewModel.isLockDelayEnforcedEnabled()
}
prefLockAccessDocumentProvider = findPreference(PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER)
prefTouchesWithOtherVisibleWindows = findPreference(PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS)
prefPasscode?.isVisible = !securityViewModel.isSecurityEnforcedEnabled()
prefPattern?.isVisible = !securityViewModel.isSecurityEnforcedEnabled()
// Passcode lock
prefPasscode?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (securityViewModel.isPatternSet()) {
showMessageInSnackbar(getString(R.string.pattern_already_set))
} else {
val intent = Intent(activity, PassCodeActivity::class.java)
if (newValue as Boolean) {
intent.action = PassCodeActivity.ACTION_CREATE
enablePasscodeLauncher.launch(intent)
} else {
intent.action = PassCodeActivity.ACTION_REMOVE
disablePasscodeLauncher.launch(intent)
}
}
false
}
// Pattern lock
prefPattern?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (securityViewModel.isPasscodeSet()) {
showMessageInSnackbar(getString(R.string.passcode_already_set))
} else {
val intent = Intent(activity, PatternActivity::class.java)
if (newValue as Boolean) {
intent.action = PatternActivity.ACTION_REQUEST_WITH_RESULT
enablePatternLauncher.launch(intent)
} else {
intent.action = PatternActivity.ACTION_CHECK_WITH_RESULT
disablePatternLauncher.launch(intent)
}
}
false
}
// Biometric lock
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
screenSecurity?.removePreferenceFromScreen(prefBiometric)
} else if (prefBiometric != null) {
if (!BiometricManager.isHardwareDetected()) { // Biometric not supported
screenSecurity?.removePreferenceFromScreen(prefBiometric)
} else {
if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { // Disable biometric lock if Passcode or Pattern locks are disabled
disableBiometric()
}
prefBiometric?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
val incomingValue = newValue as Boolean
// No biometric enrolled yet
if (incomingValue && !BiometricManager.hasEnrolledBiometric()) {
showMessageInSnackbar(getString(R.string.biometric_not_enrolled))
return@setOnPreferenceChangeListener false
}
true
}
}
}
// Lock application
if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) {
prefLockApplication?.isEnabled = false
}
// Lock access from document provider
prefLockAccessDocumentProvider?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
securityViewModel.setPrefLockAccessDocumentProvider(true)
notifyDocumentProviderRoots(requireContext())
true
}
// Touches with other visible windows
prefTouchesWithOtherVisibleWindows?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (newValue as Boolean) {
activity?.let {
AlertDialog.Builder(it)
.setTitle(getString(R.string.confirmation_touches_with_other_windows_title))
.setMessage(getString(R.string.confirmation_touches_with_other_windows_message))
.setNegativeButton(getString(R.string.common_no), null)
.setPositiveButton(
getString(R.string.common_yes)
) { _: DialogInterface?, _: Int ->
securityViewModel.setPrefTouchesWithOtherVisibleWindows(true)
prefTouchesWithOtherVisibleWindows?.isChecked = true
}
.show()
.avoidScreenshotsIfNeeded()
}
return@setOnPreferenceChangeListener false
}
true
}
}
private fun enableBiometricAndLockApplication() {
prefBiometric?.apply {
isEnabled = true
summary = null
}
prefLockApplication?.isEnabled = !securityViewModel.isLockDelayEnforcedEnabled()
}
private fun disableBiometric() {
prefBiometric?.apply {
isChecked = false
isEnabled = false
summary = getString(R.string.prefs_biometric_summary)
}
}
companion object {
private const val SCREEN_SECURITY = "security_screen"
const val PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER = "lock_access_from_document_provider"
const val PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS = "touches_with_other_visible_windows"
const val EXTRAS_LOCK_ENFORCED = "EXTRAS_LOCK_ENFORCED"
const val PREFERENCE_LOCK_ATTEMPTS = "PrefLockAttempts"
}
}
| gpl-2.0 | ea04736ee885a283bc87264caee0529f | 45.34252 | 158 | 0.66392 | 5.678244 | false | false | false | false |
devknightz/MinimalWeatherApp | app/src/main/java/you/devknights/minimalweather/network/model/WeatherResponse.kt | 1 | 2834 | /*
* Copyright 2017 vinayagasundar
* Copyright 2017 randhirgupta
*
* 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 you.devknights.minimalweather.network.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import you.devknights.minimalweather.database.entity.WeatherEntity
class WeatherResponse {
@SerializedName("coord")
@Expose
private var coord: Coord? = null
@SerializedName("weather")
@Expose
private var weather: List<Weather>? = null
@SerializedName("base")
@Expose
private var base: String? = null
@SerializedName("main")
@Expose
private var main: Main? = null
@SerializedName("visibility")
@Expose
private var visibility: Int = 0
@SerializedName("wind")
@Expose
private var wind: Wind? = null
@SerializedName("clouds")
@Expose
private var clouds: Clouds? = null
@SerializedName("dt")
@Expose
private var dt: Int = 0
@SerializedName("sys")
@Expose
private var sys: Sys? = null
@SerializedName("id")
@Expose
private var id: Int = 0
@SerializedName("name")
@Expose
private var name: String? = null
@SerializedName("cod")
@Expose
private var cod: Int = 0
fun buildWeather(): WeatherEntity {
val weatherEntity = WeatherEntity()
weatherEntity.placeId = id
weatherEntity.placeName = name
weatherEntity.placeLat = coord?.lat ?: 0.toDouble()
weatherEntity.placeLon = coord?.lon ?: 0.toDouble()
weather?.let {
if (it.isNotEmpty()) {
val weather = it[0]
weatherEntity.weatherId = weather.id
weatherEntity.weatherMain = weather.main
weatherEntity.weatherDescription = weather.description
weatherEntity.weatherIcon = weather.icon
}
}
weatherEntity.temperature = main?.temp ?: 0.toFloat()
weatherEntity.pressure = main?.pressure ?: 0.toFloat()
weatherEntity.humidity = main?.humidity ?: 0.toFloat()
weatherEntity.windSpeed = wind?.speed?.toFloat() ?: 0.toFloat()
weatherEntity.sunriseTime = sys?.sunrise ?: 0
weatherEntity.sunsetTime = sys?.sunset ?: 0
return weatherEntity
}
}
| apache-2.0 | 2ccfeb14b8f21cb3880df58a3f6185fc | 28.520833 | 76 | 0.65561 | 4.498413 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2019/Day7.kt | 1 | 1740 | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.lang.Integer.max
/** https://adventofcode.com/2019/day/7 */
class Day7 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines[0].split(",").map { it.toInt() }
var maxThrusterA = 0
for (phasing in genPerms(0, mutableListOf())) {
maxThrusterA = max(maxThrusterA, runA(phasing, input))
}
var maxThrusterB = 0
for (phasing in genPerms(0, mutableListOf(), 5)) {
maxThrusterB = max(maxThrusterB, runB(phasing, input))
}
return Result("$maxThrusterA", "$maxThrusterB")
}
private fun genPerms(n: Int, list: MutableList<Int>,
offset: Int = 0): MutableList<List<Int>> {
if (n > 4) return mutableListOf(list)
val result = mutableListOf<List<Int>>()
for (x in offset..offset + 4) {
if (x in list) continue
val listX = ArrayList(list)
listX.add(x)
result.addAll(genPerms(n + 1, listX, offset))
}
return result
}
private fun runA(phasing: List<Int>, program: List<Int>): Int {
val vms =
(0..4).map { createVm(program.toMutableList(), mutableListOf(phasing[it])) }
var lastOutput = 0
for (vm in vms) {
vm.addInput(lastOutput)
lastOutput = vm.run()
}
return lastOutput
}
private fun runB(phasing: List<Int>, program: List<Int>): Int {
val vms =
(0..4).map { createVm(program.toMutableList(), mutableListOf(phasing[it])) }
for (i in 0..4) {
vms[i].sendOutputTo(vms[(i + 1) % vms.size])
}
vms[0].addInput(0)
while (!vms[4].isHalted) {
for (vm in vms) {
vm.step()
}
}
return vms[4].lastOutput.toInt()
}
} | apache-2.0 | a70110acaf1e6f5a2cecf8a2eb9a8bc9 | 27.080645 | 84 | 0.605172 | 3.359073 | false | false | false | false |
Kotlin/dokka | core/src/main/kotlin/defaultExternalLinks.kt | 1 | 1263 | package org.jetbrains.dokka
import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink
import java.net.URL
fun ExternalDocumentationLink.Companion.jdk(jdkVersion: Int): ExternalDocumentationLinkImpl =
ExternalDocumentationLink(
url =
if (jdkVersion < 11) "https://docs.oracle.com/javase/${jdkVersion}/docs/api/"
else "https://docs.oracle.com/en/java/javase/${jdkVersion}/docs/api/",
packageListUrl =
if (jdkVersion < 11) "https://docs.oracle.com/javase/${jdkVersion}/docs/api/package-list"
else "https://docs.oracle.com/en/java/javase/${jdkVersion}/docs/api/element-list"
)
fun ExternalDocumentationLink.Companion.kotlinStdlib(): ExternalDocumentationLinkImpl =
ExternalDocumentationLink("https://kotlinlang.org/api/latest/jvm/stdlib/")
fun ExternalDocumentationLink.Companion.androidSdk(): ExternalDocumentationLinkImpl =
ExternalDocumentationLink("https://developer.android.com/reference/kotlin/")
fun ExternalDocumentationLink.Companion.androidX(): ExternalDocumentationLinkImpl = ExternalDocumentationLink(
url = URL("https://developer.android.com/reference/kotlin/"),
packageListUrl = URL("https://developer.android.com/reference/kotlin/androidx/package-list")
)
| apache-2.0 | 64a1e4e591ad089785e62f28e4add384 | 41.1 | 110 | 0.761679 | 4.712687 | false | false | false | false |
googleapis/gax-kotlin | examples/src/main/kotlin/example/grpc/Language.kt | 1 | 1974 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.grpc
import com.google.api.kgax.grpc.StubFactory
import com.google.cloud.language.v1.AnalyzeEntitiesRequest
import com.google.cloud.language.v1.Document
import com.google.cloud.language.v1.LanguageServiceGrpc
import kotlinx.coroutines.runBlocking
import java.io.File
/**
* Simple example of calling the Language API with KGax.
*
* Run this example using your service account as follows:
*
* ```
* $ CREDENTIALS=<path_to_your_service_account.json> ./gradlew examples:run --args language
* ```
*/
fun languageExample(credentials: String) = runBlocking {
// create a stub factory
val factory = StubFactory(
LanguageServiceGrpc.LanguageServiceFutureStub::class,
"language.googleapis.com", 443
)
// create a stub
val stub = File(credentials).inputStream().use {
factory.fromServiceAccount(it, listOf("https://www.googleapis.com/auth/cloud-platform"))
}
// call the API
val response = stub.execute {
it.analyzeEntities(
AnalyzeEntitiesRequest.newBuilder().apply {
document = Document.newBuilder().apply {
content = "Hi there Joe"
type = Document.Type.PLAIN_TEXT
}.build()
}.build()
)
}
println("The API says: $response")
// shutdown all connections
factory.shutdown()
}
| apache-2.0 | badf8c6b6c62f65bd611d3a428022693 | 30.333333 | 96 | 0.683384 | 4.217949 | false | false | false | false |
KotlinBy/awesome-kotlin | src/main/kotlin/link/kotlin/scripts/GithubTrending.kt | 1 | 2789 | package link.kotlin.scripts
import link.kotlin.scripts.dsl.Category
import link.kotlin.scripts.dsl.Subcategory
import link.kotlin.scripts.model.Link
import link.kotlin.scripts.utils.Cache
import org.jsoup.Jsoup
import java.time.LocalDate
import java.time.format.DateTimeFormatter
private val trending = listOf(
"Monthly" to "https://github.com/trending/kotlin?since=monthly",
"Weekly" to "https://github.com/trending/kotlin?since=weekly",
"Daily" to "https://github.com/trending/kotlin?since=daily"
)
interface GithubTrending {
suspend fun fetch(): Category?
companion object
}
private class CachedGithubTrending(
private val cache: Cache,
private val githubTrending: GithubTrending
) : GithubTrending {
override suspend fun fetch(): Category? {
val date = DateTimeFormatter.BASIC_ISO_DATE.format(LocalDate.now())
val cacheKey = "github-trending-$date"
val cacheValue = cache.get(cacheKey, Category::class)
return if (cacheValue == null) {
val result = githubTrending.fetch()
result ?: cache.put(cacheKey, result)
result
} else cacheValue
}
}
private class JSoupGithubTrending(
) : GithubTrending {
override suspend fun fetch(): Category? {
val subcategories = trending.mapNotNull { it.toSubcategory() }
.deleteDuplicates()
.toMutableList()
return if (subcategories.isNotEmpty()) {
Category(
name = "Github Trending",
subcategories = subcategories
)
} else null
}
private fun List<Subcategory>.deleteDuplicates(): List<Subcategory> {
val pool = mutableSetOf<Link>()
return this.map { subcategory ->
val filtered = subcategory.links.subtract(pool)
val result = subcategory.copy(links = filtered.toMutableList())
pool.addAll(subcategory.links)
result
}
}
private fun Pair<String, String>.toSubcategory(): Subcategory? {
val doc = Jsoup.connect(this.second).get()
val isAvailable = doc.select(".Box-row").isNotEmpty()
return if (isAvailable) {
val links = doc.select(".Box-row").map {
Link(
github = it.select("h1 a").attr("href").removePrefix("/")
)
}
return Subcategory(
name = this.first,
links = links.toMutableList()
)
} else {
null
}
}
}
fun GithubTrending.Companion.default(
cache: Cache
): GithubTrending {
val jSoupGithubTrending = JSoupGithubTrending()
return CachedGithubTrending(
cache = cache,
githubTrending = jSoupGithubTrending
)
}
| apache-2.0 | 73660761468635a78da0977f7cfe30b1 | 27.752577 | 77 | 0.61886 | 4.640599 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/SurveyQuestionActivity.kt | 1 | 6591 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.google.gson.Gson
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.adapters.SurveyPagerAdapter
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.online.SurveyQuestionFragment.OnAnswerSelectedListener
import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment.Companion.newInstance
import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment.DisableSwipe
import com.mifos.objects.survey.Scorecard
import com.mifos.objects.survey.ScorecardValues
import com.mifos.objects.survey.Survey
import com.mifos.utils.Constants
import com.mifos.utils.PrefManager
import java.util.*
/**
* Created by Nasim Banu on 28,January,2016.
*/
class SurveyQuestionActivity : MifosBaseActivity(), OnAnswerSelectedListener, DisableSwipe, OnPageChangeListener {
@JvmField
@BindView(R.id.surveyPager)
var mViewPager: ViewPager? = null
@JvmField
@BindView(R.id.btnNext)
var btnNext: Button? = null
@JvmField
@BindView(R.id.tv_surveyEmpty)
var tv_surveyEmpty: TextView? = null
@JvmField
@BindView(R.id.toolbar)
var mToolbar: Toolbar? = null
private val fragments: MutableList<Fragment> = Vector()
private val listScorecardValues: MutableList<ScorecardValues> = ArrayList()
private var survey: Survey? = null
private val mScorecard = Scorecard()
private var mScorecardValue: ScorecardValues? = null
private var mMapScores = HashMap<Int, ScorecardValues>()
private var clientId = 0
private var mCurrentQuestionPosition = 1
var fragmentCommunicator: Communicator? = null
private var mPagerAdapter: PagerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_survey_question)
ButterKnife.bind(this)
//Getting Survey Gson Object
val mIntent = intent
survey = Gson().fromJson(mIntent.getStringExtra(Constants.SURVEYS), Survey::class.java)
clientId = mIntent.getIntExtra(Constants.CLIENT_ID, 1)
setSubtitleToolbar()
mPagerAdapter = SurveyPagerAdapter(supportFragmentManager, fragments)
mViewPager!!.adapter = mPagerAdapter
mViewPager!!.addOnPageChangeListener(this)
loadSurvey(survey)
val actionBar = supportActionBar
actionBar!!.setDisplayHomeAsUpEnabled(true)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
updateAnswerList()
mCurrentQuestionPosition = position + 1
setSubtitleToolbar()
}
override fun onPageScrollStateChanged(state: Int) {}
@OnClick(R.id.btnNext)
fun onClickButtonNext() {
updateAnswerList()
mViewPager!!.setCurrentItem(mViewPager!!.currentItem + 1, true)
setSubtitleToolbar()
}
override fun answer(scorecardValues: ScorecardValues?) {
mScorecardValue = scorecardValues
}
fun loadSurvey(survey: Survey?) {
if (survey != null) {
if (survey.questionDatas != null && survey.questionDatas.size > 0) {
for (i in survey.questionDatas.indices) {
fragments.add(SurveyQuestionFragment.newInstance(Gson().toJson(survey
.questionDatas[i])))
}
fragments.add(newInstance())
mPagerAdapter!!.notifyDataSetChanged()
} else {
mViewPager!!.visibility = View.GONE
btnNext!!.visibility = View.GONE
tv_surveyEmpty!!.visibility = View.VISIBLE
}
}
}
fun setUpScoreCard() {
listScorecardValues.clear()
for ((_, value) in mMapScores) {
listScorecardValues.add(value)
}
mScorecard.clientId = clientId
mScorecard.userId = PrefManager.getUserId()
mScorecard.createdOn = Date()
mScorecard.scorecardValues = listScorecardValues
}
fun updateAnswerList() {
if (mScorecardValue != null) {
Log.d(LOG_TAG, "" + mScorecardValue!!.questionId + mScorecardValue!!
.responseId + mScorecardValue!!.value)
mMapScores[mScorecardValue!!.questionId] = mScorecardValue!!
mScorecardValue = null
}
nextButtonState()
if (fragmentCommunicator != null) {
setUpScoreCard()
fragmentCommunicator!!.passScoreCardData(mScorecard, survey!!.id)
}
}
fun nextButtonState() {
if (mViewPager!!.currentItem == mPagerAdapter!!.count - 1) {
btnNext!!.visibility = View.GONE
} else {
btnNext!!.visibility = View.VISIBLE
}
}
fun setSubtitleToolbar() {
if (survey!!.questionDatas.size == 0) {
mToolbar!!.subtitle = resources.getString(R.string.survey_subtitle)
} else if (mCurrentQuestionPosition <= survey!!.questionDatas.size) {
mToolbar!!.subtitle = mCurrentQuestionPosition.toString() +
resources.getString(R.string.slash) + survey!!.questionDatas.size
} else {
mToolbar!!.subtitle = resources.getString(R.string.submit_survey)
}
}
override fun disableSwipe() {
mViewPager!!.beginFakeDrag()
mToolbar!!.subtitle = null
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putSerializable(Constants.ANSWERS, mMapScores)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mMapScores = savedInstanceState.getSerializable(Constants.ANSWERS) as HashMap<Int, ScorecardValues>
}
companion object {
val LOG_TAG = SurveyQuestionActivity::class.java.simpleName
}
} | mpl-2.0 | dcd387f43bfc3d03918baca187294cb6 | 35.622222 | 114 | 0.687453 | 4.959368 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/classes/ClassDetailActivity.kt | 1 | 10835 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.timetableapp.ui.classes
import android.app.Activity
import android.content.Intent
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.Toolbar
import android.text.Html
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.TimetableApplication
import co.timetableapp.data.handler.*
import co.timetableapp.data.query.Filters
import co.timetableapp.data.query.Query
import co.timetableapp.data.schema.AssignmentsSchema
import co.timetableapp.data.schema.ExamsSchema
import co.timetableapp.model.Class
import co.timetableapp.model.ClassTime
import co.timetableapp.model.Color
import co.timetableapp.model.Subject
import co.timetableapp.ui.agenda.AgendaActivity
import co.timetableapp.ui.base.ItemDetailActivity
import co.timetableapp.ui.base.ItemEditActivity
import co.timetableapp.ui.components.CardOfItems
import co.timetableapp.util.DateUtils
import co.timetableapp.util.UiUtils
/**
* Shows the details of a class.
*
* @see Class
* @see ClassesActivity
* @see ClassEditActivity
* @see ItemDetailActivity
*/
class ClassDetailActivity : ItemDetailActivity<Class>() {
private lateinit var mColor: Color
override fun initializeDataHandler() = ClassHandler(this)
override fun getLayoutResource() = R.layout.activity_class_detail
override fun onNullExtras() {
val intent = Intent(this, ClassEditActivity::class.java)
ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_ITEM_EDIT, null)
}
override fun setupLayout() {
setupToolbar()
setupClassDetailCard()
findViewById(R.id.main_card).setBackgroundColor(
ContextCompat.getColor(this, mColor.getLightAccentColorRes(this)))
setupRelatedItemCards()
}
private fun setupToolbar() {
val subject = Subject.create(this, mItem.subjectId)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
toolbar.navigationIcon = UiUtils.tintDrawable(this, R.drawable.ic_arrow_back_black_24dp)
toolbar.setNavigationOnClickListener { saveEditsAndClose() }
supportActionBar!!.title = mItem.makeName(subject)
mColor = Color(subject.colorId)
UiUtils.setBarColors(mColor, this, toolbar)
}
/**
* Adds content to a card displaying details about the class (such as locations, teachers, and
* the times of the class).
*/
private fun setupClassDetailCard() {
val locationBuilder = StringBuilder()
val teacherBuilder = StringBuilder()
val allClassTimes = ArrayList<ClassTime>()
// Add locations, teachers, and times to StringBuilders or ArrayLists, with no duplicates
ClassDetailHandler.getClassDetailsForClass(this, mItem.id).forEach { classDetail ->
classDetail.formatLocationName()?.let {
if (!locationBuilder.contains(it)) {
locationBuilder.append(it).append("\n")
}
}
if (classDetail.hasTeacher()) {
if (!teacherBuilder.contains(classDetail.teacher)) {
teacherBuilder.append(classDetail.teacher).append("\n")
}
}
allClassTimes.addAll(ClassTimeHandler.getClassTimesForDetail(this, classDetail.id))
}
setClassDetailTexts(
locationBuilder.toString().removeSuffix("\n"),
teacherBuilder.toString().removeSuffix("\n"),
produceClassTimesText(allClassTimes))
}
/**
* @return the list of class times as a formatted string
*/
private fun produceClassTimesText(classTimes: ArrayList<ClassTime>): String {
classTimes.sort()
val stringBuilder = StringBuilder()
// Add all time texts - not expecting duplicate values for times
classTimes.forEach {
val dayString = it.day.toString()
val formattedDayString =
dayString.substring(0, 1).toUpperCase() + dayString.substring(1).toLowerCase()
stringBuilder.append(formattedDayString)
val weekText = it.getWeekText(this)
if (weekText.isNotEmpty()) {
stringBuilder.append(" ")
.append(weekText)
}
stringBuilder.append(", ")
.append(it.startTime.toString())
.append(" - ")
.append(it.endTime.toString())
.append("\n")
}
return stringBuilder.toString().removeSuffix("\n")
}
/**
* Sets the text on the TextViews for the class detail data.
* Appropriate parts of the UI will not be displayed (i.e. when there is no text for an item).
*
* @param locations text to be displayed for the class locations
* @param teachers text to be displayed for the teachers of the class
* @param classTimes text to be displayed for the class times
*/
private fun setClassDetailTexts(locations: String, teachers: String, classTimes: String) {
val locationVisibility = if (locations.isEmpty()) View.GONE else View.VISIBLE
findViewById(R.id.viewGroup_location).visibility = locationVisibility
if (locations.isNotEmpty()) {
(findViewById(R.id.textView_location) as TextView).text = locations
}
val teacherVisibility = if (teachers.isEmpty()) View.GONE else View.VISIBLE
findViewById(R.id.viewGroup_teacher).visibility = teacherVisibility
if (teachers.isNotEmpty()) {
(findViewById(R.id.textView_teacher) as TextView).text = teachers
}
// No need to check if it's empty - all class details must have a class time
val textViewTimes = findViewById(R.id.textView_times) as TextView
textViewTimes.text = classTimes
}
/**
* Sets up the UI for cards displaying items related to this class, such as assignments and
* exams for this class.
*/
private fun setupRelatedItemCards() {
val cardContainer = findViewById(R.id.card_container) as LinearLayout
val assignmentsCard = CardOfItems.Builder(this, cardContainer)
.setTitle(R.string.title_assignments)
.setItems(createAssignmentItems())
.setItemsIconResource(R.drawable.ic_homework_black_24dp)
.setButtonProperties(R.string.view_all, View.OnClickListener {
startActivity(Intent(this@ClassDetailActivity, AgendaActivity::class.java))
})
.build()
.view
cardContainer.addView(assignmentsCard)
val examsCard = CardOfItems.Builder(this, cardContainer)
.setTitle(R.string.title_exams)
.setItems(createExamItems())
.setItemsIconResource(R.drawable.ic_assessment_black_24dp)
.setButtonProperties(R.string.view_all, View.OnClickListener {
startActivity(Intent(this@ClassDetailActivity, AgendaActivity::class.java))
})
.build()
.view
cardContainer.addView(examsCard)
}
private fun createAssignmentItems(): ArrayList<CardOfItems.CardItem> {
val timetableId = (application as TimetableApplication).currentTimetable!!.id
// Get assignments for this class
val query = Query.Builder()
.addFilter(Filters.equal(AssignmentsSchema.COL_TIMETABLE_ID, timetableId.toString()))
.addFilter(Filters.equal(AssignmentsSchema.COL_CLASS_ID, mItem.id.toString()))
.build()
// Create items
val items = ArrayList<CardOfItems.CardItem>()
val formatter = DateUtils.FORMATTER_FULL_DATE
AssignmentHandler(this).getAllItems(query).forEach {
if (it.isUpcoming() || it.isOverdue()) {
val subtitle = if (it.isOverdue()) {
"<font color=\"#F44336\"><b>${getString(R.string.due_overdue)}</b> \u2022 " +
"${it.dueDate.format(formatter)}</font>"
} else {
it.dueDate.format(formatter)
}
items.add(CardOfItems.CardItem(
it.title,
Html.fromHtml(subtitle)
))
}
}
return items
}
private fun createExamItems(): ArrayList<CardOfItems.CardItem> {
val timetableId = (application as TimetableApplication).currentTimetable!!.id
// Get exams for this class (actually for the subject of the class)
val query = Query.Builder()
.addFilter(Filters.equal(ExamsSchema.COL_TIMETABLE_ID, timetableId.toString()))
.addFilter(Filters.equal(ExamsSchema.COL_SUBJECT_ID, mItem.subjectId.toString()))
.build()
// Create items
val items = ArrayList<CardOfItems.CardItem>()
val formatter = DateUtils.FORMATTER_FULL_DATE
val subject = Subject.create(this, mItem.subjectId)
ExamHandler(this).getAllItems(query).forEach {
if (it.isUpcoming()) {
items.add(CardOfItems.CardItem(
it.makeName(subject),
Html.fromHtml(it.date.format(formatter))
))
}
}
return items
}
override fun onMenuEditClick() {
val intent = Intent(this, ClassEditActivity::class.java)
intent.putExtra(ItemEditActivity.EXTRA_ITEM, mItem)
ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_ITEM_EDIT, null)
}
override fun cancelAndClose() {
setResult(Activity.RESULT_CANCELED)
supportFinishAfterTransition()
}
override fun saveEditsAndClose() {
setResult(Activity.RESULT_OK) // to reload any changes in ClassesActivity
supportFinishAfterTransition()
}
override fun saveDeleteAndClose() {
setResult(Activity.RESULT_OK) // to reload any changes in ClassesActivity
finish()
}
}
| apache-2.0 | 2b8a12a906fbf247c72a4164f89a0b60 | 36.752613 | 101 | 0.646054 | 4.779444 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/shared/CalendarsView.kt | 1 | 8201 | package com.byagowi.persiancalendar.ui.shared
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.byagowi.persiancalendar.R
import com.byagowi.persiancalendar.databinding.CalendarItemBinding
import com.byagowi.persiancalendar.databinding.CalendarsViewBinding
import com.byagowi.persiancalendar.utils.*
import io.github.persiancalendar.calendar.CivilDate
import io.github.persiancalendar.praytimes.Clock
import java.util.*
import kotlin.math.abs
class CalendarsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
FrameLayout(context, attrs) {
private val calendarItemAdapter = CalendarItemAdapter(context)
private val binding: CalendarsViewBinding =
CalendarsViewBinding.inflate(context.layoutInflater, this, true).apply {
root.setOnClickListener { expand(!calendarItemAdapter.isExpanded) }
extraInformationContainer.visibility = View.GONE
calendarsRecyclerView.apply {
layoutManager = LinearLayoutManager(context).apply {
orientation = RecyclerView.HORIZONTAL
}
adapter = calendarItemAdapter
}
}
fun hideMoreIcon() {
binding.moreCalendar.visibility = View.GONE
}
fun expand(expanded: Boolean) {
calendarItemAdapter.isExpanded = expanded
binding.moreCalendar.setImageResource(
if (expanded)
R.drawable.ic_keyboard_arrow_up
else
R.drawable.ic_keyboard_arrow_down
)
binding.extraInformationContainer.visibility = if (expanded) View.VISIBLE else View.GONE
}
fun showCalendars(
jdn: Long, chosenCalendarType: CalendarType, calendarsToShow: List<CalendarType>
) {
val context = context ?: return
calendarItemAdapter.setDate(calendarsToShow, jdn)
binding.weekDayName.text = getWeekDayName(CivilDate(jdn))
binding.zodiac.apply {
text = getZodiacInfo(context, jdn, true)
visibility = if (text.isEmpty()) View.GONE else View.VISIBLE
}
val selectedDayAbsoluteDistance = abs(getTodayJdn() - jdn)
if (selectedDayAbsoluteDistance == 0L) {
if (isForcedIranTimeEnabled) binding.weekDayName.text = "%s (%s)".format(
getWeekDayName(CivilDate(jdn)),
context.getString(R.string.iran_time)
)
binding.diffDate.visibility = View.GONE
} else {
binding.diffDate.visibility = View.VISIBLE
val civilBase = CivilDate(2000, 1, 1)
val civilOffset = CivilDate(civilBase.toJdn() + selectedDayAbsoluteDistance)
val yearDiff = civilOffset.year - 2000
val monthDiff = civilOffset.month - 1
val dayOfMonthDiff = civilOffset.dayOfMonth - 1
var text = context.getString(R.string.date_diff_text).format(
formatNumber(selectedDayAbsoluteDistance.toInt()),
formatNumber(yearDiff),
formatNumber(monthDiff),
formatNumber(dayOfMonthDiff)
)
if (selectedDayAbsoluteDistance <= 31) text = text.split(" (")[0]
binding.diffDate.text = text
}
val mainDate = getDateFromJdnOfCalendar(chosenCalendarType, jdn)
val startOfYear = getDateOfCalendar(
chosenCalendarType,
mainDate.year, 1, 1
)
val startOfNextYear = getDateOfCalendar(
chosenCalendarType, mainDate.year + 1, 1, 1
)
val startOfYearJdn = startOfYear.toJdn()
val endOfYearJdn = startOfNextYear.toJdn() - 1
val currentWeek = calculateWeekOfYear(jdn, startOfYearJdn)
val weeksCount = calculateWeekOfYear(endOfYearJdn, startOfYearJdn)
val startOfYearText = context.getString(R.string.start_of_year_diff).format(
formatNumber((jdn - startOfYearJdn).toInt()),
formatNumber(currentWeek),
formatNumber(mainDate.month)
)
val endOfYearText = context.getString(R.string.end_of_year_diff).format(
formatNumber((endOfYearJdn - jdn).toInt()),
formatNumber(weeksCount - currentWeek),
formatNumber(12 - mainDate.month)
)
binding.startAndEndOfYearDiff.text =
listOf(startOfYearText, endOfYearText).joinToString("\n")
var equinox = ""
if (mainCalendar == chosenCalendarType && chosenCalendarType == CalendarType.SHAMSI) {
if (mainDate.month == 12 && mainDate.dayOfMonth >= 20 || mainDate.month == 1 && mainDate.dayOfMonth == 1) {
val addition = if (mainDate.month == 12) 1 else 0
val springEquinox = getSpringEquinox(mainDate.toJdn())
equinox = context.getString(R.string.spring_equinox).format(
formatNumber(mainDate.year + addition),
Clock(springEquinox[Calendar.HOUR_OF_DAY], springEquinox[Calendar.MINUTE])
.toFormattedString(forcedIn12 = true)
)
}
}
binding.equinox.apply {
text = equinox
visibility = if (equinox.isEmpty()) View.GONE else View.VISIBLE
}
binding.root.contentDescription = getA11yDaySummary(
context, jdn,
selectedDayAbsoluteDistance == 0L, emptyEventsStore(),
withZodiac = true, withOtherCalendars = true, withTitle = true
)
}
class CalendarItemAdapter internal constructor(context: Context) :
RecyclerView.Adapter<CalendarItemAdapter.ViewHolder>() {
private val calendarFont: Typeface = getCalendarFragmentFont(context)
private var calendars: List<CalendarType> = emptyList()
internal var isExpanded = false
set(expanded) {
field = expanded
calendars.indices.forEach(::notifyItemChanged)
}
private var jdn: Long = 0
internal fun setDate(calendars: List<CalendarType>, jdn: Long) {
this.calendars = calendars
this.jdn = jdn
calendars.indices.forEach(::notifyItemChanged)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
CalendarItemBinding.inflate(parent.context.layoutInflater, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position)
override fun getItemCount(): Int = calendars.size
inner class ViewHolder(private val binding: CalendarItemBinding) :
RecyclerView.ViewHolder(binding.root), OnClickListener {
init {
val applyLineMultiplier = !isCustomFontEnabled
binding.monthYear.typeface = calendarFont
binding.day.typeface = calendarFont
if (applyLineMultiplier) binding.monthYear.setLineSpacing(0f, .6f)
binding.container.setOnClickListener(this)
binding.linear.setOnClickListener(this)
}
fun bind(position: Int) {
val date = getDateFromJdnOfCalendar(calendars[position], jdn)
binding.linear.text = toLinearDate(date)
binding.linear.contentDescription = toLinearDate(date)
val firstCalendarString = formatDate(date)
binding.container.contentDescription = firstCalendarString
binding.day.contentDescription = ""
binding.day.text = formatNumber(date.dayOfMonth)
binding.monthYear.contentDescription = ""
binding.monthYear.text =
listOf(getMonthName(date), formatNumber(date.year)).joinToString("\n")
}
override fun onClick(view: View?) =
copyToClipboard(view, "converted date", view?.contentDescription)
}
}
}
| gpl-3.0 | 691c28fc7870d4438badd27e46a125da | 40.211055 | 119 | 0.638825 | 5.106476 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddDietTypeForm.kt | 1 | 1650 | package de.westnordost.streetcomplete.quests.diet_type
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.databinding.QuestDietTypeExplanationBinding
import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.diet_type.DietAvailability.*
class AddDietTypeForm : AbstractQuestAnswerFragment<DietAvailability>() {
override val contentLayoutResId = R.layout.quest_diet_type_explanation
private val binding by contentViewBinding(QuestDietTypeExplanationBinding::bind)
override val buttonPanelAnswers = listOf(
AnswerItem(R.string.quest_generic_hasFeature_no) { applyAnswer(DIET_NO) },
AnswerItem(R.string.quest_generic_hasFeature_yes) { applyAnswer(DIET_YES) },
AnswerItem(R.string.quest_hasFeature_only) { applyAnswer(DIET_ONLY) },
)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val resId = arguments?.getInt(ARG_DIET) ?: 0
if (resId > 0) {
binding.descriptionLabel.setText(resId)
} else {
binding.descriptionLabel.visibility = View.GONE
}
}
companion object {
private const val ARG_DIET = "diet_explanation"
fun create(dietExplanationResId: Int): AddDietTypeForm {
val form = AddDietTypeForm()
form.arguments = bundleOf(ARG_DIET to dietExplanationResId)
return form
}
}
}
| gpl-3.0 | 20d60088018ca6c1e4065269f966aa71 | 36.5 | 84 | 0.729697 | 4.532967 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/ThreadActivity.kt | 1 | 6010 | package com.boardgamegeek.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.Fragment
import com.boardgamegeek.R
import com.boardgamegeek.entities.ForumEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class ThreadActivity : SimpleSinglePaneActivity() {
private var threadId = BggContract.INVALID_ID
private var threadSubject = ""
private var forumId = BggContract.INVALID_ID
private var forumTitle: String = ""
private var objectId = BggContract.INVALID_ID
private var objectName = ""
private var objectType = ForumEntity.ForumType.REGION
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (objectName.isBlank()) {
supportActionBar?.title = forumTitle
supportActionBar?.subtitle = threadSubject
} else {
supportActionBar?.title = "$threadSubject - $forumTitle"
supportActionBar?.subtitle = objectName
}
if (savedInstanceState == null) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "Thread")
param(FirebaseAnalytics.Param.ITEM_ID, threadId.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, threadSubject)
}
}
}
override fun readIntent(intent: Intent) {
threadId = intent.getIntExtra(KEY_THREAD_ID, BggContract.INVALID_ID)
threadSubject = intent.getStringExtra(KEY_THREAD_SUBJECT).orEmpty()
forumId = intent.getIntExtra(KEY_FORUM_ID, BggContract.INVALID_ID)
forumTitle = intent.getStringExtra(KEY_FORUM_TITLE).orEmpty()
objectId = intent.getIntExtra(KEY_OBJECT_ID, BggContract.INVALID_ID)
objectName = intent.getStringExtra(KEY_OBJECT_NAME).orEmpty()
objectType = intent.getSerializableExtra(KEY_OBJECT_TYPE) as ForumEntity.ForumType
}
override fun onCreatePane(intent: Intent): Fragment {
return ThreadFragment.newInstance(threadId, forumId, forumTitle, objectId, objectName, objectType)
}
override val optionsMenuId = R.menu.view_share
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
ForumActivity.startUp(this, forumId, forumTitle, objectId, objectName, objectType)
finish()
}
R.id.menu_view -> {
linkToBgg("thread", threadId)
}
R.id.menu_share -> {
val description = if (objectName.isBlank())
String.format(getString(R.string.share_thread_text), threadSubject, forumTitle)
else
String.format(getString(R.string.share_thread_game_text), threadSubject, forumTitle, objectName)
val link = createBggUri("thread", threadId).toString()
share(
getString(R.string.share_thread_subject), """
$description
$link
""".trimIndent(), R.string.title_share
)
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "Thread")
param(FirebaseAnalytics.Param.ITEM_ID, threadId.toString())
param(
FirebaseAnalytics.Param.ITEM_NAME,
if (objectName.isBlank()) "$forumTitle | $threadSubject" else "$objectName | $forumTitle | $threadSubject"
)
}
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
companion object {
private const val KEY_FORUM_ID = "FORUM_ID"
private const val KEY_FORUM_TITLE = "FORUM_TITLE"
private const val KEY_OBJECT_ID = "OBJECT_ID"
private const val KEY_OBJECT_NAME = "OBJECT_NAME"
private const val KEY_OBJECT_TYPE = "OBJECT_TYPE"
private const val KEY_THREAD_ID = "THREAD_ID"
private const val KEY_THREAD_SUBJECT = "THREAD_SUBJECT"
fun start(
context: Context,
threadId: Int,
threadSubject: String,
forumId: Int,
forumTitle: String,
objectId: Int,
objectName: String,
objectType: ForumEntity.ForumType
) {
context.startActivity(createIntent(context, threadId, threadSubject, forumId, forumTitle, objectId, objectName, objectType))
}
fun startUp(
context: Context,
threadId: Int,
threadSubject: String,
forumId: Int,
forumTitle: String,
objectId: Int,
objectName: String,
objectType: ForumEntity.ForumType
) {
context.startActivity(createIntent(context, threadId, threadSubject, forumId, forumTitle, objectId, objectName, objectType).clearTop())
}
private fun createIntent(
context: Context,
threadId: Int,
threadSubject: String,
forumId: Int,
forumTitle: String,
objectId: Int,
objectName: String,
objectType: ForumEntity.ForumType,
): Intent {
return context.intentFor<ThreadActivity>(
KEY_THREAD_ID to threadId,
KEY_THREAD_SUBJECT to threadSubject,
KEY_FORUM_ID to forumId,
KEY_FORUM_TITLE to forumTitle,
KEY_OBJECT_ID to objectId,
KEY_OBJECT_NAME to objectName,
KEY_OBJECT_TYPE to objectType,
)
}
}
}
| gpl-3.0 | da6e091b196582155841788bd50aeab3 | 38.539474 | 147 | 0.606656 | 5.181034 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/model/list/ListItemModel.kt | 2 | 883 | package org.wordpress.android.fluxc.model.list
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.RawConstraints
import com.yarolegovich.wellsql.core.annotation.Table
@Table
@RawConstraints(
"FOREIGN KEY(LIST_ID) REFERENCES ListModel(_id) ON DELETE CASCADE",
"UNIQUE(LIST_ID, REMOTE_ITEM_ID) ON CONFLICT IGNORE"
)
class ListItemModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
constructor(listId: Int, remoteItemId: Long) : this() {
this.listId = listId
this.remoteItemId = remoteItemId
}
@Column var listId: Int = 0
@Column var remoteItemId: Long = 0
override fun getId(): Int = id
override fun setId(id: Int) {
this.id = id
}
}
| gpl-2.0 | 9045d8c405d3889d167725ae93e19c6a | 30.535714 | 81 | 0.723669 | 4.013636 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/pref/ext/PrefFlowableExt.kt | 1 | 931 | @file:Suppress("SpellCheckingInspection", "NOTHING_TO_INLINE")
package pref.ext
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import pref.Pref
import kotlin.reflect.KProperty0
@ExperimentalCoroutinesApi
@JvmOverloads
inline fun <T> Pref.asFlow(
prop: KProperty0<T>,
key: String? = null
): Flow<T> = callbackFlow {
val listenKey = key ?: prop.name
val listener = OnSharedPreferenceChangeListener { _, changeKey ->
if (listenKey == changeKey && !isClosedForSend) this.sendBlocking(prop.get())
}
preferences.registerOnSharedPreferenceChangeListener(listener)
awaitClose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
}
| apache-2.0 | 3e6c8e927d36b85327e3c0f38a949d68 | 34.807692 | 85 | 0.798067 | 4.874346 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/ProtobufPolymorphismTest.kt | 1 | 1344 | /*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf
import kotlinx.serialization.*
import kotlin.test.*
class ProtobufPolymorphismTest {
@Test
fun testAbstract() {
val obj = PolyBox(SimpleStringInheritor("str", 133))
assertSerializedToBinaryAndRestored(obj, PolyBox.serializer(),
ProtoBuf { encodeDefaults = true; serializersModule = SimplePolymorphicModule })
}
@Test
fun testSealed() {
val obj = SealedBox(
listOf(
SimpleSealed.SubSealedB(33),
SimpleSealed.SubSealedA("str")
)
)
assertSerializedToBinaryAndRestored(obj, SealedBox.serializer(), ProtoBuf)
}
@Serializable
sealed class Single {
@Serializable
data class Impl(val i: Int) : Single()
}
@Test
fun testSingleSealedClass() {
val expected =
"0a436b6f746c696e782e73657269616c697a6174696f6e2e70726f746f6275662e50726f746f627566506f6c796d6f72706869736d546573742e53696e676c652e496d706c1202082a"
assertEquals(expected, ProtoBuf.encodeToHexString(Single.serializer(), Single.Impl(42)))
assertEquals(Single.Impl(42), ProtoBuf.decodeFromHexString(Single.serializer(), expected))
}
}
| apache-2.0 | c620707a0c9411794f885ca265defeab | 31 | 160 | 0.681548 | 4.085106 | false | true | false | false |
MaKToff/Codename_Ghost | core/src/com/cypress/Levels/Level1.kt | 1 | 13329 | package com.cypress.Levels
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.Array
import com.cypress.CGHelpers.AssetLoader
import com.cypress.CGHelpers.Controls
import com.cypress.GameObjects.*
import com.cypress.GameObjects.Enemies.*
import com.cypress.Screens.GameOverScreen
import com.cypress.Screens.StatsScreen
import com.cypress.codenameghost.CGGame
import java.util.*
/** Contains definition of first level. */
public class Level1(private val game : CGGame, private val player : Player) : Screen {
private val assets = AssetLoader.getInstance()
private val batcher = SpriteBatch()
private var runTime = 0f
private val controls = Controls(game, player, this)
private val blockList = ArrayList<Block>()
private val enemyList = ArrayList<Warrior>()
private val itemsList = ArrayList<Item>()
private val removedBullets = ArrayList<Bullet>()
private val deadEnemies = ArrayList<Warrior>()
private val removedItems = ArrayList<Item>()
private val camera = OrthographicCamera(Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())
private var stage = Stage()
private var fan = Animation(0.02f, Array<TextureRegion>())
private var index = assets.gunNames.indexOf(player.gunType)
private var fanSoundOn = false
private var hmmSoundOn = true
private var gameStart = false
private var counter = 0
private var doorOpened = false
init {
stage = controls.getStage()
assets.activeMusic = assets.levelsMusic[1]
// adding blocks
val hSnow = TextureRegion(assets.levelsFP[1], 28, 924, 911, 73)
val vSnow = TextureRegion(assets.levelsFP[1], 907, 174, 100, 618)
val crate = TextureRegion(assets.levelsFP[1], 316, 46, 256, 128)
val roof = TextureRegion(assets.levelsFP[1], 314, 348, 386, 73)
val roof1 = TextureRegion(assets.levelsFP[1], 311, 451, 214, 46)
val roof2 = TextureRegion(assets.levelsFP[1], 313, 529, 416, 24)
val wall = TextureRegion(assets.levelsFP[1], 754, 201, 25, 225)
val door = TextureRegion(assets.levelsFP[1], 742, 448, 152, 257)
blockList.add(Block(Vector2( 86f, 950f), 911f, 73f, hSnow))
blockList.add(Block(Vector2( 86f, 656f), 911f, 73f, hSnow))
blockList.add(Block(Vector2( 997f, 950f), 125f, 73f, hSnow))
blockList.add(Block(Vector2( 520f, 390f), 465f, 73f, hSnow))
blockList.add(Block(Vector2(1330f, 374f), 880f, 73f, hSnow))
blockList.add(Block(Vector2(-166f, 68f), 256f, 128f, crate))
blockList.add(Block(Vector2( 80f, 68f), 256f, 128f, crate))
blockList.add(Block(Vector2(-110f, 190f), 256f, 128f, crate))
blockList.add(Block(Vector2( 664f, 448f), 100f, 550f, vSnow))
blockList.add(Block(Vector2( 897f, 448f), 100f, 550f, vSnow))
blockList.add(Block(Vector2(1317f, 892f), 100f, 618f, vSnow))
blockList.add(Block(Vector2(1317f, 413f), 100f, 618f, vSnow))
blockList.add(Block(Vector2(2129f, 380f), 100f, 370f, vSnow))
blockList.add(Block(Vector2(3230f, 403f), 386f, 73f, roof))
blockList.add(Block(Vector2(4376f, 929f), 386f, 73f, roof))
blockList.add(Block(Vector2(4763f, 616f), 386f, 73f, roof))
blockList.add(Block(Vector2(4559f, 357f), 214f, 46f, roof1))
blockList.add(Block(Vector2(5860f, 434f), 416f, 24f, roof2))
//blockList.add(Block(Vector2(6005f, 357f), 416f, 24f, roof2))
blockList.add(Block(Vector2(5860f, 434f), 25f, 225f, wall))
blockList.add(Block(Vector2(5999f, 100f), 152f, 257f, door))
// adding enemies
enemyList.add(Warrior(Vector2( 43f, 364f), player))
enemyList.add(Warrior(Vector2( 444f, 101f), player))
enemyList.add(Warrior(Vector2(2120f, 105f), player))
enemyList.add(Warrior(Vector2(3241f, 110f), player))
enemyList.add(Warrior(Vector2(3360f, 485f), player))
enemyList.add(Warrior(Vector2(4394f, 1013f), player))
enemyList.add(Warrior(Vector2(4608f, 404f), player))
enemyList.add(Warrior(Vector2(4612f, 110f), player))
enemyList.add(Warrior(Vector2(4821f, 700f), player))
enemyList.add(Warrior(Vector2(5850f, 110f), player))
// adding items
itemsList.add(Item(Vector2( 525f, 490f), assets.gunNames[1]))
itemsList.add(Item(Vector2(3405f, 478f), assets.ammoNames[1]))
itemsList.add(Item(Vector2(4530f, 1005f), "keyCard"))
itemsList.add(Item(Vector2(4637f, 495f), "medikit"))
// animation of fan
val fanPos = arrayOf(582, 732, 878)
val fanArray = Array<TextureRegion>()
fanArray.addAll(Array(3, {i -> TextureRegion(assets.levelsFP[1], fanPos[i], 14, 141, 134)}), 0, 3)
fan = Animation(0.02f, fanArray, Animation.PlayMode.LOOP)
}
/** Updates level information. */
private fun update() {
// if level completed
if (player.getX() >= player.mapLength) {
assets.snow?.stop()
assets.fan?.stop()
player.data[1] = 2 - player.lives
if (player.data[3] != 0) player.data[5] =
(player.data[4].toFloat() / player.data[3].toFloat() * 100).toInt()
game.availableLevels[2] = true
game.screen = StatsScreen(game, player.data)
}
// playing level1 music and sounds
if (assets.musicOn) {
if (!(assets.activeMusic?.isPlaying ?: false)) {
assets.activeMusic?.volume = 0.5f
assets.activeMusic?.play()
}
if ((player.shouldGoToLeft || player.shouldGoToRight) && player.onGround && player.getX() < 3096f)
assets.snow?.play()
else assets.snow?.stop()
if (player.getX() > 5345f && player.getX() < 6197f) {
if (!fanSoundOn) {
assets.fan?.setVolume(1, 0.5f)
assets.fan?.loop()
fanSoundOn = true
}
}
else {
assets.fan?.stop()
fanSoundOn = false
}
}
// player should shoot
index = assets.gunNames.indexOf(player.gunType)
if ((player.shouldShoot || Gdx.input.isKeyPressed(Input.Keys.ENTER))
&& counter % assets.rateOfFire[index] == 0 && index != 6) {
controls.shoot()
counter = 0
}
// player has a key
if (player.hasKey) {
blockList.removeAt(blockList.size - 1)
player.hasKey = false
doorOpened = true
}
// checking collision of bullets with enemies
for (bullet in assets.bulletsList) {
for (enemy in enemyList) {
if (bullet.getBounds().overlaps(enemy.getBound())) {
if(!bullet.enemyBulllet) {
enemy.health -= bullet.damage
if (bullet.damage == assets.bulletDamage[6]) bullet.shouldExplode = true
else if (!bullet.shouldExplode) removedBullets.add(bullet)
player.data[4]++
}
}
}
}
// checking collision of bullets with player
for (bullet in assets.bulletsList) {
if (bullet.getBounds().overlaps(player.getBound()) && bullet.enemyBulllet && !player.isDead ) {
player.health -= bullet.damage
if (player.health <= 0) {
player.health = 100
player.lives -= 1
player.isDead = true
// game over
if (player.lives < 0) {
assets.snow?.stop()
assets.fan?.stop()
assets.activeMusic?.stop()
assets.activeMusic = assets.gameOver
game.screen = GameOverScreen(game)
}
}
removedBullets.add(bullet)
}
}
// deleting dead enemy ...
for (enemy in deadEnemies)
// ... if he has already drawn his animation
if (!enemy.isDead) enemyList.remove(enemy)
// removing picked up items
for (item in removedItems) itemsList.remove(item)
// checking collision of bullets with blocks
for (bullet in assets.bulletsList)
for (block in blockList)
if(bullet.getBounds().overlaps(block.getBounds()))
if (bullet.damage == assets.bulletDamage[6]) bullet.shouldExplode = true
else if (!bullet.shouldExplode) removedBullets.add(bullet)
// removing bullets, which hit player or block
for (bullet in removedBullets) assets.bulletsList.remove(bullet)
}
/** Draws level. */
public override fun render(delta: Float) {
if (player.onGround) gameStart = true
runTime += delta
update()
counter++
// drawing background color
Gdx.gl.glClearColor(1f, 1f, 1f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
// setting camera
if (!gameStart) camera.position.set(120f, 1243f, 0f)
else camera.position.set(player.getX() + 100, player.getY() + 220, 0f)
camera.zoom = assets.zoom
batcher.projectionMatrix = camera.combined
camera.update()
// drawing background
batcher.begin()
if (player.getX() < 3096f) batcher.draw(assets.levelsBG[1][0], -400f, 0f, 4096f, 2048f)
else batcher.draw(assets.levelsBG[1][1], 2696f, 0f, 4096f, 2048f)
batcher.end()
// drawing blocks
for (block in blockList) block.draw(batcher)
// check collision with picked up items
for (item in itemsList) {
item.draw(batcher)
if (player.getBound().overlaps(item.getBounds())) {
item.activity(player)
removedItems.add(item)
}
}
// drawing terminal and hint
batcher.begin()
if (doorOpened)
batcher.draw(TextureRegion(assets.levelsFP[1], 171, 835, 94, 70), 5799f, 162f, 94f, 70f) // info
else {
batcher.draw(TextureRegion(assets.levelsFP[1], 28, 835, 94, 70), 5799f, 162f, 94f, 70f) // info
if (player.getX() >= 5799 && player.getX() <= 5893 && player.getY() <= 100f) {
var hint = TextureRegion(assets.levelsFP[1], 319, 568, 249, 163)
if (assets.language != "english")
hint = TextureRegion(assets.levelsFP[1], 319, 748, 249, 163)
batcher.draw(hint, 5831f, 281f, 249f, 163f)
if (hmmSoundOn) {
assets.neutral[(Math.random() * 1000).toInt() % 3]?.play()
hmmSoundOn = false
}
}
else hmmSoundOn = true
}
batcher.end()
// drawing bullets
if (!assets.bulletsList.isEmpty() && assets.bulletsList[0].distance() > 600)
assets.bulletsList.removeFirst()
for (b in assets.bulletsList) b.draw(runTime, batcher)
// drawing player
if (player.lives >= 0) {
player.update()
player.checkCollision(blockList)
player.draw(runTime, batcher)
}
// drawing enemies
for (enemy in enemyList) {
if(enemy.health <= 0 && !enemy.isDead) {
enemy.isDead = true
deadEnemies.add(enemy)
player.data[0] += 50
player.data[2]++
}
if (enemy.health > 0) {
enemy.update(runTime)
enemy.checkCollision(blockList)
}
enemy.draw(runTime, batcher)
}
// drawing first plan objects
batcher.begin()
batcher.enableBlending()
batcher.draw(TextureRegion(assets.levelsFP[1], 19, 0, 221, 417), 350f, 980f, 221f, 417f) // spruce
batcher.draw(TextureRegion(assets.levelsFP[1], 29, 437, 236, 356), 6151f, 77f, 236f, 356f) // fence
batcher.draw(fan.getKeyFrame(runTime), 5885f, 527f, 141f, 132f)
batcher.end()
// drawing stage
if (gameStart && !player.isDead) {
controls.update()
stage.act(runTime)
stage.draw()
}
}
public override fun resize(width : Int, height : Int) {}
public override fun show() {}
public override fun hide() {}
public override fun pause() {}
/** Restores screen after pause. */
public override fun resume() {
game.screen = this
Gdx.input.inputProcessor = stage
}
/** Dispose level 1. */
public override fun dispose() {
stage.dispose()
game.dispose()
}
} | apache-2.0 | b1d09932d5150b41c844505022d1eac4 | 39.03003 | 112 | 0.577988 | 3.952847 | false | false | false | false |
PaulWoitaschek/Voice | logging/debug/src/main/kotlin/voice/logging/debug/DebugLogWriter.kt | 1 | 2037 | package voice.logging.debug
import android.util.Log
import voice.logging.core.LogWriter
import voice.logging.core.Logger
import java.util.regex.Pattern
internal class DebugLogWriter : LogWriter {
/**
* This logic was borrowed from Timber: https://github.com/JakeWharton/timber
*/
override fun log(severity: Logger.Severity, message: String, throwable: Throwable?) {
val tag = Throwable().stackTrace
.first { it.className !in fqcnIgnore }
.let(::createStackElementTag)
val priority = severity.priority
if (message.length < MAX_LOG_LENGTH) {
if (priority == Log.ASSERT) {
Log.wtf(tag, message)
} else {
Log.println(priority, tag, message)
}
return
}
// Split by line, then ensure each line can fit into Log's maximum length.
var i = 0
val length = message.length
while (i < length) {
var newline = message.indexOf('\n', i)
newline = if (newline != -1) newline else length
do {
val end = newline.coerceAtMost(i + MAX_LOG_LENGTH)
val part = message.substring(i, end)
if (priority == Log.ASSERT) {
Log.wtf(tag, part)
} else {
Log.println(priority, tag, part)
}
i = end
} while (i < newline)
i++
}
}
}
private val fqcnIgnore = listOf(
DebugLogWriter::class.java.name,
Logger::class.java.name,
)
private const val MAX_LOG_LENGTH = 4000
private val ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$")
private fun createStackElementTag(element: StackTraceElement): String {
var tag = element.className.substringAfterLast('.')
val matcher = ANONYMOUS_CLASS.matcher(tag)
if (matcher.find()) {
tag = matcher.replaceAll("")
}
return "$tag:${element.lineNumber}"
}
private val Logger.Severity.priority: Int
get() = when (this) {
Logger.Severity.Verbose -> Log.VERBOSE
Logger.Severity.Debug -> Log.DEBUG
Logger.Severity.Info -> Log.INFO
Logger.Severity.Warn -> Log.WARN
Logger.Severity.Error -> Log.ERROR
}
| gpl-3.0 | 5961deb9a91879955a8aa6ae8063ae77 | 27.291667 | 87 | 0.645557 | 3.836158 | false | false | false | false |
PaulWoitaschek/Voice | bookOverview/src/main/kotlin/voice/bookOverview/deleteBook/DeleteBookDialog.kt | 1 | 2553 | package voice.bookOverview.deleteBook
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import voice.bookOverview.R
@Composable
internal fun DeleteBookDialog(
viewState: DeleteBookViewState,
onDismiss: () -> Unit,
onConfirmDeletion: () -> Unit,
onDeleteCheckBoxChecked: (Boolean) -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(stringResource(R.string.delete_book_dialog_title))
},
confirmButton = {
Button(
onClick = onConfirmDeletion,
enabled = viewState.deleteCheckBoxChecked,
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.error,
),
) {
Text(stringResource(id = R.string.delete))
}
},
dismissButton = {
TextButton(
onClick = onDismiss,
) {
Text(stringResource(id = R.string.dialog_cancel))
}
},
text = {
Column {
Text(stringResource(id = R.string.delete_book_dialog_content))
Spacer(modifier = Modifier.heightIn(8.dp))
Text(viewState.fileToDelete, style = MaterialTheme.typography.bodyLarge)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.padding(top = 8.dp)
.fillMaxWidth()
.clickable {
onDeleteCheckBoxChecked(!viewState.deleteCheckBoxChecked)
},
) {
Checkbox(
checked = viewState.deleteCheckBoxChecked,
onCheckedChange = onDeleteCheckBoxChecked,
)
Text(stringResource(id = R.string.delete_book_dialog_deletion_confirmation))
}
}
},
)
}
| gpl-3.0 | b6a7513aab014ba3e88fdae5f3b710a5 | 30.9125 | 86 | 0.702311 | 4.693015 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/zhuishu.kt | 1 | 2010 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.textList
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
/**
* Created by AoEiuV020 on 2018.06.08-18:30:24.
*/
class Zhuishu : DslJsoupNovelContext() {init {
// timeout,
hide = true
site {
name = "追书网"
baseUrl = "https://www.mangg.net"
logo = "https://www.mangg.net/images/logo.gif"
}
search {
get {
// https://www.mangg.net/search.php?q=%E9%83%BD%E5%B8%82
url = "/search.php"
data {
"q" to it
}
}
document {
items("div.result-list > div") {
name("> div.result-game-item-detail > h3 > a")
author("> div.result-game-item-detail > div > p:nth-child(1) > span:nth-child(2)")
}
}
}
// https://www.zhuishu.tw/id58054/
bookIdRegex = "/id(\\d+)"
detailPageTemplate = "/id%s/"
detail {
document {
novel {
name("#info > h1")
author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)"))
}
image("#fmimg > img")
update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
introduction("#intro")
}
}
chapters {
document {
items("#list > dl > dd > a")
lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
}
}
// https://www.zhuishu.tw/id58054/200787.html
bookIdWithChapterIdRegex = "/id(\\d+/\\d+)"
contentPageTemplate = "/id%s.html"
content {
document {
items("#content", block = { e ->
// 这网站正文第一行开关都有个utf8bom,不会被当成空白符过滤掉,
e.textList().map { it.removePrefix("\ufeff").trimStart() }
})
}
}
}
}
| gpl-3.0 | 1070626f49c89a9626bb174c568bcf2f | 28.661538 | 113 | 0.492739 | 3.4614 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UnreachableCatchBlock.kt | 1 | 2834 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.safeAs
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
/**
* Reports unreachable catch blocks.
* Catch blocks can be unreachable if the exception has already been caught in the block above.
*
* <noncompliant>
* fun test() {
* try {
* foo()
* } catch (t: Throwable) {
* bar()
* } catch (e: Exception) {
* // Unreachable
* baz()
* }
* }
* </noncompliant>
*
* <compliant>
* fun test() {
* try {
* foo()
* } catch (e: Exception) {
* baz()
* } catch (t: Throwable) {
* bar()
* }
* }
* </compliant>
*
*/
@RequiresTypeResolution
class UnreachableCatchBlock(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Warning,
"Unreachable catch block detected.",
Debt.FIVE_MINS
)
@Suppress("ReturnCount")
override fun visitCatchSection(catchClause: KtCatchClause) {
super.visitCatchSection(catchClause)
if (bindingContext == BindingContext.EMPTY) return
val tryExpression = catchClause.getStrictParentOfType<KtTryExpression>() ?: return
val prevCatchClauses = tryExpression.catchClauses.takeWhile { it != catchClause }
if (prevCatchClauses.isEmpty()) return
val catchClassDescriptor = catchClause.catchClassDescriptor() ?: return
if (prevCatchClauses.any { catchClassDescriptor.isSubclassOf(it) }) {
report(CodeSmell(issue, Entity.from(catchClause), "This catch block is unreachable."))
}
}
private fun KtCatchClause.catchClassDescriptor(): ClassDescriptor? {
val typeReference = catchParameter?.typeReference ?: return null
return bindingContext[BindingContext.TYPE, typeReference]?.constructor?.declarationDescriptor?.safeAs()
}
private fun ClassDescriptor.isSubclassOf(catchClause: KtCatchClause): Boolean {
val catchClassDescriptor = catchClause.catchClassDescriptor() ?: return false
return isSubclassOf(catchClassDescriptor)
}
}
| apache-2.0 | 40f72cbcb58d14f535ddbd58f075558f | 33.987654 | 111 | 0.707128 | 4.455975 | false | true | false | false |
renard314/textfairy | app/src/main/java/com/renard/ocr/util/AppStorage.kt | 1 | 2039 | package com.renard.ocr.util
import android.app.DownloadManager
import android.content.Context
import android.os.Environment
import android.os.Environment.MEDIA_MOUNTED
import android.os.StatFs
import com.renard.ocr.R
import java.io.File
object AppStorage {
private const val EXTERNAL_APP_DIRECTORY = "textfee"
private const val IMAGE_DIRECTORY = "pictures"
private const val CACHE_DIRECTORY = "thumbnails"
private const val OCR_DATA_DIRECTORY = "tessdata"
@JvmStatic
fun getImageDirectory(context: Context) = getAppDirectory(context)?.requireDirectory(IMAGE_DIRECTORY)
@JvmStatic
fun getCacheDirectory(context: Context) = getAppDirectory(context)?.requireDirectory(CACHE_DIRECTORY)
@JvmStatic
fun getTrainingDataDir(context: Context) = getAppDirectory(context)?.requireDirectory(OCR_DATA_DIRECTORY)
@JvmStatic
fun getPDFDir(context: Context) = getAppDirectory(context)?.requireDirectory(context.getString(R.string.config_pdf_file_dir))
private fun getAppDirectory(context: Context) =
if(Environment.getExternalStorageState()== MEDIA_MOUNTED){
context.getExternalFilesDir(EXTERNAL_APP_DIRECTORY)!!.also { it.mkdirs() }
} else {
null
}
@JvmStatic
fun setTrainedDataDestinationForDownload(context: Context, request: DownloadManager.Request, trainedDataFileName: String) {
request.setDestinationInExternalFilesDir(context, EXTERNAL_APP_DIRECTORY, "$OCR_DATA_DIRECTORY/$trainedDataFileName")
}
private fun File.requireDirectory(dir: String) =
File(this, dir).also { it.mkdirs() }
/**
* @return the free space on sdcard in bytes
*/
@JvmStatic
fun getFreeSpaceInBytes(context: Context): Long {
return try {
val stat = StatFs(getAppDirectory(context).toString())
val availableBlocks = stat.availableBlocks.toLong()
availableBlocks * stat.blockSize
} catch (ex: Exception) {
-1
}
}
} | apache-2.0 | 9cc80ea26ce25e408b5dc827c4a993f3 | 34.172414 | 129 | 0.700343 | 4.623583 | false | false | false | false |
soniccat/android-taskmanager | app_wordteacher/src/main/java/com/aglushkov/general/networkstatus/ConnectivityManager.kt | 1 | 2867 | package com.aglushkov.general.networkstatus
import android.content.Context
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.net.NetworkRequest
import android.os.Build
import com.aglushkov.modelcore.resource.CustomStateFlow
class ConnectivityManager constructor(val context: Context) {
private var connectivityManager = getConnectivityManager()
private val stateFlow = CustomStateFlow<Boolean>(false)
val flow = stateFlow.flow
@Volatile var isDeviceOnline = false
private set
@Volatile var isWifiMode = false
private set
private var networkCallback = object : android.net.ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
checkNetworkState()
}
override fun onLost(network: Network) {
super.onLost(network)
checkNetworkState()
}
}
fun register() {
registerNetworkCallback()
}
fun unregister() {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
private fun registerNetworkCallback() {
val builder = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
connectivityManager.registerNetworkCallback(builder.build(), networkCallback)
}
fun checkNetworkState() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network = connectivityManager.activeNetwork
updateCapabilities(network)
} else {
updateCapabilitiesLegacy(connectivityManager.activeNetworkInfo)
}
if (stateFlow.value != isDeviceOnline) {
stateFlow.offer(isDeviceOnline)
}
}
private fun updateCapabilities(network: Network?) {
val capabilities = if (network != null) connectivityManager.getNetworkCapabilities(network) else null
capabilities?.let {
isDeviceOnline = true
isWifiMode = it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} ?: run {
isDeviceOnline = false
isWifiMode = false
}
}
private fun updateCapabilitiesLegacy(networkInfo: NetworkInfo?) {
if (networkInfo?.isConnected == true && networkInfo?.isAvailable) {
isDeviceOnline = true
val isWifi = networkInfo.type == android.net.ConnectivityManager.TYPE_WIFI
val isWiMax = networkInfo.type == android.net.ConnectivityManager.TYPE_WIMAX
isWifiMode = isWifi || isWiMax
} else {
isDeviceOnline = false
isWifiMode = false
}
}
private fun getConnectivityManager() =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
} | mit | 3120750624cdac967b36dfcfdfc3aeb4 | 31.965517 | 109 | 0.671434 | 5.45057 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/series_recordings/SeriesRecordingDetailsFragment.kt | 1 | 5522 | package org.tvheadend.tvhclient.ui.features.dvr.series_recordings
import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import org.tvheadend.data.entity.SeriesRecording
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.SeriesRecordingDetailsFragmentBinding
import org.tvheadend.tvhclient.ui.base.BaseFragment
import org.tvheadend.tvhclient.ui.common.*
import org.tvheadend.tvhclient.ui.common.interfaces.ClearSearchResultsOrPopBackStackInterface
import org.tvheadend.tvhclient.ui.common.interfaces.RecordingRemovedInterface
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.extensions.visible
class SeriesRecordingDetailsFragment : BaseFragment(), RecordingRemovedInterface, ClearSearchResultsOrPopBackStackInterface {
private lateinit var seriesRecordingViewModel: SeriesRecordingViewModel
private var recording: SeriesRecording? = null
private lateinit var binding: SeriesRecordingDetailsFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.series_recording_details_fragment, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
seriesRecordingViewModel = ViewModelProvider(requireActivity())[SeriesRecordingViewModel::class.java]
if (!isDualPane) {
toolbarInterface.setTitle(getString(R.string.details))
toolbarInterface.setSubtitle("")
}
arguments?.let {
seriesRecordingViewModel.currentIdLiveData.value = it.getString("id", "")
}
seriesRecordingViewModel.recordingLiveData.observe(viewLifecycleOwner, {
recording = it
showRecordingDetails()
})
}
private fun showRecordingDetails() {
recording?.let {
binding.recording = it
binding.htspVersion = htspVersion
binding.isDualPane = isDualPane
binding.duplicateDetectionText = if (it.dupDetect < seriesRecordingViewModel.duplicateDetectionList.size) {
seriesRecordingViewModel.duplicateDetectionList[it.dupDetect]
} else {
seriesRecordingViewModel.duplicateDetectionList[0]
}
// The toolbar is hidden as a default to prevent pressing any icons if no recording
// has been loaded yet. The toolbar is shown here because a recording was loaded
binding.nestedToolbar.visible()
activity?.invalidateOptionsMenu()
} ?: run {
binding.scrollview.gone()
binding.status.text = getString(R.string.error_loading_recording_details)
binding.status.visible()
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val recording = this.recording ?: return
preparePopupOrToolbarSearchMenu(menu, recording.title, isConnectionToServerAvailable)
binding.nestedToolbar.menu.findItem(R.id.menu_edit_recording)?.isVisible = true
binding.nestedToolbar.menu.findItem(R.id.menu_remove_recording)?.isVisible = true
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.external_search_options_menu, menu)
binding.nestedToolbar.inflateMenu(R.menu.recording_details_toolbar_menu)
binding.nestedToolbar.setOnMenuItemClickListener { this.onOptionsItemSelected(it) }
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val ctx = context ?: return super.onOptionsItemSelected(item)
val recording = this.recording ?: return super.onOptionsItemSelected(item)
return when (item.itemId) {
R.id.menu_edit_recording -> editSelectedSeriesRecording(requireActivity(), recording.id)
R.id.menu_remove_recording -> showConfirmationToRemoveSelectedSeriesRecording(ctx, recording, this)
R.id.menu_search_imdb -> return searchTitleOnImdbWebsite(ctx, recording.title)
R.id.menu_search_fileaffinity -> return searchTitleOnFileAffinityWebsite(ctx, recording.title)
R.id.menu_search_youtube -> return searchTitleOnYoutube(ctx, recording.title)
R.id.menu_search_google -> return searchTitleOnGoogle(ctx, recording.title)
R.id.menu_search_epg -> return searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, recording.title)
else -> super.onOptionsItemSelected(item)
}
}
override fun onRecordingRemoved() {
if (!isDualPane) {
activity?.onBackPressed()
} else {
val detailsFragment = activity?.supportFragmentManager?.findFragmentById(R.id.details)
if (detailsFragment != null) {
activity?.supportFragmentManager?.beginTransaction()?.also {
it.remove(detailsFragment)
it.commit()
}
}
}
}
companion object {
fun newInstance(id: String): SeriesRecordingDetailsFragment {
val f = SeriesRecordingDetailsFragment()
val args = Bundle()
args.putString("id", id)
f.arguments = args
return f
}
}
}
| gpl-3.0 | 34b19160b3c9f7505aabb91f6d34dc4a | 43.532258 | 125 | 0.698479 | 5.239089 | false | false | false | false |
aglne/mycollab | mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/MessageRelayEmailNotificationActionImpl.kt | 3 | 5866 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.schedule.email.service
import com.hp.gagawa.java.elements.A
import com.mycollab.common.MonitorTypeConstants
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.StringUtils
import com.mycollab.html.LinkUtils
import com.mycollab.module.project.ProjectLinkGenerator
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.ProjectRelayEmailNotification
import com.mycollab.module.project.domain.SimpleMessage
import com.mycollab.module.project.i18n.MessageI18nEnum
import com.mycollab.module.project.service.MessageService
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.schedule.email.ItemFieldMapper
import com.mycollab.schedule.email.MailContext
import com.mycollab.schedule.email.project.MessageRelayEmailNotificationAction
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class MessageRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleMessage>(), MessageRelayEmailNotificationAction {
@Autowired private lateinit var messageService: MessageService
override fun getItemName(): String = StringUtils.trim(bean!!.title, 100)
override fun getProjectName(): String = bean!!.projectName!!
override fun getCreateSubject(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCreateSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), messageLink())
override fun getUpdateSubject(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getUpdateSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), messageLink())
override fun getCommentSubject(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCommentSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage(
MessageI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), messageLink())
private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write()
private fun userLink(context: MailContext<SimpleMessage>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write()
private fun messageLink() = A(ProjectLinkGenerator.generateMessagePreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write()
override fun getItemFieldMapper(): ItemFieldMapper = ItemFieldMapper()
override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleMessage? =
messageService.findById(notification.typeid.toInt(), notification.saccountid)
override fun getType(): String = ProjectTypeConstants.MESSAGE
override fun getTypeId(): String = "${bean!!.id}"
override fun buildExtraTemplateVariables(context: MailContext<SimpleMessage>) {
val emailNotification = context.emailNotification
val summary = bean!!.title
val summaryLink = ProjectLinkGenerator.generateMessagePreviewFullLink(siteUrl, bean!!.projectid, bean!!.id)
val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else ""
val userAvatar = LinkUtils.newAvatar(avatarId)
val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}"
val actionEnum = when (emailNotification.action) {
MonitorTypeConstants.CREATE_ACTION -> MessageI18nEnum.MAIL_CREATE_ITEM_HEADING
MonitorTypeConstants.UPDATE_ACTION -> MessageI18nEnum.MAIL_UPDATE_ITEM_HEADING
MonitorTypeConstants.ADD_COMMENT_ACTION -> MessageI18nEnum.MAIL_COMMENT_ITEM_HEADING
else -> throw MyCollabException("Not support action ${emailNotification.action}")
}
contentGenerator.putVariable("projectName", bean!!.projectName!!)
contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid))
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("name", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
contentGenerator.putVariable("message", bean!!.message)
}
} | agpl-3.0 | 7622011105fc5e2c44e4ac724570f4a0 | 52.816514 | 176 | 0.777835 | 5.060397 | false | false | false | false |
e16din/Incl | src/com/e16din/incl/InclButterKnife.kt | 1 | 1174 | package com.e16din.incl
import com.e16din.incl.BaseIncl.InsertionType.*
class InclButterKnife : BaseIncl() {
companion object {
const val VER = "8.4.0"
const val CLASSPATH_BUTTERKNIFE = "classpath 'com.jakewharton:butterknife-gradle-plugin:$VER'"
const val PLUGIN_BUTTERKNIFE = "com.jakewharton.butterknife"
const val VERSION_BUTTERKNIFE = """def ver_butterkinife = "$VER""""
const val COMPILE_BUTTERKNIFE = """compile "com.jakewharton:butterknife:${'$'}{ver_butterkinife}""""
const val APT_BUTTERKNIFE = """apt "com.jakewharton:butterknife-compiler:${'$'}{ver_butterkinife}""""
}
override fun name() = "ButterKnife"
override fun include() {
includeApt()
insert(TYPE_APPLY_PLUGIN, PLUGIN_BUTTERKNIFE)
insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, VERSION_BUTTERKNIFE)
insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, COMPILE_BUTTERKNIFE)
insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, APT_BUTTERKNIFE)
insert(TYPE_ALL_PROJECTS_REPOSITORY, "\n $REPOSITORY_MAVEN_CENTRAL")
insert(TYPE_DEPENDENCIES_CLASSPATH, CLASSPATH_BUTTERKNIFE)
}
} | mit | 54f78eca2a648d9ac675fc52c523d7f5 | 34.606061 | 109 | 0.689949 | 4.207885 | false | false | false | false |
edsilfer/star-wars-wiki | app/src/main/java/br/com/edsilfer/android/starwarswiki/model/dictionary/TMDBResponseDictionary.kt | 1 | 633 | package br.com.edsilfer.android.starwarswiki.model.dictionary
import com.google.gson.Gson
/**
* Created by ferna on 2/22/2017.
*/
class TMDBResponseDictionary {
val vote_average = ""
val backdrop_path = ""
val adult = ""
val id : Long = 0.toLong()
val title = ""
val overview = ""
val original_language = ""
val genre_ids = mutableListOf<String>()
val release_date = ""
val original_title = ""
val vote_count = ""
val poster_path = ""
val video = ""
val popularity = ""
val homepage = ""
override fun toString(): String {
return Gson().toJson(this)
}
} | apache-2.0 | 73e29e7011b3dd4bb48fc46b70b47430 | 21.642857 | 61 | 0.600316 | 3.813253 | false | false | false | false |
deskchanproject/DeskChanJava | src/main/kotlin/info/deskchan/MessageData/GUI/SetPanel.kt | 2 | 3952 | package info.deskchan.MessageData.GUI
import info.deskchan.core.MessageData
/**
* Set panel state.
*
* @property id System id of panel (will be transformed to "sender-id")
* @property name Title of panel
* @property type Type of panel, default: TAB
* @property action Action to perform to panel. SET by default
* @property controls Panel content
* @property onSave If present, adds button 'Save' at the bottom of panel, onSave will be message tag to send panel data
* @property onClose If present, onClose will be message tag to send panel data when closed
**/
@MessageData.Tag("gui:set-panel")
class SetPanel : MessageData {
enum class PanelType {
/** Creates tab in main menu of options **/
TAB,
/** Creates submenu in 'Plugins' tab after plugin control block **/
SUBMENU,
/** Creates custom window to show independently from options **/
WINDOW,
/** Creates panel that opens up in options window but set no link to it, so panel can be opened only through command or custom buttons. **/
PANEL
}
enum class ActionType {
/** Show panel on screen. Panel will be created if it haven't yet **/
SHOW,
/** Closes panel. No deletion will be performed, panel will save its state. **/
HIDE,
/** Register panel inside program. It will create all necessary links, but panel will not be opened. **/
SET,
/** Update panel content. Panel should be created before updating its content. **/
UPDATE,
/** Close panel and unregister it. **/
DELETE
}
val id: String
var name: String? = null
var controls: MutableList<Map<String, Any>>?
var onSave: String? = null
var onClose: String? = null
private var type: String = "TAB"
private var action: String = "SET"
fun getPanelType() = PanelType.valueOf(type.toUpperCase())
fun setPanelType(value: PanelType){
type = value.toString()
}
fun getActionType() = ActionType.valueOf(action.toUpperCase())
fun setActionType(value: ActionType){
action = value.toString()
}
constructor(id: String, vararg controls: Map<String, Any>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
}
constructor(id: String, controls: Collection<Map<String, Any>>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
}
constructor(id: String, panelType: PanelType, actionType: ActionType, vararg controls: Map<String, Any>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
setPanelType(panelType)
setActionType(actionType)
}
constructor(id: String, panelType: PanelType, actionType: ActionType, controls: Collection<Map<String, Any>>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
setPanelType(panelType)
setActionType(actionType)
}
constructor(id: String, panelType: PanelType, actionType: ActionType, name: String?, onClose: String?, onSave: String?,
vararg controls: Map<String, Any>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
setPanelType(panelType)
setActionType(actionType)
this.name = name
this.onClose = onClose
this.onSave = onSave
}
constructor(id: String, panelType: PanelType, actionType: ActionType, name: String?, onClose: String?, onSave: String?,
controls: Collection<Map<String, Any>>){
this.id = id
this.controls = if (controls.size > 0) controls.toMutableList() else null
setPanelType(panelType)
setActionType(actionType)
this.name = name
this.onClose = onClose
this.onSave = onSave
}
} | lgpl-3.0 | ad19925a7f028893d40f376d82969bc7 | 33.675439 | 147 | 0.647014 | 4.506271 | false | false | false | false |
android/xAnd11 | core/src/android/java/org/monksanctum/xand11/Font.kt | 1 | 8425 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.monksanctum.xand11.core
import android.graphics.Paint
import android.graphics.Typeface
import org.monksanctum.xand11.atoms.AtomManager
import org.monksanctum.xand11.core.Platform.Companion.intToHexString
import org.monksanctum.xand11.core.Utils.toCard16
import org.monksanctum.xand11.fonts.FontSpec
import org.monksanctum.xand11.graphics.XDrawable
actual class Font actual internal constructor(private val mSpec: FontSpec, name: String?) {
actual val fontProperties: MutableList<FontProperty> = ArrayList()
val mChars: MutableList<CharInfo> = ArrayList()
actual var minBounds = CharInfo()
actual var maxBounds = CharInfo()
actual val minCharOrByte2: Char = 32.toChar() // Card16
actual val defaultChar: Char = 32.toChar() // Card16
actual var maxCharOrByte2: Char = 255.toChar() // Card16
actual var isRtl: Boolean = false
actual val minByte1: Byte = 0
actual val maxByte1: Byte = 0
actual var allCharsExist: Boolean = false
actual var fontAscent: Int = 0 // Int16
actual var fontDescent: Int = 0 // Int16
val paint: Paint
// Platform.logd("Font", "getChars");
// ArrayList<CharInfo> chars = new ArrayList();
// char[] bytes = new char[maxCharOrByte2 - minCharOrByte2];
// float[] widths = new float[bytes.length];
// Rect bounds = new Rect();
// for (int i = 0; i < bytes.length; i++) {
// bytes[i] = (char) (i + minCharOrByte2);
// }
// mPaint.getTextWidths(new String(bytes), widths);
// for (int i = 0; i < bytes.length; i++) {
// CharInfo info = new CharInfo();
// float width = widths[i];
// mPaint.getTextBounds(bytes, i, 1, bounds);
// info.leftSideBearing = toCard16(bounds.left);
// info.rightSideBearing = toCard16(bounds.right);
// info.characterWidth = (int) width;
// info.ascent = toCard16(-bounds.top);
// info.descent = toCard16(bounds.bottom);
// chars.add(info);
// }
// Platform.logd("Font", "Done");
actual val chars: List<CharInfo>
get() = mChars
init {
paint = Paint()
// TODO: Add default and fixed.
if (mSpec.getSpec(0) == DEFAULT) {
paint.typeface = Typeface.DEFAULT
} else if (mSpec.getSpec(0) == FIXED) {
paint.typeface = Typeface.MONOSPACE
} else {
var base = Typeface.DEFAULT
var style = Typeface.NORMAL
if (FontSpec.WEIGHT_BOLD == mSpec.getSpec(FontSpec.WEIGHT_NAME)) {
style = style or Typeface.BOLD
}
if (FontSpec.SLANT_ITALICS == mSpec.getSpec(FontSpec.SLANT)) {
style = style or Typeface.ITALIC
}
try {
val sizeStr = mSpec.getSpec(FontSpec.PIXEL_SIZE)
val n = java.lang.Float.valueOf(sizeStr)
if (n > 0) {
paint.textSize = n * FONT_SCALING
}
} catch (e: java.lang.NumberFormatException) {
}
val type = mSpec.getSpec(FontSpec.FAMILY_NAME)
if (FontSpec.SPACING_PROPORTIONAL != mSpec.getSpec(FontSpec.SPACING)) {
base = Typeface.MONOSPACE
} else if (FontSpec.FAMILY_DEFAULT == type) {
base = Typeface.DEFAULT
} else if (FontSpec.FAMILY_SERIF == type) {
base = Typeface.SERIF
} else if (FontSpec.FAMILY_SANS_SERIF == type) {
base = Typeface.SANS_SERIF
} else {
base = Typeface.create(type, style)
}
if (FontSpec.REGISTRY_10646 == mSpec.getSpec(FontSpec.CHARSET_REGISTRY)) {
maxCharOrByte2 = 65534.toChar()
}
paint.typeface = Typeface.create(base, style)
}
// Calculate the minimum and maximum widths.
val bytes = CharArray(255 - minCharOrByte2.toInt() + 1)
val widths = FloatArray(bytes.size)
for (i in bytes.indices) {
bytes[i] = (i + minCharOrByte2.toInt()).toChar()
}
val metrics = paint.fontMetricsInt
fontAscent = (-metrics.ascent).toShort().toInt()
fontDescent = metrics.descent.toShort().toInt()
maxBounds.ascent = (-metrics.top).toShort().toInt()
maxBounds.descent = metrics.bottom.toShort().toInt()
paint.getTextWidths(String(bytes), widths)
val bounds = Rect()
minBounds.characterWidth = Int.MAX_VALUE
for (i in widths.indices) {
val width = widths[i]
if (width < minBounds.characterWidth) {
minBounds.characterWidth = width.toInt()
}
if (width > maxBounds.characterWidth) {
maxBounds.characterWidth = width.toInt()
}
// TODO: Don't hold this stuff in memory, seems wasteful.
val info = CharInfo()
paint.getTextBounds(bytes, i, 1, bounds)
info.leftSideBearing = toCard16(bounds.left)
info.rightSideBearing = toCard16(bounds.right)
info.characterWidth = width.toInt()
info.ascent = toCard16(-bounds.top)
info.descent = toCard16(bounds.bottom)
mChars.add(info)
}
maxBounds.rightSideBearing = maxBounds.characterWidth
if (name != null) {
val nameProp = FontProperty()
nameProp.name = AtomManager.instance.internAtom("FONT")
nameProp.value = AtomManager.instance.internAtom(name)
fontProperties.add(nameProp)
}
}
actual fun measureText(s: String): Float {
return paint.measureText(s)
}
actual fun paintGetTextBounds(text: String, start: Int, length: Int, bounds: Rect) {
return paint.getTextBounds(text, start, length, bounds)
}
override fun toString(): String {
return mSpec.toString()
}
actual fun getTextBounds(str: String, x: Int, y: Int, rect: Rect) {
rect.left = x
rect.right = x + paint.measureText(str).toInt()
rect.top = y - maxBounds.ascent
rect.bottom = y + maxBounds.descent
}
actual fun drawText(drawable: XDrawable, context: GraphicsContext,
str: String, x: Int, y: Int, rect: Rect) {
val paint = paint
paint.style = Paint.Style.FILL
paint.color = context.background
val canvas = drawable.lockCanvas(context)
canvas.drawRect(rect, paint)
paint.color = context.foreground
canvas.drawText(str, x.toFloat(), y.toFloat(), paint)
if (DEBUG) Platform.logd("DrawingProtocol", "Drawing text " + x + " " + y + " \""
+ str + "\" " + intToHexString(context.foreground))
drawable.unlockCanvas()
}
actual class FontProperty {
actual var name: Int = 0 // Atom
actual var value: Int = 0
}
actual class CharInfo {
actual var leftSideBearing: Int = 0 // Int16
actual var rightSideBearing: Int = 0 // Int16
actual var characterWidth: Int = 0 // Int16
actual var ascent: Int = 0 // Int16
actual var descent: Int = 0 // Int16
actual var attributes: Int = 0 // Card16
}
actual companion object {
actual val LEFT_TO_RIGHT: Byte = 0
actual val RIGHT_TO_LEFT: Byte = 1
actual internal val DEFAULT = "cursor"
actual internal val FIXED = "fixed"
private val FONT_SCALING = 2.5f
fun getTextBounds(str: String, paint: Paint, x: Int, y: Int, rect: Rect) {
paint.getTextBounds(str, 0, str.length, rect)
rect.offset(x, y)
}
}
}
| apache-2.0 | ab1c43a30ccc4a2b452b19bf83458b1c | 35.630435 | 91 | 0.588961 | 4.280996 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/input/key/Key.android.kt | 3 | 52941 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.key
import android.view.KeyEvent
import android.view.KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
import android.view.KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.key.Key.Companion.Number
import androidx.compose.ui.util.packInts
import androidx.compose.ui.util.unpackInt1
/**
* Actual implementation of [Key] for Android.
*
* @param keyCode an integer code representing the key pressed.
*
* @sample androidx.compose.ui.samples.KeyEventIsAltPressedSample
*/
@JvmInline
actual value class Key(val keyCode: Long) {
actual companion object {
/** Unknown key. */
@ExperimentalComposeUiApi
actual val Unknown = Key(KeyEvent.KEYCODE_UNKNOWN)
/**
* Soft Left key.
*
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom left
* of the display.
*/
@ExperimentalComposeUiApi
actual val SoftLeft = Key(KeyEvent.KEYCODE_SOFT_LEFT)
/**
* Soft Right key.
*
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom right
* of the display.
*/
@ExperimentalComposeUiApi
actual val SoftRight = Key(KeyEvent.KEYCODE_SOFT_RIGHT)
/**
* Home key.
*
* This key is handled by the framework and is never delivered to applications.
*/
@ExperimentalComposeUiApi
actual val Home = Key(KeyEvent.KEYCODE_HOME)
/** Back key. */
@ExperimentalComposeUiApi
actual val Back = Key(KeyEvent.KEYCODE_BACK)
/** Help key. */
@ExperimentalComposeUiApi
actual val Help = Key(KeyEvent.KEYCODE_HELP)
/**
* Navigate to previous key.
*
* Goes backward by one item in an ordered collection of items.
*/
@ExperimentalComposeUiApi
actual val NavigatePrevious = Key(KeyEvent.KEYCODE_NAVIGATE_PREVIOUS)
/**
* Navigate to next key.
*
* Advances to the next item in an ordered collection of items.
*/
@ExperimentalComposeUiApi
actual val NavigateNext = Key(KeyEvent.KEYCODE_NAVIGATE_NEXT)
/**
* Navigate in key.
*
* Activates the item that currently has focus or expands to the next level of a navigation
* hierarchy.
*/
@ExperimentalComposeUiApi
actual val NavigateIn = Key(KeyEvent.KEYCODE_NAVIGATE_IN)
/**
* Navigate out key.
*
* Backs out one level of a navigation hierarchy or collapses the item that currently has
* focus.
*/
@ExperimentalComposeUiApi
actual val NavigateOut = Key(KeyEvent.KEYCODE_NAVIGATE_OUT)
/** Consumed by the system for navigation up. */
@ExperimentalComposeUiApi
actual val SystemNavigationUp = Key(KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP)
/** Consumed by the system for navigation down. */
@ExperimentalComposeUiApi
actual val SystemNavigationDown = Key(KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN)
/** Consumed by the system for navigation left. */
@ExperimentalComposeUiApi
actual val SystemNavigationLeft = Key(KeyEvent.KEYCODE_SYSTEM_NAVIGATION_LEFT)
/** Consumed by the system for navigation right. */
@ExperimentalComposeUiApi
actual val SystemNavigationRight = Key(KeyEvent.KEYCODE_SYSTEM_NAVIGATION_RIGHT)
/** Call key. */
@ExperimentalComposeUiApi
actual val Call = Key(KeyEvent.KEYCODE_CALL)
/** End Call key. */
@ExperimentalComposeUiApi
actual val EndCall = Key(KeyEvent.KEYCODE_ENDCALL)
/**
* Up Arrow Key / Directional Pad Up key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionUp = Key(KeyEvent.KEYCODE_DPAD_UP)
/**
* Down Arrow Key / Directional Pad Down key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionDown = Key(KeyEvent.KEYCODE_DPAD_DOWN)
/**
* Left Arrow Key / Directional Pad Left key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionLeft = Key(KeyEvent.KEYCODE_DPAD_LEFT)
/**
* Right Arrow Key / Directional Pad Right key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionRight = Key(KeyEvent.KEYCODE_DPAD_RIGHT)
/**
* Center Arrow Key / Directional Pad Center key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionCenter = Key(KeyEvent.KEYCODE_DPAD_CENTER)
/** Directional Pad Up-Left. */
@ExperimentalComposeUiApi
actual val DirectionUpLeft = Key(KeyEvent.KEYCODE_DPAD_UP_LEFT)
/** Directional Pad Down-Left. */
@ExperimentalComposeUiApi
actual val DirectionDownLeft = Key(KeyEvent.KEYCODE_DPAD_DOWN_LEFT)
/** Directional Pad Up-Right. */
@ExperimentalComposeUiApi
actual val DirectionUpRight = Key(KeyEvent.KEYCODE_DPAD_UP_RIGHT)
/** Directional Pad Down-Right. */
@ExperimentalComposeUiApi
actual val DirectionDownRight = Key(KeyEvent.KEYCODE_DPAD_DOWN_RIGHT)
/**
* Volume Up key.
*
* Adjusts the speaker volume up.
*/
@ExperimentalComposeUiApi
actual val VolumeUp = Key(KeyEvent.KEYCODE_VOLUME_UP)
/**
* Volume Down key.
*
* Adjusts the speaker volume down.
*/
@ExperimentalComposeUiApi
actual val VolumeDown = Key(KeyEvent.KEYCODE_VOLUME_DOWN)
/** Power key. */
@ExperimentalComposeUiApi
actual val Power = Key(KeyEvent.KEYCODE_POWER)
/**
* Camera key.
*
* Used to launch a camera application or take pictures.
*/
@ExperimentalComposeUiApi
actual val Camera = Key(KeyEvent.KEYCODE_CAMERA)
/** Clear key. */
@ExperimentalComposeUiApi
actual val Clear = Key(KeyEvent.KEYCODE_CLEAR)
/** '0' key. */
@ExperimentalComposeUiApi
actual val Zero = Key(KeyEvent.KEYCODE_0)
/** '1' key. */
@ExperimentalComposeUiApi
actual val One = Key(KeyEvent.KEYCODE_1)
/** '2' key. */
@ExperimentalComposeUiApi
actual val Two = Key(KeyEvent.KEYCODE_2)
/** '3' key. */
@ExperimentalComposeUiApi
actual val Three = Key(KeyEvent.KEYCODE_3)
/** '4' key. */
@ExperimentalComposeUiApi
actual val Four = Key(KeyEvent.KEYCODE_4)
/** '5' key. */
@ExperimentalComposeUiApi
actual val Five = Key(KeyEvent.KEYCODE_5)
/** '6' key. */
@ExperimentalComposeUiApi
actual val Six = Key(KeyEvent.KEYCODE_6)
/** '7' key. */
@ExperimentalComposeUiApi
actual val Seven = Key(KeyEvent.KEYCODE_7)
/** '8' key. */
@ExperimentalComposeUiApi
actual val Eight = Key(KeyEvent.KEYCODE_8)
/** '9' key. */
@ExperimentalComposeUiApi
actual val Nine = Key(KeyEvent.KEYCODE_9)
/** '+' key. */
@ExperimentalComposeUiApi
actual val Plus = Key(KeyEvent.KEYCODE_PLUS)
/** '-' key. */
@ExperimentalComposeUiApi
actual val Minus = Key(KeyEvent.KEYCODE_MINUS)
/** '*' key. */
@ExperimentalComposeUiApi
actual val Multiply = Key(KeyEvent.KEYCODE_STAR)
/** '=' key. */
@ExperimentalComposeUiApi
actual val Equals = Key(KeyEvent.KEYCODE_EQUALS)
/** '#' key. */
@ExperimentalComposeUiApi
actual val Pound = Key(KeyEvent.KEYCODE_POUND)
/** 'A' key. */
@ExperimentalComposeUiApi
actual val A = Key(KeyEvent.KEYCODE_A)
/** 'B' key. */
@ExperimentalComposeUiApi
actual val B = Key(KeyEvent.KEYCODE_B)
/** 'C' key. */
@ExperimentalComposeUiApi
actual val C = Key(KeyEvent.KEYCODE_C)
/** 'D' key. */
@ExperimentalComposeUiApi
actual val D = Key(KeyEvent.KEYCODE_D)
/** 'E' key. */
@ExperimentalComposeUiApi
actual val E = Key(KeyEvent.KEYCODE_E)
/** 'F' key. */
@ExperimentalComposeUiApi
actual val F = Key(KeyEvent.KEYCODE_F)
/** 'G' key. */
@ExperimentalComposeUiApi
actual val G = Key(KeyEvent.KEYCODE_G)
/** 'H' key. */
@ExperimentalComposeUiApi
actual val H = Key(KeyEvent.KEYCODE_H)
/** 'I' key. */
@ExperimentalComposeUiApi
actual val I = Key(KeyEvent.KEYCODE_I)
/** 'J' key. */
@ExperimentalComposeUiApi
actual val J = Key(KeyEvent.KEYCODE_J)
/** 'K' key. */
@ExperimentalComposeUiApi
actual val K = Key(KeyEvent.KEYCODE_K)
/** 'L' key. */
@ExperimentalComposeUiApi
actual val L = Key(KeyEvent.KEYCODE_L)
/** 'M' key. */
@ExperimentalComposeUiApi
actual val M = Key(KeyEvent.KEYCODE_M)
/** 'N' key. */
@ExperimentalComposeUiApi
actual val N = Key(KeyEvent.KEYCODE_N)
/** 'O' key. */
@ExperimentalComposeUiApi
actual val O = Key(KeyEvent.KEYCODE_O)
/** 'P' key. */
@ExperimentalComposeUiApi
actual val P = Key(KeyEvent.KEYCODE_P)
/** 'Q' key. */
@ExperimentalComposeUiApi
actual val Q = Key(KeyEvent.KEYCODE_Q)
/** 'R' key. */
@ExperimentalComposeUiApi
actual val R = Key(KeyEvent.KEYCODE_R)
/** 'S' key. */
@ExperimentalComposeUiApi
actual val S = Key(KeyEvent.KEYCODE_S)
/** 'T' key. */
@ExperimentalComposeUiApi
actual val T = Key(KeyEvent.KEYCODE_T)
/** 'U' key. */
@ExperimentalComposeUiApi
actual val U = Key(KeyEvent.KEYCODE_U)
/** 'V' key. */
@ExperimentalComposeUiApi
actual val V = Key(KeyEvent.KEYCODE_V)
/** 'W' key. */
@ExperimentalComposeUiApi
actual val W = Key(KeyEvent.KEYCODE_W)
/** 'X' key. */
@ExperimentalComposeUiApi
actual val X = Key(KeyEvent.KEYCODE_X)
/** 'Y' key. */
@ExperimentalComposeUiApi
actual val Y = Key(KeyEvent.KEYCODE_Y)
/** 'Z' key. */
@ExperimentalComposeUiApi
actual val Z = Key(KeyEvent.KEYCODE_Z)
/** ',' key. */
@ExperimentalComposeUiApi
actual val Comma = Key(KeyEvent.KEYCODE_COMMA)
/** '.' key. */
@ExperimentalComposeUiApi
actual val Period = Key(KeyEvent.KEYCODE_PERIOD)
/** Left Alt modifier key. */
@ExperimentalComposeUiApi
actual val AltLeft = Key(KeyEvent.KEYCODE_ALT_LEFT)
/** Right Alt modifier key. */
@ExperimentalComposeUiApi
actual val AltRight = Key(KeyEvent.KEYCODE_ALT_RIGHT)
/** Left Shift modifier key. */
@ExperimentalComposeUiApi
actual val ShiftLeft = Key(KeyEvent.KEYCODE_SHIFT_LEFT)
/** Right Shift modifier key. */
@ExperimentalComposeUiApi
actual val ShiftRight = Key(KeyEvent.KEYCODE_SHIFT_RIGHT)
/** Tab key. */
@ExperimentalComposeUiApi
actual val Tab = Key(KeyEvent.KEYCODE_TAB)
/** Space key. */
@ExperimentalComposeUiApi
actual val Spacebar = Key(KeyEvent.KEYCODE_SPACE)
/**
* Symbol modifier key.
*
* Used to enter alternate symbols.
*/
@ExperimentalComposeUiApi
actual val Symbol = Key(KeyEvent.KEYCODE_SYM)
/**
* Browser special function key.
*
* Used to launch a browser application.
*/
@ExperimentalComposeUiApi
actual val Browser = Key(KeyEvent.KEYCODE_EXPLORER)
/**
* Envelope special function key.
*
* Used to launch a mail application.
*/
@ExperimentalComposeUiApi
actual val Envelope = Key(KeyEvent.KEYCODE_ENVELOPE)
/** Enter key. */
@ExperimentalComposeUiApi
actual val Enter = Key(KeyEvent.KEYCODE_ENTER)
/**
* Backspace key.
*
* Deletes characters before the insertion point, unlike [Delete].
*/
@ExperimentalComposeUiApi
actual val Backspace = Key(KeyEvent.KEYCODE_DEL)
/**
* Delete key.
*
* Deletes characters ahead of the insertion point, unlike [Backspace].
*/
@ExperimentalComposeUiApi
actual val Delete = Key(KeyEvent.KEYCODE_FORWARD_DEL)
/** Escape key. */
@ExperimentalComposeUiApi
actual val Escape = Key(KeyEvent.KEYCODE_ESCAPE)
/** Left Control modifier key. */
@ExperimentalComposeUiApi
actual val CtrlLeft = Key(KeyEvent.KEYCODE_CTRL_LEFT)
/** Right Control modifier key. */
@ExperimentalComposeUiApi
actual val CtrlRight = Key(KeyEvent.KEYCODE_CTRL_RIGHT)
/** Caps Lock key. */
@ExperimentalComposeUiApi
actual val CapsLock = Key(KeyEvent.KEYCODE_CAPS_LOCK)
/** Scroll Lock key. */
@ExperimentalComposeUiApi
actual val ScrollLock = Key(KeyEvent.KEYCODE_SCROLL_LOCK)
/** Left Meta modifier key. */
@ExperimentalComposeUiApi
actual val MetaLeft = Key(KeyEvent.KEYCODE_META_LEFT)
/** Right Meta modifier key. */
@ExperimentalComposeUiApi
actual val MetaRight = Key(KeyEvent.KEYCODE_META_RIGHT)
/** Function modifier key. */
@ExperimentalComposeUiApi
actual val Function = Key(KeyEvent.KEYCODE_FUNCTION)
/** System Request / Print Screen key. */
@ExperimentalComposeUiApi
actual val PrintScreen = Key(KeyEvent.KEYCODE_SYSRQ)
/** Break / Pause key. */
@ExperimentalComposeUiApi
actual val Break = Key(KeyEvent.KEYCODE_BREAK)
/**
* Home Movement key.
*
* Used for scrolling or moving the cursor around to the start of a line
* or to the top of a list.
*/
@ExperimentalComposeUiApi
actual val MoveHome = Key(KeyEvent.KEYCODE_MOVE_HOME)
/**
* End Movement key.
*
* Used for scrolling or moving the cursor around to the end of a line
* or to the bottom of a list.
*/
@ExperimentalComposeUiApi
actual val MoveEnd = Key(KeyEvent.KEYCODE_MOVE_END)
/**
* Insert key.
*
* Toggles insert / overwrite edit mode.
*/
@ExperimentalComposeUiApi
actual val Insert = Key(KeyEvent.KEYCODE_INSERT)
/** Cut key. */
@ExperimentalComposeUiApi
actual val Cut = Key(KeyEvent.KEYCODE_CUT)
/** Copy key. */
@ExperimentalComposeUiApi
actual val Copy = Key(KeyEvent.KEYCODE_COPY)
/** Paste key. */
@ExperimentalComposeUiApi
actual val Paste = Key(KeyEvent.KEYCODE_PASTE)
/** '`' (backtick) key. */
@ExperimentalComposeUiApi
actual val Grave = Key(KeyEvent.KEYCODE_GRAVE)
/** '[' key. */
@ExperimentalComposeUiApi
actual val LeftBracket = Key(KeyEvent.KEYCODE_LEFT_BRACKET)
/** ']' key. */
@ExperimentalComposeUiApi
actual val RightBracket = Key(KeyEvent.KEYCODE_RIGHT_BRACKET)
/** '/' key. */
@ExperimentalComposeUiApi
actual val Slash = Key(KeyEvent.KEYCODE_SLASH)
/** '\' key. */
@ExperimentalComposeUiApi
actual val Backslash = Key(KeyEvent.KEYCODE_BACKSLASH)
/** ';' key. */
@ExperimentalComposeUiApi
actual val Semicolon = Key(KeyEvent.KEYCODE_SEMICOLON)
/** ''' (apostrophe) key. */
@ExperimentalComposeUiApi
actual val Apostrophe = Key(KeyEvent.KEYCODE_APOSTROPHE)
/** '@' key. */
@ExperimentalComposeUiApi
actual val At = Key(KeyEvent.KEYCODE_AT)
/**
* Number modifier key.
*
* Used to enter numeric symbols.
* This key is not Num Lock; it is more like [AltLeft].
*/
@ExperimentalComposeUiApi
actual val Number = Key(KeyEvent.KEYCODE_NUM)
/**
* Headset Hook key.
*
* Used to hang up calls and stop media.
*/
@ExperimentalComposeUiApi
actual val HeadsetHook = Key(KeyEvent.KEYCODE_HEADSETHOOK)
/**
* Camera Focus key.
*
* Used to focus the camera.
*/
@ExperimentalComposeUiApi
actual val Focus = Key(KeyEvent.KEYCODE_FOCUS)
/** Menu key. */
@ExperimentalComposeUiApi
actual val Menu = Key(KeyEvent.KEYCODE_MENU)
/** Notification key. */
@ExperimentalComposeUiApi
actual val Notification = Key(KeyEvent.KEYCODE_NOTIFICATION)
/** Search key. */
@ExperimentalComposeUiApi
actual val Search = Key(KeyEvent.KEYCODE_SEARCH)
/** Page Up key. */
@ExperimentalComposeUiApi
actual val PageUp = Key(KeyEvent.KEYCODE_PAGE_UP)
/** Page Down key. */
@ExperimentalComposeUiApi
actual val PageDown = Key(KeyEvent.KEYCODE_PAGE_DOWN)
/**
* Picture Symbols modifier key.
*
* Used to switch symbol sets (Emoji, Kao-moji).
*/
@ExperimentalComposeUiApi
actual val PictureSymbols = Key(KeyEvent.KEYCODE_PICTSYMBOLS)
/**
* Switch Charset modifier key.
*
* Used to switch character sets (Kanji, Katakana).
*/
@ExperimentalComposeUiApi
actual val SwitchCharset = Key(KeyEvent.KEYCODE_SWITCH_CHARSET)
/**
* A Button key.
*
* On a game controller, the A button should be either the button labeled A
* or the first button on the bottom row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonA = Key(KeyEvent.KEYCODE_BUTTON_A)
/**
* B Button key.
*
* On a game controller, the B button should be either the button labeled B
* or the second button on the bottom row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonB = Key(KeyEvent.KEYCODE_BUTTON_B)
/**
* C Button key.
*
* On a game controller, the C button should be either the button labeled C
* or the third button on the bottom row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonC = Key(KeyEvent.KEYCODE_BUTTON_C)
/**
* X Button key.
*
* On a game controller, the X button should be either the button labeled X
* or the first button on the upper row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonX = Key(KeyEvent.KEYCODE_BUTTON_X)
/**
* Y Button key.
*
* On a game controller, the Y button should be either the button labeled Y
* or the second button on the upper row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonY = Key(KeyEvent.KEYCODE_BUTTON_Y)
/**
* Z Button key.
*
* On a game controller, the Z button should be either the button labeled Z
* or the third button on the upper row of controller buttons.
*/
@ExperimentalComposeUiApi
actual val ButtonZ = Key(KeyEvent.KEYCODE_BUTTON_Z)
/**
* L1 Button key.
*
* On a game controller, the L1 button should be either the button labeled L1 (or L)
* or the top left trigger button.
*/
@ExperimentalComposeUiApi
actual val ButtonL1 = Key(KeyEvent.KEYCODE_BUTTON_L1)
/**
* R1 Button key.
*
* On a game controller, the R1 button should be either the button labeled R1 (or R)
* or the top right trigger button.
*/
@ExperimentalComposeUiApi
actual val ButtonR1 = Key(KeyEvent.KEYCODE_BUTTON_R1)
/**
* L2 Button key.
*
* On a game controller, the L2 button should be either the button labeled L2
* or the bottom left trigger button.
*/
@ExperimentalComposeUiApi
actual val ButtonL2 = Key(KeyEvent.KEYCODE_BUTTON_L2)
/**
* R2 Button key.
*
* On a game controller, the R2 button should be either the button labeled R2
* or the bottom right trigger button.
*/
@ExperimentalComposeUiApi
actual val ButtonR2 = Key(KeyEvent.KEYCODE_BUTTON_R2)
/**
* Left Thumb Button key.
*
* On a game controller, the left thumb button indicates that the left (or only)
* joystick is pressed.
*/
@ExperimentalComposeUiApi
actual val ButtonThumbLeft = Key(KeyEvent.KEYCODE_BUTTON_THUMBL)
/**
* Right Thumb Button key.
*
* On a game controller, the right thumb button indicates that the right
* joystick is pressed.
*/
@ExperimentalComposeUiApi
actual val ButtonThumbRight = Key(KeyEvent.KEYCODE_BUTTON_THUMBR)
/**
* Start Button key.
*
* On a game controller, the button labeled Start.
*/
@ExperimentalComposeUiApi
actual val ButtonStart = Key(KeyEvent.KEYCODE_BUTTON_START)
/**
* Select Button key.
*
* On a game controller, the button labeled Select.
*/
@ExperimentalComposeUiApi
actual val ButtonSelect = Key(KeyEvent.KEYCODE_BUTTON_SELECT)
/**
* Mode Button key.
*
* On a game controller, the button labeled Mode.
*/
@ExperimentalComposeUiApi
actual val ButtonMode = Key(KeyEvent.KEYCODE_BUTTON_MODE)
/** Generic Game Pad Button #1. */
@ExperimentalComposeUiApi
actual val Button1 = Key(KeyEvent.KEYCODE_BUTTON_1)
/** Generic Game Pad Button #2. */
@ExperimentalComposeUiApi
actual val Button2 = Key(KeyEvent.KEYCODE_BUTTON_2)
/** Generic Game Pad Button #3. */
@ExperimentalComposeUiApi
actual val Button3 = Key(KeyEvent.KEYCODE_BUTTON_3)
/** Generic Game Pad Button #4. */
@ExperimentalComposeUiApi
actual val Button4 = Key(KeyEvent.KEYCODE_BUTTON_4)
/** Generic Game Pad Button #5. */
@ExperimentalComposeUiApi
actual val Button5 = Key(KeyEvent.KEYCODE_BUTTON_5)
/** Generic Game Pad Button #6. */
@ExperimentalComposeUiApi
actual val Button6 = Key(KeyEvent.KEYCODE_BUTTON_6)
/** Generic Game Pad Button #7. */
@ExperimentalComposeUiApi
actual val Button7 = Key(KeyEvent.KEYCODE_BUTTON_7)
/** Generic Game Pad Button #8. */
@ExperimentalComposeUiApi
actual val Button8 = Key(KeyEvent.KEYCODE_BUTTON_8)
/** Generic Game Pad Button #9. */
@ExperimentalComposeUiApi
actual val Button9 = Key(KeyEvent.KEYCODE_BUTTON_9)
/** Generic Game Pad Button #10. */
@ExperimentalComposeUiApi
actual val Button10 = Key(KeyEvent.KEYCODE_BUTTON_10)
/** Generic Game Pad Button #11. */
@ExperimentalComposeUiApi
actual val Button11 = Key(KeyEvent.KEYCODE_BUTTON_11)
/** Generic Game Pad Button #12. */
@ExperimentalComposeUiApi
actual val Button12 = Key(KeyEvent.KEYCODE_BUTTON_12)
/** Generic Game Pad Button #13. */
@ExperimentalComposeUiApi
actual val Button13 = Key(KeyEvent.KEYCODE_BUTTON_13)
/** Generic Game Pad Button #14. */
@ExperimentalComposeUiApi
actual val Button14 = Key(KeyEvent.KEYCODE_BUTTON_14)
/** Generic Game Pad Button #15. */
@ExperimentalComposeUiApi
actual val Button15 = Key(KeyEvent.KEYCODE_BUTTON_15)
/** Generic Game Pad Button #16. */
@ExperimentalComposeUiApi
actual val Button16 = Key(KeyEvent.KEYCODE_BUTTON_16)
/**
* Forward key.
*
* Navigates forward in the history stack. Complement of [Back].
*/
@ExperimentalComposeUiApi
actual val Forward = Key(KeyEvent.KEYCODE_FORWARD)
/** F1 key. */
@ExperimentalComposeUiApi
actual val F1 = Key(KeyEvent.KEYCODE_F1)
/** F2 key. */
@ExperimentalComposeUiApi
actual val F2 = Key(KeyEvent.KEYCODE_F2)
/** F3 key. */
@ExperimentalComposeUiApi
actual val F3 = Key(KeyEvent.KEYCODE_F3)
/** F4 key. */
@ExperimentalComposeUiApi
actual val F4 = Key(KeyEvent.KEYCODE_F4)
/** F5 key. */
@ExperimentalComposeUiApi
actual val F5 = Key(KeyEvent.KEYCODE_F5)
/** F6 key. */
@ExperimentalComposeUiApi
actual val F6 = Key(KeyEvent.KEYCODE_F6)
/** F7 key. */
@ExperimentalComposeUiApi
actual val F7 = Key(KeyEvent.KEYCODE_F7)
/** F8 key. */
@ExperimentalComposeUiApi
actual val F8 = Key(KeyEvent.KEYCODE_F8)
/** F9 key. */
@ExperimentalComposeUiApi
actual val F9 = Key(KeyEvent.KEYCODE_F9)
/** F10 key. */
@ExperimentalComposeUiApi
actual val F10 = Key(KeyEvent.KEYCODE_F10)
/** F11 key. */
@ExperimentalComposeUiApi
actual val F11 = Key(KeyEvent.KEYCODE_F11)
/** F12 key. */
@ExperimentalComposeUiApi
actual val F12 = Key(KeyEvent.KEYCODE_F12)
/**
* Num Lock key.
*
* This is the Num Lock key; it is different from [Number].
* This key alters the behavior of other keys on the numeric keypad.
*/
@ExperimentalComposeUiApi
actual val NumLock = Key(KeyEvent.KEYCODE_NUM_LOCK)
/** Numeric keypad '0' key. */
@ExperimentalComposeUiApi
actual val NumPad0 = Key(KeyEvent.KEYCODE_NUMPAD_0)
/** Numeric keypad '1' key. */
@ExperimentalComposeUiApi
actual val NumPad1 = Key(KeyEvent.KEYCODE_NUMPAD_1)
/** Numeric keypad '2' key. */
@ExperimentalComposeUiApi
actual val NumPad2 = Key(KeyEvent.KEYCODE_NUMPAD_2)
/** Numeric keypad '3' key. */
@ExperimentalComposeUiApi
actual val NumPad3 = Key(KeyEvent.KEYCODE_NUMPAD_3)
/** Numeric keypad '4' key. */
@ExperimentalComposeUiApi
actual val NumPad4 = Key(KeyEvent.KEYCODE_NUMPAD_4)
/** Numeric keypad '5' key. */
@ExperimentalComposeUiApi
actual val NumPad5 = Key(KeyEvent.KEYCODE_NUMPAD_5)
/** Numeric keypad '6' key. */
@ExperimentalComposeUiApi
actual val NumPad6 = Key(KeyEvent.KEYCODE_NUMPAD_6)
/** Numeric keypad '7' key. */
@ExperimentalComposeUiApi
actual val NumPad7 = Key(KeyEvent.KEYCODE_NUMPAD_7)
/** Numeric keypad '8' key. */
@ExperimentalComposeUiApi
actual val NumPad8 = Key(KeyEvent.KEYCODE_NUMPAD_8)
/** Numeric keypad '9' key. */
@ExperimentalComposeUiApi
actual val NumPad9 = Key(KeyEvent.KEYCODE_NUMPAD_9)
/** Numeric keypad '/' key (for division). */
@ExperimentalComposeUiApi
actual val NumPadDivide = Key(KeyEvent.KEYCODE_NUMPAD_DIVIDE)
/** Numeric keypad '*' key (for multiplication). */
@ExperimentalComposeUiApi
actual val NumPadMultiply = Key(KeyEvent.KEYCODE_NUMPAD_MULTIPLY)
/** Numeric keypad '-' key (for subtraction). */
@ExperimentalComposeUiApi
actual val NumPadSubtract = Key(KeyEvent.KEYCODE_NUMPAD_SUBTRACT)
/** Numeric keypad '+' key (for addition). */
@ExperimentalComposeUiApi
actual val NumPadAdd = Key(KeyEvent.KEYCODE_NUMPAD_ADD)
/** Numeric keypad '.' key (for decimals or digit grouping). */
@ExperimentalComposeUiApi
actual val NumPadDot = Key(KeyEvent.KEYCODE_NUMPAD_DOT)
/** Numeric keypad ',' key (for decimals or digit grouping). */
@ExperimentalComposeUiApi
actual val NumPadComma = Key(KeyEvent.KEYCODE_NUMPAD_COMMA)
/** Numeric keypad Enter key. */
@ExperimentalComposeUiApi
actual val NumPadEnter = Key(KeyEvent.KEYCODE_NUMPAD_ENTER)
/** Numeric keypad '=' key. */
@ExperimentalComposeUiApi
actual val NumPadEquals = Key(KeyEvent.KEYCODE_NUMPAD_EQUALS)
/** Numeric keypad '(' key. */
@ExperimentalComposeUiApi
actual val NumPadLeftParenthesis = Key(KeyEvent.KEYCODE_NUMPAD_LEFT_PAREN)
/** Numeric keypad ')' key. */
@ExperimentalComposeUiApi
actual val NumPadRightParenthesis = Key(KeyEvent.KEYCODE_NUMPAD_RIGHT_PAREN)
/** Play media key. */
@ExperimentalComposeUiApi
actual val MediaPlay = Key(KeyEvent.KEYCODE_MEDIA_PLAY)
/** Pause media key. */
@ExperimentalComposeUiApi
actual val MediaPause = Key(KeyEvent.KEYCODE_MEDIA_PAUSE)
/** Play/Pause media key. */
@ExperimentalComposeUiApi
actual val MediaPlayPause = Key(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
/** Stop media key. */
@ExperimentalComposeUiApi
actual val MediaStop = Key(KeyEvent.KEYCODE_MEDIA_STOP)
/** Record media key. */
@ExperimentalComposeUiApi
actual val MediaRecord = Key(KeyEvent.KEYCODE_MEDIA_RECORD)
/** Play Next media key. */
@ExperimentalComposeUiApi
actual val MediaNext = Key(KeyEvent.KEYCODE_MEDIA_NEXT)
/** Play Previous media key. */
@ExperimentalComposeUiApi
actual val MediaPrevious = Key(KeyEvent.KEYCODE_MEDIA_PREVIOUS)
/** Rewind media key. */
@ExperimentalComposeUiApi
actual val MediaRewind = Key(KeyEvent.KEYCODE_MEDIA_REWIND)
/** Fast Forward media key. */
@ExperimentalComposeUiApi
actual val MediaFastForward = Key(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD)
/**
* Close media key.
*
* May be used to close a CD tray, for example.
*/
@ExperimentalComposeUiApi
actual val MediaClose = Key(KeyEvent.KEYCODE_MEDIA_CLOSE)
/**
* Audio Track key.
*
* Switches the audio tracks.
*/
@ExperimentalComposeUiApi
actual val MediaAudioTrack = Key(KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK)
/**
* Eject media key.
*
* May be used to eject a CD tray, for example.
*/
@ExperimentalComposeUiApi
actual val MediaEject = Key(KeyEvent.KEYCODE_MEDIA_EJECT)
/**
* Media Top Menu key.
*
* Goes to the top of media menu.
*/
@ExperimentalComposeUiApi
actual val MediaTopMenu = Key(KeyEvent.KEYCODE_MEDIA_TOP_MENU)
/** Skip forward media key. */
@ExperimentalComposeUiApi
actual val MediaSkipForward = Key(KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD)
/** Skip backward media key. */
@ExperimentalComposeUiApi
actual val MediaSkipBackward = Key(KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD)
/**
* Step forward media key.
*
* Steps media forward, one frame at a time.
*/
@ExperimentalComposeUiApi
actual val MediaStepForward = Key(KeyEvent.KEYCODE_MEDIA_STEP_FORWARD)
/**
* Step backward media key.
*
* Steps media backward, one frame at a time.
*/
@ExperimentalComposeUiApi
actual val MediaStepBackward = Key(KeyEvent.KEYCODE_MEDIA_STEP_BACKWARD)
/**
* Mute key.
*
* Mutes the microphone, unlike [VolumeMute].
*/
@ExperimentalComposeUiApi
actual val MicrophoneMute = Key(KeyEvent.KEYCODE_MUTE)
/**
* Volume Mute key.
*
* Mutes the speaker, unlike [MicrophoneMute].
*
* This key should normally be implemented as a toggle such that the first press
* mutes the speaker and the second press restores the original volume.
*/
@ExperimentalComposeUiApi
actual val VolumeMute = Key(KeyEvent.KEYCODE_VOLUME_MUTE)
/**
* Info key.
*
* Common on TV remotes to show additional information related to what is
* currently being viewed.
*/
@ExperimentalComposeUiApi
actual val Info = Key(KeyEvent.KEYCODE_INFO)
/**
* Channel up key.
*
* On TV remotes, increments the television channel.
*/
@ExperimentalComposeUiApi
actual val ChannelUp = Key(KeyEvent.KEYCODE_CHANNEL_UP)
/**
* Channel down key.
*
* On TV remotes, decrements the television channel.
*/
@ExperimentalComposeUiApi
actual val ChannelDown = Key(KeyEvent.KEYCODE_CHANNEL_DOWN)
/** Zoom in key. */
@ExperimentalComposeUiApi
actual val ZoomIn = Key(KeyEvent.KEYCODE_ZOOM_IN)
/** Zoom out key. */
@ExperimentalComposeUiApi
actual val ZoomOut = Key(KeyEvent.KEYCODE_ZOOM_OUT)
/**
* TV key.
*
* On TV remotes, switches to viewing live TV.
*/
@ExperimentalComposeUiApi
actual val Tv = Key(KeyEvent.KEYCODE_TV)
/**
* Window key.
*
* On TV remotes, toggles picture-in-picture mode or other windowing functions.
* On Android Wear devices, triggers a display offset.
*/
@ExperimentalComposeUiApi
actual val Window = Key(KeyEvent.KEYCODE_WINDOW)
/**
* Guide key.
*
* On TV remotes, shows a programming guide.
*/
@ExperimentalComposeUiApi
actual val Guide = Key(KeyEvent.KEYCODE_GUIDE)
/**
* DVR key.
*
* On some TV remotes, switches to a DVR mode for recorded shows.
*/
@ExperimentalComposeUiApi
actual val Dvr = Key(KeyEvent.KEYCODE_DVR)
/**
* Bookmark key.
*
* On some TV remotes, bookmarks content or web pages.
*/
@ExperimentalComposeUiApi
actual val Bookmark = Key(KeyEvent.KEYCODE_BOOKMARK)
/**
* Toggle captions key.
*
* Switches the mode for closed-captioning text, for example during television shows.
*/
@ExperimentalComposeUiApi
actual val Captions = Key(KeyEvent.KEYCODE_CAPTIONS)
/**
* Settings key.
*
* Starts the system settings activity.
*/
@ExperimentalComposeUiApi
actual val Settings = Key(KeyEvent.KEYCODE_SETTINGS)
/**
* TV power key.
*
* On TV remotes, toggles the power on a television screen.
*/
@ExperimentalComposeUiApi
actual val TvPower = Key(KeyEvent.KEYCODE_TV_POWER)
/**
* TV input key.
*
* On TV remotes, switches the input on a television screen.
*/
@ExperimentalComposeUiApi
actual val TvInput = Key(KeyEvent.KEYCODE_TV_INPUT)
/**
* Set-top-box power key.
*
* On TV remotes, toggles the power on an external Set-top-box.
*/
@ExperimentalComposeUiApi
actual val SetTopBoxPower = Key(KeyEvent.KEYCODE_STB_POWER)
/**
* Set-top-box input key.
*
* On TV remotes, switches the input mode on an external Set-top-box.
*/
@ExperimentalComposeUiApi
actual val SetTopBoxInput = Key(KeyEvent.KEYCODE_STB_INPUT)
/**
* A/V Receiver power key.
*
* On TV remotes, toggles the power on an external A/V Receiver.
*/
@ExperimentalComposeUiApi
actual val AvReceiverPower = Key(KeyEvent.KEYCODE_AVR_POWER)
/**
* A/V Receiver input key.
*
* On TV remotes, switches the input mode on an external A/V Receiver.
*/
@ExperimentalComposeUiApi
actual val AvReceiverInput = Key(KeyEvent.KEYCODE_AVR_INPUT)
/**
* Red "programmable" key.
*
* On TV remotes, acts as a contextual/programmable key.
*/
@ExperimentalComposeUiApi
actual val ProgramRed = Key(KeyEvent.KEYCODE_PROG_RED)
/**
* Green "programmable" key.
*
* On TV remotes, acts as a contextual/programmable key.
*/
@ExperimentalComposeUiApi
actual val ProgramGreen = Key(KeyEvent.KEYCODE_PROG_GREEN)
/**
* Yellow "programmable" key.
*
* On TV remotes, acts as a contextual/programmable key.
*/
@ExperimentalComposeUiApi
actual val ProgramYellow = Key(KeyEvent.KEYCODE_PROG_YELLOW)
/**
* Blue "programmable" key.
*
* On TV remotes, acts as a contextual/programmable key.
*/
@ExperimentalComposeUiApi
actual val ProgramBlue = Key(KeyEvent.KEYCODE_PROG_BLUE)
/**
* App switch key.
*
* Should bring up the application switcher dialog.
*/
@ExperimentalComposeUiApi
actual val AppSwitch = Key(KeyEvent.KEYCODE_APP_SWITCH)
/**
* Language Switch key.
*
* Toggles the current input language such as switching between English and Japanese on
* a QWERTY keyboard. On some devices, the same function may be performed by
* pressing Shift+Space.
*/
@ExperimentalComposeUiApi
actual val LanguageSwitch = Key(KeyEvent.KEYCODE_LANGUAGE_SWITCH)
/**
* Manner Mode key.
*
* Toggles silent or vibrate mode on and off to make the device behave more politely
* in certain settings such as on a crowded train. On some devices, the key may only
* operate when long-pressed.
*/
@ExperimentalComposeUiApi
actual val MannerMode = Key(KeyEvent.KEYCODE_MANNER_MODE)
/**
* 3D Mode key.
*
* Toggles the display between 2D and 3D mode.
*/
@ExperimentalComposeUiApi
actual val Toggle2D3D = Key(KeyEvent.KEYCODE_3D_MODE)
/**
* Contacts special function key.
*
* Used to launch an address book application.
*/
@ExperimentalComposeUiApi
actual val Contacts = Key(KeyEvent.KEYCODE_CONTACTS)
/**
* Calendar special function key.
*
* Used to launch a calendar application.
*/
@ExperimentalComposeUiApi
actual val Calendar = Key(KeyEvent.KEYCODE_CALENDAR)
/**
* Music special function key.
*
* Used to launch a music player application.
*/
@ExperimentalComposeUiApi
actual val Music = Key(KeyEvent.KEYCODE_MUSIC)
/**
* Calculator special function key.
*
* Used to launch a calculator application.
*/
@ExperimentalComposeUiApi
actual val Calculator = Key(KeyEvent.KEYCODE_CALCULATOR)
/** Japanese full-width / half-width key. */
@ExperimentalComposeUiApi
actual val ZenkakuHankaru = Key(KeyEvent.KEYCODE_ZENKAKU_HANKAKU)
/** Japanese alphanumeric key. */
@ExperimentalComposeUiApi
actual val Eisu = Key(KeyEvent.KEYCODE_EISU)
/** Japanese non-conversion key. */
@ExperimentalComposeUiApi
actual val Muhenkan = Key(KeyEvent.KEYCODE_MUHENKAN)
/** Japanese conversion key. */
@ExperimentalComposeUiApi
actual val Henkan = Key(KeyEvent.KEYCODE_HENKAN)
/** Japanese katakana / hiragana key. */
@ExperimentalComposeUiApi
actual val KatakanaHiragana = Key(KeyEvent.KEYCODE_KATAKANA_HIRAGANA)
/** Japanese Yen key. */
@ExperimentalComposeUiApi
actual val Yen = Key(KeyEvent.KEYCODE_YEN)
/** Japanese Ro key. */
@ExperimentalComposeUiApi
actual val Ro = Key(KeyEvent.KEYCODE_RO)
/** Japanese kana key. */
@ExperimentalComposeUiApi
actual val Kana = Key(KeyEvent.KEYCODE_KANA)
/**
* Assist key.
*
* Launches the global assist activity. Not delivered to applications.
*/
@ExperimentalComposeUiApi
actual val Assist = Key(KeyEvent.KEYCODE_ASSIST)
/**
* Brightness Down key.
*
* Adjusts the screen brightness down.
*/
@ExperimentalComposeUiApi
actual val BrightnessDown = Key(KeyEvent.KEYCODE_BRIGHTNESS_DOWN)
/**
* Brightness Up key.
*
* Adjusts the screen brightness up.
*/
@ExperimentalComposeUiApi
actual val BrightnessUp = Key(KeyEvent.KEYCODE_BRIGHTNESS_UP)
/**
* Sleep key.
*
* Puts the device to sleep. Behaves somewhat like [Power] but it
* has no effect if the device is already asleep.
*/
@ExperimentalComposeUiApi
actual val Sleep = Key(KeyEvent.KEYCODE_SLEEP)
/**
* Wakeup key.
*
* Wakes up the device. Behaves somewhat like [Power] but it
* has no effect if the device is already awake.
*/
@ExperimentalComposeUiApi
actual val WakeUp = Key(KeyEvent.KEYCODE_WAKEUP)
/** Put device to sleep unless a wakelock is held. */
@ExperimentalComposeUiApi
actual val SoftSleep = Key(KeyEvent.KEYCODE_SOFT_SLEEP)
/**
* Pairing key.
*
* Initiates peripheral pairing mode. Useful for pairing remote control
* devices or game controllers, especially if no other input mode is
* available.
*/
@ExperimentalComposeUiApi
actual val Pairing = Key(KeyEvent.KEYCODE_PAIRING)
/**
* Last Channel key.
*
* Goes to the last viewed channel.
*/
@ExperimentalComposeUiApi
actual val LastChannel = Key(KeyEvent.KEYCODE_LAST_CHANNEL)
/**
* TV data service key.
*
* Displays data services like weather, sports.
*/
@ExperimentalComposeUiApi
actual val TvDataService = Key(KeyEvent.KEYCODE_TV_DATA_SERVICE)
/**
* Voice Assist key.
*
* Launches the global voice assist activity. Not delivered to applications.
*/
@ExperimentalComposeUiApi
actual val VoiceAssist = Key(KeyEvent.KEYCODE_VOICE_ASSIST)
/**
* Radio key.
*
* Toggles TV service / Radio service.
*/
@ExperimentalComposeUiApi
actual val TvRadioService = Key(KeyEvent.KEYCODE_TV_RADIO_SERVICE)
/**
* Teletext key.
*
* Displays Teletext service.
*/
@ExperimentalComposeUiApi
actual val TvTeletext = Key(KeyEvent.KEYCODE_TV_TELETEXT)
/**
* Number entry key.
*
* Initiates to enter multi-digit channel number when each digit key is assigned
* for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC
* User Control Code.
*/
@ExperimentalComposeUiApi
actual val TvNumberEntry = Key(KeyEvent.KEYCODE_TV_NUMBER_ENTRY)
/**
* Analog Terrestrial key.
*
* Switches to analog terrestrial broadcast service.
*/
@ExperimentalComposeUiApi
actual val TvTerrestrialAnalog = Key(KeyEvent.KEYCODE_TV_TERRESTRIAL_ANALOG)
/**
* Digital Terrestrial key.
*
* Switches to digital terrestrial broadcast service.
*/
@ExperimentalComposeUiApi
actual val TvTerrestrialDigital = Key(KeyEvent.KEYCODE_TV_TERRESTRIAL_DIGITAL)
/**
* Satellite key.
*
* Switches to digital satellite broadcast service.
*/
@ExperimentalComposeUiApi
actual val TvSatellite = Key(KeyEvent.KEYCODE_TV_SATELLITE)
/**
* BS key.
*
* Switches to BS digital satellite broadcasting service available in Japan.
*/
@ExperimentalComposeUiApi
actual val TvSatelliteBs = Key(KeyEvent.KEYCODE_TV_SATELLITE_BS)
/**
* CS key.
*
* Switches to CS digital satellite broadcasting service available in Japan.
*/
@ExperimentalComposeUiApi
actual val TvSatelliteCs = Key(KeyEvent.KEYCODE_TV_SATELLITE_CS)
/**
* BS/CS key.
*
* Toggles between BS and CS digital satellite services.
*/
@ExperimentalComposeUiApi
actual val TvSatelliteService = Key(KeyEvent.KEYCODE_TV_SATELLITE_SERVICE)
/**
* Toggle Network key.
*
* Toggles selecting broadcast services.
*/
@ExperimentalComposeUiApi
actual val TvNetwork = Key(KeyEvent.KEYCODE_TV_NETWORK)
/**
* Antenna/Cable key.
*
* Toggles broadcast input source between antenna and cable.
*/
@ExperimentalComposeUiApi
actual val TvAntennaCable = Key(KeyEvent.KEYCODE_TV_ANTENNA_CABLE)
/**
* HDMI #1 key.
*
* Switches to HDMI input #1.
*/
@ExperimentalComposeUiApi
actual val TvInputHdmi1 = Key(KeyEvent.KEYCODE_TV_INPUT_HDMI_1)
/**
* HDMI #2 key.
*
* Switches to HDMI input #2.
*/
@ExperimentalComposeUiApi
actual val TvInputHdmi2 = Key(KeyEvent.KEYCODE_TV_INPUT_HDMI_2)
/**
* HDMI #3 key.
*
* Switches to HDMI input #3.
*/
@ExperimentalComposeUiApi
actual val TvInputHdmi3 = Key(KeyEvent.KEYCODE_TV_INPUT_HDMI_3)
/**
* HDMI #4 key.
*
* Switches to HDMI input #4.
*/
@ExperimentalComposeUiApi
actual val TvInputHdmi4 = Key(KeyEvent.KEYCODE_TV_INPUT_HDMI_4)
/**
* Composite #1 key.
*
* Switches to composite video input #1.
*/
@ExperimentalComposeUiApi
actual val TvInputComposite1 = Key(KeyEvent.KEYCODE_TV_INPUT_COMPOSITE_1)
/**
* Composite #2 key.
*
* Switches to composite video input #2.
*/
@ExperimentalComposeUiApi
actual val TvInputComposite2 = Key(KeyEvent.KEYCODE_TV_INPUT_COMPOSITE_2)
/**
* Component #1 key.
*
* Switches to component video input #1.
*/
@ExperimentalComposeUiApi
actual val TvInputComponent1 = Key(KeyEvent.KEYCODE_TV_INPUT_COMPONENT_1)
/**
* Component #2 key.
*
* Switches to component video input #2.
*/
@ExperimentalComposeUiApi
actual val TvInputComponent2 = Key(KeyEvent.KEYCODE_TV_INPUT_COMPONENT_2)
/**
* VGA #1 key.
*
* Switches to VGA (analog RGB) input #1.
*/
@ExperimentalComposeUiApi
actual val TvInputVga1 = Key(KeyEvent.KEYCODE_TV_INPUT_VGA_1)
/**
* Audio description key.
*
* Toggles audio description off / on.
*/
@ExperimentalComposeUiApi
actual val TvAudioDescription = Key(KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION)
/**
* Audio description mixing volume up key.
*
* Increase the audio description volume as compared with normal audio volume.
*/
@ExperimentalComposeUiApi
actual val TvAudioDescriptionMixingVolumeUp = Key(KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP)
/**
* Audio description mixing volume down key.
*
* Lessen audio description volume as compared with normal audio volume.
*/
@ExperimentalComposeUiApi
actual val TvAudioDescriptionMixingVolumeDown = Key(KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN)
/**
* Zoom mode key.
*
* Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.)
*/
@ExperimentalComposeUiApi
actual val TvZoomMode = Key(KeyEvent.KEYCODE_TV_ZOOM_MODE)
/**
* Contents menu key.
*
* Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control Code
*/
@ExperimentalComposeUiApi
actual val TvContentsMenu = Key(KeyEvent.KEYCODE_TV_CONTENTS_MENU)
/**
* Media context menu key.
*
* Goes to the context menu of media contents. Corresponds to Media Context-sensitive
* Menu (0x11) of CEC User Control Code.
*/
@ExperimentalComposeUiApi
actual val TvMediaContextMenu = Key(KeyEvent.KEYCODE_TV_MEDIA_CONTEXT_MENU)
/**
* Timer programming key.
*
* Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of
* CEC User Control Code.
*/
@ExperimentalComposeUiApi
actual val TvTimerProgramming = Key(KeyEvent.KEYCODE_TV_TIMER_PROGRAMMING)
/**
* Primary stem key for Wearables.
*
* Main power/reset button.
*/
@ExperimentalComposeUiApi
actual val StemPrimary = Key(KeyEvent.KEYCODE_STEM_PRIMARY)
/** Generic stem key 1 for Wearables. */
@ExperimentalComposeUiApi
actual val Stem1 = Key(KeyEvent.KEYCODE_STEM_1)
/** Generic stem key 2 for Wearables. */
@ExperimentalComposeUiApi
actual val Stem2 = Key(KeyEvent.KEYCODE_STEM_2)
/** Generic stem key 3 for Wearables. */
@ExperimentalComposeUiApi
actual val Stem3 = Key(KeyEvent.KEYCODE_STEM_3)
/** Show all apps. */
@ExperimentalComposeUiApi
actual val AllApps = Key(KeyEvent.KEYCODE_ALL_APPS)
/** Refresh key. */
@ExperimentalComposeUiApi
actual val Refresh = Key(KeyEvent.KEYCODE_REFRESH)
/** Thumbs up key. Apps can use this to let user up-vote content. */
@ExperimentalComposeUiApi
actual val ThumbsUp = Key(KeyEvent.KEYCODE_THUMBS_UP)
/** Thumbs down key. Apps can use this to let user down-vote content. */
@ExperimentalComposeUiApi
actual val ThumbsDown = Key(KeyEvent.KEYCODE_THUMBS_DOWN)
/**
* Used to switch current [account][android.accounts.Account] that is
* consuming content. May be consumed by system to set account globally.
*/
@ExperimentalComposeUiApi
actual val ProfileSwitch = Key(KeyEvent.KEYCODE_PROFILE_SWITCH)
}
actual override fun toString(): String = "Key code: $keyCode"
}
/**
* The native keycode corresponding to this [Key].
*/
val Key.nativeKeyCode: Int
get() = unpackInt1(keyCode)
fun Key(nativeKeyCode: Int): Key = Key(packInts(nativeKeyCode, 0))
| apache-2.0 | 693225ad766da20686eb3d1027de7b70 | 29.977765 | 99 | 0.58909 | 4.95563 | false | false | false | false |
AndroidX/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/lookahead/CraneDemo.kt | 3 | 4582 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.lookahead
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentWithReceiverOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
@Composable
fun CraneDemo() {
val avatar = remember {
movableContentWithReceiverOf<SceneScope> {
Box(
Modifier
.sharedElement()
.background(Color(0xffff6f69), RoundedCornerShape(20))
.fillMaxSize()
)
}
}
val parent = remember {
movableContentWithReceiverOf<SceneScope, @Composable () -> Unit> { child ->
Surface(
modifier = Modifier
.sharedElement()
.background(Color(0xfffdedac)),
color = Color(0xfffdedac),
shape = RoundedCornerShape(10.dp)
) {
child()
}
}
}
var fullScreen by remember { mutableStateOf(false) }
Box(
Modifier
.fillMaxSize()
.padding(10.dp)
.clickable { fullScreen = !fullScreen },
contentAlignment = Alignment.Center
) {
SceneHost(Modifier.fillMaxSize()) {
if (fullScreen) {
Box(Modifier.offset(100.dp, 150.dp)) {
parent {
Box(
Modifier
.padding(10.dp)
.wrapContentSize(Alignment.Center)
.size(50.dp)
) {
avatar()
}
}
}
} else {
parent {
Column(Modifier.fillMaxSize()) {
val alpha = produceState(0f) {
animate(0f, 1f, animationSpec = tween(200)) { value, _ ->
this.value = value
}
}
Box(
Modifier
.fillMaxWidth()
.height(300.dp)
.graphicsLayer {
this.alpha = alpha.value
}
.background(Color.DarkGray)
.animateContentSize())
Box(
Modifier
.padding(10.dp)
.size(60.dp)
) {
avatar()
}
}
}
}
}
}
}
| apache-2.0 | 45d41c86cafb04eefac13c619ab1777d | 35.365079 | 85 | 0.551724 | 5.448276 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/editor/IssueLinkProviderExtension.kt | 1 | 3396 | package com.github.jk1.ytplugin.editor
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.editor.IssueNavigationLinkFactory.createNavigationLink
import com.github.jk1.ytplugin.editor.IssueNavigationLinkFactory.createdByYouTrackPlugin
import com.github.jk1.ytplugin.editor.IssueNavigationLinkFactory.pointsTo
import com.github.jk1.ytplugin.editor.IssueNavigationLinkFactory.setProjects
import com.github.jk1.ytplugin.logger
import com.github.jk1.ytplugin.rest.AdminRestClient
import com.github.jk1.ytplugin.tasks.YouTrackServer
import com.intellij.concurrency.JobScheduler
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.IssueNavigationConfiguration
import com.intellij.openapi.vcs.IssueNavigationLink
import java.util.concurrent.TimeUnit
class IssueLinkProviderExtension : StartupActivity.Background {
companion object {
const val ALL_USERS = "All Users"
}
override fun runActivity(project: Project) {
// update navigation links every 30 min to recognize new projects
val projectListRefreshTask = JobScheduler.getScheduler().scheduleWithFixedDelay({
updateNavigationLinkPatterns(project)
}, 1, 60, TimeUnit.MINUTES)
// update navigation links when server connection configuration has been changed
ComponentAware.of(project).taskManagerComponent.addConfigurationChangeListener {
updateNavigationLinkPatterns(project)
}
Disposer.register(ComponentAware.of(project).sourceNavigatorComponent, // any project-level disposable will do
Disposable { projectListRefreshTask.cancel(false) })
}
private fun updateNavigationLinkPatterns(project: Project) {
val navigationConfig = IssueNavigationConfiguration.getInstance(project)
navigationConfig.links.remove(null) // where are these nulls coming from I wonder
ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories().forEach { server ->
val links = navigationConfig.links.filter { it.pointsTo(server) }
val generatedLinks = links.filter { it.createdByYouTrackPlugin }
if (links.isEmpty()) {
// no issue links to that server have been defined so far
val link = createNavigationLink(server.url)
updateIssueLinkProjects(link, server)
navigationConfig.links.add(link)
} else if (generatedLinks.isNotEmpty()) {
// there is a link created by plugin, let's actualize it
updateIssueLinkProjects(generatedLinks.first(), server)
} else {
logger.debug("Issue navigation link pattern for ${server.url} has been overridden and won't be updated")
}
}
}
private fun updateIssueLinkProjects(link: IssueNavigationLink, repo: YouTrackServer) {
try {
val projects = AdminRestClient(repo).getAccessibleProjects()
if (projects.isEmpty()) {
logger.debug("No accessible projects found for ${repo.url}")
} else {
link.setProjects(projects)
}
} catch (e: Exception) {
logger.info(e)
}
}
}
| apache-2.0 | 90d0e4ca1dd5fa4c27caf04e44c55fec | 46.166667 | 120 | 0.712898 | 4.950437 | false | true | false | false |
Undin/intellij-rust | src/test/kotlin/org/rustSlowTests/ide/lineMarkers/CargoTestLineMarkerStatusTest.kt | 3 | 2812 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rustSlowTests.ide.lineMarkers
import org.intellij.lang.annotations.Language
import org.rust.cargo.icons.CargoIcons
import org.rust.ide.lineMarkers.CargoTestRunLineMarkerContributor.Companion.getTestStateIcon
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.descendantOfTypeStrict
import org.rustSlowTests.cargo.runconfig.test.CargoTestRunnerTestBase
import javax.swing.Icon
class CargoTestLineMarkerStatusTest : CargoTestRunnerTestBase() {
fun `test show a green mark for a passed test`() = checkTestStateIcon<RsFunction>("""
#[test]
fn passing_test() {
assert!(true);
}
""", CargoIcons.TEST_GREEN)
fun `test show a red mark for a failed test`() = checkTestStateIcon<RsFunction>("""
#[test]
fn failing_test() {
assert!(false);
}
""", CargoIcons.TEST_RED)
fun `test show a mark for an ignored test`() = checkTestStateIcon<RsFunction>("""
#[test]
#[ignore]
fn ignored_test() {}
""", CargoIcons.TEST)
fun `test show a green mark for a passed mod`() = checkTestStateIcon<RsMod>("""
mod tests {
#[test]
fn passing_test() {
assert!(true);
}
}
""", CargoIcons.TEST_GREEN)
fun `test show a red mark for a failed mod`() = checkTestStateIcon<RsMod>("""
mod tests {
#[test]
fn failing_test() {
assert!(false);
}
}
""", CargoIcons.TEST_RED)
fun `test show a mark for an ignored mod`() = checkTestStateIcon<RsMod>("""
mod tests {
#[test]
#[ignore]
fn ignored_test() {}
}
""", CargoIcons.TEST)
private inline fun <reified E : RsElement> checkTestStateIcon(@Language("Rust") code: String, expected: Icon) {
val testProject = buildProject {
toml("Cargo.toml", """
[package]
name = "sandbox"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", """
/*caret*/$code
""")
}
}
val file = myFixture.configureFromTempProjectFile(testProject.fileWithCaret)
val configuration = createTestRunConfigurationFromContext()
executeAndGetTestRoot(configuration)
val element = file.descendantOfTypeStrict<E>() ?: error("No ${E::class.java} in\n$code")
val actual = getTestStateIcon(element)
assertEquals(expected, actual)
}
}
| mit | f3a1a68b5f1da93b1e738ea5c6060ec3 | 30.954545 | 115 | 0.585704 | 4.572358 | false | true | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/lerp/DefaultLerpers.kt | 1 | 3905 | package com.teamwizardry.librarianlib.core.util.lerp
import com.teamwizardry.librarianlib.math.Rect2d
import com.teamwizardry.librarianlib.math.Vec2d
import com.teamwizardry.librarianlib.math.minus
import com.teamwizardry.librarianlib.math.plus
import com.teamwizardry.librarianlib.math.times
import dev.thecodewarrior.mirror.Mirror
import net.minecraft.util.math.Vec3d
import java.awt.Color
import kotlin.math.roundToInt
import kotlin.math.roundToLong
//region primitives =============================================================================================================
public object BooleanLerper: Lerper<Boolean>() {
override fun lerp(from: Boolean, to: Boolean, fraction: Float): Boolean = if(fraction < 0.5f) from else to
}
public object PrimitiveBooleanLerper: Lerper<Boolean>(Mirror.types.boolean) {
override fun lerp(from: Boolean, to: Boolean, fraction: Float): Boolean = if(fraction < 0.5f) from else to
}
public object DoubleLerper: Lerper<Double>() {
override fun lerp(from: Double, to: Double, fraction: Float): Double = from + (to - from) * fraction
}
public object PrimitiveDoubleLerper: Lerper<Double>(Mirror.types.double) {
override fun lerp(from: Double, to: Double, fraction: Float): Double = from + (to - from) * fraction
}
public object FloatLerper: Lerper<Float>() {
override fun lerp(from: Float, to: Float, fraction: Float): Float = from + (to - from) * fraction
}
public object PrimitiveFloatLerper: Lerper<Float>(Mirror.types.float) {
override fun lerp(from: Float, to: Float, fraction: Float): Float = from + (to - from) * fraction
}
public object IntLerper: Lerper<Int>() {
override fun lerp(from: Int, to: Int, fraction: Float): Int = (from + (to - from) * fraction).toInt()
}
public object PrimitiveIntLerper: Lerper<Int>(Mirror.types.int) {
override fun lerp(from: Int, to: Int, fraction: Float): Int = (from + (to - from) * fraction).toInt()
}
public object LongLerper: Lerper<Long>() {
override fun lerp(from: Long, to: Long, fraction: Float): Long = (from + (to - from) * fraction).toLong()
}
public object PrimitiveLongLerper: Lerper<Long>(Mirror.types.long) {
override fun lerp(from: Long, to: Long, fraction: Float): Long = (from + (to - from) * fraction).toLong()
}
//endregion =====================================================================================================================
//region vectors ================================================================================================================
public object Vec2dLerper: Lerper<Vec2d>() {
override fun lerp(from: Vec2d, to: Vec2d, fraction: Float): Vec2d = from + (to - from) * fraction
}
public object Vec3dLerper: Lerper<Vec3d>() {
override fun lerp(from: Vec3d, to: Vec3d, fraction: Float): Vec3d = from + (to - from) * fraction
}
public object Rect2dLerper: Lerper<Rect2d>() {
override fun lerp(from: Rect2d, to: Rect2d, fraction: Float): Rect2d {
return Rect2d(
from.pos + (to.pos - from.pos) * fraction,
from.size + (to.size - from.size) * fraction
)
}
}
//endregion =====================================================================================================================
//region others =================================================================================================================
public object ColorLerper: Lerper<Color>() {
override fun lerp(from: Color, to: Color, fraction: Float): Color = Color(
lerp(from.red, to.red, fraction),
lerp(from.green, to.green, fraction),
lerp(from.blue, to.blue, fraction),
lerp(from.alpha, to.alpha, fraction)
)
private fun lerp(from: Int, to: Int, fraction: Float): Int = (from + (to - from) * fraction).toInt()
}
//endregion =====================================================================================================================
| lgpl-3.0 | 3a5a140eaf34bca9685cb3b9105587aa | 46.621951 | 129 | 0.57516 | 4.180942 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/execution/model/events/TaskFailedEvent.kt | 1 | 3967 | /*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.execution.model.events
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.config.SetupCommand
import java.nio.file.Path
sealed class TaskFailedEvent : TaskEvent()
data class ExecutionFailedEvent(val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(message: '$message')"
}
data class TaskNetworkCreationFailedEvent(val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(message: '$message')"
}
data class ImageBuildFailedEvent(val source: BuildImage, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(source: $source, message: '$message')"
}
data class ImagePullFailedEvent(val source: PullImage, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(source: $source, message: '$message')"
}
data class ContainerCreationFailedEvent(val container: Container, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', message: '$message')"
}
data class ContainerDidNotBecomeHealthyEvent(val container: Container, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', message: '$message')"
}
data class ContainerRunFailedEvent(val container: Container, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', message: '$message')"
}
data class ContainerStopFailedEvent(val container: Container, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', message: '$message')"
}
data class ContainerRemovalFailedEvent(val container: Container, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', message: '$message')"
}
data class TaskNetworkDeletionFailedEvent(val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(message: '$message')"
}
data class TemporaryFileDeletionFailedEvent(val filePath: Path, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(file path: '$filePath', message: '$message')"
}
data class TemporaryDirectoryDeletionFailedEvent(val directoryPath: Path, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(directory path: '$directoryPath', message: '$message')"
}
object UserInterruptedExecutionEvent : TaskFailedEvent() {
override fun toString() = this::class.simpleName!!
}
data class SetupCommandExecutionErrorEvent(val container: Container, val command: SetupCommand, val message: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', command: $command, message: '$message')"
}
data class SetupCommandFailedEvent(val container: Container, val command: SetupCommand, val exitCode: Int, val output: String) : TaskFailedEvent() {
override fun toString() = "${this::class.simpleName}(container: '${container.name}', command: $command, exit code: $exitCode, output: '$output')"
}
| apache-2.0 | 0c920b5a5a8ae18f8edaf015a967768c | 45.670588 | 149 | 0.74061 | 4.549312 | false | false | false | false |
mocovenwitch/heykotlin | app/src/main/java/com/mocoven/heykotlin/playground/Practice1.kt | 1 | 1142 | package com.mocoven.heykotlin.playground
import java.util.*
/**
* Syntax practice in Playground 1
*
* Created by Mocoven on 21/03/2017.
*/
class Practice1 {
fun mysum(a: Int, b: Int) = a + b
/**
* Compiler would compains about nullable value which might generate null exception
*/
fun nullComplain() {
// #1 - Compiler complains
// var b: String? = "abc"
// val l = b.length
}
/**
* Elvis expression/operator
*/
fun elvisOperator(value: String?): Int {
// #2 - Elvis Operator
val b: String? = value
val b1 = b?.length ?: -1
val b2 = if (b != null) b.length else -1 // we write Java in this way
return b1
}
/**
* Break "val is immutable".
*
* [2017-3-23] Update:
* While my colleague Arun says, it does not break val immutability, it is only not pure functional.
* Later I agree.
*/
fun breakImmutable(): Int {
val number: Int = Random().nextInt()
return number
}
/**
* Keep "val is immutable"
*/
val immutableField: Int = Random().nextInt()
}
| mit | 2d081512dd953dd9a562198ddf2f7be0 | 20.961538 | 104 | 0.558669 | 3.707792 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mcp/fabricloom/FabricLoomDecompileSourceProvider.kt | 1 | 3987 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.fabricloom
import com.demonwav.mcdev.platform.forge.inspections.sideonly.Side
import com.demonwav.mcdev.platform.forge.inspections.sideonly.SideOnlyUtil
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.runGradleTaskWithCallback
import com.intellij.codeInsight.AttachSourcesProvider
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.externalSystem.task.TaskCallback
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.ActionCallback
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import java.nio.file.Paths
import org.jetbrains.plugins.gradle.util.GradleUtil
class FabricLoomDecompileSourceProvider : AttachSourcesProvider {
override fun getActions(
orderEntries: List<LibraryOrderEntry>,
psiFile: PsiFile
): Collection<AttachSourcesProvider.AttachSourcesAction> {
if (psiFile !is PsiJavaFile || !psiFile.packageName.startsWith("net.minecraft")) {
return emptyList()
}
val module = psiFile.findModule() ?: return emptyList()
val loomData = GradleUtil.findGradleModuleData(module)?.children
?.find { it.key == FabricLoomData.KEY }?.data as? FabricLoomData
?: return emptyList()
val env = if (!loomData.splitMinecraftJar) {
"single"
} else if (isClientClass(psiFile)) {
"client"
} else {
"common"
}
val decompileTasks = loomData.decompileTasks[env] ?: return emptyList()
return decompileTasks.map(::DecompileAction)
}
private fun isClientClass(psiFile: PsiJavaFile): Boolean {
return psiFile.classes.any { psiClass ->
return SideOnlyUtil.getSideForClass(psiClass).second == Side.CLIENT
}
}
private class DecompileAction(val decompiler: FabricLoomData.Decompiler) :
AttachSourcesProvider.AttachSourcesAction {
override fun getName(): String = "Decompile with ${decompiler.name}"
override fun getBusyText(): String = "Decompiling Minecraft..."
override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>): ActionCallback {
val project = orderEntriesContainingFile.firstOrNull()?.ownerModule?.project
?: return ActionCallback.REJECTED
val projectPath = project.basePath ?: return ActionCallback.REJECTED
val callback = ActionCallback()
val taskCallback = object : TaskCallback {
override fun onSuccess() {
attachSources(orderEntriesContainingFile, decompiler.sourcesPath)
callback.setDone()
}
override fun onFailure() = callback.setRejected()
}
runGradleTaskWithCallback(
project,
Paths.get(projectPath),
{ settings -> settings.taskNames = listOf(decompiler.taskName) },
taskCallback
)
return callback
}
private fun attachSources(libraryEntries: List<LibraryOrderEntry>, sourcePath: String): ActionCallback? {
// Distinct because for some reason the same library is in there twice
for (libraryEntry in libraryEntries.distinctBy { it.libraryName }) {
val library = libraryEntry.library
if (library != null) {
runWriteActionAndWait {
val model = library.modifiableModel
model.addRoot("jar://$sourcePath!/", OrderRootType.SOURCES)
model.commit()
}
}
}
return ActionCallback.DONE
}
}
}
| mit | 8caffb240d6dd7b7b9c8b9148500361a | 36.613208 | 113 | 0.650113 | 5.366083 | false | false | false | false |
C6H2Cl2/SolidXp | src/main/java/c6h2cl2/solidxp/tileentity/TileXpCollector.kt | 1 | 4565 | package c6h2cl2.solidxp.tileentity
import c6h2cl2.solidxp.MOD_ID
import c6h2cl2.solidxp.SolidXpRegistry
import net.minecraft.entity.item.EntityXPOrb
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.inventory.IInventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.ITickable
import net.minecraft.util.math.AxisAlignedBB
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.items.CapabilityItemHandler
import net.minecraftforge.items.ItemStackHandler
/**
* @author C6H2Cl2
*/
class TileXpCollector : TileXpMachineBase(), IInventory, ITickable {
val inventory = (CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.defaultInstance as ItemStackHandler)
var range = 4.0
var limit = 100
init {
inventory.setSize(1)
}
override fun update() {
//経験値オーブの取得
val entities = world.getEntitiesWithinAABB(EntityXPOrb::class.java, AxisAlignedBB(pos.x - range, pos.y - range, pos.z - range, pos.x + range, pos.y + range, pos.z + range))
var totalXp = 0L
//経験値オーブの経験値の総量をカウント
entities.forEach {
totalXp += it.xpValue
world.removeEntity(it)
if (totalXp >= limit) {
return@forEach
}
}
totalXp += xpStorage.xpValue
val stack = inventory.getStackInSlot(0)
val xpValue = getXpValue(xpStorage.xpTier)
//XpTierが変わっていた場合、変換
if (stack.metadata != xpStorage.xpTier) {
totalXp += getXpValue(stack.metadata) * stack.count
inventory.setStackInSlot(0, ItemStack.EMPTY)
}
//追加するItemの数
var count = 0
while (totalXp >= xpValue && count < 64) {
count++
totalXp -= xpValue
}
//Itemの追加処理
if (count != 0) {
val itemStack = inventory.insertItem(0, ItemStack(SolidXpRegistry.solidXp, count, xpStorage.xpTier), false)
//余剰分は経験値に戻しましょうねー
if (itemStack != ItemStack.EMPTY) {
totalXp += xpValue * itemStack.count
}
}
xpStorage.xpValue = totalXp
}
// Template Overrides ===========================================================================================================================
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? {
return if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) inventory as T else super.getCapability(capability, facing)
}
override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound {
compound.setTag(INVENTORY, inventory.serializeNBT())
return super.writeToNBT(compound)
}
override fun readFromNBT(compound: NBTTagCompound?) {
compound ?: return
inventory.deserializeNBT(compound.getTag(INVENTORY) as NBTTagCompound)
super.readFromNBT(compound)
}
// IInventory Impl ==============================================================================================================================
override fun getStackInSlot(index: Int): ItemStack {
return inventory.getStackInSlot(index)
}
override fun decrStackSize(index: Int, count: Int): ItemStack {
return inventory.extractItem(index, count, false)
}
override fun clear() {
inventory.setStackInSlot(0, ItemStack.EMPTY)
}
override fun isEmpty(): Boolean {
return inventory.getStackInSlot(0) == ItemStack.EMPTY
}
override fun setInventorySlotContents(index: Int, stack: ItemStack) {
inventory.setStackInSlot(index, stack)
}
override fun removeStackFromSlot(index: Int): ItemStack {
return inventory.extractItem(index, 64, false)
}
override fun getFieldCount() = 0
override fun getField(id: Int) = 0
override fun hasCustomName() = false
override fun getSizeInventory() = 1
override fun getName() = "$MOD_ID.xpCollector"
override fun isUsableByPlayer(player: EntityPlayer?) = true
override fun isItemValidForSlot(index: Int, stack: ItemStack?) = true
override fun getInventoryStackLimit() = 64
override fun openInventory(player: EntityPlayer?) {}
override fun setField(id: Int, value: Int) {}
override fun closeInventory(player: EntityPlayer?) {}
} | mpl-2.0 | 55a3620954f5e4d962e49221b9af233b | 35.644628 | 180 | 0.63501 | 4.477778 | false | false | false | false |
VKCOM/vk-android-sdk | core/src/main/java/com/vk/api/sdk/auth/VKAccessToken.kt | 1 | 5944 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.vk.api.sdk.auth
import android.os.Bundle
import com.vk.api.sdk.VKKeyValueStorage
import com.vk.dto.common.id.UserId
import com.vk.dto.common.id.toUserId
import java.util.*
class VKAccessToken(params: Map<String, String?>) {
constructor(
userId: UserId,
accessToken: String,
secret: String?,
expiresInSec: Int,
createdMs: Long
) : this(
mapOf(
USER_ID to userId.toString(),
ACCESS_TOKEN to accessToken,
SECRET to secret,
EXPIRES_IN to expiresInSec.toString(),
CREATED to createdMs.toString(),
HTTPS_REQUIRED to "1"
)
)
val userId: UserId
val accessToken: String
val secret: String?
val createdMs: Long
val email: String?
val phone: String?
val phoneAccessKey: String?
val expiresInSec: Int
private val httpsRequired: Boolean
val isValid: Boolean
get() = expiresInSec <= 0 || createdMs + expiresInSec * 1000 > System.currentTimeMillis()
init {
this.userId = params[USER_ID]?.toLong()?.toUserId()!!
this.accessToken = params[ACCESS_TOKEN]!!
this.secret = params[SECRET]
this.httpsRequired = "1" == params[HTTPS_REQUIRED]
this.createdMs = if (params.containsKey(CREATED)) params[CREATED]!!.toLong() else System.currentTimeMillis()
this.expiresInSec = if (params.containsKey(EXPIRES_IN)) params[EXPIRES_IN]!!.toInt() else -1
this.email = if (params.containsKey(EMAIL)) params[EMAIL] else null
this.phone = if (params.containsKey(PHONE)) params[PHONE] else null
this.phoneAccessKey = if (params.containsKey(PHONE_ACCESS_KEY)) params[PHONE_ACCESS_KEY] else null
}
fun save(bundle: Bundle) {
val vkTokenBundle = Bundle()
val tokenParams = toMap()
for ((key, value) in tokenParams) {
vkTokenBundle.putString(key, value)
}
bundle.putBundle(VK_ACCESS_TOKEN_KEY, vkTokenBundle)
}
fun save(storage: VKKeyValueStorage) {
val tokenParams = toMap()
for ((key, value) in tokenParams) {
storage.putOrRemove(key, value)
}
}
private fun toMap(): Map<String, String?> {
val result = HashMap<String, String?>()
result[ACCESS_TOKEN] = accessToken
result[SECRET] = secret
result[HTTPS_REQUIRED] = if (httpsRequired) "1" else "0"
result[CREATED] = createdMs.toString()
result[EXPIRES_IN] = expiresInSec.toString()
result[USER_ID] = userId.toString()
result[EMAIL] = email
result[PHONE] = phone
result[PHONE_ACCESS_KEY] = phoneAccessKey
return result
}
companion object {
private const val ACCESS_TOKEN = "access_token"
private const val EXPIRES_IN = "expires_in"
private const val USER_ID = "user_id"
private const val SECRET = "secret"
private const val HTTPS_REQUIRED = "https_required"
private const val CREATED = "created"
private const val VK_ACCESS_TOKEN_KEY = "vk_access_token"
private const val EMAIL = "email"
private const val PHONE = "phone"
private const val PHONE_ACCESS_KEY = "phone_access_key"
val KEYS = listOf(
ACCESS_TOKEN,
EXPIRES_IN,
USER_ID,
SECRET,
HTTPS_REQUIRED,
CREATED,
VK_ACCESS_TOKEN_KEY,
EMAIL,
PHONE,
PHONE_ACCESS_KEY
)
fun restore(bundle: Bundle?): VKAccessToken? {
if (bundle == null) {
return null
}
val vkTokenBundle = bundle.getBundle(VK_ACCESS_TOKEN_KEY) ?: return null
val tokenParams = HashMap<String, String?>()
for (key in vkTokenBundle.keySet()) {
tokenParams[key] = vkTokenBundle.getString(key)
}
return VKAccessToken(tokenParams)
}
fun remove(keyValueStorage: VKKeyValueStorage) {
KEYS.forEach { keyValueStorage.remove(it) }
}
fun restore(keyValueStorage: VKKeyValueStorage): VKAccessToken? {
val tokenParams = HashMap<String, String?>(KEYS.size)
for (key in KEYS) {
keyValueStorage.get(key)?.let {
tokenParams[key] = it
}
}
return if (tokenParams.containsKey(ACCESS_TOKEN) && tokenParams.containsKey(USER_ID)) {
VKAccessToken(tokenParams)
}
else null
}
}
} | mit | 54d93b515cd0cb9be115c11386d9d717 | 35.925466 | 116 | 0.601279 | 4.661961 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/service/SilenceService.kt | 1 | 7067 | package de.tum.`in`.tumcampusapp.service
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.app.JobIntentService
import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Const.SILENCE_SERVICE_JOB_ID
import de.tum.`in`.tumcampusapp.utils.Utils
import org.joda.time.DateTime
/**
* Service used to silence the mobile during lectures
*/
class SilenceService : JobIntentService() {
/**
* We can't and won't change the ringer modes, if the device is in DoNotDisturb mode. DnD requires
* explicit user interaction, so we are out of the game until DnD is off again
*/
// See: https://stackoverflow.com/questions/31387137/android-detect-do-not-disturb-status
// Settings.System.getInt(getContentResolver(), Settings.System.DO_NOT_DISTURB, 1);
private val isDoNotDisturbActive: Boolean
get() {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
notificationManager.currentInterruptionFilter != android.app.NotificationManager.INTERRUPTION_FILTER_ALL
} else {
try {
val mode = Settings.Global.getInt(contentResolver, "zen_mode")
mode != 0
} catch (e: Settings.SettingNotFoundException) {
false
}
}
}
override fun onCreate() {
super.onCreate()
Utils.log("SilenceService has started")
}
override fun onDestroy() {
super.onDestroy()
Utils.log("SilenceService has stopped")
}
override fun onHandleWork(intent: Intent) {
// Abort, if the settingsPrefix changed
if (!Utils.getSettingBool(this, Const.SILENCE_SERVICE, false)) {
// Don't schedule a new run, since the service is disabled
return
}
if (!hasPermissions(this)) {
Utils.setSetting(this, Const.SILENCE_SERVICE, false)
return
}
val alarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val newIntent = Intent(this, SilenceService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val startTime = System.currentTimeMillis()
var waitDuration = CHECK_INTERVAL.toLong()
Utils.log("SilenceService enabled, checking for lectures …")
val calendarController = CalendarController(this)
if (!calendarController.hasLectures()) {
Utils.logv("No lectures available")
alarmManager.set(AlarmManager.RTC, startTime + waitDuration, pendingIntent)
return
}
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
val currentLectures = calendarController.currentLectures
Utils.log("Current lectures: " + currentLectures.size)
if (currentLectures.isEmpty() || isDoNotDisturbActive) {
if (Utils.getSettingBool(this, Const.SILENCE_ON, false) && !isDoNotDisturbActive) {
// default: old state
Utils.log("set ringer mode to old state")
val ringerMode = Utils.getSetting(this, Const.SILENCE_OLD_STATE, AudioManager.RINGER_MODE_NORMAL.toString())
audioManager.ringerMode = ringerMode.toInt()
Utils.setSetting(this, Const.SILENCE_ON, false)
val nextCalendarItems = calendarController.nextCalendarItems
// Check if we have a "next" item in the database and
// update the refresh interval until then. Otherwise use default interval.
if (!nextCalendarItems.isEmpty()) {
// refresh when next event has started
waitDuration = getWaitDuration(nextCalendarItems[0].dtstart)
}
}
} else {
// remember old state if just activated ; in doubt dont change
if (!Utils.getSettingBool(this, Const.SILENCE_ON, true)) {
Utils.setSetting(this, Const.SILENCE_OLD_STATE, audioManager.ringerMode)
}
// if current lecture(s) found, silence the mobile
Utils.setSetting(this, Const.SILENCE_ON, true)
// Set into silent or vibrate mode based on current setting
val mode = Utils.getSetting(this, "silent_mode_set_to", "0")
audioManager.ringerMode = when (mode) {
RINGER_MODE_SILENT -> AudioManager.RINGER_MODE_VIBRATE
else -> AudioManager.RINGER_MODE_SILENT
}
// refresh when event has ended
waitDuration = getWaitDuration(currentLectures[0].dtstart)
}
alarmManager.set(AlarmManager.RTC, startTime + waitDuration, pendingIntent)
}
companion object {
/**
* Interval in milliseconds to check for current lectures
*/
private const val CHECK_INTERVAL = 60000 * 15 // 15 Minutes
private const val CHECK_DELAY = 10000 // 10 Seconds after Calendar changed
private const val RINGER_MODE_SILENT = "0"
private fun getWaitDuration(eventDateTime: DateTime): Long {
val eventTime = eventDateTime.millis
return Math.min(CHECK_INTERVAL.toLong(), eventTime - System.currentTimeMillis() + CHECK_DELAY)
}
@JvmStatic fun enqueueWork(context: Context, work: Intent) {
enqueueWork(context, SilenceService::class.java, SILENCE_SERVICE_JOB_ID, work)
}
/**
* Check if the app has the permissions to enable "Do Not Disturb".
*/
@JvmStatic fun hasPermissions(context: Context): Boolean {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
return !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !notificationManager.isNotificationPolicyAccessGranted)
}
/**
* Request the "Do Not Disturb" permissions for android version >= N.
*/
@JvmStatic fun requestPermissions(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return
}
if (hasPermissions(context)) {
return
}
requestPermissionsSDK23(context)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun requestPermissionsSDK23(context: Context) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
context.startActivity(intent)
}
}
}
| gpl-3.0 | 5e1e212a73a0b0153dbc7d772340b17c | 39.603448 | 126 | 0.640623 | 4.892659 | false | false | false | false |
mannersio/manners | clients/jvm/manners-fake-provider/src/main/kotlin/io/manners/FakeProvider.kt | 1 | 2876 | package io.manners
import com.google.gson.Gson
import okhttp3.HttpUrl
import okhttp3.MediaType
import java.util.*
class FakeProvider(val consumerName: String, val providereName: String) {
private val client = okhttp3.OkHttpClient()
private val gson = Gson()
private var process: Process? = null
fun start() {
process = Runtime.getRuntime().exec(arrayOf("../manners-bin/src/main/resources/manners", "fake-provider"))
val scanner = Scanner(process?.inputStream)
do {
val line = scanner.nextLine()
println(line)
} while (!line.contains("listening"))
}
fun stop() {
process?.destroy()
process?.waitFor()
}
fun setup(spec: ProviderSpecification) {
val payload = gson.toJson(InteractionWrapper(spec.result()))
println(payload)
val body = okhttp3.RequestBody.create(MediaType.parse("application/json"), payload)
val req = okhttp3.Request.Builder()
.put(body)
.url(HttpUrl.parse("http://0.0.0.0:1234/interactions"))
.header("X-Pact-Mock-Service", "True")
.build()
val res = client.newCall(req).execute()
if (res.code() != 200) {
throw Exception("could not setup interactions: " + res.body().string())
}
}
fun verify() {
val verifyReq = okhttp3.Request.Builder()
.get()
.url(HttpUrl.parse("http://0.0.0.0:1234/interactions/verification"))
.header("X-Pact-Mock-Service", "True")
.build()
val verifyRes = client.newCall(verifyReq).execute()
if (verifyRes.code() != 200) {
throw Exception("Interaction verification failed: " + verifyRes.body().string())
}
val cleanReq = okhttp3.Request.Builder()
.delete()
.url(HttpUrl.parse("http://0.0.0.0:1234/interactions"))
.header("X-Pact-Mock-Service", "True")
.build()
val cleanRes = client.newCall(cleanReq).execute()
if (cleanRes.code() != 200) {
throw Exception("Couldn't clean up interactions: " + cleanRes.body().string())
}
val payload = gson.toJson(ContractHeader(ServiceDescription(consumerName), ServiceDescription(providereName)))
val body = okhttp3.RequestBody.create(MediaType.parse("application/json"), payload)
val contractReq = okhttp3.Request.Builder()
.post(body)
.url(HttpUrl.parse("http://0.0.0.0:1234/pact"))
.header("X-Pact-Mock-Service", "True")
.build()
val contractRes = client.newCall(contractReq).execute()
if (contractRes.code() != 200) {
throw Exception("Couldn't persist contract: " + cleanRes.body().string())
}
}
} | mit | 85f2501f6190ff0f3d79bba4df87b5bd | 34.9625 | 118 | 0.580668 | 4.180233 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/view/SlidingRelativeLayout.kt | 1 | 905 | package de.westnordost.streetcomplete.view
import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.core.view.doOnPreDraw
class SlidingRelativeLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: RelativeLayout(context, attrs, defStyleAttr) {
var yFraction: Float = 0f
set(fraction) {
field = fraction
postAfterViewMeasured { translationY = height * yFraction }
}
var xFraction: Float = 0f
set(fraction) {
field = fraction
postAfterViewMeasured { translationX = width * xFraction }
}
private fun postAfterViewMeasured(callback: () -> Unit) {
if (width != 0 || height != 0) {
callback()
} else {
doOnPreDraw { callback() }
}
}
}
| gpl-3.0 | 64a4ec69be44ff1354f41a212077f207 | 27.28125 | 71 | 0.627624 | 4.73822 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_revenue/ui/delegate/CourseBenefitSummaryViewDelegate.kt | 2 | 6440 | package org.stepik.android.view.course_revenue.ui.delegate
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import kotlinx.android.synthetic.main.view_course_benefit_summary.view.*
import org.stepic.droid.R
import org.stepic.droid.ui.util.collapse
import org.stepic.droid.ui.util.expand
import org.stepic.droid.util.DateTimeHelper
import org.stepik.android.presentation.course_revenue.CourseBenefitSummaryFeature
import org.stepik.android.view.course_revenue.mapper.RevenuePriceMapper
import ru.nobird.android.view.base.ui.delegate.ViewStateDelegate
import java.text.DecimalFormat
import java.util.Currency
import java.util.TimeZone
import java.util.Locale
class CourseBenefitSummaryViewDelegate(
containerView: View,
private val revenuePriceMapper: RevenuePriceMapper,
private val onCourseSummaryClicked: (Boolean) -> Unit,
private val onContactSupportClicked: () -> Unit
) {
private val context = containerView.context
private val courseBenefitsSummaryLoading = containerView.courseBenefitSummaryLoading
private val courseBenefitSummaryEmpty = containerView.courseBenefitSummaryEmpty
private val courseBenefitSummaryContainer = containerView.courseBenefitSummaryInformation
private val courseBenefitSummaryInformationExpansion = containerView.courseBenefitSummaryInformationExpansion
private val courseBenefitSummaryArrow = containerView.courseBenefitSummaryArrow
private val courseBenefitExperimentDisclaimer = containerView.courseBenefitExperimentDisclaimer
private val courseBenefitOperationDisclaimer = containerView.courseBenefitOperationDisclaimer
private val courseBenefitCurrentEarningsTitle = containerView.courseBenefitSummaryEarningsCurrentMonthText
private val courseBenefitCurrentEarningsValue = containerView.courseBenefitSummaryEarningsCurrentMonthValue
private val courseBenefitCurrentTurnoverTitle = containerView.courseBenefitSummaryTurnoverCurrentMonthText
private val courseBenefitCurrentTurnoverValue = containerView.courseBenefitSummaryTurnoverCurrentMonthValue
private val courseBenefitTotalEarningsTitle = containerView.courseBenefitSummaryEarningsTotalText
private val courseBenefitTotalEarningsValue = containerView.courseBenefitSummaryEarningsTotalValue
private val courseBenefitTotalTurnoverTitle = containerView.courseBenefitSummaryTurnoverTotalText
private val courseBenefitTotalTurnoverValue = containerView.courseBenefitSummaryTurnoverTotalValue
private val viewStateDelegate = ViewStateDelegate<CourseBenefitSummaryFeature.State>()
init {
viewStateDelegate.addState<CourseBenefitSummaryFeature.State.Loading>(courseBenefitsSummaryLoading)
viewStateDelegate.addState<CourseBenefitSummaryFeature.State.Empty>(courseBenefitSummaryEmpty, courseBenefitOperationDisclaimer)
viewStateDelegate.addState<CourseBenefitSummaryFeature.State.Content>(courseBenefitSummaryContainer, courseBenefitOperationDisclaimer)
courseBenefitExperimentDisclaimer.text = buildSpannedString {
bold { append(context.getString(R.string.course_benefits_contact_support_part_1)) }
append(context.getString(R.string.course_benefits_contact_support_part_2))
color(ContextCompat.getColor(context, R.color.color_overlay_violet)) {
append(context.getString(R.string.course_benefits_contact_support_part_3))
}
append(".")
}
courseBenefitExperimentDisclaimer.setOnClickListener { onContactSupportClicked() }
courseBenefitSummaryContainer.setOnClickListener {
courseBenefitSummaryArrow.changeState()
val isExpanded = courseBenefitSummaryArrow.isExpanded()
onCourseSummaryClicked(isExpanded)
if (isExpanded) {
courseBenefitSummaryInformationExpansion.expand()
} else {
courseBenefitSummaryInformationExpansion.collapse()
}
}
}
fun render(state: CourseBenefitSummaryFeature.State) {
viewStateDelegate.switchState(state)
if (state is CourseBenefitSummaryFeature.State.Content) {
val currency = Currency.getInstance(state.courseBenefitSummary.currencyCode)
val decimalFormat = DecimalFormat().apply { setCurrency(currency) }
decimalFormat.minimumFractionDigits = 2
val currentMonthDate = DateTimeHelper.getPrintableDate(
state.courseBenefitSummary.currentDate,
DateTimeHelper.DISPLAY_MONTH_YEAR_NOMINAL_PATTERN,
TimeZone.getDefault()
).capitalize(Locale.ROOT)
val totalDate = DateTimeHelper.getPrintableDate(
state.courseBenefitSummary.beginPaymentDate,
DateTimeHelper.DISPLAY_MONTH_YEAR_GENITIVE_PATTERN,
TimeZone.getDefault()
).capitalize(Locale.ROOT)
courseBenefitCurrentEarningsTitle.text = context.getString(R.string.course_benefits_earning_current_month, currentMonthDate)
courseBenefitCurrentEarningsValue.text = revenuePriceMapper.mapToDisplayPrice(state.courseBenefitSummary.currencyCode, decimalFormat.format(state.courseBenefitSummary.monthUserIncome.toDoubleOrNull() ?: 0.0))
courseBenefitCurrentTurnoverTitle.text = context.getString(R.string.course_benefits_turnover_current_month, currentMonthDate)
courseBenefitCurrentTurnoverValue.text = revenuePriceMapper.mapToDisplayPrice(state.courseBenefitSummary.currencyCode, decimalFormat.format(state.courseBenefitSummary.monthTurnover.toDoubleOrNull() ?: 0.0))
courseBenefitTotalEarningsTitle.text = context.getString(R.string.course_benefits_earnings_total, totalDate)
courseBenefitTotalEarningsValue.text = revenuePriceMapper.mapToDisplayPrice(state.courseBenefitSummary.currencyCode, decimalFormat.format(state.courseBenefitSummary.totalUserIncome.toDoubleOrNull() ?: 0.0))
courseBenefitTotalTurnoverTitle.text = context.getString(R.string.course_beneifts_turnover_total, totalDate)
courseBenefitTotalTurnoverValue.text = revenuePriceMapper.mapToDisplayPrice(state.courseBenefitSummary.currencyCode, decimalFormat.format(state.courseBenefitSummary.totalTurnover.toDoubleOrNull() ?: 0.0))
}
}
} | apache-2.0 | d0098b4b79303d5ede96cf8e56bb2a8e | 55.5 | 220 | 0.786335 | 5.775785 | false | false | false | false |
enihsyou/Sorting-algorithm | Java_part/Assigment7/Q2/src/Q2.kt | 1 | 2839 | import kotlin.system.measureTimeMillis
fun permute(listToPermute: List<Int>): List<IntArray> {
val targetN = listToPermute.size
val marked = BooleanArray(targetN)
val result = mutableListOf<IntArray>()
val workingArray: Array<Int> = Array(targetN, { -1 })
/**
* 检查已经生成的部分排列数 是否能满足八皇后的要求,速度比下面的方法快了1.5x
* @param putting 接下来要放的皇后在第几排
* */
fun canPlace(putting: Int): Boolean {
val place = workingArray.count { it != -1 }
for ((index, value) in workingArray.withIndex()) {/*value是前面部分排列中的皇后在第几排的信息*/
if (index > place) break
/*如果两个皇后在同一排或者同一条对角线*/
if (value == putting || Math.abs(value - putting) == Math.abs(index - place))
return false
}
return true
}
/**
* 深度优先方式生成排列数
* @param currentLevel 当前处理的数字
* */
fun dfs(currentLevel: Int) {
if (currentLevel == targetN) {
result.add(workingArray.toIntArray())
return
}
for (i in 0 until targetN) {
if (!marked[i]) {
if (!canPlace(listToPermute[i])) {
continue
}
workingArray.set(currentLevel, listToPermute[i])
marked[i] = true
dfs(currentLevel + 1)
workingArray.set(currentLevel, -1)
marked[i] = false
}
}
}
dfs(0)
/*第一种使用排序数的方法*/
//fun <T> permute2(input: List<T>): List<List<T>> {
// if (input.size == 1) return listOf(input)
// val perms = mutableListOf<List<T>>()
// val toInsert = input[0]
// for (perm in permute2(input.drop(1))) {
// for (i in 0..perm.size) {
// val newPerm = perm.toMutableList()
// newPerm.add(i, toInsert)
// perms.add(newPerm)
// }
// }
// return perms
//}
// var result: MutableList<List<Int>> = mutableListOf()
// l1@ for (perm in perms) {
// for ((index, queen) in perm.withIndex()) {
// for (i in 0 until index)
// if (i != index &&
// Math.abs(perm[i] - queen) == Math.abs(index - i)) continue@l1
//
// }
// result.add(perm)
// }
return result
}
fun Queen(N: Int) {
val input = IntArray(N, { it }).toList()
val result = permute(input)
fun print(list: IntArray) {
println(list.toList())
list.forEach { value ->
(0 until list.size).forEach { i ->
when (i) {
value -> print('Q')
else -> print('.')
}
}
print('\n')
}
println()
}
println("There are ${result.size} possible solutions, namely:\n")
for (perm in result) print(perm)
}
fun main(args: Array<String>) {
val executionTime = measureTimeMillis { Queen(8) }
println("Execution Time = $executionTime ms")
}
| mit | eb7f4eed0cc5cf4c0d335f515fe38484 | 25.31 | 83 | 0.583428 | 3.173703 | false | false | false | false |
jdiazcano/modulartd | editor/core/src/main/kotlin/com/jdiazcano/modulartd/tabs/GameTab.kt | 1 | 5328 | package com.jdiazcano.modulartd.tabs
import com.github.salomonbrys.kodein.instance
import com.jdiazcano.modulartd.beans.Map
import com.jdiazcano.modulartd.bus.Bus
import com.jdiazcano.modulartd.bus.BusTopic
import com.jdiazcano.modulartd.injections.kodein
import com.jdiazcano.modulartd.ui.widgets.CoinEditor
import com.jdiazcano.modulartd.utils.sneakyChange
import com.jdiazcano.modulartd.utils.translate
import com.kotcrab.vis.ui.widget.VisScrollPane
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.VisValidatableTextField
class GameTab: BaseTab<Map>(translate("tabs.game"), true, false) {
private val superTable = VisTable(true)
private val scroll = VisScrollPane(superTable)
private val textName = VisValidatableTextField()
private val textMaker = VisValidatableTextField()
private val textDescription = VisValidatableTextField()
private val textAuthorNotes = VisValidatableTextField()
private val coinEditor = CoinEditor(kodein.instance<Map>().coins)
private val textTotalUnitsMap = VisValidatableTextField()
private val textInterestRatio = VisValidatableTextField()
private val textTurretSellProfit = VisValidatableTextField()
init {
Bus.register<Map>(BusTopic.MAP_LOAD) {
updateUI(it)
}
setUpValidableForm()
placeComponents()
addUpdateListeners()
addTextFieldsForEvents()
//scroll.setScrollingDisabled(true, false)
content.add("Game properties").expandX().center().row()
content.add(scroll).expand().top().left().pad(30F)
}
private fun addTextFieldsForEvents() {
textFields += textName
textFields += textDescription
textFields += textMaker
textFields += textAuthorNotes
textFields += textTurretSellProfit
textFields += textTotalUnitsMap
textFields += textInterestRatio
}
private fun addUpdateListeners() {
val map = kodein.instance<Map>()
textName.text = map.name
textName.sneakyChange {
map.name = textName.text
game.dirty = true
}
textMaker.text = map.author
textMaker.sneakyChange {
map.author = textMaker.text
game.dirty = true
}
textDescription.text = map.description
textDescription.sneakyChange {
map.description = textDescription.text
game.dirty = true
}
textAuthorNotes.text = map.authorNotes
textAuthorNotes.sneakyChange {
map.authorNotes = textAuthorNotes.text
game.dirty = true
}
textTotalUnitsMap.text = map.unitCount.toString()
textTotalUnitsMap.sneakyChange {
map.unitCount = textTotalUnitsMap.text.toInt()
game.dirty = true
}
textInterestRatio.text = map.interestRatio.toString()
textInterestRatio.sneakyChange {
map.interestRatio = textInterestRatio.text.toFloat()
game.dirty = true
}
textTurretSellProfit.text = map.turretSellProfit.toString()
textTurretSellProfit.sneakyChange {
map.turretSellProfit = textTurretSellProfit.text.toFloat()
game.dirty = true
}
}
private fun placeComponents() {
superTable.add(translate("name")).left(); superTable.add(textName).row()
superTable.add(translate("author")).left(); superTable.add(textMaker).row()
superTable.add(translate("description")).left(); superTable.add(textDescription).row()
superTable.add(translate("authorNotes")).left(); superTable.add(textAuthorNotes).row()
superTable.add(translate("unitsMap")).left(); superTable.add(textTotalUnitsMap).row()
superTable.add(translate("interestRatio")).left(); superTable.add(textInterestRatio).row()
superTable.add(translate("turretSellProfit")).left();superTable.add(textTurretSellProfit).row()
superTable.add(coinEditor).colspan(999).expandX().fillX().height(300F)
}
private fun setUpValidableForm() {
validator.notEmpty(textName, "Name can't be empty")
validator.notEmpty(textMaker, "Maker can't be empty")
validator.notEmpty(textDescription, "Description can't be empty")
// Notes CAN be empty!!! validator.notEmpty(textAuthorNotes, "Name can't be empty")
validator.valueGreaterThan(textTotalUnitsMap, "It needs to be a positive value", 0F, true)
validator.valueGreaterThan(textInterestRatio, "It needs to be a positive value", 0F, true)
validator.valueGreaterThan(textTurretSellProfit, "It needs to be a positive value", 0F, true)
}
override fun newItem() {
throw NotImplementedError("This is something that should never be called!!!!")
}
override fun updateUI(item: Map) {
disableProgrammaticEvents()
textName.text = item.name
textDescription.text = item.description
textMaker.text = item.author
textAuthorNotes.text = item.authorNotes
textTurretSellProfit.text = item.turretSellProfit.toString()
textTotalUnitsMap.text = item.unitCount.toString()
textInterestRatio.text = item.interestRatio.toString()
enableProgrammaticEvents()
}
} | apache-2.0 | 6b807e7135c8d66fa7d0aa674fc2e29e | 36.528169 | 103 | 0.678866 | 5.035917 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/crash/GlobalExceptionHandler.kt | 1 | 3000 | package eu.kanade.tachiyomi.crash
import android.content.Context
import android.content.Intent
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import logcat.LogPriority
import kotlin.system.exitProcess
class GlobalExceptionHandler private constructor(
private val applicationContext: Context,
private val defaultHandler: Thread.UncaughtExceptionHandler,
private val activityToBeLaunched: Class<*>,
) : Thread.UncaughtExceptionHandler {
object ThrowableSerializer : KSerializer<Throwable> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("Throwable", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Throwable =
Throwable(message = decoder.decodeString())
override fun serialize(encoder: Encoder, value: Throwable) =
encoder.encodeString(value.stackTraceToString())
}
override fun uncaughtException(thread: Thread, exception: Throwable) {
try {
logcat(priority = LogPriority.ERROR, throwable = exception)
launchActivity(applicationContext, activityToBeLaunched, exception)
exitProcess(0)
} catch (_: Exception) {
defaultHandler.uncaughtException(thread, exception)
}
}
private fun launchActivity(
applicationContext: Context,
activity: Class<*>,
exception: Throwable,
) {
val intent = Intent(applicationContext, activity).apply {
putExtra(INTENT_EXTRA, Json.encodeToString(ThrowableSerializer, exception))
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
applicationContext.startActivity(intent)
}
companion object {
private const val INTENT_EXTRA = "Throwable"
fun initialize(
applicationContext: Context,
activityToBeLaunched: Class<*>,
) {
val handler = GlobalExceptionHandler(
applicationContext,
Thread.getDefaultUncaughtExceptionHandler() as Thread.UncaughtExceptionHandler,
activityToBeLaunched,
)
Thread.setDefaultUncaughtExceptionHandler(handler)
}
fun getThrowableFromIntent(intent: Intent): Throwable? {
return try {
Json.decodeFromString(ThrowableSerializer, intent.getStringExtra(INTENT_EXTRA)!!)
} catch (e: Exception) {
logcat(LogPriority.ERROR, e) { "Wasn't able to retrive throwable from intent" }
null
}
}
}
}
| apache-2.0 | 08ff3cf19a3e2cc88db2a822ae2f7523 | 36.5 | 97 | 0.689 | 5.703422 | false | false | false | false |
MKA-Nigeria/MKAN-Report-Android | videos_module/src/main/java/com/abdulmujibaliu/koutube/fragments/parent/BaseVideoTabFragment.kt | 1 | 2159 | package com.abdulmujibaliu.koutube.fragments.parent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import com.abdulmujibaliu.koutube.R
import com.abdulmujibaliu.koutube.data.models.YoutubeVideo
import com.abdulmujibaliu.koutube.data.repositories.PlayListRepository
import com.abdulmujibaliu.koutube.data.repositories.contracts.RepositoryContracts
import com.abdulmujibaliu.koutube.fragments.videos.VideoClickListener
import com.aliumujib.mkanapps.coremodule.base.BaseFragment
/**
* A simple [Fragment] subclass.
*/
abstract class BaseVideoTabFragment : BaseFragment(), VideoClickListener {
//val TAG: String = javaClass.simpleName
protected var parentView: ParentViewContract.View? = null
protected var loadingIndicator: ProgressBar? = null
val dataSource: RepositoryContracts.IDataSource = PlayListRepository.getInstance()!!
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_base, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onAttachToParentFragment(parentFragment)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadingIndicator = view!!.findViewById(R.id.progressBar)
}
override fun hideLoading() {
loadingIndicator!!.visibility = View.GONE
}
override fun showLoading() {
loadingIndicator!!.visibility = View.VISIBLE
}
// In the child fragment.
private fun onAttachToParentFragment(fragment: Fragment) {
try {
parentView = fragment as ParentViewContract.View
} catch (e: ClassCastException) {
throw ClassCastException(
fragment.toString() + " must implement ParentViewContract.View")
}
}
}// Required empty public constructor
| mit | 65972c8371399aa4832bc333910bedd2 | 29.842857 | 88 | 0.731357 | 5.044393 | false | false | false | false |
pocmo/focus-android | app/src/gecko/java/org/mozilla/focus/web/LocalizedContentGecko.kt | 1 | 4904 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.web
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.support.v4.util.ArrayMap
import android.view.View
import org.mozilla.focus.R
import org.mozilla.focus.locale.Locales
import org.mozilla.focus.utils.HtmlLoader
import org.mozilla.focus.utils.SupportUtils
import org.mozilla.gecko.GeckoSession
import java.io.File
import java.io.PrintWriter
object LocalizedContentGecko {
// We can't use "about:" because webview silently swallows about: pages, hence we use
// a custom scheme.
val URL_ABOUT = "focus:about"
val URL_RIGHTS = "focus:rights"
val mplUrl = "https://www.mozilla.org/en-US/MPL/"
val trademarkPolicyUrl = "https://www.mozilla.org/foundation/trademarks/policy/"
val gplUrl = "gpl.html"
val trackingProtectionUrl = "https://wiki.mozilla.org/Security/Tracking_protection#Lists"
val licensesUrl = "licenses.html"
fun handleInternalContent(url: String, geckoSession: GeckoSession, context: Context): Boolean {
if (URL_ABOUT == url) {
loadAbout(geckoSession, context)
return true
} else if (URL_RIGHTS == url) {
loadRights(geckoSession, context)
return true
}
return false
}
/**
* Load the content for focus:about
*/
private fun loadAbout(geckoSession: GeckoSession, context: Context) {
val resources = Locales.getLocalizedResources(context)
val substitutionMap = ArrayMap<String, String>()
val appName = context.resources.getString(R.string.app_name)
val learnMoreURL = SupportUtils.getManifestoURL()
var aboutVersion = ""
try {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
aboutVersion = String.format("%s (Build #%s)", packageInfo.versionName, packageInfo.versionCode)
} catch (e: PackageManager.NameNotFoundException) {
// Nothing to do if we can't find the package name.
}
substitutionMap["%about-version%"] = aboutVersion
val aboutContent = resources.getString(R.string.about_content, appName, learnMoreURL)
substitutionMap["%about-content%"] = aboutContent
val wordmark = HtmlLoader.loadPngAsDataURI(context, R.drawable.wordmark)
substitutionMap["%wordmark%"] = wordmark
putLayoutDirectionIntoMap(substitutionMap, context)
val data = HtmlLoader.loadResourceFile(context, R.raw.about, substitutionMap)
val path = context.filesDir
val file = File(path, "about.html")
writeDataToFile(file, data)
geckoSession.loadUri(Uri.fromFile(file))
}
/**
* Load the content for focus:rights
*/
private fun loadRights(geckoSession: GeckoSession, context: Context) {
val resources = Locales.getLocalizedResources(context)
val appName = resources.getString(R.string.app_name)
val substitutionMap = ArrayMap<String, String>()
val content1 = resources.getString(R.string.your_rights_content1, appName)
substitutionMap["%your-rights-content1%"] = content1
val content2 = resources.getString(R.string.your_rights_content2, appName, mplUrl)
substitutionMap["%your-rights-content2%"] = content2
val content3 = resources.getString(R.string.your_rights_content3, appName, trademarkPolicyUrl)
substitutionMap["%your-rights-content3%"] = content3
val content4 = resources.getString(R.string.your_rights_content4, appName, licensesUrl)
substitutionMap["%your-rights-content4%"] = content4
val content5 = resources.getString(R.string.your_rights_content5, appName, gplUrl, trackingProtectionUrl)
substitutionMap["%your-rights-content5%"] = content5
putLayoutDirectionIntoMap(substitutionMap, context)
val data = HtmlLoader.loadResourceFile(context, R.raw.rights, substitutionMap)
val path = context.filesDir
val file = File(path, "rights.html")
writeDataToFile(file, data)
geckoSession.loadUri(Uri.fromFile(file))
}
private fun writeDataToFile(file: File, data: String) {
PrintWriter(file).use({ out -> out.println(data) })
}
private fun putLayoutDirectionIntoMap(substitutionMap: ArrayMap<String, String>, context: Context) {
val layoutDirection = context.resources.configuration.layoutDirection
val direction = when (layoutDirection) {
View.LAYOUT_DIRECTION_LTR -> "ltr"
View.LAYOUT_DIRECTION_RTL -> "rtl"
else -> "auto"
}
substitutionMap["%dir%"] = direction
}
}
| mpl-2.0 | de74bb4b89a16339b88d82c04577c94e | 36.723077 | 113 | 0.685971 | 4.264348 | false | false | false | false |
xiprox/Tensuu | common-app/src/main/java/tr/xip/scd/tensuu/common/ext/Calendar.kt | 1 | 1175 | package tr.xip.scd.tensuu.common.ext
import java.util.*
import java.util.Calendar.*
/**
* Calendar related extensions
*/
var Calendar.year: Int
get() = get(YEAR)
set(value) = set(YEAR, value)
var Calendar.month: Int
get() = get(MONTH)
set(value) = set(MONTH, value)
var Calendar.dayOfMonth
get() = get(DAY_OF_MONTH)
set(value) = set(DAY_OF_MONTH, value)
var Calendar.dayOfWeek
get() = get(DAY_OF_WEEK)
set(value) = set(DAY_OF_WEEK, value)
fun Calendar.addChainable(field: Int, amount: Int): Calendar {
add(field, amount)
return this
}
/**
* Strips this calendar of its hour, minute, second, and millisecond values, then returns the
* resulting Calendar object.
*/
fun Calendar.stripToDate(): Calendar {
set(HOUR_OF_DAY, 0)
set(HOUR, 0)
set(MINUTE, 0)
set(SECOND, 0)
set(MILLISECOND, 0)
return this
}
/**
* Applies [Calendar.stripToDate] on this calendar and returns a timestamp from the resulting calendar.
*/
fun Calendar.strippedTimestamp(): Long {
return stripToDate().timeInMillis
}
fun Calendar.setTimeInMillisAndReturn(time: Long): Calendar {
timeInMillis = time
return this
} | gpl-3.0 | 9d69c5a91cf67258585f1023f14761f7 | 20.777778 | 103 | 0.68 | 3.415698 | false | false | false | false |
unbroken-dome/gradle-xjc-plugin | src/integrationTest/kotlin/org/unbrokendome/gradle/plugins/xjc/testutil/GradleProjectExtension.kt | 1 | 5814 | package org.unbrokendome.gradle.plugins.xjc.testutil
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import org.junit.platform.commons.util.AnnotationUtils
import org.junit.platform.commons.util.ReflectionUtils
import org.unbrokendome.gradle.plugins.xjc.testlib.DirectoryBuilder
import org.unbrokendome.gradle.plugins.xjc.testlib.directory
import java.io.File
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.lang.reflect.Parameter
import java.nio.file.Files
import java.nio.file.Path
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class GradleProjectSetup
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class GradleProjectDir
private object GradleProjectNamespaceKey
private val namespace = ExtensionContext.Namespace.create(GradleProjectNamespaceKey)
private val ExtensionContext.store: ExtensionContext.Store
get() = getStore(namespace)
private class GradleProjectDirResource : ExtensionContext.Store.CloseableResource {
companion object StoreKey
val directory: File = Files.createTempDirectory("gradle").toFile()
override fun close() {
directory.deleteRecursively()
}
}
typealias ProjectDirInitializer = (projectDir: File, context: ExtensionContext) -> Unit
private object ProjectDirInitializerStoreKey
private operator fun ProjectDirInitializer?.plus(other: ProjectDirInitializer?): ProjectDirInitializer? {
return when {
this == null -> other
other == null -> this
else -> {
{ projectDir, context ->
this(projectDir, context)
other(projectDir, context)
}
}
}
}
private fun methodProjectDirInitializer(method: Method): ProjectDirInitializer = { projectDir, context ->
val target = if (method.modifiers and Modifier.STATIC == 0) {
context.requiredTestInstance
} else null
val args = method.parameters.map<Parameter, Any> { param ->
when (param.type) {
File::class.java -> projectDir
Path::class.java -> projectDir.toPath()
DirectoryBuilder::class.java -> DirectoryBuilder(projectDir)
else -> error("Cannot resolve argument for parameter \"${param.name}\" @SetupGradleProject method $method")
}
}
method.invoke(target, *args.toTypedArray())
}
@Suppress("UNCHECKED_CAST")
private val ExtensionContext.projectDirInitializer: ProjectDirInitializer?
get() = store.get(ProjectDirInitializerStoreKey) as ProjectDirInitializer?
fun ExtensionContext.setupProjectDir(initializer: (projectDir: File) -> Unit) {
store.put(
ProjectDirInitializerStoreKey,
this.projectDirInitializer + { projectDir, _ -> initializer(projectDir) }
)
}
val ExtensionContext.gradleProjectDir: File
get() {
val resource = store.getOrComputeIfAbsent(GradleProjectDirResource, {
GradleProjectDirResource().also {
initGradleProject(it.directory)
}
}, GradleProjectDirResource::class.java)
return resource.directory
}
private fun ExtensionContext.initGradleProject(projectDir: File) {
projectDirInitializer?.invoke(projectDir, this)
// Create a settings file if the test setup didn't create one, otherwise Gradle searches up the
// directory hierarchy (and might actually find one)
directory(projectDir) {
if (!Files.exists(path.resolve("settings.gradle")) &&
!Files.exists(path.resolve("settings.gradle.kts"))
) {
file(
name = "settings.gradle",
contents = """
rootProject.name = '${projectDir.name}'
""".trimIndent()
)
}
}
}
class GradleProjectExtension
@JvmOverloads constructor(
private val projectDirInitializer: ((projectDir: File) -> Unit)? = null
) : BeforeAllCallback, BeforeEachCallback, ParameterResolver {
@ExperimentalStdlibApi
override fun beforeAll(context: ExtensionContext) {
val initializerFromMethods = AnnotationUtils.findAnnotatedMethods(
context.requiredTestClass, GradleProjectSetup::class.java,
ReflectionUtils.HierarchyTraversalMode.TOP_DOWN
).asSequence()
.map(::methodProjectDirInitializer)
.reduceOrNull { acc, initializer -> (acc + initializer)!! }
if (initializerFromMethods != null) {
context.store.put(
ProjectDirInitializerStoreKey,
context.projectDirInitializer + initializerFromMethods
)
}
}
@Suppress("UNCHECKED_CAST")
override fun beforeEach(context: ExtensionContext) {
if (projectDirInitializer != null) {
context.setupProjectDir(projectDirInitializer)
}
}
override fun supportsParameter(
parameterContext: ParameterContext,
extensionContext: ExtensionContext
): Boolean =
parameterContext.isAnnotated(GradleProjectDir::class.java) &&
parameterContext.parameter.type in setOf(File::class.java, Path::class.java)
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any? {
val projectDir = extensionContext.gradleProjectDir
return when (parameterContext.parameter.type) {
File::class.java -> projectDir
Path::class.java -> projectDir.toPath()
else -> error("Invalid parameter type")
}
}
}
| mit | 24efa64dd6809f8bf0bb5ce4a0dd1219 | 30.945055 | 119 | 0.696938 | 5.108963 | false | false | false | false |
square/wire | wire-grpc-tests/src/test/java/com/squareup/wire/GrpcOnMockWebServerTest.kt | 1 | 3700 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.wire.mockwebserver.GrpcDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.runBlocking
import okhttp3.Call
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.mockwebserver.MockWebServer
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Timeout
import routeguide.Feature
import routeguide.Point
import routeguide.Rectangle
import routeguide.RouteGuideClient
import routeguide.RouteNote
import routeguide.RouteSummary
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
class GrpcOnMockWebServerTest {
@JvmField @Rule val mockWebServer = MockWebServer()
@JvmField @Rule val timeout = Timeout(30, TimeUnit.SECONDS)
private lateinit var okhttpClient: OkHttpClient
private lateinit var grpcClient: GrpcClient
private lateinit var routeGuideService: RouteGuideClient
private var callReference = AtomicReference<Call>()
private val fakeRouteGuide = FakeRouteGuide()
/** This is a pass through interceptor that tests can replace without extra plumbing. */
private var interceptor: Interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain) = chain.proceed(chain.request())
}
@Before
fun setUp() {
mockWebServer.dispatcher = GrpcDispatcher(
services = listOf(fakeRouteGuide),
delegate = mockWebServer.dispatcher
)
mockWebServer.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)
okhttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
callReference.set(chain.call())
interceptor.intercept(chain)
}
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE))
.build()
grpcClient = GrpcClient.Builder()
.client(okhttpClient)
.baseUrl(mockWebServer.url("/"))
.build()
routeGuideService = grpcClient.create(RouteGuideClient::class)
}
@Test
fun requestResponseSuspend() {
runBlocking {
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.execute(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree"))
assertThat(fakeRouteGuide.recordedGetFeatureCalls)
.containsExactly(Point(latitude = 5, longitude = 6))
}
}
class FakeRouteGuide : RouteGuideClient {
val recordedGetFeatureCalls = mutableListOf<Point>()
override fun GetFeature() = GrpcCall<Point, Feature> { request ->
recordedGetFeatureCalls += request
return@GrpcCall Feature(name = "tree")
}
override fun ListFeatures(): GrpcStreamingCall<Rectangle, Feature> {
TODO("Not yet implemented")
}
override fun RecordRoute(): GrpcStreamingCall<Point, RouteSummary> {
TODO("Not yet implemented")
}
override fun RouteChat(): GrpcStreamingCall<RouteNote, RouteNote> {
TODO("Not yet implemented")
}
}
}
| apache-2.0 | b9cdd18f40c1dbd8a94fc9d2e01a38e9 | 32.035714 | 90 | 0.749459 | 4.579208 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/statistics/src/org/jetbrains/kotlin/idea/statistics/ProjectConfigurationCollector.kt | 3 | 4039 | // 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.statistics
import com.intellij.facet.ProjectFacetManager
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.buildSystemType
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.isNative
class ProjectConfigurationCollector : ProjectUsagesCollector() {
override fun getGroup() = GROUP
override fun getMetrics(project: Project): Set<MetricEvent> {
val metrics = mutableSetOf<MetricEvent>()
val modulesWithFacet = ProjectFacetManager.getInstance(project).getModulesWithFacet(KotlinFacetType.TYPE_ID)
if (modulesWithFacet.isNotEmpty()) {
modulesWithFacet.forEach {
val buildSystem = getBuildSystemType(it)
val platform = getPlatform(it)
metrics.add(
buildEvent.metric(
systemField.with(buildSystem),
platformField.with(platform),
isMPPBuild.with(it.isMultiPlatformModule || it.isNewMultiPlatformModule),
pluginInfoField.with(KotlinIdePlugin.getPluginInfo())
)
)
}
}
return metrics
}
private fun getPlatform(it: Module): String {
return when {
it.platform.isJvm() -> {
if (it.name.contains("android")) "jvm.android"
else "jvm"
}
it.platform.isJs() -> "js"
it.platform.isCommon() -> "common"
it.platform.isNative() -> "native." + (it.platform?.componentPlatforms?.first()?.targetName ?: "unknown")
else -> "unknown"
}
}
private fun getBuildSystemType(it: Module): String {
val buildSystem = it.buildSystemType
return when {
buildSystem == BuildSystemType.JPS -> "JPS"
buildSystem.toString().toLowerCase().contains("maven") -> "Maven"
buildSystem.toString().toLowerCase().contains("gradle") -> "Gradle"
else -> "unknown"
}
}
companion object {
private val GROUP = EventLogGroup("kotlin.project.configuration", 6)
private val systemField = EventFields.String("system", listOf("JPS", "Maven", "Gradle", "unknown"))
private val platformField = EventFields.String("platform", composePlatformFields())
private val isMPPBuild = EventFields.Boolean("isMPP")
private val pluginInfoField = EventFields.PluginInfo
private fun composePlatformFields(): List<String> {
return listOf(
listOf("jvm", "jvm.android", "js", "common", "native.unknown", "unknown"),
KonanTarget.predefinedTargets.keys.map { "native.$it" }
).flatten()
}
private val buildEvent = GROUP.registerVarargEvent(
"Build",
systemField,
platformField,
isMPPBuild,
pluginInfoField
)
}
}
| apache-2.0 | e6accc5a954895a8240bf257b9dfbe09 | 40.214286 | 158 | 0.664769 | 5.023632 | false | true | false | false |
PolymerLabs/arcs | java/arcs/core/data/testutil/Generators.kt | 1 | 17773 | package arcs.core.data.testutil
import arcs.core.common.Referencable
import arcs.core.data.CollectionType
import arcs.core.data.CreatableStorageKey
import arcs.core.data.FieldName
import arcs.core.data.FieldType
import arcs.core.data.HandleMode
import arcs.core.data.Plan
import arcs.core.data.PrimitiveType
import arcs.core.data.RawEntity
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.SingletonType
import arcs.core.data.util.ReferencablePrimitive
import arcs.core.data.util.toReferencable
import arcs.core.entity.EntityBaseSpec
import arcs.core.host.ParticleRegistration
import arcs.core.host.testutil.ParticleRegistrationGenerator
import arcs.core.storage.RawReference
import arcs.core.storage.StorageKey
import arcs.core.testutil.ChooseFromList
import arcs.core.testutil.FuzzingRandom
import arcs.core.testutil.Generator
import arcs.core.testutil.Transformer
import arcs.core.testutil.Value
import arcs.core.testutil.midSizedAlphaNumericString
import arcs.core.testutil.midSizedUnicodeString
import arcs.core.type.Type
import arcs.core.util.ArcsDuration
import arcs.core.util.ArcsInstant
import arcs.core.util.BigInt
/**
* Generators for arcs.core.data classes.
*/
/**
* Generate a [Plan.Particle] given a generator for name, location and connection map.
*/
class PlanParticleGenerator(
val name: Generator<String>,
val location: Generator<String>,
val connections: Generator<Map<String, Plan.HandleConnection>>
) : Generator<Plan.Particle> {
override operator fun invoke(): Plan.Particle {
return Plan.Particle(name(), location(), connections())
}
}
/**
* Generate a [Plan.Handle] given a generator for [StorageKey] and [Type].
*/
class HandleGenerator(
val storageKey: Generator<StorageKey>,
val type: Generator<Type>
) : Generator<Plan.Handle> {
override operator fun invoke(): Plan.Handle {
return Plan.Handle(storageKey(), type(), emptyList())
}
}
/**
* Generate a [Plan.HandleConnection] given a generator for [Plan.Handle] and [Type], and a
* transformer to generate compatible [HandleMode] given [Type].
*/
class HandleConnectionGenerator(
val handle: Generator<Plan.Handle>,
val mode: Transformer<Type, HandleMode>,
val type: Generator<Type>
) : Generator<Plan.HandleConnection> {
override operator fun invoke(): Plan.HandleConnection {
val theType = type()
return Plan.HandleConnection(
handle(),
mode(theType),
theType,
emptyList()
)
}
}
/**
* Given a list of [Plan.Particle]s, generate a [Plan].
*/
class PlanFromParticles(val s: FuzzingRandom) : Transformer<List<Plan.Particle>, Plan>() {
override operator fun invoke(i: List<Plan.Particle>): Plan {
val handles = i.flatMap { it.handles.values.map { hc -> hc.handle } }.distinct()
return Plan(
i.toList(), // clone list
handles,
emptyList()
)
}
}
/**
* Generate a [CreatableStorageKey] from a manifestName generator.
*/
class CreatableStorageKeyGenerator(
val nameFromManifest: Generator<String>
) : Generator<StorageKey> {
override operator fun invoke(): CreatableStorageKey {
return CreatableStorageKey(nameFromManifest())
}
}
/**
* Pairs a [ParticleRegistration] with a [Plan.Particle]. These two objects need to
* have similar information in order for a plan to successfully start:
* - the location in Plan.Particle has to match the ParticleRegistration's ParticleIdentifier
* - the Particle instance returned by the ParticleRegistration's ParticleConstructor needs
* - to have a handle field with a HandleHolder that recognizes any handleConnections listed in
* - the Plan.Particle as valid.
*
* Because of these interdependencies, it's useful for random test case generation to treat
* the two structures as a pair; hence this data class.
*/
data class ParticleInfo(val registration: ParticleRegistration, val plan: Plan.Particle)
/**
* Generates a [ParticleInfo] given a name and connection map. This generator ensures
* that the [ParticleRegistration] and [Plan.Particle] inside the [ParticleInfo] are
* set up such that the [Plan.Particle] correctly references the [ParticleRegistration],
* which in turn creates a [Particle] with the correct handle structure.
*/
// TODO(shanestephens): the minimal dependency here is actually that ParticleRegistration
// needs the location of the particle (to generate the ParticleIdentifier correctly) and
// the name of the particle and handleConnections (to generate the ParticleConstructor
// correctly). This should allow the rest of the details of connection to be filled in
// later.
// TODO(shanestephens): pass a location into ParticleRegistrationGenerator rather than extracting
// one.
class ParticleInfoGenerator(
val s: FuzzingRandom,
val name: Generator<String>,
val connections: Generator<Map<String, Plan.HandleConnection>>
) : Generator<ParticleInfo> {
override operator fun invoke(): ParticleInfo {
val theName = name()
val theConnections = connections()
val emptySchema = Schema(
emptySet(),
SchemaFields(emptyMap(), emptyMap()),
"empty-hash"
)
val theEntities = theConnections.mapValues { setOf(EntityBaseSpec(emptySchema)) }
val registration = ParticleRegistrationGenerator(s, Value(theName), Value(theEntities))()
val location = registration.first.id
val particle = PlanParticleGenerator(
Value(theName),
Value(location),
Value(theConnections)
)()
return ParticleInfo(registration, particle)
}
}
/**
* Given a [Type], generates a valid [HandleMode] for that [Type].
*/
class HandleModeFromType(val s: FuzzingRandom) : Transformer<Type, HandleMode>() {
override operator fun invoke(i: Type): HandleMode =
when (i) {
is SingletonType<*> -> ChooseFromList(
s,
listOf(
HandleMode.Read,
HandleMode.Write
)
)()
is CollectionType<*> -> ChooseFromList(
s,
listOf(
HandleMode.Read,
HandleMode.Write,
HandleMode.Query,
HandleMode.ReadWrite,
HandleMode.ReadQuery,
HandleMode.WriteQuery,
HandleMode.ReadWriteQuery
)
)()
else -> throw UnsupportedOperationException(
"I don't know how to generate HandleModes for type $i"
)
}
}
/**
* A [Generator] of primitive [FieldType]s.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
*/
class PrimitiveFieldTypeGenerator(
val s: FuzzingRandom
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val primitiveType = ChooseFromList(s, PrimitiveType.values().toList())()
return FieldTypeWithReferencedSchemas.justType(FieldType.Primitive(primitiveType))
}
}
/**
* A [Generator] of Tuple [FieldType]s.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
* TODO(b/180656030): Tuple support might be going away? Remove this Generator if so.
*/
class TupleFieldTypeGenerator(
val s: FuzzingRandom,
val fields: Generator<FieldTypeWithReferencedSchemas>,
val size: Generator<Int>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val tupleFields = (1..size()).map { fields() }
return FieldTypeWithReferencedSchemas(
FieldType.Tuple(tupleFields.map { it.fieldType }),
tupleFields.map { it.schemas }.foldRight(emptyMap()) { a, b -> a.plus(b) }
)
}
}
/**
* A [Generator] of ListOf [FieldType]s.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
*/
class ListFieldTypeGenerator(
val field: Generator<FieldTypeWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val memberType = field()
return FieldTypeWithReferencedSchemas(
FieldType.ListOf(memberType.fieldType),
memberType.schemas
)
}
}
/**
* A [Generator] of NullableOf [FieldType]s.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
*/
class NullableFieldTypeGenerator(
val field: Generator<FieldTypeWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val memberType = field()
return FieldTypeWithReferencedSchemas(
FieldType.NullableOf(memberType.fieldType),
memberType.schemas
)
}
}
/**
* A [Generator] of [FieldType]s representing inline entities.
*
* Note that inline entities are referenced by schema hash rather than direct incorporation
* of the inline schema into the parent schema. For this reason, this generator returns
* [FieldTypeWithReferencedSchemas] objects that encapsulate both a [FieldType] and any schemas
* referenced by that [FieldType].
*/
class InlineEntityFieldTypeGenerator(
val schema: Generator<SchemaWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val theSchema = schema()
return FieldTypeWithReferencedSchemas(
FieldType.InlineEntity(theSchema.schema.hash),
theSchema.schemas + (theSchema.schema.hash to theSchema.schema)
)
}
}
/**
* A [Generator] of [FieldType]s representing references.
*
* Note that entities referenced by references are described by schema hash rather than direct
* incorporation of the inline schema into the field. For this reason, this generator returns
* [FieldTypeWithReferencedSchemas] objects that encapsulate both a [FieldType] and any schemas
* referenced by that [FieldType].
*/
class ReferenceFieldTypeGenerator(
val schema: Generator<SchemaWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
val theSchema = schema()
return FieldTypeWithReferencedSchemas(
FieldType.EntityRef(theSchema.schema.hash),
theSchema.schemas + (theSchema.schema.hash to theSchema.schema)
)
}
}
/**
* A [Generator] of [FieldType]s that one could validly make an ordered list of.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
*/
class FieldTypeValidForListGenerator(
val s: FuzzingRandom,
val schema: Generator<SchemaWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
return ChooseFromList(
s,
listOf(
PrimitiveFieldTypeGenerator(s),
InlineEntityFieldTypeGenerator(schema),
ReferenceFieldTypeGenerator(schema)
)
).invoke().invoke()
}
}
/**
* A [Generator] of [FieldType]s.
*
* Note that some [FieldType]s reference schema hashes that are expected to be in a global
* registry. For this reason, all [FieldType] generators return [FieldTypeWithReferencedSchemas]
* objects that encapsulate both a [FieldType] and any schemas referenced by that [FieldType].
*/
class FieldTypeGenerator(
val s: FuzzingRandom,
val schema: Generator<SchemaWithReferencedSchemas>
) : Generator<FieldTypeWithReferencedSchemas> {
override fun invoke(): FieldTypeWithReferencedSchemas {
return ChooseFromList(
s,
listOf(
PrimitiveFieldTypeGenerator(s),
ListFieldTypeGenerator(FieldTypeValidForListGenerator(s, schema)),
InlineEntityFieldTypeGenerator(schema),
ReferenceFieldTypeGenerator(schema),
NullableFieldTypeGenerator(FieldTypeValidForListGenerator(s, schema))
)
).invoke().invoke()
}
}
/**
* A [Transformer] that, given a [PrimitiveType], can produce [ReferencablePrimitive] objects
* with appropriate data.
*/
class ReferencablePrimitiveFromPrimitiveType(
val s: FuzzingRandom,
val unicode: Boolean = true
) : Transformer<PrimitiveType, ReferencablePrimitive<*>>() {
override fun invoke(i: PrimitiveType): ReferencablePrimitive<*> {
return when (i) {
PrimitiveType.Boolean -> s.nextBoolean().toReferencable()
PrimitiveType.BigInt -> BigInt.valueOf(s.nextLong()).toReferencable()
PrimitiveType.Byte -> s.nextByte().toReferencable()
PrimitiveType.Char -> s.nextChar().toReferencable()
PrimitiveType.Double -> s.nextDouble().toReferencable()
PrimitiveType.Duration -> ArcsDuration.valueOf(s.nextLong()).toReferencable()
PrimitiveType.Float -> s.nextFloat().toReferencable()
PrimitiveType.Instant -> ArcsInstant.ofEpochMilli(s.nextLong()).toReferencable()
PrimitiveType.Int -> s.nextInt().toReferencable()
PrimitiveType.Long -> s.nextLong().toReferencable()
PrimitiveType.Number -> s.nextDouble().toReferencable()
PrimitiveType.Short -> s.nextShort().toReferencable()
PrimitiveType.Text ->
(if (unicode) midSizedUnicodeString(s) else midSizedAlphaNumericString(s))()
.toReferencable()
}
}
}
/**
* A [Transformer] that, given a [FieldTypeWithReferencedSchemas] can produce [Referencable]
* objects with appropriate data.
*/
class NonNullableReferencableFromFieldType(
val referencablePrimitive: Transformer<PrimitiveType, ReferencablePrimitive<*>>,
val listLength: Generator<Int>,
val rawEntity: Transformer<SchemaWithReferencedSchemas, RawEntity>,
val rawReference: Generator<RawReference>
) : Transformer<FieldTypeWithReferencedSchemas, Referencable>() {
override fun invoke(i: FieldTypeWithReferencedSchemas): Referencable {
return when (i.fieldType) {
is FieldType.Primitive -> referencablePrimitive(i.fieldType.primitiveType)
is FieldType.ListOf -> {
val primitiveField = FieldTypeWithReferencedSchemas(
i.fieldType.primitiveType,
i.schemas
)
(1..listLength()).map { invoke(primitiveField) }.toReferencable(i.fieldType)
}
is FieldType.InlineEntity -> {
val schema = i.schemas[i.fieldType.schemaHash]!!
rawEntity(SchemaWithReferencedSchemas(schema, i.schemas))
}
is FieldType.EntityRef -> rawReference()
is FieldType.Tuple ->
TODO("b/180656030: values of Tuple type aren't yet supported")
is FieldType.NullableOf -> {
val innerField = FieldTypeWithReferencedSchemas(
i.fieldType.innerType,
i.schemas
)
invoke(innerField)
}
}
}
}
/**
* A [Transformer] that, given a [FieldTypeWithReferencedSchemas] can produce [Referencable?]
* objects with appropriate data.
*/
class NullableReferencableFromFieldType(
val nonNullableReferencablePrimitive: Transformer<FieldTypeWithReferencedSchemas, Referencable>,
val isNull: Generator<Boolean>
) : Transformer<FieldTypeWithReferencedSchemas, Referencable?>() {
override fun invoke(i: FieldTypeWithReferencedSchemas): Referencable? {
return when {
i.fieldType is FieldType.NullableOf && isNull() -> null
else -> nonNullableReferencablePrimitive.invoke(i)
}
}
}
/**
* A [Generator] that builds [SchemaWithReferencedSchemas] objects ([Schema]s and their
* dependent sub-[Schema]s) from a set of [schemaName]s and maps of [singletons] and
* [collections] fields.
*/
class SchemaGenerator(
val schemaName: Generator<Set<String>>,
val singletons: Generator<Map<FieldName, FieldTypeWithReferencedSchemas>>,
val collections: Generator<Map<FieldName, FieldTypeWithReferencedSchemas>>,
val hash: Generator<String>
) : Generator<SchemaWithReferencedSchemas> {
override fun invoke(): SchemaWithReferencedSchemas {
val theSingletons = singletons()
val theCollections = collections()
val schema = Schema(
schemaName().map { SchemaName(it) }.toSet(),
SchemaFields(
theSingletons.mapValues { it.value.fieldType },
theCollections.mapValues { it.value.fieldType }
),
hash()
)
val schemas = mutableMapOf<String, Schema>()
theSingletons.map { it.value.schemas }.plus(theCollections.map { it.value.schemas }).forEach {
schemas.putAll(it)
}
return SchemaWithReferencedSchemas(schema, schemas)
}
}
/**
* A data class that encapsulates a [FieldType] with all [Schema] objects referenced by
* that [FieldType].
*/
data class FieldTypeWithReferencedSchemas(
val fieldType: FieldType,
val schemas: Map<String, Schema>
) {
companion object {
val SENTINEL_EMPTY_MAP = emptyMap<String, Schema>()
fun justType(fieldType: FieldType): FieldTypeWithReferencedSchemas {
return FieldTypeWithReferencedSchemas(fieldType, SENTINEL_EMPTY_MAP)
}
}
}
/**
* A data class that encapsulates a [Schema] with all other [Schema] objects referenced by
* fields of that [Schema].
*/
data class SchemaWithReferencedSchemas(
val schema: Schema,
val schemas: Map<String, Schema>
)
| bsd-3-clause | f58f71c89280ff97e0c8f2f06333cc87 | 35.123984 | 98 | 0.734654 | 4.703096 | false | false | false | false |
grpc/grpc-kotlin | compiler/src/main/java/io/grpc/kotlin/generator/protoc/ProtoFileName.kt | 1 | 1703 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.kotlin.generator.protoc
import com.google.protobuf.DescriptorProtos.FileDescriptorProto
import com.google.protobuf.Descriptors.FileDescriptor
import com.google.protobuf.compiler.PluginProtos
/**
* Represents the name of a proto file, relative to the root of the source tree, with
* lower_underscore naming.
*/
data class ProtoFileName(private val path: String) : Comparable<ProtoFileName> {
val name: String
get() = path.substringAfterLast('/').removeSuffix(".proto")
override operator fun compareTo(other: ProtoFileName): Int = path.compareTo(other.path)
}
/** Returns the filename of the specified file descriptor in proto form. */
val FileDescriptorProto.fileName: ProtoFileName
get() = ProtoFileName(name)
/** Returns the filename of the specified file descriptor. */
val FileDescriptor.fileName: ProtoFileName
get() = toProto().fileName
val FileDescriptorProto.dependencyNames: List<ProtoFileName>
get() = dependencyList.map(::ProtoFileName)
val PluginProtos.CodeGeneratorRequest.filesToGenerate: List<ProtoFileName>
get() = fileToGenerateList.map(::ProtoFileName)
| apache-2.0 | 3745347e41fcc5fad8e4c6974cf97131 | 36.021739 | 89 | 0.769818 | 4.411917 | false | false | false | false |
grpc/grpc-kotlin | examples/client/src/main/kotlin/io/grpc/examples/helloworld/HelloWorldClient.kt | 1 | 1647 | /*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.examples.helloworld
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import io.grpc.examples.helloworld.GreeterGrpcKt.GreeterCoroutineStub
import java.io.Closeable
import java.util.concurrent.TimeUnit
class HelloWorldClient(private val channel: ManagedChannel) : Closeable {
private val stub: GreeterCoroutineStub = GreeterCoroutineStub(channel)
suspend fun greet(name: String) {
val request = helloRequest { this.name = name }
val response = stub.sayHello(request)
println("Received: ${response.message}")
}
override fun close() {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
}
}
/**
* Greeter, uses first argument as name to greet if present;
* greets "world" otherwise.
*/
suspend fun main(args: Array<String>) {
val port = 50051
val channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build()
val client = HelloWorldClient(channel)
val user = args.singleOrNull() ?: "world"
client.greet(user)
}
| apache-2.0 | c45059efef55ef3e84dd316651d626eb | 30.673077 | 92 | 0.730419 | 4.212276 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerRefHelper.kt | 2 | 13318 | // 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.search.refIndex
import com.intellij.compiler.backwardRefs.LanguageCompilerRefAdapter
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiModifier
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.Processor
import org.jetbrains.jps.backwardRefs.CompilerRef
import org.jetbrains.jps.backwardRefs.NameEnumerator
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.numberOfArguments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasBody
import org.jetbrains.kotlin.psi.psiUtil.isTopLevelKtOrJavaMember
class KotlinCompilerRefHelper : LanguageCompilerRefAdapter.ExternalLanguageHelper() {
override fun getAffectedFileTypes(): Set<FileType> = setOf(KotlinFileType.INSTANCE)
override fun asCompilerRef(element: PsiElement, names: NameEnumerator): CompilerRef? = asCompilerRefs(element, names)?.singleOrNull()
override fun asCompilerRefs(element: PsiElement, names: NameEnumerator): List<CompilerRef>? =
when (val originalElement = element.unwrapped) {
is KtClass -> originalElement.asClassCompilerRef(names)?.let(::listOf)
is KtObjectDeclaration -> originalElement.asObjectCompilerRefs(names)
is KtConstructor<*> -> originalElement.asConstructorCompilerRef(names)
is KtCallableDeclaration -> originalElement.asCallableCompilerRefs(names)
else -> null
}
override fun getHierarchyRestrictedToLibraryScope(
baseRef: CompilerRef,
basePsi: PsiElement,
names: NameEnumerator,
libraryScope: GlobalSearchScope
): List<CompilerRef> {
val baseClass = when (basePsi) {
is KtClassOrObject, is PsiClass -> basePsi
is PsiMember -> basePsi.containingClass
is KtCallableDeclaration -> basePsi.containingClassOrObject?.takeUnless { it is KtObjectDeclaration }
else -> null
} ?: return emptyList()
val overridden = mutableListOf<CompilerRef>()
val processor = Processor { psiClass: PsiClass ->
psiClass.takeUnless { it.hasModifierProperty(PsiModifier.PRIVATE) }
?.let { runReadAction { it.qualifiedName } }
?.let { names.tryEnumerate(it) }
?.let { overridden.add(baseRef.override(it)) }
true
}
HierarchySearchRequest(
originalElement = baseClass,
searchScope = libraryScope,
searchDeeply = true,
).searchInheritors().forEach(processor)
return overridden
}
}
private fun KtCallableDeclaration.asCallableCompilerRefs(names: NameEnumerator): List<CompilerRef>? {
if (isTopLevelKtOrJavaMember()) return asTopLevelCompilerRefs(names)
val containingClassOrObject = containingClassOrObject ?: return null
return when (containingClassOrObject) {
is KtClass -> asClassMemberCompilerRefs(containingClassOrObject, names)
is KtObjectDeclaration -> asObjectMemberCompilerRefs(containingClassOrObject, names)
else -> null
}
}
private fun KtCallableDeclaration.asClassMemberCompilerRefs(
containingClass: KtClass,
names: NameEnumerator,
): List<CompilerRef>? = when (this) {
is KtNamedFunction -> asClassMemberFunctionCompilerRefs(containingClass, names)
is KtProperty -> asClassMemberPropertyCompilerRefs(containingClass, names)
is KtParameter -> asParameterCompilerRefs(containingClass, names)
else -> null
}
private fun KtCallableDeclaration.asObjectMemberCompilerRefs(
containingObject: KtObjectDeclaration,
names: NameEnumerator,
): List<CompilerRef>? = when (this) {
is KtNamedFunction -> asObjectMemberFunctionCompilerRefs(containingObject, names)
is KtProperty -> asObjectMemberPropertyCompilerRefs(containingObject, names)
else -> null
}
private fun KtCallableDeclaration.asTopLevelCompilerRefs(names: NameEnumerator): List<CompilerRef.CompilerMember>? =
containingKtFile.javaFileFacadeFqName.asString().asClassCompilerRef(names).let { owner ->
when (this) {
is KtNamedFunction -> asFunctionCompilerRefs(owner, names)
is KtProperty -> asPropertyCompilerRefs(owner, names)
else -> null
}
}
private fun String.asClassCompilerRef(
names: NameEnumerator,
): CompilerClassHierarchyElementDefWithSearchId = JavaCompilerClassRefWithSearchId.create(this, names)
private fun KtClassOrObject.asClassCompilerRef(
names: NameEnumerator,
): CompilerClassHierarchyElementDefWithSearchId? = JavaCompilerClassRefWithSearchId.create(this, names)
private fun KtObjectDeclaration.asObjectCompilerRefs(names: NameEnumerator): List<CompilerRef.NamedCompilerRef>? {
val classCompilerRef = asClassCompilerRef(names) ?: return null
val instanceField = if (isCompanion()) {
asCompanionCompilerRef(names)
} else {
classCompilerRef.createField(names.tryEnumerate("INSTANCE"))
}
return listOfNotNull(classCompilerRef, instanceField)
}
private fun KtObjectDeclaration.asCompanionCompilerRef(names: NameEnumerator): CompilerRef.NamedCompilerRef? {
val name = name ?: return null
val owner = containingClassOrObject?.asClassCompilerRef(names) ?: return null
return owner.createField(names.tryEnumerate(name))
}
private fun KtConstructor<*>.asConstructorCompilerRef(names: NameEnumerator): List<CompilerRef.CompilerMember>? {
val owner = getContainingClassOrObject().asClassCompilerRef(names) ?: return null
val nameId = names.tryEnumerate("<init>")
return asCompilerRefsWithJvmOverloads(owner, nameId)
}
private fun KtNamedFunction.asFunctionCompilerRefs(
owner: CompilerClassHierarchyElementDefWithSearchId,
names: NameEnumerator,
isDefaultImplsMember: Boolean = false,
): List<CompilerRef.CompilerMember> {
val jvmName = KotlinPsiHeuristics.findJvmName(this) ?: name
val nameId = names.tryEnumerate(jvmName)
return asCompilerRefsWithJvmOverloads(owner, nameId, isDefaultImplsMember)
}
private fun KtNamedFunction.asClassMemberFunctionCompilerRefs(
containingClass: KtClass,
names: NameEnumerator,
): List<CompilerRef>? = asClassMemberCompilerRefs(
containingClass = containingClass,
names = names,
methodHandler = { owner -> asFunctionCompilerRefs(owner, names) },
defaultMethodHandler = { owner -> asFunctionCompilerRefs(owner, names, isDefaultImplsMember = true) },
)
private fun KtProperty.asClassMemberPropertyCompilerRefs(
containingClass: KtClass,
names: NameEnumerator,
): List<CompilerRef>? = asClassMemberCompilerRefs(
containingClass = containingClass,
names = names,
methodHandler = { owner -> asPropertyCompilerRefs(owner, names) },
defaultMethodHandler = { owner -> asPropertyCompilerRefs(owner, names, fieldOwner = null, isDefaultImplsMember = true) },
)
private fun KtCallableDeclaration.asClassMemberCompilerRefs(
containingClass: KtClass,
names: NameEnumerator,
methodHandler: (owner: CompilerClassHierarchyElementDefWithSearchId) -> List<CompilerRef>?,
defaultMethodHandler: (owner: CompilerClassHierarchyElementDefWithSearchId) -> List<CompilerRef>? = methodHandler,
): List<CompilerRef>? {
val owner = containingClass.asClassCompilerRef(names) ?: return null
val compilerMembers = methodHandler(owner)
if (!containingClass.isInterface() || !hasBody()) return compilerMembers
val defaultImplQualifier = owner.jvmClassName + JvmAbi.DEFAULT_IMPLS_SUFFIX
val defaultImplMembers = defaultMethodHandler(defaultImplQualifier.asClassCompilerRef(names))
?: return compilerMembers
return compilerMembers?.plus(defaultImplMembers) ?: defaultImplMembers
}
private fun KtNamedFunction.asObjectMemberFunctionCompilerRefs(
containingObject: KtObjectDeclaration,
names: NameEnumerator,
): List<CompilerRef.CompilerMember>? {
val owner = containingObject.asClassCompilerRef(names) ?: return null
val compilerMembers = asFunctionCompilerRefs(owner, names)
val additionalOwner = containingObject.takeIf { KotlinPsiHeuristics.hasJvmStaticAnnotation(this) }
?.containingClassOrObject
?.asClassCompilerRef(names)
?: return compilerMembers
return compilerMembers + asFunctionCompilerRefs(additionalOwner, names)
}
private fun KtFunction.asCompilerRefsWithJvmOverloads(
owner: CompilerClassHierarchyElementDefWithSearchId,
nameId: Int,
isDefaultImplsMember: Boolean = false,
): List<CompilerRef.CompilerMember> {
val numberOfArguments = numberOfArguments(countReceiver = true) + (1.takeIf { isDefaultImplsMember } ?: 0)
if (!KotlinPsiHeuristics.hasJvmOverloadsAnnotation(this)) {
val mainMethodRef = owner.createMethod(nameId, numberOfArguments)
return if (this is KtPrimaryConstructor && valueParameters.all(KtParameter::hasDefaultValue)) {
listOf(mainMethodRef, owner.createMethod(nameId, 0))
} else {
listOf(mainMethodRef)
}
}
return numberOfArguments.minus(valueParameters.count(KtParameter::hasDefaultValue)).rangeTo(numberOfArguments).map {
owner.createMethod(nameId, it)
}
}
private fun KtProperty.asObjectMemberPropertyCompilerRefs(
containingObject: KtObjectDeclaration,
names: NameEnumerator,
): List<CompilerRef.CompilerMember>? {
val owner = containingObject.asClassCompilerRef(names) ?: return null
if (!containingObject.isCompanion()) {
return asPropertyCompilerRefs(owner, names)
}
val fieldOwner = containingObject.containingClassOrObject?.asClassCompilerRef(names)
val compilerMembers = asPropertyCompilerRefs(owner, names, fieldOwner)
if (!KotlinPsiHeuristics.hasJvmStaticAnnotation(this) || fieldOwner == null) return compilerMembers
val staticMembers = asPropertyCompilerRefs(fieldOwner, names, fieldOwner = null) ?: return compilerMembers
return compilerMembers?.plus(staticMembers) ?: staticMembers
}
private fun KtProperty.asPropertyCompilerRefs(
owner: CompilerClassHierarchyElementDefWithSearchId,
names: NameEnumerator,
fieldOwner: CompilerClassHierarchyElementDefWithSearchId? = owner,
isDefaultImplsMember: Boolean = false,
): List<CompilerRef.CompilerMember>? = asPropertyOrParameterCompilerRefs(owner, names, isVar, fieldOwner, isDefaultImplsMember)
private fun KtParameter.asParameterCompilerRefs(
containingClass: KtClass,
names: NameEnumerator,
): List<CompilerRef.CompilerMember>? {
if (!hasValOrVar()) return null
val owner = containingClass.asClassCompilerRef(names) ?: return null
if (containingClassOrObject?.isAnnotation() == true) {
val name = name ?: return null
return listOf(owner.createMethod(names.tryEnumerate(name), 0))
}
val compilerMembers = asPropertyOrParameterCompilerRefs(owner, names, isMutable)
val componentFunctionMember = asComponentFunctionName?.let {
owner.createMethod(names.tryEnumerate(it), 0)
} ?: return compilerMembers
return compilerMembers?.plus(componentFunctionMember) ?: listOf(componentFunctionMember)
}
private fun <T> T.asPropertyOrParameterCompilerRefs(
owner: CompilerClassHierarchyElementDefWithSearchId,
names: NameEnumerator,
isMutable: Boolean,
fieldOwner: CompilerClassHierarchyElementDefWithSearchId? = owner,
isDefaultImplsMember: Boolean = false,
): List<CompilerRef.CompilerMember>? where T : KtCallableDeclaration, T : KtValVarKeywordOwner {
val name = name ?: return null
if (fieldOwner != null && (hasModifier(KtTokens.CONST_KEYWORD) || KotlinPsiHeuristics.hasJvmFieldAnnotation(this))) {
return listOf(fieldOwner.createField(names.tryEnumerate(name)))
}
val field = if (fieldOwner != null && hasModifier(KtTokens.LATEINIT_KEYWORD)) {
fieldOwner.createField(names.tryEnumerate(name))
} else {
null
}
val numberOfArguments = numberOfArguments(countReceiver = true) + (1.takeIf { isDefaultImplsMember } ?: 0)
val jvmGetterName = KotlinPsiHeuristics.findJvmGetterName(this) ?: JvmAbi.getterName(name)
val getter = owner.createMethod(names.tryEnumerate(jvmGetterName), numberOfArguments)
val setter = if (isMutable) {
val jvmSetterName = KotlinPsiHeuristics.findJvmSetterName(this) ?: JvmAbi.setterName(name)
owner.createMethod(names.tryEnumerate(jvmSetterName), numberOfArguments + 1)
} else {
null
}
return listOfNotNull(field, getter, setter)
} | apache-2.0 | 6b9ae52862b62cedf84345e7fec952a3 | 43.694631 | 158 | 0.758147 | 5.422638 | false | false | false | false |
danvratil/FBEventSync | app/src/main/java/cz/dvratil/fbeventsync/preferences/StoreHelper.kt | 1 | 2303 | /*
Copyright (C) 2018 Daniel Vrátil <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.dvratil.fbeventsync.preferences
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import cz.dvratil.fbeventsync.Logger
import java.sql.SQLException
class StoreHelper(context: Context, dbName: String)
: SQLiteOpenHelper(context, dbName, null, STORE_VERSION) {
companion object {
private const val TAG = "PREFS"
private const val STORE_VERSION = 1
const val INT_TABLE = "prefs_int"
const val STRING_TABLE = "prefs_string"
const val FLOAT_TABLE = "prefs_float"
}
private val mLogger = Logger.getInstance(context)
override fun onCreate(db: SQLiteDatabase) {
try {
db.execSQL(
"CREATE TABLE $STRING_TABLE (" +
"key TEXT NOT NULL UNIQUE PRIMARY KEY, " +
"value TEXT)"
)
db.execSQL(
"CREATE TABLE $INT_TABLE (" +
"key TEXT NOT NULL UNIQUE PRIMARY KEY, " +
"value INTEGER)"
)
db.execSQL(
"CREATE TABLE $FLOAT_TABLE (" +
"key TEXT NOT NULL UNIQUE PRIMARY KEY, " +
"value REAL)"
)
} catch (e: SQLException) {
mLogger.error(TAG, "SQLException when creating new schema: $e")
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Nothing to do yet
}
} | gpl-3.0 | a693cdbf08d93934356377e89a4f3e61 | 30.121622 | 82 | 0.605995 | 4.756198 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/PostingActivityUseCase.kt | 1 | 3778 | package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases
import android.view.View
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.stats.insights.PostingActivityModel
import org.wordpress.android.fluxc.model.stats.insights.PostingActivityModel.Day
import org.wordpress.android.fluxc.store.StatsStore.InsightType.POSTING_ACTIVITY
import org.wordpress.android.fluxc.store.stats.insights.PostingActivityStore
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Empty
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Title
import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler
import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider
import java.util.Calendar
import javax.inject.Inject
import javax.inject.Named
class PostingActivityUseCase
@Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher,
private val store: PostingActivityStore,
private val statsSiteProvider: StatsSiteProvider,
private val postingActivityMapper: PostingActivityMapper,
private val popupMenuHandler: ItemPopupMenuHandler
) : StatelessUseCase<PostingActivityModel>(POSTING_ACTIVITY, mainDispatcher, backgroundDispatcher) {
override fun buildLoadingItem(): List<BlockListItem> = listOf(Title(R.string.stats_insights_posting_activity))
override fun buildEmptyItem(): List<BlockListItem> {
return listOf(buildTitle(), Empty())
}
override suspend fun loadCachedData(): PostingActivityModel? {
return store.getPostingActivity(statsSiteProvider.siteModel, getStartDate(), getEndDate())
}
override suspend fun fetchRemoteData(forced: Boolean): State<PostingActivityModel> {
val response = store.fetchPostingActivity(statsSiteProvider.siteModel, getStartDate(), getEndDate(), forced)
val model = response.model
val error = response.error
return when {
error != null -> State.Error(error.message ?: error.type.name)
model != null && model.months.isNotEmpty() -> State.Data(
model
)
else -> State.Empty()
}
}
override fun buildUiModel(domainModel: PostingActivityModel): List<BlockListItem> {
val items = mutableListOf<BlockListItem>()
items.add(buildTitle())
val activityItem = postingActivityMapper.buildActivityItem(
domainModel.months,
domainModel.max
)
items.add(activityItem)
return items
}
private fun buildTitle() = Title(R.string.stats_insights_posting_activity, menuAction = this::onMenuClick)
private fun getEndDate(): Day {
val endDate = Calendar.getInstance()
return Day(
endDate.get(Calendar.YEAR),
endDate.get(Calendar.MONTH),
endDate.getActualMaximum(Calendar.DAY_OF_MONTH)
)
}
private fun getStartDate(): Day {
val startDate = Calendar.getInstance()
startDate.add(Calendar.MONTH, -2)
return Day(
startDate.get(Calendar.YEAR),
startDate.get(Calendar.MONTH),
startDate.getActualMinimum(Calendar.DAY_OF_MONTH)
)
}
private fun onMenuClick(view: View) {
popupMenuHandler.onMenuClick(view, type)
}
}
| gpl-2.0 | 7b47eb78b3348cf4b7495949ce1b9bf0 | 40.977778 | 116 | 0.725516 | 4.658446 | false | false | false | false |
JoeSteven/HuaBan | app/src/main/java/com/joe/zatuji/extension/Extension.kt | 1 | 7764 | package com.joe.zatuji.extension
import android.app.Activity
import android.graphics.Bitmap
import android.net.Uri
import android.support.v4.app.Fragment
import android.widget.ImageView
import com.bumptech.glide.GenericTransitionOptions
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.github.chrisbanes.photoview.PhotoView
import com.joe.zatuji.R
import com.joe.zatuji.helper.EglHelper
import com.joe.zatuji.repo.bean.IDetailPicture
import com.joey.cheetah.core.ktextension.dp2px
import com.joey.cheetah.core.ktextension.logD
import com.joey.cheetah.core.ktextension.screenHeight
import com.joey.cheetah.core.ktextension.screenWidth
import com.joey.cheetah.core.media.glide.GlideApp
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import java.io.File
import java.util.*
/**
* Description:
* author:Joey
* date:2018/11/21
*/
val ImageView.randomBgColor: IntArray
get() = intArrayOf(R.color.DefaultGreen, R.color.DefaultBlue, R.color.DefaultRed, R.color.DefaultPurple)
fun ImageView.getRandomColor(): Int {
val random = Random()
return randomBgColor[random.nextInt(4)]
}
fun ImageView.loadThumbnail(img: Any, size: Float = 0.4f, resizeWidth: Int = -1, resizeHeight: Int = -1) {
var requests = GlideApp.with(context)
var request = when (img) {
is String -> requests.load(img)
is File -> requests.load(img)
is Int -> requests.load(img)
is Uri -> requests.load(img)
else -> requests.load(img)
}
request.centerCrop()
.placeholder(getRandomColor())
.error(R.drawable.error_img)
.transition(DrawableTransitionOptions.withCrossFade(300))
if (resizeWidth != -1 && resizeHeight != -1) {
request.override(resizeWidth, resizeHeight)
}
request.sizeMultiplier(size)
request.into(this)
}
fun PhotoView.loadDetail(pic: IDetailPicture, success: () -> Unit = {}, error: (e: Exception) -> Unit = {}) {
val resize = resizeFullScreen(pic.getPicWidth(), pic.getPicHeight(), pic.getPicType())
scaleType = ImageView.ScaleType.FIT_XY
if (pic.getPicType().contains("gif")) {
GlideApp.with(context)
.asGif()
.load(pic.getPicUrl())
.transition(GenericTransitionOptions.with(android.R.anim.fade_in))
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.error(R.drawable.error_img)
.listener(object : RequestListener<GifDrawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<GifDrawable>?, isFirstResource: Boolean): Boolean {
error(e ?: Exception())
return false
}
override fun onResourceReady(resource: GifDrawable?, model: Any?, target: Target<GifDrawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
success()
return false
}
})
.into(this)
} else {
setZoomable(true)
scaleType = ImageView.ScaleType.FIT_CENTER
GlideApp.with(context)
.asBitmap()
.load(pic.getPicUrl())
.fitCenter()
.override(resize[0], resize[1])
.transition(BitmapTransitionOptions.withCrossFade(300))
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.error(R.drawable.error_img)
.listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
error(e ?: Exception())
return false
}
override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
success()
if (resource == null){
return false
}
val oldHeight = resource.height
val oldWidth = resource.width
if (EglHelper.getMaxTextureSize() <= 0){
return false
}
return when {
oldHeight > EglHelper.getMaxTextureSize() -> {
logD("PicDetail", "height oversize:$oldHeight , max:${EglHelper.getMaxTextureSize()}")
setImageBitmap(Bitmap.createScaledBitmap(resource, resource.width * EglHelper.getMaxTextureSize() / oldHeight, EglHelper.getMaxTextureSize(), true))
true
}
oldWidth > EglHelper.getMaxTextureSize() -> {
logD("PicDetail", "width oversize:$oldHeight , max:${EglHelper.getMaxTextureSize()}")
setImageBitmap(Bitmap.createScaledBitmap(resource, resource.height * EglHelper.getMaxTextureSize() / oldWidth, EglHelper.getMaxTextureSize(), true))
true
}
else -> false
}
}
})
.into(this)
}
}
fun ImageView.resizeGrid(width: Int, height: Int):IntArray {
//获取屏幕宽高
// 先把宽resize为item宽,再取计算高度
val resizeWidth = (context.screenWidth - context.dp2px(12))/2
val times = (resizeWidth *1F)/width
var resizeHeight = (height * times).toInt()
resizeHeight = when {
resizeHeight < context.dp2px(120) -> context.dp2px(120)
resizeHeight > context.dp2px(300) -> context.dp2px(300)
else -> resizeHeight
}
layoutParams.width = resizeWidth
layoutParams.height = resizeHeight
return intArrayOf(resizeWidth, (height * times).toInt())
}
fun ImageView.resizeFullScreen(width: Int, height: Int, type: String?):IntArray {
//获取屏幕宽高
// 先把宽resize为屏幕宽,再取计算高度
val times = (context.screenWidth*1F)/width
layoutParams.width = context.screenWidth
val resizeHeight = (height*times).toInt()
if (resizeHeight < context.screenHeight && type?.contains("gif") != true) {
layoutParams.height = context.screenHeight
} else {
layoutParams.height = resizeHeight
}
return intArrayOf(layoutParams.width, resizeHeight)
}
fun Activity.selectSingleImage() {
selectSingleImage(PictureSelector.create(this))
}
fun Fragment.selectSingleImage() {
selectSingleImage(PictureSelector.create(this))
}
fun selectSingleImage(selector: PictureSelector) {
selector.openGallery(PictureMimeType.ofImage())
.maxSelectNum(1)
.imageSpanCount(4)
.selectionMode(PictureConfig.SINGLE)
.previewImage(true)
.isCamera(true)
.enableCrop(true)
.compress(true)
.isGif(false)
.circleDimmedLayer(true)
.freeStyleCropEnabled(true)
.forResult(PictureConfig.CHOOSE_REQUEST)
}
| apache-2.0 | a2a4c0476493f1a91a938b80f346f339 | 38.628866 | 180 | 0.615635 | 4.66222 | false | false | false | false |
android/nowinandroid | core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/DropdownMenu.kt | 1 | 5047 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.designsystem.component
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
/**
* Now in Android dropdown menu button with included trailing icon as well as text label and item
* content slots.
*
* @param items The list of items to display in the menu.
* @param onItemClick Called when the user clicks on a menu item.
* @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services.
* @param dismissOnItemClick Whether the menu should be dismissed when an item is clicked.
* @param itemText The text label content for a given item.
* @param itemLeadingIcon The leading icon content for a given item.
* @param itemTrailingIcon The trailing icon content for a given item.
*/
@Composable
fun <T> NiaDropdownMenuButton(
items: List<T>,
onItemClick: (item: T) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
dismissOnItemClick: Boolean = true,
text: @Composable () -> Unit,
itemText: @Composable (item: T) -> Unit,
itemLeadingIcon: @Composable ((item: T) -> Unit)? = null,
itemTrailingIcon: @Composable ((item: T) -> Unit)? = null
) {
var expanded by remember { mutableStateOf(false) }
Box(modifier = modifier) {
NiaOutlinedButton(
onClick = { expanded = true },
enabled = enabled,
text = text,
trailingIcon = {
Icon(
imageVector = if (expanded) NiaIcons.ArrowDropUp else NiaIcons.ArrowDropDown,
contentDescription = null
)
}
)
NiaDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
items = items,
onItemClick = onItemClick,
dismissOnItemClick = dismissOnItemClick,
itemText = itemText,
itemLeadingIcon = itemLeadingIcon,
itemTrailingIcon = itemTrailingIcon
)
}
}
/**
* Now in Android dropdown menu with item content slots. Wraps Material 3 [DropdownMenu] and
* [DropdownMenuItem].
*
* @param expanded Whether the menu is currently open and visible to the user.
* @param onDismissRequest Called when the user requests to dismiss the menu, such as by
* tapping outside the menu's bounds.
* @param items The list of items to display in the menu.
* @param onItemClick Called when the user clicks on a menu item.
* @param dismissOnItemClick Whether the menu should be dismissed when an item is clicked.
* @param itemText The text label content for a given item.
* @param itemLeadingIcon The leading icon content for a given item.
* @param itemTrailingIcon The trailing icon content for a given item.
*/
@Composable
fun <T> NiaDropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
items: List<T>,
onItemClick: (item: T) -> Unit,
dismissOnItemClick: Boolean = true,
itemText: @Composable (item: T) -> Unit,
itemLeadingIcon: @Composable ((item: T) -> Unit)? = null,
itemTrailingIcon: @Composable ((item: T) -> Unit)? = null
) {
DropdownMenu(
expanded = expanded,
onDismissRequest = onDismissRequest
) {
items.forEach { item ->
DropdownMenuItem(
text = { itemText(item) },
onClick = {
onItemClick(item)
if (dismissOnItemClick) onDismissRequest()
},
leadingIcon = if (itemLeadingIcon != null) {
{ itemLeadingIcon(item) }
} else {
null
},
trailingIcon = if (itemTrailingIcon != null) {
{ itemTrailingIcon(item) }
} else {
null
}
)
}
}
}
| apache-2.0 | 0bdb533f5596cd2fbd461beb3a4b2a04 | 37.234848 | 97 | 0.656628 | 4.811249 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/card/ksx6924/KSX6924Application.kt | 1 | 8525 | /*
* KSX6924Application.kt
*
* Copyright 2018 Google
* Copyright 2019 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.card.ksx6924
import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface
import au.id.micolous.metrodroid.card.iso7816.*
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.tmoney.TMoneyTransitData
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.ui.ListItemRecursive
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.hexString
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* Implements the T-Money ISO 7816 application. This is used by T-Money in South Korea, and
* Snapper Plus cards in Wellington, New Zealand.
*
* @see [KROCAPConfigDFApplication], [TMoneyTransitData]
*/
@Serializable
data class KSX6924Application (
override val generic: ISO7816ApplicationCapsule,
val balance: ImmutableByteArray,
// Returned by CLA=90 INS=78
val extraRecords: List<ImmutableByteArray> = emptyList()): ISO7816Application() {
@Transient
override val type: String
get() = TYPE
@Transient
override val rawData: List<ListItem>?
get() {
val sli = mutableListOf<ListItem>()
sli.add(ListItemRecursive.collapsedValue(R.string.tmoney_balance,
balance.toHexDump()))
for (i in extraRecords.indices) {
val d = extraRecords[i]
val r = if (d.isAllZero() || d.isAllFF())
R.string.page_title_format_empty
else
R.string.page_title_format
sli.add(ListItemRecursive.collapsedValue(
Localizer.localizeString(r, i.hexString), d.toHexDump()))
}
return sli.toList()
}
@Transient
val transactionRecords: List<ImmutableByteArray>?
get() =
(getSfiFile(TRANSACTION_FILE)
?: getFile(ISO7816Selector.makeSelector(FILE_NAME, TRANSACTION_FILE)))
?.recordList
@Transient
private val purseInfoData: ImmutableByteArray?
get() = generic.appFci?.let { ISO7816TLV.findBERTLV(it, TAG_PURSE_INFO, false) }
@Transient
val purseInfo: KSX6924PurseInfo
get() = KSX6924PurseInfo(purseInfoData!!)
@Transient
val serial: String
get() = purseInfo.serial
override fun parseTransitIdentity(card: ISO7816Card): TransitIdentity? {
for (factory in KSX6924Registry.allFactories) {
if (factory.check(this)) {
return factory.parseTransitIdentity(this)
}
}
// Fallback
return TMoneyTransitData.FACTORY.parseTransitIdentity(this)
}
override fun parseTransitData(card: ISO7816Card): TransitData? {
for (factory in KSX6924Registry.allFactories) {
if (factory.check(this)) {
val d = factory.parseTransitData(this)
if (d != null) {
return d
}
}
}
// Fallback
return TMoneyTransitData.FACTORY.parseTransitData(this)
}
companion object {
private const val TAG = "KSX6924Application"
val APP_NAME = listOf(
// T-Money, Snapper
ImmutableByteArray.fromHex("d4100000030001"),
// Cashbee / eB
ImmutableByteArray.fromHex("d4100000140001"),
// MOIBA (untested)
ImmutableByteArray.fromHex("d4100000300001"),
// K-Cash (untested)
ImmutableByteArray.fromHex("d4106509900020")
)
val FILE_NAME = ImmutableByteArray.fromHex("d4100000030001")
val TAG_PURSE_INFO = ImmutableByteArray.fromHex("b0")
private const val INS_GET_BALANCE: Byte = 0x4c
private const val INS_GET_RECORD: Byte = 0x78
private const val BALANCE_RESP_LEN: Byte = 4
const val TRANSACTION_FILE = 4
private const val TYPE = "ksx6924"
private const val OLD_TYPE = "tmoney"
val FACTORY: ISO7816ApplicationFactory = object : ISO7816ApplicationFactory {
override val typeMap: Map<String, KSerializer<out ISO7816Application>>
get() = mapOf(TYPE to serializer(), OLD_TYPE to serializer())
override val applicationNames: List<ImmutableByteArray>
get() = APP_NAME
/**
* Dumps a KS X 6924 (T-Money) card in the field.
* @param capsule ISO7816 app info of the tag.
* @param protocol Tag to dump.
* @return TMoneyCard of the card contents. Returns null if an unsupported card is in the
* field.
*/
override suspend fun dumpTag(protocol: ISO7816Protocol,
capsule: ISO7816ApplicationMutableCapsule,
feedbackInterface: TagReaderFeedbackInterface): List<ISO7816Application>? {
val balanceResponse: ImmutableByteArray
val extraRecords = ArrayList<ImmutableByteArray>()
try {
feedbackInterface.updateStatusText(Localizer.localizeString(R.string.card_reading_type,
TMoneyTransitData.CARD_INFO.name))
feedbackInterface.updateProgressBar(0, 37)
feedbackInterface.showCardType(TMoneyTransitData.CARD_INFO)
capsule.dumpAllSfis(protocol, feedbackInterface, 0, 32)
balanceResponse = protocol.sendRequest(ISO7816Protocol.CLASS_90, INS_GET_BALANCE,
0.toByte(), 0.toByte(), BALANCE_RESP_LEN)
feedbackInterface.updateProgressBar(1, 37)
// TODO: Understand this data
try {
// Works on T-Money, Snapper
// Fails on Cashbee
for (i in 0..0xf) {
Log.d(TAG, "sending proprietary record get = $i")
val ba = protocol.sendRequest(
ISO7816Protocol.CLASS_90, INS_GET_RECORD, i.toByte(), 0.toByte(), 0x10.toByte())
extraRecords.add(ba)
}
} catch (e: Exception) {
Log.w(TAG, "Caught exception on proprietary record get: $e")
}
for (i in 1..5) {
try {
capsule.dumpFile(protocol, ISO7816Selector.makeSelector(FILE_NAME, i), 0)
} catch (e: Exception) {
Log.w(TAG, "Caught exception on file 4200/${i.hexString}: $e")
}
feedbackInterface.updateProgressBar(32 + i, 37)
}
try {
capsule.dumpFile(protocol, ISO7816Selector.makeSelector(0xdf00), 0)
} catch (e: Exception) {
Log.w(TAG, "Caught exception on file df00: $e")
}
} catch (e: Exception) {
Log.w(TAG, "Got exception $e")
return null
}
return listOf<ISO7816Application>(KSX6924Application(capsule.freeze(),
balanceResponse, extraRecords))
}
}
}
}
| gpl-3.0 | 2c4e0cbb0fda5c634f993dd42232bda8 | 37.400901 | 116 | 0.588504 | 4.800113 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/multiplatform/typeAliases/jvm/aliases.kt | 9 | 436 | @file:Suppress("ACTUAL_WITHOUT_EXPECT")
package aliases
actual interface <!LINE_MARKER("descr='Has expects in common module'")!>A<!> {
actual fun <!LINE_MARKER("descr='Has expects in common module'")!>commonFun<!>()
fun platformFun()
}
typealias A2 = A1
typealias A3 = A
actual typealias <!LINE_MARKER("descr='Has expects in common module'")!>B<!> = A
typealias B2 = B
typealias B3 = B1
class PlatformInv<T>(val value: T)
| apache-2.0 | 2b46bb67993bd9316dbdfd6bdfadbe95 | 23.222222 | 84 | 0.694954 | 3.544715 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTrimMarginToTrimIndentIntention.kt | 1 | 3360 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.calculateIndent
import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.isStartOfLine
import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.isSurroundedByLineBreaksOrBlanks
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLiteralStringTemplateEntry
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class ConvertTrimMarginToTrimIndentIntention : SelfTargetingIntention<KtCallExpression>(
KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.trim.indent")
) {
override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean {
val template = (element.getQualifiedExpressionForSelector()?.receiverExpression as? KtStringTemplateExpression) ?: return false
if (!template.text.startsWith("\"\"\"")) return false
val callee = element.calleeExpression ?: return false
if (callee.text != "trimMargin" || callee.getCallableDescriptor()?.fqNameSafe != FqName("kotlin.text.trimMargin")) return false
if (!template.isSurroundedByLineBreaksOrBlanks()) return false
val marginPrefix = element.marginPrefix() ?: return false
return template.entries.all { entry ->
!entry.isStartOfLine() || entry.text.dropWhile { it.isWhitespace() }.startsWith(marginPrefix)
}
}
override fun applyTo(element: KtCallExpression, editor: Editor?) {
val qualifiedExpression = element.getQualifiedExpressionForSelector()
val template = (qualifiedExpression?.receiverExpression as? KtStringTemplateExpression) ?: return
val marginPrefix = element.marginPrefix() ?: return
val indent = template.calculateIndent()
val newTemplate = buildString {
template.entries.forEach { entry ->
val text = entry.text
if (entry.isStartOfLine()) {
append(indent)
append(entry.text.dropWhile { it.isWhitespace() }.replaceFirst(marginPrefix, ""))
} else {
append(text)
}
}
}
qualifiedExpression.replace(KtPsiFactory(element).createExpression("\"\"\"$newTemplate\"\"\".trimIndent()"))
}
}
private fun KtCallExpression.marginPrefix(): String? {
val argument = valueArguments.firstOrNull()?.getArgumentExpression()
if (argument != null) {
if (argument !is KtStringTemplateExpression) return null
val entry = argument.entries.toList().singleOrNull() as? KtLiteralStringTemplateEntry ?: return null
return entry.text.replace("\"", "")
}
return "|"
}
| apache-2.0 | d0daa9dcb299542e58c46ca61d43ea7a | 51.5 | 135 | 0.732143 | 5.308057 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt | 2 | 14740 | // 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.debugger.evaluate.compilation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.backend.common.output.OutputFile
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.KotlinCodegenFacade
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_FUNCTION_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledCodeFragmentData.MethodSignature
import org.jetbrains.kotlin.idea.debugger.evaluate.getResolutionFacadeForCodeFragment
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo
import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor
import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.utils.Printer
class CodeFragmentCodegenException(val reason: Exception) : Exception()
class CodeFragmentCompiler(private val executionContext: ExecutionContext) {
companion object {
fun useIRFragmentCompiler(): Boolean =
Registry.get("debugger.kotlin.evaluator.use.jvm.ir.backend").asBoolean()
}
data class CompilationResult(
val classes: List<ClassToLoad>,
val parameterInfo: CodeFragmentParameterInfo,
val localFunctionSuffixes: Map<CodeFragmentParameter.Dumb, String>,
val mainMethodSignature: MethodSignature
)
fun compile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
val result = ReadAction.nonBlocking<Result<CompilationResult>> {
try {
Result.success(doCompile(codeFragment, filesToCompile, bindingContext, moduleDescriptor))
} catch (ex: ProcessCanceledException) {
throw ex
} catch (ex: Exception) {
Result.failure(ex)
}
}.executeSynchronously()
return result.getOrThrow()
}
private fun initBackend(codeFragment: KtCodeFragment): FragmentCompilerCodegen {
return if (useIRFragmentCompiler()) {
IRFragmentCompilerCodegen()
} else {
OldFragmentCompilerCodegen(codeFragment)
}
}
private fun doCompile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
require(codeFragment is KtBlockCodeFragment || codeFragment is KtExpressionCodeFragment) {
"Unsupported code fragment type: $codeFragment"
}
val project = codeFragment.project
val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment)
@OptIn(FrontendInternals::class)
val resolveSession = resolutionFacade.getFrontendService(ResolveSession::class.java)
val moduleDescriptorWrapper = EvaluatorModuleDescriptor(codeFragment, moduleDescriptor, filesToCompile, resolveSession)
val defaultReturnType = moduleDescriptor.builtIns.unitType
val returnType = getReturnType(codeFragment, bindingContext, defaultReturnType)
val fragmentCompilerBackend = initBackend(codeFragment)
val compilerConfiguration = CompilerConfiguration().apply {
languageVersionSettings = codeFragment.languageVersionSettings
fragmentCompilerBackend.configureCompiler(this)
}
val parameterInfo = fragmentCompilerBackend.computeFragmentParameters(executionContext, codeFragment, bindingContext)
val (classDescriptor, methodDescriptor) = createDescriptorsForCodeFragment(
codeFragment, Name.identifier(GENERATED_CLASS_NAME), Name.identifier(GENERATED_FUNCTION_NAME),
parameterInfo, returnType, moduleDescriptorWrapper.packageFragmentForEvaluator
)
fragmentCompilerBackend.initCodegen(classDescriptor, methodDescriptor, parameterInfo)
val generationState = GenerationState.Builder(
project, ClassBuilderFactories.BINARIES, moduleDescriptorWrapper,
bindingContext, filesToCompile, compilerConfiguration
).apply {
fragmentCompilerBackend.configureGenerationState(
this,
bindingContext,
compilerConfiguration,
classDescriptor,
methodDescriptor,
parameterInfo
)
generateDeclaredClassFilter(GeneratedClassFilterForCodeFragment(codeFragment))
}.build()
try {
KotlinCodegenFacade.compileCorrectFiles(generationState)
return fragmentCompilerBackend.extractResult(methodDescriptor, parameterInfo, generationState).also {
generationState.destroy()
}
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Exception) {
throw CodeFragmentCodegenException(e)
} finally {
fragmentCompilerBackend.cleanupCodegen()
}
}
private class GeneratedClassFilterForCodeFragment(private val codeFragment: KtCodeFragment) : GenerationState.GenerateClassFilter() {
override fun shouldGeneratePackagePart(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") file: KtFile) = file == codeFragment
override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.containingFile == codeFragment
override fun shouldGenerateCodeFragment(script: KtCodeFragment) = script == this.codeFragment
override fun shouldGenerateScript(script: KtScript) = false
}
private fun getReturnType(
codeFragment: KtCodeFragment,
bindingContext: BindingContext,
defaultReturnType: SimpleType
): KotlinType {
return when (codeFragment) {
is KtExpressionCodeFragment -> {
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, codeFragment.getContentElement()]
typeInfo?.type ?: defaultReturnType
}
is KtBlockCodeFragment -> {
val blockExpression = codeFragment.getContentElement()
val lastStatement = blockExpression.statements.lastOrNull() ?: return defaultReturnType
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, lastStatement]
typeInfo?.type ?: defaultReturnType
}
else -> defaultReturnType
}
}
private fun createDescriptorsForCodeFragment(
declaration: KtCodeFragment,
className: Name,
methodName: Name,
parameterInfo: CodeFragmentParameterInfo,
returnType: KotlinType,
packageFragmentDescriptor: PackageFragmentDescriptor
): Pair<ClassDescriptor, FunctionDescriptor> {
val classDescriptor = ClassDescriptorImpl(
packageFragmentDescriptor, className, Modality.FINAL, ClassKind.OBJECT,
emptyList(),
KotlinSourceElement(declaration),
false,
LockBasedStorageManager.NO_LOCKS
)
val methodDescriptor = SimpleFunctionDescriptorImpl.create(
classDescriptor, Annotations.EMPTY, methodName,
CallableMemberDescriptor.Kind.SYNTHESIZED, classDescriptor.source
)
val parameters = parameterInfo.parameters.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
methodDescriptor, null, index, Annotations.EMPTY, Name.identifier("p$index"),
parameter.targetType,
declaresDefaultValue = false,
isCrossinline = false,
isNoinline = false,
varargElementType = null,
source = SourceElement.NO_SOURCE
)
}
methodDescriptor.initialize(
null, classDescriptor.thisAsReceiverParameter, emptyList(), emptyList(),
parameters, returnType, Modality.FINAL, DescriptorVisibilities.PUBLIC
)
val memberScope = EvaluatorMemberScopeForMethod(methodDescriptor)
val constructor = ClassConstructorDescriptorImpl.create(classDescriptor, Annotations.EMPTY, true, classDescriptor.source)
classDescriptor.initialize(memberScope, setOf(constructor), constructor)
return Pair(classDescriptor, methodDescriptor)
}
}
private class EvaluatorMemberScopeForMethod(private val methodDescriptor: SimpleFunctionDescriptor) : MemberScopeImpl() {
override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> {
return if (name == methodDescriptor.name) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return if (kindFilter.accepts(methodDescriptor) && nameFilter(methodDescriptor.name)) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getFunctionNames() = setOf(methodDescriptor.name)
override fun printScopeStructure(p: Printer) {
p.println(this::class.java.simpleName)
}
}
private class EvaluatorModuleDescriptor(
val codeFragment: KtCodeFragment,
val moduleDescriptor: ModuleDescriptor,
filesToCompile: List<KtFile>,
resolveSession: ResolveSession
) : ModuleDescriptor by moduleDescriptor {
private val declarationProvider = object : PackageMemberDeclarationProvider {
private val rootPackageFiles =
filesToCompile.filter { it.packageFqName == FqName.ROOT } + codeFragment
override fun getPackageFiles() = rootPackageFiles
override fun containsFile(file: KtFile) = file in rootPackageFiles
override fun getDeclarationNames() = emptySet<Name>()
override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean) = emptyList<KtDeclaration>()
override fun getClassOrObjectDeclarations(name: Name) = emptyList<KtClassOrObjectInfo<*>>()
override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean) = emptyList<FqName>()
override fun getFunctionDeclarations(name: Name) = emptyList<KtNamedFunction>()
override fun getPropertyDeclarations(name: Name) = emptyList<KtProperty>()
override fun getTypeAliasDeclarations(name: Name) = emptyList<KtTypeAlias>()
override fun getDestructuringDeclarationsEntries(name: Name) = emptyList<KtDestructuringDeclarationEntry>()
override fun getScriptDeclarations(name: Name) = emptyList<KtScriptInfo>()
}
// NOTE: Without this override, psi2ir complains when introducing new symbol
// when creating an IrFileImpl in `createEmptyIrFile`.
override fun getOriginal(): DeclarationDescriptor {
return this
}
val packageFragmentForEvaluator = LazyPackageDescriptor(this, FqName.ROOT, resolveSession, declarationProvider)
val rootPackageDescriptorWrapper: PackageViewDescriptor =
object : DeclarationDescriptorImpl(Annotations.EMPTY, FqName.ROOT.shortNameOrSpecial()), PackageViewDescriptor {
private val rootPackageDescriptor = moduleDescriptor.safeGetPackage(FqName.ROOT)
override fun getContainingDeclaration() = rootPackageDescriptor.containingDeclaration
override val fqName get() = rootPackageDescriptor.fqName
override val module get() = this@EvaluatorModuleDescriptor
override val memberScope by lazy {
if (fragments.isEmpty()) {
MemberScope.Empty
} else {
val scopes = fragments.map { it.getMemberScope() } + SubpackagesScope(module, fqName)
ChainedMemberScope.create("package view scope for $fqName in ${module.name}", scopes)
}
}
override val fragments = listOf(packageFragmentForEvaluator)
override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R {
return visitor.visitPackageViewDescriptor(this, data)
}
}
override fun getPackage(fqName: FqName): PackageViewDescriptor =
if (fqName != FqName.ROOT) {
moduleDescriptor.safeGetPackage(fqName)
} else {
rootPackageDescriptorWrapper
}
private fun ModuleDescriptor.safeGetPackage(fqName: FqName): PackageViewDescriptor =
try {
getPackage(fqName)
} catch (e: InvalidModuleException) {
throw ProcessCanceledException(e)
}
}
internal val OutputFile.internalClassName: String
get() = relativePath.removeSuffix(".class").replace('/', '.')
| apache-2.0 | 6a74ba5f8dc63552d9fe067031987aac | 44.776398 | 158 | 0.718046 | 5.884232 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-plugins/ktor-client-tracing/jvm/test/TracingWrapperTest.kt | 1 | 9779 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugin.tracing.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.websocket.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.util.date.*
import junit.framework.Assert.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.*
import org.junit.*
import kotlin.coroutines.*
class TracingWrapperTest {
@Test
fun testGet() = runBlocking {
val tracer = TestTracer()
HttpClient(TracingWrapper(CIO, tracer)).use { client ->
val result: String = client.get("http://www.google.com/")
assertNotNull(result)
}
synchronized(tracer) {
assertEquals(1, tracer.requestWillBeSentCalls.size)
assertEquals(1, tracer.responseHeadersReceivedCalls.size)
assertEquals(1, tracer.interpretResponseCalls.size)
val expectedRequestId = tracer.requestWillBeSentCalls[0].requestId
with(tracer.requestWillBeSentCalls[0]) {
assertEquals(HttpMethod.Get, requestData.method)
assertEquals("http://www.google.com/", requestData.url.toString())
assertEquals(expectedRequestId, requestId)
}
with(tracer.responseHeadersReceivedCalls[0]) {
assertEquals(HttpStatusCode.OK, responseData.statusCode)
assertEquals(expectedRequestId, requestId)
}
with(tracer.interpretResponseCalls[0]) {
assertEquals(expectedRequestId, requestId)
}
}
}
@Test
fun testOutgoingChannelTracerOffer() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = OutgoingChannelTracer("42", tracer, channel)
val deferred = async { channel.receive() }
while (!channelTracer.offer(Frame.Text("Text"))) {
}
deferred.await()
assertEquals(1, tracer.webSocketFrameSentCalls.size)
with(tracer.webSocketFrameSentCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
fun testOutgoingChannelTracerSend() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = OutgoingChannelTracer("42", tracer, channel)
val deferred = async { channel.receive() }
channelTracer.send(Frame.Text("Text"))
deferred.await()
assertEquals(1, tracer.webSocketFrameSentCalls.size)
with(tracer.webSocketFrameSentCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
fun testIncomingChannelTracerIterator() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = IncomingChannelTracer("42", tracer, channel)
val deferred = async {
channel.send(Frame.Text("Text1"))
channel.send(Frame.Text("Text2"))
channel.send(Frame.Text("Text3"))
channel.close()
}
for (frame in channelTracer) {
}
deferred.await()
assertEquals(3, tracer.webSocketFrameReceivedCalls.size)
for (i in 1..3) {
with(tracer.webSocketFrameReceivedCalls[i - 1]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text$i", (frame as Frame.Text).readText())
}
}
} finally {
channel.close()
}
}
@Test
fun testIncomingChannelTracerPoll() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = IncomingChannelTracer("42", tracer, channel)
val deferred = async { channel.send(Frame.Text("Text")) }
while (channelTracer.poll() == null) {
yield()
}
deferred.await()
assertEquals(1, tracer.webSocketFrameReceivedCalls.size)
with(tracer.webSocketFrameReceivedCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
fun testIncomingChannelTracerReceive() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = IncomingChannelTracer("42", tracer, channel)
val deferred = async { channel.send(Frame.Text("Text")) }
channelTracer.receive()
deferred.await()
assertEquals(1, tracer.webSocketFrameReceivedCalls.size)
with(tracer.webSocketFrameReceivedCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
@OptIn(InternalCoroutinesApi::class)
fun testIncomingChannelTracerReceiveOrClosed() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = IncomingChannelTracer("42", tracer, channel)
val deferred = async { channel.send(Frame.Text("Text")) }
channelTracer.receiveOrClosed()
deferred.await()
assertEquals(1, tracer.webSocketFrameReceivedCalls.size)
with(tracer.webSocketFrameReceivedCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
fun testIncomingChannelTracerReceiveOrNull() = runBlocking {
val channel = Channel<Frame>(Channel.Factory.UNLIMITED)
try {
val tracer = TestTracer()
val channelTracer = IncomingChannelTracer("42", tracer, channel)
val deferred = async { channel.send(Frame.Text("Text")) }
channelTracer.receiveOrNull()
deferred.await()
assertEquals(1, tracer.webSocketFrameReceivedCalls.size)
with(tracer.webSocketFrameReceivedCalls[0]) {
assertEquals("42", requestId)
assertTrue(frame is Frame.Text)
assertEquals("Text", (frame as Frame.Text).readText())
}
} finally {
channel.close()
}
}
@Test
fun testTracingWrapperExecute() = runBlocking {
val requestData = HttpRequestData(
Url("http://www.google.com"),
HttpMethod.Get,
Headers.Empty,
object : OutgoingContent.ByteArrayContent() {
override fun bytes(): ByteArray = ByteArray(42)
},
Job(),
Attributes()
)
val responseData =
HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, "body", Job())
val tracer = TestTracer()
val tracingWrapperFactory = TracingWrapper(TestHttpClientEngineFactory(responseData), tracer)
val tracingWrapper = tracingWrapperFactory.create()
tracingWrapper.execute(requestData)
assertEquals(1, tracer.requestWillBeSentCalls.size)
assertEquals(1, tracer.responseHeadersReceivedCalls.size)
assertEquals(1, tracer.interpretResponseCalls.size)
with(tracer.requestWillBeSentCalls[0]) {
assertEquals("0", requestId)
assertEquals(requestData, this.requestData)
}
with(tracer.responseHeadersReceivedCalls[0]) {
assertEquals("0", requestId)
assertEquals(requestData, this.requestData)
assertEquals(responseData, this.responseData)
}
with(tracer.interpretResponseCalls[0]) {
assertEquals("0", requestId)
assertEquals("body", body)
}
}
}
class TestHttpClientEngineFactory(private val responseData: HttpResponseData) :
HttpClientEngineFactory<HttpClientEngineConfig> {
override fun create(block: HttpClientEngineConfig.() -> Unit): HttpClientEngine {
return TestHttpClientEngine(responseData)
}
}
class TestHttpClientEngine(private val responseData: HttpResponseData) : HttpClientEngine {
override val config: HttpClientEngineConfig = HttpClientEngineConfig()
override val coroutineContext: CoroutineContext = Job()
override val dispatcher: CoroutineDispatcher = Dispatchers.Default
override fun close() {}
@InternalAPI
override suspend fun execute(data: HttpRequestData): HttpResponseData {
return responseData
}
}
| apache-2.0 | a10812afc882bd4e3cabd0afed3924ee | 33.312281 | 118 | 0.59955 | 5.274542 | false | true | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/utilities/MavenUtilities.kt | 1 | 4031 | package org.roylance.yaclib.core.utilities
import org.apache.maven.model.io.xpp3.MavenXpp3Reader
import org.apache.maven.model.io.xpp3.MavenXpp3Writer
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.services.IProjectBuilderServices
import java.io.File
import java.io.FileReader
import java.io.FileWriter
object MavenUtilities : IProjectBuilderServices {
const val PomName = "pom"
const val PomXml = "$PomName.xml"
override fun incrementVersion(location: String,
dependency: YaclibModel.Dependency): YaclibModel.ProcessReport {
val reader = MavenXpp3Reader()
val pomFile = File(location, PomXml)
if (!pomFile.exists()) {
pomFile.createNewFile()
}
val model = reader.read(FileReader(pomFile))
val minorVersion = model.properties.getProperty(JavaUtilities.MinorName)
model.properties.setProperty(JavaUtilities.MinorName, minorVersion.toString())
MavenXpp3Writer().write(FileWriter(pomFile), model)
return YaclibModel.ProcessReport.newBuilder()
.setNewMinor(minorVersion)
.setNewMajor(dependency.majorVersion)
.setContent("${dependency.majorVersion}.$minorVersion")
.build()
}
override fun updateDependencyVersion(location: String,
otherDependency: YaclibModel.Dependency): YaclibModel.ProcessReport {
val reader = MavenXpp3Reader()
val pomFile = File(location, PomXml)
if (!pomFile.exists()) {
pomFile.createNewFile()
}
val variableName = JavaUtilities.buildPackageVariableName(otherDependency)
val model = reader.read(FileReader(pomFile))
if (otherDependency.thirdPartyDependencyVersion.isEmpty()) {
model.properties.setProperty(variableName,
"${otherDependency.majorVersion}.${otherDependency.minorVersion}")
} else {
model.properties.setProperty(variableName, otherDependency.thirdPartyDependencyVersion)
}
MavenXpp3Writer().write(FileWriter(pomFile), model)
return YaclibModel.ProcessReport.newBuilder()
.build()
}
override fun getVersion(location: String): YaclibModel.ProcessReport {
val reader = MavenXpp3Reader()
val pomFile = File(location, PomXml)
if (!pomFile.exists()) {
pomFile.createNewFile()
}
val model = reader.read(FileReader(pomFile))
return YaclibModel.ProcessReport.newBuilder()
.setNewMinor(model.properties.getProperty(JavaUtilities.MinorName))
.setNewMajor(model.properties.getProperty(JavaUtilities.MajorName))
.build()
}
override fun setVersion(location: String,
dependency: YaclibModel.Dependency): YaclibModel.ProcessReport {
val reader = MavenXpp3Reader()
val pomFile = File(location, PomXml)
if (!pomFile.exists()) {
pomFile.createNewFile()
}
val model = reader.read(FileReader(pomFile))
model.properties.setProperty(JavaUtilities.MinorName, dependency.minorVersion.toString())
model.properties.setProperty(JavaUtilities.MajorName, dependency.majorVersion.toString())
MavenXpp3Writer().write(FileWriter(pomFile), model)
return YaclibModel.ProcessReport.getDefaultInstance()
}
override fun clean(location: String): YaclibModel.ProcessReport {
return FileProcessUtilities.executeProcess(location, InitUtilities.Maven, "clean")
}
override fun build(location: String): YaclibModel.ProcessReport {
return FileProcessUtilities.executeProcess(location, InitUtilities.Maven, "compile")
}
override fun buildPackage(location: String,
dependency: YaclibModel.Dependency): YaclibModel.ProcessReport {
return FileProcessUtilities.executeProcess(location, InitUtilities.Maven, "package")
}
override fun publish(location: String, dependency: YaclibModel.Dependency,
apiKey: String): YaclibModel.ProcessReport {
return YaclibModel.ProcessReport.getDefaultInstance()
}
override fun restoreDependencies(location: String,
doAnonymously: Boolean): YaclibModel.ProcessReport {
return YaclibModel.ProcessReport.getDefaultInstance()
}
} | mit | b241c20c573fc805c44ed2e5f22c6253 | 34.681416 | 93 | 0.747953 | 4.927873 | false | false | false | false |
xenomachina/kotlin-argparser | src/main/kotlin/com/xenomachina/argparser/WrappingDelegate.kt | 1 | 1849 | // Copyright © 2016 Laurence Gonsalves
//
// This file is part of kotlin-argparser, a library which can be found at
// http://github.com/xenomachina/kotlin-argparser
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, see http://www.gnu.org/licenses/
package com.xenomachina.argparser
internal class WrappingDelegate<U, W>(
private val inner: ArgParser.Delegate<U>,
private val wrap: (U) -> W
) : ArgParser.Delegate<W>() {
override val parser: ArgParser
get() = inner.parser
override val value: W
get() = wrap(inner.value)
override val hasValue: Boolean
get() = inner.hasValue
override val errorName: String
get() = inner.errorName
override val help: String
get() = inner.help
override fun validate() {
inner.validate()
}
override fun toHelpFormatterValue(): HelpFormatter.Value = inner.toHelpFormatterValue()
override fun addValidator(validator: ArgParser.Delegate<W>.() -> Unit): ArgParser.Delegate<W> =
apply { inner.addValidator { validator(this@WrappingDelegate) } }
override val hasValidators: Boolean
get() = inner.hasValidators
override fun registerLeaf(root: ArgParser.Delegate<*>) {
inner.registerLeaf(root)
}
}
| lgpl-2.1 | 4d0cd66c1824d45189cf425d2388eee9 | 32 | 99 | 0.701299 | 4.307692 | false | false | false | false |
adrianswiatek/price-comparator | PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/adapters/CardsAdapter.kt | 1 | 1659 | package com.aswiatek.pricecomparator.adapters
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.aswiatek.pricecomparator.R
import com.aswiatek.pricecomparator.buisinesslogic.Mode
import com.aswiatek.pricecomparator.events.CardsEvent
import com.aswiatek.pricecomparator.model.Card
import com.squareup.otto.Bus
class CardsAdapter(
private val context: Context,
private val cards: MutableList<Card>,
private val bus: Bus)
: RecyclerView.Adapter<CardsViewHolder>() {
init {
bus.register(this)
}
private var mUndoData: UndoData = UndoData(cards[0], 0)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardsViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.activity_main_card, parent, false)
return CardsViewHolder(context, view, bus)
}
override fun onBindViewHolder(holder: CardsViewHolder, position: Int) =
holder.set(cards[position])
override fun getItemCount() = cards.size
fun getActiveOrEmpty(): Card =
cards.firstOrNull { it.isActive } ?: Card()
fun removeAt(position: Int) {
mUndoData = UndoData(cards[position], position)
cards.removeAt(position)
notifyItemRemoved(position)
bus.post(CardsEvent(null, Mode.Empty, "0"))
}
fun add(card: Card) {
cards.add(0, card)
notifyItemInserted(0)
}
fun restore() {
cards.add(mUndoData.position, mUndoData.card)
notifyItemInserted(mUndoData.position)
}
}
| mit | 48f2d8c4e2a1427a4a9c3343bdff7072 | 26.65 | 88 | 0.698614 | 4.297927 | false | false | false | false |
jrenner/kotlin_raytracer | core/src/org/jrenner/raytracer/Light.kt | 1 | 1045 | package org.jrenner.raytracer
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.math.Vector3
class Light {
companion object {
fun createLights(rt: RayTracer) {
rt.createLight(100f, -100f, 1000f)
//rt.createLight(1000f, -1000f, 0f)
//rt.createLight(-50f, -50f, 0f)
//rt.createLight(0f, 50f, 0f)
//rt.createLight(30f, 10f, 0f)
// rt.createLight(-30f, -50f, 0f)
// rt.createLight(-50f, -30f, 0f)
}
}
var brightness = 0.8f
val position = Vector3(-10f, 0f, 0f)
val color = Color.WHITE
val attenConst = 0f
val attenLin = 0.01f
val attenExp = 0.01f
fun brightnessAtDistance(dist: Float): Float {
return brightness / (attenConst + (attenLin * dist) + (attenExp * (dist * dist)))
}
fun lightAtDistance(dist: Float): Vector3 {
val res = Vector3()
val bright = brightnessAtDistance(dist)
res.set(color.r, color.g, color.b).scl(bright)
return res
}
}
| apache-2.0 | 5cb85ee69bbdb272607b81b3174f2fa9 | 26.5 | 89 | 0.586603 | 3.195719 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/glfw/src/templates/kotlin/glfw/templates/GLFW.kt | 1 | 163447 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw.templates
import org.lwjgl.generator.*
import glfw.*
val GLFW = "GLFW".nativeClass(Module.GLFW, prefix = "GLFW", binding = GLFW_BINDING) {
documentation =
"""
Native bindings to the ${url("http://www.glfw.org/docs/latest/", "GLFW")} library.
GLFW is a free, Open Source, multi-platform library for opening a window, creating an OpenGL context and managing input. It is easy to integrate into
existing applications and does not lay claim to the main loop.
"""
IntConstant(
"""
The major version number of the GLFW header.
This is incremented when the API is changed in non-compatible ways.
""",
"VERSION_MAJOR".."3"
)
IntConstant(
"""
The minor version number of the GLFW header.
This is incremented when features are added to the API but it remains backward-compatible.
""",
"VERSION_MINOR".."4"
)
IntConstant(
"""
The revision number of the GLFW header.
This is incremented when a bug fix release is made that does not contain any API changes.
""",
"VERSION_REVISION".."0"
)
IntConstant(
"Boolean values.",
"TRUE".."1",
"FALSE".."0"
)
IntConstant(
"The key or button was released.",
"RELEASE".."0"
)
IntConstant(
"The key or button was pressed.",
"PRESS".."1"
)
IntConstant(
"The key was held down until it repeated.",
"REPEAT".."2"
)
IntConstant(
"Joystick hat states.",
"HAT_CENTERED".."0",
"HAT_UP".."1",
"HAT_RIGHT".."2",
"HAT_DOWN".."4",
"HAT_LEFT".."8",
"HAT_RIGHT_UP".."(GLFW_HAT_RIGHT | GLFW_HAT_UP)",
"HAT_RIGHT_DOWN".."(GLFW_HAT_RIGHT | GLFW_HAT_DOWN)",
"HAT_LEFT_UP".."(GLFW_HAT_LEFT | GLFW_HAT_UP)",
"HAT_LEFT_DOWN".."(GLFW_HAT_LEFT | GLFW_HAT_DOWN)"
)
IntConstant(
"The unknown key.",
"KEY_UNKNOWN".."-1"
)
IntConstant(
"Printable keys.",
"KEY_SPACE".."32",
"KEY_APOSTROPHE".."39",
"KEY_COMMA".."44",
"KEY_MINUS".."45",
"KEY_PERIOD".."46",
"KEY_SLASH".."47",
"KEY_0".."48",
"KEY_1".."49",
"KEY_2".."50",
"KEY_3".."51",
"KEY_4".."52",
"KEY_5".."53",
"KEY_6".."54",
"KEY_7".."55",
"KEY_8".."56",
"KEY_9".."57",
"KEY_SEMICOLON".."59",
"KEY_EQUAL".."61",
"KEY_A".."65",
"KEY_B".."66",
"KEY_C".."67",
"KEY_D".."68",
"KEY_E".."69",
"KEY_F".."70",
"KEY_G".."71",
"KEY_H".."72",
"KEY_I".."73",
"KEY_J".."74",
"KEY_K".."75",
"KEY_L".."76",
"KEY_M".."77",
"KEY_N".."78",
"KEY_O".."79",
"KEY_P".."80",
"KEY_Q".."81",
"KEY_R".."82",
"KEY_S".."83",
"KEY_T".."84",
"KEY_U".."85",
"KEY_V".."86",
"KEY_W".."87",
"KEY_X".."88",
"KEY_Y".."89",
"KEY_Z".."90",
"KEY_LEFT_BRACKET".."91",
"KEY_BACKSLASH".."92",
"KEY_RIGHT_BRACKET".."93",
"KEY_GRAVE_ACCENT".."96",
"KEY_WORLD_1".."161",
"KEY_WORLD_2".."162"
)
IntConstant(
"Function keys.",
"KEY_ESCAPE".."256",
"KEY_ENTER".."257",
"KEY_TAB".."258",
"KEY_BACKSPACE".."259",
"KEY_INSERT".."260",
"KEY_DELETE".."261",
"KEY_RIGHT".."262",
"KEY_LEFT".."263",
"KEY_DOWN".."264",
"KEY_UP".."265",
"KEY_PAGE_UP".."266",
"KEY_PAGE_DOWN".."267",
"KEY_HOME".."268",
"KEY_END".."269",
"KEY_CAPS_LOCK".."280",
"KEY_SCROLL_LOCK".."281",
"KEY_NUM_LOCK".."282",
"KEY_PRINT_SCREEN".."283",
"KEY_PAUSE".."284",
"KEY_F1".."290",
"KEY_F2".."291",
"KEY_F3".."292",
"KEY_F4".."293",
"KEY_F5".."294",
"KEY_F6".."295",
"KEY_F7".."296",
"KEY_F8".."297",
"KEY_F9".."298",
"KEY_F10".."299",
"KEY_F11".."300",
"KEY_F12".."301",
"KEY_F13".."302",
"KEY_F14".."303",
"KEY_F15".."304",
"KEY_F16".."305",
"KEY_F17".."306",
"KEY_F18".."307",
"KEY_F19".."308",
"KEY_F20".."309",
"KEY_F21".."310",
"KEY_F22".."311",
"KEY_F23".."312",
"KEY_F24".."313",
"KEY_F25".."314",
"KEY_KP_0".."320",
"KEY_KP_1".."321",
"KEY_KP_2".."322",
"KEY_KP_3".."323",
"KEY_KP_4".."324",
"KEY_KP_5".."325",
"KEY_KP_6".."326",
"KEY_KP_7".."327",
"KEY_KP_8".."328",
"KEY_KP_9".."329",
"KEY_KP_DECIMAL".."330",
"KEY_KP_DIVIDE".."331",
"KEY_KP_MULTIPLY".."332",
"KEY_KP_SUBTRACT".."333",
"KEY_KP_ADD".."334",
"KEY_KP_ENTER".."335",
"KEY_KP_EQUAL".."336",
"KEY_LEFT_SHIFT".."340",
"KEY_LEFT_CONTROL".."341",
"KEY_LEFT_ALT".."342",
"KEY_LEFT_SUPER".."343",
"KEY_RIGHT_SHIFT".."344",
"KEY_RIGHT_CONTROL".."345",
"KEY_RIGHT_ALT".."346",
"KEY_RIGHT_SUPER".."347",
"KEY_MENU".."348",
"KEY_LAST".."GLFW_KEY_MENU"
)
IntConstant("If this bit is set one or more Shift keys were held down.", "MOD_SHIFT"..0x0001)
IntConstant("If this bit is set one or more Control keys were held down.", "MOD_CONTROL"..0x0002)
IntConstant("If this bit is set one or more Alt keys were held down.", "MOD_ALT"..0x0004)
IntConstant("If this bit is set one or more Super keys were held down.", "MOD_SUPER"..0x0008)
IntConstant("If this bit is set the Caps Lock key is enabled and the #LOCK_KEY_MODS input mode is set.", "MOD_CAPS_LOCK"..0x0010)
IntConstant("If this bit is set the Num Lock key is enabled and the #LOCK_KEY_MODS input mode is set.", "MOD_NUM_LOCK"..0x0020)
IntConstant(
"""Mouse buttons. See ${url("http://www.glfw.org/docs/latest/input.html\\#input_mouse_button", "mouse button input")} for how these are used.""",
"MOUSE_BUTTON_1".."0",
"MOUSE_BUTTON_2".."1",
"MOUSE_BUTTON_3".."2",
"MOUSE_BUTTON_4".."3",
"MOUSE_BUTTON_5".."4",
"MOUSE_BUTTON_6".."5",
"MOUSE_BUTTON_7".."6",
"MOUSE_BUTTON_8".."7",
"MOUSE_BUTTON_LAST".."GLFW_MOUSE_BUTTON_8",
"MOUSE_BUTTON_LEFT".."GLFW_MOUSE_BUTTON_1",
"MOUSE_BUTTON_RIGHT".."GLFW_MOUSE_BUTTON_2",
"MOUSE_BUTTON_MIDDLE".."GLFW_MOUSE_BUTTON_3"
)
IntConstant(
"""Joysticks. See ${url("http://www.glfw.org/docs/latest/input.html\\#joystick", "joystick input")} for how these are used.""",
"JOYSTICK_1".."0",
"JOYSTICK_2".."1",
"JOYSTICK_3".."2",
"JOYSTICK_4".."3",
"JOYSTICK_5".."4",
"JOYSTICK_6".."5",
"JOYSTICK_7".."6",
"JOYSTICK_8".."7",
"JOYSTICK_9".."8",
"JOYSTICK_10".."9",
"JOYSTICK_11".."10",
"JOYSTICK_12".."11",
"JOYSTICK_13".."12",
"JOYSTICK_14".."13",
"JOYSTICK_15".."14",
"JOYSTICK_16".."15",
"JOYSTICK_LAST".."GLFW_JOYSTICK_16"
)
IntConstant(
"""Gamepad buttons. See ${url("http://www.glfw.org/docs/latest/input.html\\#gamepad", "gamepad")} for how these are used.""",
"GAMEPAD_BUTTON_A".."0",
"GAMEPAD_BUTTON_B".."1",
"GAMEPAD_BUTTON_X".."2",
"GAMEPAD_BUTTON_Y".."3",
"GAMEPAD_BUTTON_LEFT_BUMPER".."4",
"GAMEPAD_BUTTON_RIGHT_BUMPER".."5",
"GAMEPAD_BUTTON_BACK".."6",
"GAMEPAD_BUTTON_START".."7",
"GAMEPAD_BUTTON_GUIDE".."8",
"GAMEPAD_BUTTON_LEFT_THUMB".."9",
"GAMEPAD_BUTTON_RIGHT_THUMB".."10",
"GAMEPAD_BUTTON_DPAD_UP".."11",
"GAMEPAD_BUTTON_DPAD_RIGHT".."12",
"GAMEPAD_BUTTON_DPAD_DOWN".."13",
"GAMEPAD_BUTTON_DPAD_LEFT".."14",
"GAMEPAD_BUTTON_LAST".."GLFW_GAMEPAD_BUTTON_DPAD_LEFT",
"GAMEPAD_BUTTON_CROSS".."GLFW_GAMEPAD_BUTTON_A",
"GAMEPAD_BUTTON_CIRCLE".."GLFW_GAMEPAD_BUTTON_B",
"GAMEPAD_BUTTON_SQUARE".."GLFW_GAMEPAD_BUTTON_X",
"GAMEPAD_BUTTON_TRIANGLE".."GLFW_GAMEPAD_BUTTON_Y"
)
IntConstant(
"""Gamepad axes. See ${url("http://www.glfw.org/docs/latest/input.html\\#gamepad", "gamepad")} for how these are used.""",
"GAMEPAD_AXIS_LEFT_X".."0",
"GAMEPAD_AXIS_LEFT_Y".."1",
"GAMEPAD_AXIS_RIGHT_X".."2",
"GAMEPAD_AXIS_RIGHT_Y".."3",
"GAMEPAD_AXIS_LEFT_TRIGGER".."4",
"GAMEPAD_AXIS_RIGHT_TRIGGER".."5",
"GAMEPAD_AXIS_LAST".."GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER"
)
EnumConstant(
"Error codes.",
"NO_ERROR".enum("No error has occurred.", "0"),
"NOT_INITIALIZED".enum(
"""
GLFW has not been initialized.
This occurs if a GLFW function was called that may not be called unless the library is initialized.
""",
0x00010001
),
"NO_CURRENT_CONTEXT".enum(
"""
No context is current for this thread.
This occurs if a GLFW function was called that needs and operates on the current OpenGL or OpenGL ES context but no context is current on the
calling thread. One such function is #SwapInterval().
""",
0x00010002
),
"INVALID_ENUM".enum(
"""
One of the arguments to the function was an invalid enum value.
One of the arguments to the function was an invalid enum value, for example requesting #RED_BITS with #GetWindowAttrib().
""",
0x00010003
),
"INVALID_VALUE".enum(
"""
One of the arguments to the function was an invalid value.
One of the arguments to the function was an invalid value, for example requesting a non-existent OpenGL or OpenGL ES version like 2.7.
Requesting a valid but unavailable OpenGL or OpenGL ES version will instead result in a #VERSION_UNAVAILABLE error.
""",
0x00010004
),
"OUT_OF_MEMORY".enum(
"""
A memory allocation failed.
A bug in GLFW or the underlying operating system. Report the bug to our ${url("https://github.com/glfw/glfw/issues", "issue tracker")}.
""",
0x00010005
),
"API_UNAVAILABLE".enum(
"""
GLFW could not find support for the requested API on the system.
The installed graphics driver does not support the requested API, or does not support it via the chosen context creation API. Below are a few
examples:
Some pre-installed Windows graphics drivers do not support OpenGL. AMD only supports OpenGL ES via EGL, while Nvidia and Intel only support it via
a WGL or GLX extension. macOS does not provide OpenGL ES at all. The Mesa EGL, OpenGL and OpenGL ES libraries do not interface with the Nvidia
binary driver. Older graphics drivers do not support Vulkan.
""",
0x00010006
),
"VERSION_UNAVAILABLE".enum(
"""
The requested OpenGL or OpenGL ES version (including any requested context or framebuffer hints) is not available on this machine.
The machine does not support your requirements. If your application is sufficiently flexible, downgrade your requirements and try again. Otherwise,
inform the user that their machine does not match your requirements.
Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 comes out before the 4.x series gets that far, also fail with this
error and not #INVALID_VALUE, because GLFW cannot know what future versions will exist.
""",
0x00010007
),
"PLATFORM_ERROR".enum(
"""
A platform-specific error occurred that does not match any of the more specific categories.
A bug or configuration error in GLFW, the underlying operating system or its drivers, or a lack of required resources. Report the issue to our
${url("https://github.com/glfw/glfw/issues", "issue tracker")}.
""",
0x00010008
),
"FORMAT_UNAVAILABLE".enum(
"""
The requested format is not supported or available.
If emitted during window creation, one or more hard constraints did not match any of the available pixel formats. If your application is
sufficiently flexible, downgrade your requirements and try again. Otherwise, inform the user that their machine does not match your requirements.
If emitted when querying the clipboard, ignore the error or report it to the user, as appropriate.
""",
0x00010009
),
"NO_WINDOW_CONTEXT".enum(
"""
The specified window does not have an OpenGL or OpenGL ES context.
A window that does not have an OpenGL or OpenGL ES context was passed to a function that requires it to have one.
Application programmer error. Fix the offending call.
""",
0x0001000A
),
"CURSOR_UNAVAILABLE".enum(
"""
The specified cursor shape is not available.
The specified standard cursor shape is not available, either because the current platform cursor theme does not provide it or because it is not
available on the platform.
Platform or system settings limitation. Pick another standard cursor shape or create a custom cursor.
""",
0x0001000B
),
"FEATURE_UNAVAILABLE".enum(
"""
The requested feature is not provided by the platform.
The requested feature is not provided by the platform, so GLFW is unable to implement it. The documentation for each function notes if it could
emit this error.
Platform or platform version limitation. The error can be ignored unless the feature is critical to the application.
A function call that emits this error has no effect other than the error and updating any existing out parameters.
""",
0x0001000C
),
"FEATURE_UNIMPLEMENTED".enum(
"""
The requested feature has not yet been implemented in GLFW for this platform.
An incomplete implementation of GLFW for this platform, hopefully fixed in a future release. The error can be ignored unless the feature is
critical to the application.
A function call that emits this error has no effect other than the error and updating any existing out parameters.
""",
0x0001000D
),
"PLATFORM_UNAVAILABLE".enum(
"""
Platform unavailable or no matching platform was found.
If emitted during initialization, no matching platform was found. If #PLATFORM is set to #ANY_PLATFORM, GLFW could not detect any of the platforms
supported by this library binary, except for the {@code Null} platform. If set to a specific platform, it is either not supported by this library
binary or GLFW was not able to detect it.
If emitted by a native access function, GLFW was initialized for a different platform than the function is for.
Failure to detect any platform usually only happens on non-macOS Unix systems, either when no window system is running or the program was run from
a terminal that does not have the necessary environment variables. Fall back to a different platform if possible or notify the user that no usable
platform was detected.
Failure to detect a specific platform may have the same cause as above or because support for that platform was not compiled in. Call
#PlatformSupported() to check whether a specific platform is supported by a library binary.
""",
0x0001000E
)
)
val WindowHints = EnumConstant(
"Window attributes.",
"FOCUSED".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will be given input focus when created. This hint is ignored for full screen and
initially hidden windows.
{@code GetWindowAttrib}: Indicates whether the specified window has input focus.
""",
0x00020001
),
"ICONIFIED".enum("{@code GetWindowAttrib}: Indicates whether the specified window is iconified, whether by the user or with #IconifyWindow().", 0x00020002),
"RESIZABLE".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will be resizable <i>by the user</i>. The window will still be resizable using the
#SetWindowSize() function. This hint is ignored for full screen windows.
{@code GetWindowAttrib}: Indicates whether the specified window is resizable <i>by the user</i>.
""",
0x00020003),
"VISIBLE".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will be initially visible. This hint is ignored for full screen windows. Windows created
hidden are completely invisible to the user until shown. This can be useful if you need to set up your window further before showing it, for
example moving it to a specific location.
{@code GetWindowAttrib}: Indicates whether the specified window is visible. Window visibility can be controlled with #ShowWindow() and #HideWindow().
""",
0x00020004),
"DECORATED".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will have window decorations such as a border, a close widget, etc. An undecorated window
may still allow the user to generate close events on some platforms. This hint is ignored for full screen windows.
{@code GetWindowAttrib}: Indicates whether the specified window has decorations such as a border, a close widget, etc.
""",
0x00020005),
"AUTO_ICONIFY".enum(
"""
{@code WindowHint}: Specifies whether the full screen window will automatically iconify and restore the previous video mode on input focus loss. This
hint is ignored for windowed mode windows.
""",
0x00020006),
"FLOATING".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will be floating above other regular windows, also called topmost or always-on-top. This
is intended primarily for debugging purposes and cannot be used to implement proper full screen windows. This hint is ignored for full screen
windows.
{@code GetWindowAttrib}: Indicates whether the specified window is floating, also called topmost or always-on-top.
""",
0x00020007),
"MAXIMIZED".enum(
"""
{@code WindowHint}: Specifies whether the windowed mode window will be maximized when created. This hint is ignored for full screen windows.
{@code GetWindowAttrib}: Indicates whether the specified window is maximized, whether by the user or #MaximizeWindow().
""",
0x00020008),
"CENTER_CURSOR".enum(
"""
{@code WindowHint}: Specifies whether the cursor should be centered over newly created full screen windows. This hint is ignored for windowed mode
windows.
""",
0x00020009),
"TRANSPARENT_FRAMEBUFFER".enum(
"""
{@code WindowHint}: Specifies whether the window framebuffer will be transparent. If enabled and supported by the system, the window framebuffer
alpha channel will be used to combine the framebuffer with the background. This does not affect window decorations.
""",
0x0002000A),
"HOVERED".enum(
"{@code GetWindowAttrib}: Indicates whether the cursor is currently directly over the content area of the window, with no other windows between.",
0x0002000B),
"FOCUS_ON_SHOW".enum(
"""
{@code WindowHint}: Specifies whether input focuses on calling show window.
{@code GetWindowAttrib}: Indicates whether input focuses on calling show window.
""",
0x0002000C),
"MOUSE_PASSTHROUGH".enum(
"""
{@code WindowHint}: Specifies whether the window is transparent to mouse input, letting any mouse events pass through to whatever window is behind
it. This is only supported for undecorated windows. Decorated windows with this enabled will behave differently between platforms.
{@code GetWindowAttrib}: Indicates whether the window is transparent to mouse input.
""",
0x0002000D),
"POSITION_X".enum(
"{@code WindowHint}: Initial position x-coordinate window hint.",
0x0002000E),
"POSITION_Y".enum(
"{@code WindowHint}: Initial position y-coordinate window hint.",
0x0002000F)
).javaDocLinks
val InputModes = IntConstant(
"Input options.",
"CURSOR"..0x00033001,
"STICKY_KEYS"..0x00033002,
"STICKY_MOUSE_BUTTONS"..0x00033003,
"LOCK_KEY_MODS"..0x00033004,
"RAW_MOUSE_MOTION"..0x00033005
).javaDocLinks
IntConstant(
"Cursor state.",
"CURSOR_NORMAL"..0x00034001,
"CURSOR_HIDDEN"..0x00034002,
"CURSOR_DISABLED"..0x00034003,
"CURSOR_CAPTURED"..0x00034004
)
IntConstant("The regular arrow cursor shape.", "ARROW_CURSOR"..0x00036001)
IntConstant("The text input I-beam cursor shape.", "IBEAM_CURSOR"..0x00036002)
IntConstant("The crosshair cursor shape.", "CROSSHAIR_CURSOR"..0x00036003)
IntConstant("The pointing hand cursor shape.", "POINTING_HAND_CURSOR"..0x00036004)
IntConstant(
"""
The horizontal resize/move arrow shape.
This is usually a horizontal double-headed arrow.
""",
"RESIZE_EW_CURSOR"..0x00036005
)
IntConstant(
"""
The vertical resize/move shape.
This is usually a vertical double-headed arrow.
""",
"RESIZE_NS_CURSOR"..0x00036006
)
IntConstant(
"""
The top-left to bottom-right diagonal resize/move shape.
This is usually a diagonal double-headed arrow.
${note(ul(
"<b>macOS</b>: This shape is provided by a private system API and may fail with #CURSOR_UNAVAILABLE in the future.",
"<b>X11</b>: This shape is provided by a newer standard not supported by all cursor themes.",
"<b>Wayland</b>: This shape is provided by a newer standard not supported by all cursor themes."
))}
""",
"RESIZE_NWSE_CURSOR"..0x00036007
)
IntConstant(
"""
The top-right to bottom-left diagonal resize/move shape.
This is usually a diagonal double-headed arrow.
${note(ul(
"<b>macOS</b>: This shape is provided by a private system API and may fail with #CURSOR_UNAVAILABLE in the future.",
"<b>X11</b>: This shape is provided by a newer standard not supported by all cursor themes.",
"<b>Wayland</b>: This shape is provided by a newer standard not supported by all cursor themes."
))}
""",
"RESIZE_NESW_CURSOR"..0x00036008
)
IntConstant(
"""
The omni-directional resize cursor/move shape.
This is usually either a combined horizontal and vertical double-headed arrow or a grabbing hand.
""",
"RESIZE_ALL_CURSOR"..0x00036009
)
IntConstant(
"""
The operation-not-allowed shape.
This is usually a circle with a diagonal line through it.
${note(ul(
"<b>X11</b>: This shape is provided by a newer standard not supported by all cursor themes.",
"<b>Wayland</b>: This shape is provided by a newer standard not supported by all cursor themes."
))}
""",
"NOT_ALLOWED_CURSOR"..0x0003600A
)
IntConstant("Legacy name for compatibility.", "HRESIZE_CURSOR".."GLFW_RESIZE_EW_CURSOR")
IntConstant("Legacy name for compatibility.", "VRESIZE_CURSOR".."GLFW_RESIZE_NS_CURSOR")
IntConstant("Legacy name for compatibility.", "HAND_CURSOR".."GLFW_POINTING_HAND_CURSOR")
IntConstant(
"Monitor events.",
"CONNECTED"..0x00040001,
"DISCONNECTED"..0x00040002
)
IntConstant(
"""
Joystick hat buttons init hint.
Specifies whether to also expose joystick hats as buttons, for compatibility with earlier versions of GLFW that did not have #GetJoystickHats().
Possible values are #TRUE and #FALSE.
""",
"JOYSTICK_HAT_BUTTONS"..0x00050001
)
IntConstant(
"""
ANGLE rendering backend init hint.
Specifies the platform type (rendering backend) to request when using OpenGL ES and EGL via ${url(
"https://chromium.googlesource.com/angle/angle/",
"ANGLE")
}. If the requested platform type is unavailable, ANGLE will use its default. Possible values are one of #ANGLE_PLATFORM_TYPE_NONE,
#ANGLE_PLATFORM_TYPE_OPENGL, #ANGLE_PLATFORM_TYPE_OPENGLES, #ANGLE_PLATFORM_TYPE_D3D9, #ANGLE_PLATFORM_TYPE_D3D11, #ANGLE_PLATFORM_TYPE_VULKAN and
#ANGLE_PLATFORM_TYPE_METAL.
""",
"ANGLE_PLATFORM_TYPE"..0x00050002
)
IntConstant(
"",
"ANY_POSITION"..0x80000000.i
)
IntConstant(
"Platform selection init hint.",
"PLATFORM"..0x00050003
)
IntConstant(
"""
macOS specific init hint.
Specifies whether to set the current directory to the application to the {@code Contents/Resources} subdirectory of the application's bundle, if
present. Possible values are #TRUE` and #FALSE`. This is ignored on other platforms.
""",
"COCOA_CHDIR_RESOURCES"..0x00051001
)
IntConstant(
"""
macOS specific init hint.
Specifies whether to create the menu bar and dock icon when GLFW is initialized. This applies whether the menu bar is created from a nib or manually by
GLFW. Possible values are #TRUE and #FALSE. This is ignored on other platforms.
""",
"COCOA_MENUBAR"..0x00051002
)
IntConstant(
"""
X11 specific init hint.
""",
"X11_XCB_VULKAN_SURFACE"..0x00052001
)
IntConstant(
"Hint value for #PLATFORM that enables automatic platform selection.",
"ANY_PLATFORM"..0x00060000,
"PLATFORM_WIN32"..0x00060001,
"PLATFORM_COCOA"..0x00060002,
"PLATFORM_WAYLAND"..0x00060003,
"PLATFORM_X11"..0x00060004,
"PLATFORM_NULL"..0x00060005
)
IntConstant(
"Don't care value.",
"DONT_CARE".."-1"
)
// [ OpenGL ]
val PixelFormatHints = IntConstant(
"PixelFormat hints.",
"RED_BITS"..0x00021001,
"GREEN_BITS"..0x00021002,
"BLUE_BITS"..0x00021003,
"ALPHA_BITS"..0x00021004,
"DEPTH_BITS"..0x00021005,
"STENCIL_BITS"..0x00021006,
"ACCUM_RED_BITS"..0x00021007,
"ACCUM_GREEN_BITS"..0x00021008,
"ACCUM_BLUE_BITS"..0x00021009,
"ACCUM_ALPHA_BITS"..0x0002100A,
"AUX_BUFFERS"..0x0002100B,
"STEREO"..0x0002100C,
"SAMPLES"..0x0002100D,
"SRGB_CAPABLE"..0x0002100E,
"REFRESH_RATE"..0x0002100F,
"DOUBLEBUFFER"..0x00021010
).javaDocLinks
val ClientAPIHints = EnumConstant(
"Client API hints.",
"CLIENT_API".enum(
"""
{@code WindowHint}: Specifies which client API to create the context for. Possible values are #OPENGL_API, #OPENGL_ES_API and #NO_API. This is a hard
constraint.
{@code GetWindowAttrib}: Indicates the client API provided by the window's context; either #OPENGL_API, #OPENGL_ES_API or #NO_API.
""",
0x00022001
),
"CONTEXT_VERSION_MAJOR".enum(
"""
{@code WindowHint}: Specifies the client API major version that the created context must be compatible with. The exact behavior of this hint depends on
the requested client API.
${note(ul(
"""
While there is no way to ask the driver for a context of the highest supported version, GLFW will attempt to provide this when you ask for a
version 1.0 context, which is the default for these hints.
""",
"""
<b>OpenGL</b>: #CONTEXT_VERSION_MAJOR and #CONTEXT_VERSION_MINOR are not hard constraints, but creation will fail if the OpenGL version of the
created context is less than the one requested. It is therefore perfectly safe to use the default of version 1.0 for legacy code and you will
still get backwards-compatible contexts of version 3.0 and above when available.
""",
"""
<b>OpenGL ES</b>: #CONTEXT_VERSION_MAJOR and #CONTEXT_VERSION_MINOR are not hard constraints, but creation will fail if the OpenGL ES version
of the created context is less than the one requested. Additionally, OpenGL ES 1.x cannot be returned if 2.0 or later was requested, and vice
versa. This is because OpenGL ES 3.x is backward compatible with 2.0, but OpenGL ES 2.0 is not backward compatible with 1.x.
"""
))}
{@code GetWindowAttrib}: Indicate the client API major version of the window's context.
""",
0x00022002
),
"CONTEXT_VERSION_MINOR".enum(
"""
{@code WindowHint}: Specifies the client API minor version that the created context must be compatible with. The exact behavior of this hint depends on
the requested client API.
{@code GetWindowAttrib}: Indicate the client API minor version of the window's context.
""",
0x00022003
),
"CONTEXT_REVISION".enum("{@code GetWindowAttrib}: Indicates the client API version of the window's context.", 0x00022004),
"CONTEXT_ROBUSTNESS".enum(
"""
{@code WindowHint}: Specifies the robustness strategy to be used by the context. This can be one of #NO_RESET_NOTIFICATION or #LOSE_CONTEXT_ON_RESET, or
#NO_ROBUSTNESS to not request a robustness strategy.
{@code GetWindowAttrib}: Indicates the robustness strategy used by the context. This is #LOSE_CONTEXT_ON_RESET or #NO_RESET_NOTIFICATION if the window's
context supports robustness, or #NO_ROBUSTNESS otherwise.
""",
0x00022005
),
"OPENGL_FORWARD_COMPAT".enum(
"""
{@code WindowHint}: Specifies whether the OpenGL context should be forward-compatible, i.e. one where all functionality deprecated in the requested
version of OpenGL is removed. This must only be used if the requested OpenGL version is 3.0 or above. If OpenGL ES is requested, this hint is
ignored.
{@code GetWindowAttrib}: Indicates if the window's context is an OpenGL forward-compatible one.
""",
0x00022006
),
"CONTEXT_DEBUG".enum(
"""
{@code WindowHint}: Specifies whether to create a debug context, which may have additional error and performance issue reporting functionality.
{@code GetWindowAttrib}: Indicates if the window's context is a debug context.
""",
0x00022007
),
"OPENGL_DEBUG_CONTEXT".enum(
"Alias of #CONTEXT_DEBUG for compatibility with earlier versions.",
"GLFW_CONTEXT_DEBUG"
),
"OPENGL_PROFILE".enum(
"""
{@code WindowHint}: Specifies which OpenGL profile to create the context for. Possible values are one of #OPENGL_CORE_PROFILE or #OPENGL_COMPAT_PROFILE,
or #OPENGL_ANY_PROFILE to not request a specific profile. If requesting an OpenGL version below 3.2, #OPENGL_ANY_PROFILE must be used. If OpenGL ES
is requested, this hint is ignored.
{@code GetWindowAttrib}: Indicates the OpenGL profile used by the context. This is #OPENGL_CORE_PROFILE or #OPENGL_COMPAT_PROFILE if the context uses a
known profile, or #OPENGL_ANY_PROFILE if the OpenGL profile is unknown or the context is an OpenGL ES context. Note that the returned profile may
not match the profile bits of the context flags, as GLFW will try other means of detecting the profile when no bits are set.
""",
0x00022008
),
"CONTEXT_RELEASE_BEHAVIOR".enum(
"""
{@code WindowHint}: Specifies the release behavior to be used by the context. If the behavior is #ANY_RELEASE_BEHAVIOR, the default behavior of the
context creation API will be used. If the behavior is #RELEASE_BEHAVIOR_FLUSH, the pipeline will be flushed whenever the context is released from
being the current one. If the behavior is #RELEASE_BEHAVIOR_NONE, the pipeline will not be flushed on release.
""",
0x00022009
),
"CONTEXT_NO_ERROR".enum(
"""
{@code WindowHint}: Specifies whether errors should be generated by the context. If enabled, situations that would have generated errors instead cause
undefined behavior.
""",
0x0002200A
),
"CONTEXT_CREATION_API".enum(
"""
{@code WindowHint}: Specifies which context creation API to use to create the context. Possible values are #NATIVE_CONTEXT_API, #EGL_CONTEXT_API
and #OSMESA_CONTEXT_API. This is a hard constraint. If no client API is requested, this hint is ignored.
${note(ul(
"<b>macOS</b>: The EGL API is not available on this platform and requests to use it will fail.",
"<b>Wayland, Mir</b>: The EGL API <i>is</i> the native context creation API, so this hint will have no effect.",
"""
An OpenGL extension loader library that assumes it knows which context creation API is used on a given platform may fail if you change this
hint. This can be resolved by having it load via #GetProcAddress(), which always uses the selected API.
"""
))}
{@code GetWindowAttrib}: Indicates the context creation API used to create the window's context; either #NATIVE_CONTEXT_API or #EGL_CONTEXT_API.
""",
0x0002200B
),
"SCALE_TO_MONITOR".enum(
"""
{@code WindowHint}: Specifies whether the window content area should be resized based on the monitor content scale of any monitor it is placed on.
This includes the initial placement when the window is created. Possible values are #TRUE and #FALSE.
This hint only has an effect on platforms where screen coordinates and pixels always map 1:1 such as Windows and X11. On platforms like macOS the
resolution of the framebuffer is changed independently of the window size.
""",
0x0002200C
)
).javaDocLinks
IntConstant(
"""
Specifies whether to use full resolution framebuffers on Retina displays.
This is ignored on other platforms.
""",
"COCOA_RETINA_FRAMEBUFFER"..0x00023001
)
IntConstant(
"""
Specifies the UTF-8 encoded name to use for autosaving the window frame, or if empty disables frame autosaving for the window.
This is ignored on other platforms.
""",
"COCOA_FRAME_NAME"..0x00023002
)
IntConstant(
"""
Specifies whether to enable Automatic Graphics Switching, i.e. to allow the system to choose the integrated GPU for the OpenGL context and move it
between GPUs if necessary or whether to force it to always run on the discrete GPU. This only affects systems with both integrated and discrete GPUs.
This is ignored on other platforms.
""",
"COCOA_GRAPHICS_SWITCHING"..0x00023003
)
IntConstant(
"""
The desired ASCII encoded class and instance parts of the ICCCM {@code WM_CLASS} window property.
These are ignored on other platforms.
""",
"X11_CLASS_NAME"..0x00024001,
"X11_INSTANCE_NAME"..0x00024002
)
IntConstant(
"""
Specifies whether to allow access to the window menu via the Alt+Space and Alt-and-then-Space keyboard shortcuts.
This is ignored on other platforms.
""",
"WIN32_KEYBOARD_MENU"..0x00025001
)
IntConstant(
"""
Allows specification of the Wayland {@code app_id}.
This is ignored on other platforms.
""",
"WAYLAND_APP_ID"..0x00026001
)
val ClientAPIValues = IntConstant(
"Values for the #CLIENT_API hint.",
"NO_API".."0",
"OPENGL_API"..0x00030001,
"OPENGL_ES_API"..0x00030002
).javaDocLinks
val ContextRobustnessValues = IntConstant(
"Values for the #CONTEXT_ROBUSTNESS hint.",
"NO_ROBUSTNESS".."0",
"NO_RESET_NOTIFICATION"..0x00031001,
"LOSE_CONTEXT_ON_RESET"..0x00031002
).javaDocLinks
val OpenGLProfileValues = IntConstant(
"Values for the #OPENGL_PROFILE hint.",
"OPENGL_ANY_PROFILE".."0",
"OPENGL_CORE_PROFILE"..0x00032001,
"OPENGL_COMPAT_PROFILE"..0x00032002
).javaDocLinks
val ContextReleaseBehaviorValues = IntConstant(
"Values for the #CONTEXT_RELEASE_BEHAVIOR hint.",
"ANY_RELEASE_BEHAVIOR".."0",
"RELEASE_BEHAVIOR_FLUSH"..0x00035001,
"RELEASE_BEHAVIOR_NONE"..0x00035002
).javaDocLinks
val ContextCreationAPIValues = IntConstant(
"Values for the #CONTEXT_CREATION_API hint.",
"NATIVE_CONTEXT_API"..0x00036001,
"EGL_CONTEXT_API"..0x00036002,
"OSMESA_CONTEXT_API"..0x00036003
).javaDocLinks
IntConstant(
"Values for the #ANGLE_PLATFORM_TYPE hint.",
"ANGLE_PLATFORM_TYPE_NONE"..0x00037001,
"ANGLE_PLATFORM_TYPE_OPENGL"..0x00037002,
"ANGLE_PLATFORM_TYPE_OPENGLES"..0x00037003,
"ANGLE_PLATFORM_TYPE_D3D9"..0x00037004,
"ANGLE_PLATFORM_TYPE_D3D11"..0x00037005,
"ANGLE_PLATFORM_TYPE_VULKAN"..0x00037007,
"ANGLE_PLATFORM_TYPE_METAL"..0x00037008
)
Code(
javaInit = statement("$t${t}EventLoop.check();")
)..intb(
"Init",
"""
Initializes the GLFW library. Before most GLFW functions can be used, GLFW must be initialized, and before an application terminates GLFW should be
terminated in order to free any resources allocated during or after initialization.
If this function fails, it calls #Terminate() before returning. If it succeeds, you should call #Terminate() before the application exits.
Additional calls to this function after successful initialization but before termination will return #TRUE immediately.
The #PLATFORM init hint controls which platforms are considered during initialization. This also depends on which platforms the library was compiled to
support.
${note(ul(
"This function must only be called from the main thread.",
"""
<b>macOS</b>: This function will change the current directory of the application to the `Contents/Resources` subdirectory of the application's
bundle, if present. This can be disabled with the #COCOA_CHDIR_RESOURCES init hint.
""",
"""
<b>macOS</b>: This function will create the main menu and dock icon for the application. If GLFW finds a {@code MainMenu.nib} it is loaded and
assumed to contain a menu bar. Otherwise a minimal menu bar is created manually with common commands like Hide, Quit and About. The About entry
opens a minimal about dialog with information from the application's bundle. The menu bar and dock icon can be disabled entirely with the
#COCOA_MENUBAR init hint.
""",
"""
<b>x11</b>: This function will set the {@code LC_CTYPE} category of the application locale according to the current environment if that category is
still "C". This is because the "C" locale breaks Unicode text input.
"""
))}
""",
returnDoc =
"""
#TRUE if successful, or #FALSE if an error occurred.
Possible errors include #PLATFORM_UNAVAILABLE and #PLATFORM_ERROR.
""",
since = "version 1.0"
)
void(
"Terminate",
"""
Terminates the GLFW library.
This function destroys all remaining windows and cursors, restores any modified gamma ramps and frees any other allocated resources. Once this function
is called, you must again call #Init() successfully before you will be able to use most GLFW functions.
If GLFW has been successfully initialized, this function should be called before the application exits. If initialization fails, there is no need to
call this function, as it is called by #Init() before it returns failure.
This function has no effect if GLFW is not initialized.
${note(ul(
"This function may be called before #Init().",
"This function must only be called from the main thread.",
"This function must not be called from a callback.",
"No window's context may be current on another thread when this function is called."
))}
""",
since = "version 1.0"
)
void(
"InitHint",
"""
Sets hints for the next initialization of GLFW.
The values you set hints to are never reset by GLFW, but they only take effect during initialization. Once GLFW has been initialized, any values you
set will be ignored until the library is terminated and initialized again.
Some hints are platform specific. These may be set on any platform but they will only affect their specific platform. Other platforms will simply
ignore them. Setting these hints requires no platform specific headers or functions.
${note(ul(
"This function may be called before #Init().",
"This function must only be called from the main thread."
))}
""",
int(
"hint",
"the init hint to set",
"#JOYSTICK_HAT_BUTTONS #ANGLE_PLATFORM_TYPE #COCOA_CHDIR_RESOURCES #COCOA_MENUBAR #PLATFORM #X11_XCB_VULKAN_SURFACE"
),
int("value", "the new value of the init hint"),
since = "version 3.3"
)
void(
"InitAllocator",
"""
Sets the init allocator to the desired value.
To use the default allocator, call this function with a #NULL argument.
If you specify an allocator struct, every member must be a valid function pointer. If any member is #NULL, this function emits #INVALID_VALUE and the
init allocator is unchanged.
${note(ul(
"Possible errors include #INVALID_VALUE.",
"The specified allocator is copied before this function returns.",
"This function must only be called from the main thread."
))}
""",
nullable..GLFWallocator.const.p("allocator", "the allocator to use at the next initialization, or #NULL to use the default one"),
since = "version 3.4"
)
void(
"GetVersion",
"""
Retrieves the major, minor and revision numbers of the GLFW library. It is intended for when you are using GLFW as a shared library and want to ensure
that you are using the minimum required version.
${note(ul(
"Any or all of the version arguments may be #NULL.",
"This function always succeeds.",
"This function may be called before #Init().",
"This function may be called from any thread."
))}
""",
nullable..Check(1)..int.p("major", "where to store the major version number, or #NULL"),
nullable..Check(1)..int.p("minor", "where to store the minor version number, or #NULL"),
nullable..Check(1)..int.p("rev", "where to store the revision number, or #NULL"),
since = "version 1.0"
)
Nonnull..charASCII.const.p(
"GetVersionString",
"""
Returns the compile-time generated version string of the GLFW library binary. It describes the version, platforms, compiler and any platform or
operating system specific compile-time options. It should not be confused with the OpenGL or OpenGL ES version string, queried with
{@code glGetString}.
<b>Do not use the version string</b> to parse the GLFW library version. The #GetVersion() function already provides the version of the library binary
in numerical format.
<b>Do not use the version string</b> to parse what platforms are supported. The #PlatformSupported() function lets you query platform support.
${note(ul(
"This function always succeeds.",
"This function may be called before #Init().",
"This function may be called from any thread.",
"The returned string is static and compile-time generated."
))}
""",
returnDoc = "the ASCII encoded GLFW version string",
since = "version 3.0"
)
int(
"GetError",
"""
Returns and clears the last error for the calling thread.
This function returns and clears the error code of the last error that occurred on the calling thread and optionally a UTF-8 encoded human-readable
description of it. If no error has occurred since the last call, it returns #NO_ERROR (zero), and the description pointer is set to #NULL.
${note(ul(
"This function may be called before #Init().",
"This function may be called from any thread.",
"""
The returned string is allocated and freed by GLFW. You should not free it yourself. It is guaranteed to be valid only until the next error occurs
or the library is terminated.
"""
))}
""",
Check("1")..nullable..charUTF8.const.p.p("description", "where to store the error description pointer, or #NULL"),
returnDoc = "the last error code for the calling thread, or #NO_ERROR (zero)",
since = "version 3.3"
)
GLFWerrorfun(
"SetErrorCallback",
"""
Sets the error callback, which is called with an error code and a human-readable description each time a GLFW error occurs.
The error code is set before the callback is called. Calling #GetError() from the error callback will return the same value as the error code argument.
The error callback is called on the thread where the error occurred. If you are using GLFW from multiple threads, your error callback needs to be
written accordingly.
Because the description string may have been generated specifically for that error, it is not guaranteed to be valid after the callback has returned. If
you wish to use it after the callback returns, you need to make a copy.
Once set, the error callback remains set even after the library has been terminated.
${note(ul(
"This function may be called before #Init().",
"This function must only be called from the main thread."
))}
""",
nullable..GLFWerrorfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 3.0"
)
int(
"GetPlatform",
"""
Returns the currently selected platform.
This function returns the platform that was selected during initialization. The returned value will be one of #PLATFORM_WIN32, #PLATFORM_COCOA,
#PLATFORM_WAYLAND, #PLATFORM_X11 or #PLATFORM_NULL.
This function may be called from any thread.
""",
void(),
returnDoc =
"""
the currently selected platform, or zero if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.4"
)
intb(
"PlatformSupported",
"""
Returns whether the library includes support for the specified platform.
This function returns whether the library was compiled with support for the specified platform.
This function may be called before #Init().
This function may be called from any thread.
""",
int("platform", "the platform to query", "#PLATFORM_WIN32 #PLATFORM_COCOA #PLATFORM_WAYLAND #PLATFORM_X11 #PLATFORM_NULL"),
returnDoc =
"""
#TRUE if the platform is supported, or #FALSE otherwise.
Possible errors include #INVALID_ENUM.
""",
since = "version 3.4"
)
GLFWmonitor.p.p(
"GetMonitors",
"""
Returns an array of handles for all currently connected monitors. The primary monitor is always first in the returned array. If no monitors were found,
this function returns #NULL.
The returned array is allocated and freed by GLFW. You should not free it yourself. It is guaranteed to be valid only until the monitor configuration
changes or the library is terminated.
This function must only be called from the main thread.
""",
AutoSizeResult..int.p("count", "where to store the number of monitors in the returned array. This is set to zero if an error occurred."),
returnDoc = "an array of monitor handlers, or #NULL if no monitors were found or if an error occurred",
since = "version 3.0"
)
GLFWmonitor.p(
"GetPrimaryMonitor",
"""
Returns the primary monitor. This is usually the monitor where elements like the task bar or global menu bar are located.
This function must only be called from the main thread.
The primary monitor is always first in the array returned by #GetMonitors().
""",
returnDoc = "the primary monitor, or #NULL if no monitors were found or if an error occurred",
since = "version 3.0"
)
void(
"GetMonitorPos",
"""
Returns the position, in screen coordinates, of the upper-left corner of the specified monitor.
Any or all of the position arguments may be #NULL. If an error occurs, all non-#NULL position arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
nullable..Check(1)..int.p("xpos", "where to store the monitor x-coordinate, or #NULL"),
nullable..Check(1)..int.p("ypos", "where to store the monitor y-coordinate, or #NULL"),
since = "version 3.0"
)
void(
"GetMonitorWorkarea",
"""
Retrieves the work area of the monitor.
This function returns the position, in screen coordinates, of the upper-left corner of the work area of the specified monitor along with the work area
size in screen coordinates. The work area is defined as the area of the monitor not occluded by the window system task bar where present. If no task
bar exists then the work area is the monitor resolution in screen coordinates.
Any or all of the position and size arguments may be #NULL. If an error occurs, all non-#NULL position and size arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
nullable..Check(1)..int.p("xpos", "where to store the working area x-coordinate, or #NULL"),
nullable..Check(1)..int.p("ypos", "where to store the working area y-coordinate, or #NULL"),
nullable..Check(1)..int.p("width", "where to store the working area width, or #NULL"),
nullable..Check(1)..int.p("height", "where to store the working area height, or #NULL"),
since = "version 3.3"
)
void(
"GetMonitorPhysicalSize",
"""
Returns the size, in millimetres, of the display area of the specified monitor.
Some platforms do not provide accurate monitor size information, either because the monitor
${url("https://en.wikipedia.org/wiki/Extended_display_identification_data", "EDID")} data is incorrect or because the driver does not report it
accurately.
Any or all of the size arguments may be #NULL. If an error occurs, all non-#NULL size arguments will be set to zero.
${note(ul(
"This function must only be called from the main thread.",
"""
<b>Windows</b>: On Windows 8 and earlier the physical size is calculated from the current resolution and system DPI instead of querying the monitor
EDID data.
"""
))}
""",
GLFWmonitor.p("monitor", "the monitor to query"),
nullable..Check(1)..int.p("widthMM", "where to store the width, in millimetres, of the monitor's display area, or #NULL"),
nullable..Check(1)..int.p("heightMM", "where to store the height, in millimetres, of the monitor's display area, or #NULL"),
since = "version 3.0"
)
void(
"GetMonitorContentScale",
"""
Retrieves the content scale for the specified monitor.
This function retrieves the content scale for the specified monitor. The content scale is the ratio between the current DPI and the platform's default
DPI. This is especially important for text and any UI elements. If the pixel dimensions of your UI scaled by this look appropriate on your machine then
it should appear at a reasonable size on other machines regardless of their DPI and scaling settings. This relies on the system DPI and scaling
settings being somewhat correct.
The content scale may depend on both the monitor resolution and pixel density and on user settings. It may be very different from the raw DPI
calculated from the physical size and current resolution.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
nullable..Check(1)..float.p("xscale", "where to store the x-axis content scale, or #NULL"),
nullable..Check(1)..float.p("yscale", "where to store the y-axis content scale, or #NULL"),
since = "version 3.3"
)
charUTF8.const.p(
"GetMonitorName",
"""
Returns a human-readable name, encoded as UTF-8, of the specified monitor. The name typically reflects the make and model of the monitor and is not
guaranteed to be unique among the connected monitors.
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified monitor is disconnected or the
library is terminated.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
returnDoc = "the UTF-8 encoded name of the monitor, or #NULL if an error occurred",
since = "version 3.0"
)
void(
"SetMonitorUserPointer",
"""
Sets the user pointer of the specified monitor.
This function sets the user-defined pointer of the specified monitor. The current value is retained until the monitor is disconnected. The initial
value is #NULL.
This function may be called from the monitor callback, even for a monitor that is being disconnected.
This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.p("monitor", "the monitor whose pointer to set"),
opaque_p("pointer", "the new value"),
since = "version 3.3"
)
opaque_p(
"GetMonitorUserPointer",
"""
Returns the user pointer of the specified monitor.
This function returns the current value of the user-defined pointer of the specified monitor. The initial value is #NULL.
This function may be called from the monitor callback, even for a monitor that is being disconnected.
This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.p("monitor", "the monitor whose pointer to return"),
since = "version 3.3"
)
GLFWmonitorfun(
"SetMonitorCallback",
"""
Sets the monitor configuration callback, or removes the currently set callback. This is called when a monitor is connected to or disconnected from the
system.
This function must only be called from the main thread.
""",
nullable..GLFWmonitorfun("cbfun", "the new callback, or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set or the library had not been initialized",
since = "version 3.0"
)
GLFWvidmode.const.p(
"GetVideoModes",
"""
Returns an array of all video modes supported by the specified monitor.
The returned array is sorted in ascending order, first by color bit depth (the sum of all channel depths), then by resolution area (the product of
width and height), then resolution width and finally by refresh rate.
The returned array is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified monitor is disconnected, this
function is called again for that monitor or the library is terminated.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
AutoSizeResult..int.p("count", "where to store the number of video modes in the returned array. This is set to zero if an error occurred."),
returnDoc = "an array of video modes, or #NULL if an error occurred",
since = "version 1.0"
)
GLFWvidmode.const.p(
"GetVideoMode",
"""
Returns the current video mode of the specified monitor. If you have created a full screen window for that monitor, the return value will depend on
whether that window is iconified.
The returned array is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified monitor is disconnected or the
library is terminated.
This function must only be called from the main thread.
""",
GLFWmonitor.p("monitor", "the monitor to query"),
returnDoc = "the current mode of the monitor, or #NULL if an error occurred",
since = "version 3.0"
)
void(
"SetGamma",
"""
Generates a gamma ramp and sets it for the specified monitor.
This function generates an appropriately sized gamma ramp from the specified exponent and then calls #SetGammaRamp() with it. The value must be a
finite number greater than zero.
The software controlled gamma ramp is applied <em>in addition</em> to the hardware gamma correction, which today is usually an approximation of sRGB
gamma. This means that setting a perfectly linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
For gamma correct rendering with OpenGL or OpenGL ES, see the #SRGB_CAPABLE hint.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: Gamma handling is a privileged protocol, this function will thus never be implemented and emits #PLATFORM_ERROR."
)}
""",
GLFWmonitor.p("monitor", "the monitor whose gamma ramp to set"),
float("gamma", "the desired exponent"),
since = "version 3.0"
)
GLFWgammaramp.const.p(
"GetGammaRamp",
"""
Returns the current gamma ramp of the specified monitor.
The returned structure and its arrays are allocated and freed by GLFW. You should not free them yourself. They are valid until the specified monitor is
disconnected, this function is called again for that monitor or the library is terminated.
Notes:
${ul(
"This function must only be called from the main thread.",
"""
<b>Wayland</b>: Gamma handling is a privileged protocol, this function will thus never be implemented and emits #PLATFORM_ERROR while returning
#NULL.
"""
)}
""",
GLFWmonitor.p("monitor", "the monitor to query"),
returnDoc = "the current gamma ramp, or #NULL if an error occurred",
since = "version 3.0"
)
void(
"SetGammaRamp",
"""
Sets the current gamma ramp for the specified monitor.
This function sets the current gamma ramp for the specified monitor. The original gamma ramp for that monitor is saved by GLFW the first time this
function is called and is restored by #Terminate().
The software controlled gamma ramp is applied <em>in addition</em> to the hardware gamma correction, which today is usually an approximation of sRGB
gamma. This means that setting a perfectly linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
For gamma correct rendering with OpenGL or OpenGL ES, see the #SRGB_CAPABLE hint.
${note(ul(
"This function must only be called from the main thread.",
"The size of the specified gamma ramp should match the size of the current ramp for that monitor.",
"<b>Windows</b>: The gamma ramp size must be 256.",
"<b>Wayland</b>: Gamma handling is a privileged protocol, this function will thus never be implemented and emits #PLATFORM_ERROR.",
"The specified gamma ramp is copied before this function returns."
))}
""",
GLFWmonitor.p("monitor", "the monitor whose gamma ramp to set"),
GLFWgammaramp.const.p("ramp", "the gamma ramp to use"),
since = "version 3.0"
)
void(
"DefaultWindowHints",
"""
Resets all window hints to their default values. See #WindowHint() for details.
This function must only be called from the main thread.
""",
since = "version 3.0"
)
void(
"WindowHint",
"""
Sets hints for the next call to #CreateWindow(). The hints, once set, retain their values until changed by a call to this function or
#DefaultWindowHints(), or until the library is terminated.
Only integer value hints can be set with this function. String value hints are set with #WindowHintString().
This function does not check whether the specified hint values are valid. If you set hints to invalid values this will instead be reported by the next
call to #CreateWindow().
Some hints are platform specific. These may be set on any platform but they will only affect their specific platform. Other platforms will ignore them.
Setting these hints requires no platform specific headers or functions.
<h5>Supported and default values</h5>
${table(
tr(th("Name"), th("Default value"), th("Supported values")),
tr(td("#RESIZABLE"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#VISIBLE"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#DECORATED"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#FOCUSED"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#AUTO_ICONIFY"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#FLOATING"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#MAXIMIZED"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#CENTER_CURSOR"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#TRANSPARENT_FRAMEBUFFER"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#FOCUS_ON_SHOW"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#SCALE_TO_MONITOR"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#MOUSE_PASSTHROUGH"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#RED_BITS"), td("8"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#GREEN_BITS"), td("8"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#BLUE_BITS"), td("8"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#ALPHA_BITS"), td("8"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#DEPTH_BITS"), td("24"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#STENCIL_BITS"), td("8"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#ACCUM_RED_BITS"), td("0"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#ACCUM_GREEN_BITS"), td("0"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#ACCUM_BLUE_BITS"), td("0"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#ACCUM_ALPHA_BITS"), td("0"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#AUX_BUFFERS"), td("0"), td("0 to Integer#MAX_VALUE")),
tr(td("#SAMPLES"), td("0"), td("0 to Integer#MAX_VALUE")),
tr(td("#REFRESH_RATE"), td("#DONT_CARE"), td("0 to Integer#MAX_VALUE or #DONT_CARE")),
tr(td("#STEREO"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#SRGB_CAPABLE"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#DOUBLEBUFFER"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#CLIENT_API"), td("#OPENGL_API"), td(ClientAPIValues)),
tr(td("#CONTEXT_CREATION_API"), td("#NATIVE_CONTEXT_API"), td(ContextCreationAPIValues)),
tr(td("#CONTEXT_VERSION_MAJOR"), td("1"), td("Any valid major version number of the chosen client API")),
tr(td("#CONTEXT_VERSION_MINOR"), td("0"), td("Any valid minor version number of the chosen client API")),
tr(td("#CONTEXT_ROBUSTNESS"), td("#NO_ROBUSTNESS"), td(ContextRobustnessValues)),
tr(td("#CONTEXT_RELEASE_BEHAVIOR"), td("#ANY_RELEASE_BEHAVIOR"), td(ContextReleaseBehaviorValues)),
tr(td("#CONTEXT_NO_ERROR"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#OPENGL_FORWARD_COMPAT"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#OPENGL_DEBUG_CONTEXT"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#OPENGL_PROFILE"), td("#OPENGL_ANY_PROFILE"), td(OpenGLProfileValues)),
tr(td("#WIN32_KEYBOARD_MENU"), td("#FALSE"), td("#TRUE or #FALSE")),
tr(td("#COCOA_RETINA_FRAMEBUFFER"), td("#TRUE"), td("#TRUE or #FALSE")),
tr(td("#COCOA_GRAPHICS_SWITCHING"), td("#FALSE"), td("#TRUE or #FALSE"))
)}
This function must only be called from the main thread.
""",
int(
"hint",
"the window hint to set",
"""
${WindowHints.replace(" ?#(?:ICONIFIED|HOVERED)".toRegex(), "")} ${ClientAPIHints.replace("#CONTEXT_REVISION ", "")} $PixelFormatHints #COCOA_RETINA_FRAMEBUFFER
#COCOA_GRAPHICS_SWITCHING
"""
),
int("value", "the new value of the window hint"),
since = "version 2.2"
)
void(
"WindowHintString",
"""
Sets the specified window hint to the desired value.
This function sets hints for the next call to #CreateWindow(). The hints, once set, retain their values until changed by a call to this function or
#DefaultWindowHints(), or until the library is terminated.
Only string type hints can be set with this function. Integer value hints are set with #WindowHint().
This function does not check whether the specified hint values are valid. If you set hints to invalid values this will instead be reported by the next
call to #CreateWindow().
Some hints are platform specific. These may be set on any platform but they will only affect their specific platform. Other platforms will ignore them.
Setting these hints requires no platform specific headers or functions.
<h5>Supported and default values</h5>
${table(
tr(th("Name"), th("Default value"), th("Supported values")),
tr(td("#COCOA_FRAME_NAME"), td("\"\""), td("A UTF-8 encoded frame autosave name")),
tr(td("#X11_CLASS_NAME"), td("\"\""), td("An ASCII encoded {@code WM_CLASS} class name")),
tr(td("#X11_INSTANCE_NAME"), td("\"\""), td("An ASCII encoded {@code WM_CLASS} instance name")),
tr(td("#WAYLAND_APP_ID"), td("\"\""), td("An ASCII encoded Wayland {@code app_id} name"))
)}
This function must only be called from the main thread.
""",
int("hint", "the window hint to set", "#COCOA_FRAME_NAME #X11_CLASS_NAME #X11_INSTANCE_NAME #WAYLAND_APP_ID"),
charUTF8.const.p("value", "the new value of the window hint. The specified string is copied before this function returns."),
since = "version 3.3"
)
GLFWwindow.p(
"CreateWindow",
"""
Creates a window and its associated OpenGL or OpenGL ES context. Most of the options controlling how the window and its context should be created are
specified with window hints.
Successful creation does not change which context is current. Before you can use the newly created context, you need to make it current. For information
about the {@code share} parameter, see ${url("http://www.glfw.org/docs/latest/context.html\\#context_sharing", "context sharing")}.
The created window, framebuffer and context may differ from what you requested, as not all parameters and hints are hard constraints. This includes the
size of the window, especially for full screen windows. To query the actual attributes of the created window, framebuffer and context, use queries like
#GetWindowAttrib() and #GetWindowSize() and #GetFramebufferSize().
To create a full screen window, you need to specify the monitor the window will cover. If no monitor is specified, the window will be windowed mode.
Unless you have a way for the user to choose a specific monitor, it is recommended that you pick the primary monitor. For more information on how to
query connected monitors, see ${url("http://www.glfw.org/docs/latest/monitor.html\\#monitor_monitors", "monitors")}.
For full screen windows, the specified size becomes the resolution of the window's <i>desired video mode</i>. As long as a full screen window is not
iconified, the supported video mode most closely matching the desired video mode is set for the specified monitor. For more information about full
screen windows, including the creation of so called <i>windowed full screen</i> or <i>borderless full screen</i> windows, see
${url("http://www.glfw.org/docs/latest/window.html\\#window_windowed_full_screen", "full screen")}.
Once you have created the window, you can switch it between windowed and full screen mode with #SetWindowMonitor(). If the window has an OpenGL or
OpenGL ES context, it will be unaffected.
By default, newly created windows use the placement recommended by the window system. To create the window at a specific position, set the #POSITION_X
and #POSITION_Y window hints before creation. To restore the default behavior, set either or both hints back to #ANY_POSITION.
As long as at least one full screen window is not iconified, the screensaver is prohibited from starting.
Window systems put limits on window sizes. Very large or very small window dimensions may be overridden by the window system on creation. Check the
actual ${url("http://www.glfw.org/docs/latest/window.html\\#window_size", "size")} after creation.
The ${url("http://www.glfw.org/docs/latest/window.html\\#buffer_swap", "swap interval")} is not set during window creation and the initial value may vary
depending on driver settings and defaults.
${note(ul(
"This function must only be called from the main thread.",
"<b>Windows</b>: Window creation will fail if the Microsoft GDI software OpenGL implementation is the only one available.",
"""
<b>Windows</b>: If the executable has an icon resource named {@code GLFW_ICON}, it will be set as the initial icon for the window. If no such icon
is present, the {@code IDI_APPLICATION} icon will be used instead. To set a different icon, see #SetWindowIcon().
""",
"<b>Windows</b>: The context to share resources with may not be current on any other thread.",
"""
The OS only supports core profile contexts for OpenGL versions 3.2 and later. Before creating an OpenGL context of version 3.2 or later you must
set the #OPENGL_PROFILE hint accordingly. OpenGL 3.0 and 3.1 contexts are not supported at all on macOS.
""",
"""
<b>macOS</b>: The GLFW window has no icon, as it is not a document window, but the dock icon will be the same as the application bundle's icon. For
more information on bundles, see the
${url("https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/", "Bundle Programming Guide")} in the Mac
Developer Library.
""",
"""
<b>macOS</b>: On macOS 10.10 and later the window frame will not be rendered at full resolution on Retina displays unless the
#COCOA_RETINA_FRAMEBUFFER hint is #TRUE and the {@code NSHighResolutionCapable} key is enabled in the application bundle's {@code Info.plist}. For
more information, see ${url(
"https://developer.apple.com/library/content/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html",
"High Resolution Guidelines for macOS")
} in the Mac Developer Library.
""",
"""
<b>macOS</b>: When activating frame autosaving with #COCOA_FRAME_NAME, the specified window size and position may be overridden by previously saved
values.
""",
"<b>X11</b>: Some window managers will not respect the placement of initially hidden windows.",
"""
<b>X11</b>: Due to the asynchronous nature of X11, it may take a moment for a window to reach its requested state. This means you may not be able
to query the final size, position or other attributes directly after window creation.
""",
"""
<b>X11</b>: The class part of the {@code WM_CLASS} window property will by default be set to the window title passed to this function. The instance
part will use the contents of the {@code RESOURCE_NAME} environment variable, if present and not empty, or fall back to the window title. Set the
#X11_CLASS_NAME and #X11_INSTANCE_NAME window hints to override this.
""",
"""
<b>Wayland</b>: Compositors should implement the xdg-decoration protocol for GLFW to decorate the window properly. If this protocol isn't
supported, or if the compositor prefers client-side decorations, a very simple fallback frame will be drawn using the {@code wp_viewporter}
protocol. A compositor can still emit close, maximize or fullscreen events, using for instance a keybind mechanism. If neither of these protocols
is supported, the window won't be decorated.
""",
"<b>Wayland</b>: A full screen window will not attempt to change the mode, no matter what the requested size or refresh rate.",
"<b>Wayland</b>: Screensaver inhibition requires the idle-inhibit protocol to be implemented in the user's compositor."
))}
""",
int("width", "the desired width, in screen coordinates, of the window"),
int("height", "the desired height, in screen coordinates, of the window"),
charUTF8.const.p("title", "initial, UTF-8 encoded window title"),
nullable..GLFWmonitor.p("monitor", "the monitor to use for fullscreen mode, or #NULL for windowed mode"),
nullable..GLFWwindow.p("share", " the window whose context to share resources with, or #NULL to not share resources"),
returnDoc = "the handle of the created window, or #NULL if an error occurred",
since = "version 1.0"
)
void(
"DestroyWindow",
"""
Destroys the specified window and its context. On calling this function, no further callbacks will be called for that window.
If the context of the specified window is current on the main thread, it is detached before being destroyed.
${note(ul(
"This function must only be called from the main thread.",
"This function must not be called from a callback.",
"The context of the specified window must not be current on any other thread when this function is called."
))}
""",
nullable..GLFWwindow.p("window", "the window to destroy"),
since = "version 1.0"
)
intb(
"WindowShouldClose",
"""
Returns the value of the close flag of the specified window.
This function may be called from any thread.
""",
GLFWwindow.p("window", "the window to query"),
returnDoc = "the value of the close flag",
since = "version 3.0"
)
void(
"SetWindowShouldClose",
"""
Sets the value of the close flag of the specified window. This can be used to override the user's attempt to close the window, or to signal that it
should be closed.
This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", "the window whose flag to change"),
intb("value", "the new value"),
since = "version 3.0"
)
void(
"SetWindowTitle",
"""
Sets the window title, encoded as UTF-8, of the specified window.
This function must only be called from the main thread.
<b>macOS</b>: The window title will not be updated until the next time you process events.
""",
GLFWwindow.p("window", "the window whose title to change"),
charUTF8.const.p("title", "the UTF-8 encoded window title"),
since = "version 1.0"
)
void(
"SetWindowIcon",
"""
Sets the icon for the specified window.
This function sets the icon of the specified window. If passed an array of candidate images, those of or closest to the sizes desired by the system are
selected. If no images are specified, the window reverts to its default icon.
The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with the red channel first. They are arranged canonically as
packed sequential rows, starting from the top-left corner.
The desired image sizes varies depending on platform and system settings. The selected images will be rescaled as needed. Good sizes include 16x16,
32x32 and 48x48.
Notes:
${ul(
"This function must only be called from the main thread.",
"The specified image data is copied before this function returns.",
"""
<b>macOS</b>: Regular windows do not have icons on macOS. This function will emit #FEATURE_UNAVAILABLE. The dock icon will be the same as the
application bundle's icon. For more information on bundles, see the ${url(
"https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/",
"Bundle Programming Guide")} in the Mac Developer Library.
""",
"""
<b>Wayland</b>: There is no existing protocol to change an icon, the window will thus inherit the one defined in the application's desktop file.
This function will emit #FEATURE_UNAVAILABLE.
"""
)}
""",
GLFWwindow.p("window", "the window whose icon to set"),
AutoSize("images")..int("count", "the number of images in the specified array, or zero to revert to the default window icon"),
nullable..GLFWimage.const.p("images", "the images to create the icon from. This is ignored if count is zero."),
since = "version 3.2"
)
void(
"GetWindowPos",
"""
Retrieves the position, in screen coordinates, of the upper-left corner of the content area of the specified window.
Any or all of the position arguments may be #NULL. If an error occurs, all non-#NULL position arguments will be set to zero.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: There is no way for an application to retrieve the global position of its windows. This function will emit #FEATURE_UNAVAILABLE."
)}
""",
GLFWwindow.p("window", "the window to query"),
nullable..Check(1)..int.p("xpos", "where to store the x-coordinate of the upper-left corner of the content area, or #NULL"),
nullable..Check(1)..int.p("ypos", "where to store the y-coordinate of the upper-left corner of the content area, or #NULL"),
since = "version 3.0"
)
void(
"SetWindowPos",
"""
Sets the position, in screen coordinates, of the upper-left corner of the content area of the specified windowed mode window. If the window is a full
screen window, this function does nothing.
<b>Do not use this function</b> to move an already visible window unless you have very good reasons for doing so, as it will confuse and annoy the
user.
The window manager may put limits on what positions are allowed. GLFW cannot and should not override these limits.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: There is no way for an application to set the global position of its windows. This function will emit #FEATURE_UNAVAILABLE."
)}
""",
GLFWwindow.p("window", "the window to query"),
int("xpos", "the x-coordinate of the upper-left corner of the content area"),
int("ypos", "the y-coordinate of the upper-left corner of the content area"),
since = "version 1.0"
)
void(
"GetWindowSize",
"""
Retrieves the size, in screen coordinates, of the content area of the specified window. If you wish to retrieve the size of the framebuffer of the
window in pixels, see #GetFramebufferSize().
Any or all of the size arguments may be #NULL. If an error occurs, all non-#NULL size arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose size to retrieve"),
nullable..Check(1)..int.p("width", "where to store the width, in screen coordinates, of the content area, or #NULL"),
nullable..Check(1)..int.p("height", "where to store the height, in screen coordinates, of the content area, or #NULL"),
since = "version 1.0"
)
void(
"SetWindowSizeLimits",
"""
Sets the size limits of the content area of the specified window. If the window is full screen, the size limits only take effect if once it is made
windowed. If the window is not resizable, this function does nothing.
The size limits are applied immediately to a windowed mode window and may cause it to be resized.
The maximum dimensions must be greater than or equal to the minimum dimensions and all must be greater than or equal to zero.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: The size limits will not be applied until the window is actually resized, either by the user or by the compositor."
)}
""",
GLFWwindow.p("window", "the window to set limits for"),
int("minwidth", "the minimum width, in screen coordinates, of the content area, or #DONT_CARE"),
int("minheight", "the minimum height, in screen coordinates, of the content area, or #DONT_CARE"),
int("maxwidth", "the maximum width, in screen coordinates, of the content area, or #DONT_CARE"),
int("maxheight", "the maximum height, in screen coordinates, of the content area, or #DONT_CARE"),
since = "version 3.2"
)
void(
"SetWindowAspectRatio",
"""
Sets the required aspect ratio of the content area of the specified window. If the window is full screen, the aspect ratio only takes effect once it is
made windowed. If the window is not resizable, this function does nothing.
The aspect ratio is specified as a numerator and a denominator and both values must be greater than zero. For example, the common 16:9 aspect ratio is
specified as 16 and 9, respectively.
If the numerator and denominator is set to #DONT_CARE then the aspect ratio limit is disabled.
The aspect ratio is applied immediately to a windowed mode window and may cause it to be resized.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: The aspect ratio will not be applied until the window is actually resized, either by the user or by the compositor."
)}
""",
GLFWwindow.p("window", "the window to set limits for"),
int("numer", "the numerator of the desired aspect ratio, or #DONT_CARE"),
int("denom", "the denominator of the desired aspect ratio, or #DONT_CARE"),
since = "version 3.2"
)
void(
"SetWindowSize",
"""
Sets the size, in pixels, of the content area of the specified window.
For full screen windows, this function updates the resolution of its desired video mode and switches to the video mode closest to it, without affecting
the window's context. As the context is unaffected, the bit depths of the framebuffer remain unchanged.
If you wish to update the refresh rate of the desired video mode in addition to its resolution, see #SetWindowMonitor().
The window manager may put limits on what sizes are allowed. GLFW cannot and should not override these limits.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: A full screen window will not attempt to change the mode, no matter what the requested size."
)}
""",
GLFWwindow.p("window", "the window to resize"),
int("width", "the desired width, in screen coordinates, of the window content area"),
int("height", "the desired height, in screen coordinates, of the window content area"),
since = "version 1.0"
)
void(
"GetFramebufferSize",
"""
Retrieves the size, in pixels, of the framebuffer of the specified window. If you wish to retrieve the size of the window in screen coordinates, see
#GetWindowSize().
Any or all of the size arguments may be #NULL. If an error occurs, all non-#NULL size arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose framebuffer to query"),
nullable..Check(1)..int.p("width", "where to store the width, in pixels, of the framebuffer, or #NULL"),
nullable..Check(1)..int.p("height", "where to store the height, in pixels, of the framebuffer, or #NULL"),
since = "version 3.0"
)
void(
"GetWindowFrameSize",
"""
Retrieves the size, in screen coordinates, of each edge of the frame of the specified window. This size includes the title bar, if the window has one.
The size of the frame may vary depending on the ${url("http://www.glfw.org/docs/latest/window.html\\#window-hints_wnd", "window-related hints")} used to
create it.
Because this function retrieves the size of each window frame edge and not the offset along a particular coordinate axis, the retrieved values will
always be zero or positive.
Any or all of the size arguments may be #NULL. If an error occurs, all non-#NULL size arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose frame size to query"),
Check(1)..nullable..int.p("left", "where to store the size, in screen coordinates, of the left edge of the window frame, or #NULL"),
Check(1)..nullable..int.p("top", "where to store the size, in screen coordinates, of the top edge of the window frame, or #NULL"),
Check(1)..nullable..int.p("right", "where to store the size, in screen coordinates, of the right edge of the window frame, or #NULL"),
Check(1)..nullable..int.p("bottom", "where to store the size, in screen coordinates, of the bottom edge of the window frame, or #NULL"),
since = "version 3.1"
)
void(
"GetWindowContentScale",
"""
Retrieves the content scale for the specified window.
This function retrieves the content scale for the specified window. The content scale is the ratio between the current DPI and the platform's default
DPI. This is especially important for text and any UI elements. If the pixel dimensions of your UI scaled by this look appropriate on your machine then
it should appear at a reasonable size on other machines regardless of their DPI and scaling settings. This relies on the system DPI and scaling
settings being somewhat correct.
On platforms where each monitor can have its own content scale, the window content scale will depend on which monitor the system considers the window
to be on.
""",
GLFWwindow.p("window", "the window to query"),
nullable..Check(1)..float.p("xscale", "where to store the x-axis content scale, or #NULL"),
nullable..Check(1)..float.p("yscale", "where to store the y-axis content scale, or #NULL"),
since = "version 3.3"
)
float(
"GetWindowOpacity",
"""
Returns the opacity of the whole window.
This function returns the opacity of the window, including any decorations.
The opacity (or alpha) value is a positive finite number between zero and one, where zero is fully transparent and one is fully opaque. If the system
does not support whole window transparency, this function always returns one.
The initial opacity value for newly created windows is one.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to query"),
returnDoc = "the opacity value of the specified window",
since = "version 3.3"
)
void(
"SetWindowOpacity",
"""
Sets the opacity of the whole window.
This function sets the opacity of the window, including any decorations.
The opacity (or alpha) value is a positive finite number between zero and one, where zero is fully transparent and one is fully opaque.
The initial opacity value for newly created windows is one.
A window created with framebuffer transparency may not use whole window transparency. The results of doing this are undefined.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: There is no way to set an opacity factor for a window. This function will emit #FEATURE_UNAVAILABLE."
)}
""",
GLFWwindow.p("window", "the window to set the opacity for"),
float("opacity", "the desired opacity of the specified window"),
since = "version 3.3"
)
void(
"IconifyWindow",
"""
Iconifies (minimizes) the specified window if it was previously restored. If the window is already iconified, this function does nothing.
If the specified window is a full screen window, GLFW restores the original video mode of the monitor. The window's desired video mode is set again
when the window is restored.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: Once a window is iconified, #RestoreWindow() won’t be able to restore it. This is a design decision of the {@code xdg-shell}."
)}
""",
GLFWwindow.p("window", "the window to iconify"),
since = "version 2.1"
)
void(
"RestoreWindow",
"""
Restores the specified window if it was previously iconified (minimized) or maximized. If the window is already restored, this function does nothing.
If the specified window is an iconified full screen window, its desired video mode is set again for its monitor when the window is restored.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to restore"),
since = "version 2.1"
)
void(
"MaximizeWindow",
"""
Maximizes the specified window if it was previously not maximized. If the window is already maximized, this function does nothing.
If the specified window is a full screen window, this function does nothing.
This function may only be called from the main thread.
""",
GLFWwindow.p("window", "the window to maximize"),
since = "version 3.2"
)
void(
"ShowWindow",
"""
Makes the specified window visible if it was previously hidden. If the window is already visible or is in full screen mode, this function does nothing.
By default, windowed mode windows are focused when shown. Set the #FOCUS_ON_SHOW window hint to change this behavior for all newly created windows, or
change the behavior for an existing window with #SetWindowAttrib().
Notes:
${ul(
"This function must only be called from the main thread.",
"""
<b>Wayland</b>: Because Wayland wants every frame of the desktop to be complete, this function does not immediately make the window visible.
Instead it will become visible the next time the window framebuffer is updated after this call.
"""
)}
""",
GLFWwindow.p("window", "the window to make visible"),
since = "version 3.0"
)
void(
"HideWindow",
"""
Hides the specified window, if it was previously visible. If the window is already hidden or is in full screen mode, this function does nothing.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to hide"),
since = "version 3.0"
)
void(
"FocusWindow",
"""
Brings the specified window to front and sets input focus. The window should already be visible and not iconified.
By default, both windowed and full screen mode windows are focused when initially created. Set the #FOCUSED hint to disable this behavior.
Also by default, windowed mode windows are focused when shown with #ShowWindow(). Set the #FOCUS_ON_SHOW window hint to disable this behavior.
<b>Do not use this function</b> to steal focus from other applications unless you are certain that is what the user wants. Focus stealing can be
extremely disruptive.
For a less disruptive way of getting the user's attention, see #RequestWindowAttention().
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: It is not possible for an application to set the input focus. This function will emit #FEATURE_UNAVAILABLE."
)}
""",
GLFWwindow.p("window", "the window to give input focus"),
since = "version 3.2"
)
void(
"RequestWindowAttention",
"""
Requests user attention to the specified window.
This function requests user attention to the specified window. On platforms where this is not supported, attention is requested to the application as
a whole.
Once the user has given attention, usually by focusing the window or application, the system will end the request automatically.
${note(ul(
"This function must only be called from the main thread.",
"<b>macOS:</b> Attention is requested to the application as a whole, not the specific window."
))}
""",
GLFWwindow.p("window", "the window to request attention to"),
since = "version 3.3"
)
GLFWmonitor.p(
"GetWindowMonitor",
"""
Returns the handle of the monitor that the specified window is in full screen on.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to query"),
returnDoc = "the monitor, or #NULL if the window is in windowed mode or an error occurred",
since = "version 3.0"
)
void(
"SetWindowMonitor",
"""
Sets the mode, monitor, video mode and placement of a window.
This function sets the monitor that the window uses for full screen mode or, if the monitor is #NULL, makes it windowed mode.
When setting a monitor, this function updates the width, height and refresh rate of the desired video mode and switches to the video mode closest to
it. The window position is ignored when setting a monitor.
When the monitor is #NULL, the position, width and height are used to place the window content area. The refresh rate is ignored when no monitor is
specified.
If you only wish to update the resolution of a full screen window or the size of a windowed mode window, see #SetWindowSize().
When a window transitions from full screen to windowed mode, this function restores any previous window settings such as whether it is decorated,
floating, resizable, has size or aspect ratio limits, etc.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: The desired window position is ignored, as there is no way for an application to set this property.",
"<b>Wayland</b>: Setting the window to full screen will not attempt to change the mode, no matter what the requested size or refresh rate."
)}
""",
GLFWwindow.p("window", "the window whose monitor, size or video mode to set"),
nullable..GLFWmonitor.p("monitor", "the desired monitor, or #NULL to set windowed mode"),
int("xpos", "the desired x-coordinate of the upper-left corner of the content area"),
int("ypos", "the desired y-coordinate of the upper-left corner of the content area"),
int("width", "the desired with, in screen coordinates, of the content area or video mode"),
int("height", "the desired height, in screen coordinates, of the content area or video mode"),
int("refreshRate", "the desired refresh rate, in Hz, of the video mode, or #DONT_CARE"),
since = "version 3.2"
)
int(
"GetWindowAttrib",
"""
Returns the value of an attribute of the specified window or its OpenGL or OpenGL ES context.
This function must only be called from the main thread.
Framebuffer related hints are not window attributes.
Zero is a valid value for many window and context related attributes so you cannot use a return value of zero as an indication of errors. However, this
function should not fail as long as it is passed valid arguments and the library has been initialized.
<b>Wayland</b>: The Wayland protocol provides no way to check whether a window is iconfied, so #ICONIFIED always returns #FALSE.
""",
GLFWwindow.p("window", "the window to query"),
int(
"attrib",
"the <a href=\"http://www.glfw.org/docs/latest/window.html\\#window_attribs\">window attribute</a> whose value to return",
"${WindowHints.replace("#AUTO_ICONIFY ", "")} ${ClientAPIHints.replace("GLFW#(CONTEXT_RELEASE_BEHAVIOR|CONTEXT_NO_ERROR) ", "")}"
),
returnDoc = "the value of the attribute, or zero if an error occurred",
since = "version 3.0"
)
void(
"SetWindowAttrib",
"""
Sets an attribute of the specified window.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to set the attribute for"),
int(
"attrib",
"""
the attribute to set.
Some of these attributes are ignored for full screen windows. The new value will take effect if the window is later made windowed.
Some of these attributes are ignored for windowed mode windows. The new value will take effect if the window is later made full screen.
Calling #GetWindowAttrib() will always return the latest value, even if that value is ignored by the current mode of the window.
""",
"#DECORATED #RESIZABLE #FLOATING #AUTO_ICONIFY #FOCUS_ON_SHOW #MOUSE_PASSTHROUGH"
),
int("value", "the value to set"),
since = "version 3.3"
)
void(
"SetWindowUserPointer",
"""
Sets the user-defined pointer of the specified window. The current value is retained until the window is destroyed. The initial value is #NULL.
This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", "the window whose pointer to set"),
nullable..opaque_p("pointer", "the new value"),
since = "version 3.0"
)
opaque_p(
"GetWindowUserPointer",
"""
Returns the current value of the user-defined pointer of the specified window. The initial value is #NULL.
This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", "the window whose pointer to return"),
since = "version 3.0"
)
val CallbackReturnDoc =
"""
the previously set callback, or #NULL if no callback was set or the library had not been
${url("http://www.glfw.org/docs/latest/intro.html\\#intro_init", "initialized")}
"""
val CALLBACK_WINDOW = GLFWwindow.p("window", "the window whose callback to set")
GLFWwindowposfun(
"SetWindowPosCallback",
"""
Sets the position callback of the specified window, which is called when the window is moved. The callback is provided with the position, in screen
coordinates, of the upper-left corner of the content area of the window.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: This callback will never be called, as there is no way for an application to know its global position."
)}
""",
CALLBACK_WINDOW,
nullable..GLFWwindowposfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 1.0"
)
GLFWwindowsizefun(
"SetWindowSizeCallback",
"""
Sets the size callback of the specified window, which is called when the window is resized. The callback is provided with the size, in screen
coordinates, of the content area of the window.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowsizefun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 1.0"
)
GLFWwindowclosefun(
"SetWindowCloseCallback",
"""
Sets the close callback of the specified window, which is called when the user attempts to close the window, for example by clicking the close widget in
the title bar.
The close flag is set before this callback is called, but you can modify it at any time with #SetWindowShouldClose().
The close callback is not triggered by #DestroyWindow().
${note(ul(
"This function must only be called from the main thread.",
"<b>macOS:</b> Selecting Quit from the application menu will trigger the close callback for all windows."
))}
""",
CALLBACK_WINDOW,
nullable..GLFWwindowclosefun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 2.5"
)
GLFWwindowrefreshfun(
"SetWindowRefreshCallback",
"""
Sets the refresh callback of the specified window, which is called when the content area of the window needs to be redrawn, for example if the window has
been exposed after having been covered by another window.
On compositing window systems such as Aero, Compiz or Aqua, where the window contents are saved off-screen, this callback may be called only very
infrequently or never at all.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowrefreshfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 2.5"
)
GLFWwindowfocusfun(
"SetWindowFocusCallback",
"""
Sets the focus callback of the specified window, which is called when the window gains or loses input focus.
After the focus callback is called for a window that lost input focus, synthetic key and mouse button release events will be generated for all such
that had been pressed. For more information, see #SetKeyCallback() and #SetMouseButtonCallback().
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowfocusfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 3.0"
)
GLFWwindowiconifyfun(
"SetWindowIconifyCallback",
"""
Sets the iconification callback of the specified window, which is called when the window is iconified or restored.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowiconifyfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 3.0"
)
GLFWwindowmaximizefun(
"SetWindowMaximizeCallback",
"""
Sets the maximization callback of the specified window, which is called when the window is maximized or restored.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowmaximizefun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 3.3"
)
GLFWframebuffersizefun(
"SetFramebufferSizeCallback",
"""
Sets the framebuffer resize callback of the specified window, which is called when the framebuffer of the specified window is resized.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWframebuffersizefun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 3.0"
)
GLFWwindowcontentscalefun(
"SetWindowContentScaleCallback",
"""
Sets the window content scale callback for the specified window, which is called when the content scale of the specified window changes.
This function must only be called from the main thread.
""",
CALLBACK_WINDOW,
nullable..GLFWwindowcontentscalefun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = CallbackReturnDoc,
since = "version 3.3"
)
void(
"PollEvents",
"""
Processes all pending events.
This function processes only those events that are already in the event queue and then returns immediately. Processing events will cause the window and
input callbacks associated with those events to be called.
On some platforms, a window move, resize or menu operation will cause event processing to block. This is due to how event processing is designed on
those platforms. You can use the ${url("http://www.glfw.org/docs/latest/window.html\\#window_refresh", "window refresh callback")} to redraw the
contents of your window when necessary during such operations.
On some platforms, certain events are sent directly to the application without going through the event queue, causing callbacks to be called outside of
a call to one of the event processing functions.
Event processing is not required for joystick input to work.
${note(ul(
"This function must only be called from the main thread.",
"This function must not be called from a callback."
))}
""",
since = "version 1.0"
)
void(
"WaitEvents",
"""
Waits until events are queued and processes them.
This function puts the calling thread to sleep until at least one event is available in the event queue. Once one or more events are available, it
behaves exactly like #PollEvents(), i.e. the events in the queue are processed and the function then returns immediately. Processing events will cause
the window and input callbacks associated with those events to be called.
Since not all events are associated with callbacks, this function may return without a callback having been called even if you are monitoring all
callbacks.
On some platforms, a window move, resize or menu operation will cause event processing to block. This is due to how event processing is designed on
those platforms. You can use the ${url("http://www.glfw.org/docs/latest/window.html\\#window_refresh", "window refresh callback")} to redraw the
contents of your window when necessary during such operations.
On some platforms, certain callbacks may be called outside of a call to one of the event processing functions.
Event processing is not required for joystick input to work.
${note(ul(
"This function must only be called from the main thread.",
"This function must not be called from a callback."
))}
""",
since = "version 2.5"
)
void(
"WaitEventsTimeout",
"""
Waits with timeout until events are queued and processes them.
This function puts the calling thread to sleep until at least one event is available in the event queue, or until the specified timeout is reached. If
one or more events are available, it behaves exactly like #PollEvents(), i.e. the events in the queue are processed and the function then returns
immediately. Processing events will cause the window and input callbacks associated with those events to be called.
The timeout value must be a positive finite number.
Since not all events are associated with callbacks, this function may return without a callback having been called even if you are monitoring all
callbacks.
On some platforms, a window move, resize or menu operation will cause event processing to block. This is due to how event processing is designed on
those platforms. You can use the window refresh callback to redraw the contents of your window when necessary during such operations.
On some platforms, certain callbacks may be called outside of a call to one of the event processing functions.
Event processing is not required for joystick input to work.
${note(ul(
"This function must only be called from the main thread.",
"This function must not be called from a callback."
))}
""",
double("timeout", "the maximum amount of time, in seconds, to wait"),
since = "version 3.2"
)
void(
"PostEmptyEvent",
"""
Posts an empty event from the current thread to the main thread event queue, causing #WaitEvents() or #WaitEventsTimeout() to return.
This function may be called from any thread.
""",
since = "version 3.1"
)
int(
"GetInputMode",
"""
Returns the value of an input option for the specified window.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to query"),
int("mode", "the input mode whose value to return", InputModes),
returnDoc = "the input mode value",
since = "version 3.0"
)
void(
"SetInputMode",
"""
Sets an input option for the specified window.
If {@code mode} is #CURSOR, the value must be one of the following cursor modes:
${ul(
"#CURSOR_NORMAL makes the cursor visible and behaving normally.",
"#CURSOR_HIDDEN makes the cursor invisible when it is over the content area of the window but does not restrict the cursor from leaving.",
"""
#CURSOR_DISABLED hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful for implementing for example 3D camera
controls.
""",
"#CURSOR_CAPTURED makes the cursor visible and confines it to the content area of the window."
)}
If the {@code mode} is #STICKY_KEYS, the value must be either #TRUE to enable sticky keys, or #FALSE to disable it. If sticky keys are enabled, a key
press will ensure that #GetKey() returns #PRESS the next time it is called even if the key had been released before the call. This is useful when you
are only interested in whether keys have been pressed but not when or in which order.
If the {@code mode} is #STICKY_MOUSE_BUTTONS, the value must be either #TRUE to enable sticky mouse buttons, or #FALSE to disable it. If sticky mouse
buttons are enabled, a mouse button press will ensure that #GetMouseButton() returns #PRESS the next time it is called even if the mouse button had
been released before the call. This is useful when you are only interested in whether mouse buttons have been pressed but not when or in which order.
If the {@code mode} is #LOCK_KEY_MODS, the value must be either #TRUE to enable lock key modifier bits, or #FALSE to disable them. If enabled,
callbacks that receive modifier bits will also have the #MOD_CAPS_LOCK bit set when the event was generated with Caps Lock on, and the #MOD_NUM_LOCK
bit when Num Lock was on.
If the mode is #RAW_MOUSE_MOTION, the value must be either #TRUE to enable raw (unscaled and unaccelerated) mouse motion when the cursor is disabled,
or #FALSE to disable it. If raw motion is not supported, attempting to set this will emit #FEATURE_UNAVAILABLE. Call #RawMouseMotionSupported() to
check for support.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose input mode to set"),
int("mode", "the input mode to set", "#CURSOR #STICKY_KEYS #STICKY_MOUSE_BUTTONS"),
int("value", "the new value of the specified input mode"),
since = "GFLW 3.0"
)
intb(
"RawMouseMotionSupported",
"""
Returns whether raw mouse motion is supported.
This function returns whether raw mouse motion is supported on the current system. This status does not change after GLFW has been initialized so you
only need to check this once. If you attempt to enable raw motion on a system that does not support it, #PLATFORM_ERROR will be emitted.
Raw mouse motion is closer to the actual motion of the mouse across a surface. It is not affected by the scaling and acceleration applied to the motion
of the desktop cursor. That processing is suitable for a cursor while raw motion is better for controlling for example a 3D camera. Because of this,
raw mouse motion is only provided when the cursor is disabled.
This function must only be called from the main thread.
""",
void(),
returnDoc = "#TRUE if raw mouse motion is supported on the current machine, or #FALSE otherwise",
since = "version 3.3"
)
charUTF8.const.p(
"GetKeyName",
"""
Returns the layout-specific name of the specified printable key.
This function returns the name of the specified printable key, encoded as UTF-8. This is typically the character that key would produce without any
modifier keys, intended for displaying key bindings to the user. For dead keys, it is typically the diacritic it would add to a character.
<b>Do not use this function</b> for text input. You will break text input for many languages even if it happens to work for yours.
If the key is #KEY_UNKNOWN, the scancode is used to identify the key, otherwise the scancode is ignored. If you specify a non-printable key, or
#KEY_UNKNOWN and a scancode that maps to a non-printable key, this function returns #NULL but does not emit an error.
This behavior allows you to always pass in the arguments in the key callback without modification.
The printable keys are:
${ul(
"#KEY_APOSTROPHE",
"#KEY_COMMA",
"#KEY_MINUS",
"#KEY_PERIOD",
"#KEY_SLASH",
"#KEY_SEMICOLON",
"#KEY_EQUAL",
"#KEY_LEFT_BRACKET",
"#KEY_RIGHT_BRACKET",
"#KEY_BACKSLASH",
"#KEY_WORLD_1",
"#KEY_WORLD_2",
"#KEY_0 to #KEY_9",
"#KEY_A to #KEY_Z",
"#KEY_KP_0 to #KEY_KP_9",
"#KEY_KP_DECIMAL",
"#KEY_KP_DIVIDE",
"#KEY_KP_MULTIPLY",
"#KEY_KP_SUBTRACT",
"#KEY_KP_ADD",
"#KEY_KP_EQUAL"
)}
Names for printable keys depend on keyboard layout, while names for non-printable keys are the same across layouts but depend on the application
language and should be localized along with other user interface text.
The contents of the returned string may change when a keyboard layout change event is received.
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the library is terminated.
This function must only be called from the main thread.
""",
int("key", "the key to query, or #KEY_UNKNOWN"),
int("scancode", "the scancode of the key to query"),
returnDoc = "the UTF-8 encoded, layout-specific name of the key, or #NULL",
since = "version 3.2"
)
int(
"GetKeyScancode",
"""
Returns the platform dependent scancode of the specified key.
This function returns the platform dependent scancode of the specified key. This is intended for platform specific default keybindings.
If the key is #KEY_UNKNOWN or does not exist on the keyboard this method will return {@code -1}.
This function may be called from any thread.
""",
int("key", "the key to query, or #KEY_UNKNOWN"),
returnDoc = "the platform dependent scancode for the key, or {@code -1} if an errror occurred",
since = "version 3.3"
)
int(
"GetKey",
"""
Returns the last state reported for the specified key to the specified window. The returned state is one of #PRESS or #RELEASE. The action #REPEAT is
only reported to the key callback.
If the #STICKY_KEYS input mode is enabled, this function returns #PRESS the first time you call it for a key that was pressed, even if that
key has already been released.
The key functions deal with physical keys, with key tokens named after their use on the standard US keyboard layout. If you want to input text, use the
Unicode character callback instead.
The modifier key bit masks are not key tokens and cannot be used with this function.
<b>Do not use this function</b> to implement ${url("http://www.glfw.org/docs/latest/input.html\\#input_char", "text input")}.
${note(ul(
"This function must only be called from the main thread.",
"#KEY_UNKNOWN is not a valid key for this function."
))}
""",
GLFWwindow.p("window", "the desired window"),
int("key", "the desired keyboard key"),
returnDoc = "one of #PRESS or #RELEASE",
since = "version 1.0"
)
int(
"GetMouseButton",
"""
Returns the last state reported for the specified mouse button to the specified window. The returned state is one of #PRESS or #RELEASE. The
higher-level action #REPEAT is only reported to the mouse button callback.
If the #STICKY_MOUSE_BUTTONS input mode is enabled, this function returns #PRESS the first time you call it for a mouse button that was pressed, even
if that mouse button has already been released.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the desired window"),
int("button", "the desired mouse button"),
returnDoc = "one of #PRESS or #RELEASE",
since = "version 1.0"
)
void(
"GetCursorPos",
"""
Returns the position of the cursor, in screen coordinates, relative to the upper-left corner of the content area of the specified window.
If the cursor is disabled (with #CURSOR_DISABLED) then the cursor position is unbounded and limited only by the minimum and maximum values of a
<b>double</b>.
The coordinates can be converted to their integer equivalents with the Math#floor() function. Casting directly to an integer type works for positive
coordinates, but fails for negative ones.
Any or all of the position arguments may be #NULL. If an error occurs, all non-#NULL position arguments will be set to zero.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the desired window"),
nullable..Check(1)..double.p("xpos", "where to store the cursor x-coordinate, relative to the left edge of the content area, or #NULL"),
nullable..Check(1)..double.p("ypos", "where to store the cursor y-coordinate, relative to the to top edge of the content area, or #NULL."),
since = "version 1.0"
)
void(
"SetCursorPos",
"""
Sets the position, in screen coordinates, of the cursor relative to the upper-left corner of the content area of the specified window. The window must
have input focus. If the window does not have input focus when this function is called, it fails silently.
<b>Do not use this function</b> to implement things like camera controls. GLFW already provides the #CURSOR_DISABLED cursor mode that hides the cursor,
transparently re-centers it and provides unconstrained cursor motion. See #SetInputMode() for more information.
If the cursor mode is #CURSOR_DISABLED then the cursor position is unconstrained and limited only by the minimum and maximum values of <b>double</b>.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: This function will only work when the cursor mode is #CURSOR_DISABLED, otherwise it will do nothing."
)}
""",
GLFWwindow.p("window", "the desired window"),
double("xpos", "the desired x-coordinate, relative to the left edge of the content area"),
double("ypos", "the desired y-coordinate, relative to the top edge of the content area"),
since = "version 1.0"
)
GLFWcursor.p(
"CreateCursor",
"""
Creates a new custom cursor image that can be set for a window with #SetCursor(). The cursor can be destroyed with #DestroyCursor(). Any remaining
cursors are destroyed by #Terminate().
The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with the red channel first. They are arranged canonically as
packed sequential rows, starting from the top-left corner.
The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. Like all other coordinate systems in GLFW, the X-axis
points to the right and the Y-axis points down.
${note(ul(
"This function must only be called from the main thread.",
"The specified image data is copied before this function returns."
))}
""",
GLFWimage.const.p("image", "the desired cursor image"),
int("xhot", "the desired x-coordinate, in pixels, of the cursor hotspot"),
int("yhot", "the desired y-coordinate, in pixels, of the cursor hotspot"),
returnDoc = "the handle of the created cursor, or #NULL if an error occurred",
since = "version 3.1"
)
GLFWcursor.p(
"CreateStandardCursor",
"""
Returns a cursor with a standard shape, that can be set for a window with #SetCursor().
The images for these cursors come from the system cursor theme and their exact appearance will vary between platforms.
Most of these shapes are guaranteed to exist on every supported platform but a few may not be present. See the table below for details.
${table(
tr(th("Cursor shape"), th("Windows"), th("macOS"), th("X11"), th("Wayland")),
tr(td("#ARROW_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#IBEAM_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#CROSSHAIR_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#POINTING_HAND_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#RESIZE_EW_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#RESIZE_NS_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#RESIZE_NWSE_CURSOR"), td("Yes"), td("Yes<sup>1</sup>"), td("Maybe<sup>2</sup>"), td("Maybe<sup>2</sup>")),
tr(td("#RESIZE_NESW_CURSOR"), td("Yes"), td("Yes<sup>1</sup>"), td("Maybe<sup>2</sup>"), td("Maybe<sup>2</sup>")),
tr(td("#RESIZE_ALL_CURSOR"), td("Yes"), td("Yes"), td("Yes"), td("Yes")),
tr(td("#NOT_ALLOWED_CURSOR"), td("Yes"), td("Yes"), td("Maybe<sup>2</sup>"), td("Maybe<sup>2</sup>"))
)}
${note(
ol(
"This uses a private system API and may fail in the future.",
"This uses a newer standard that not all cursor themes support."
)
)}
If the requested shape is not available, this function emits a #CURSOR_UNAVAILABLE error and returns #NULL.
This function must only be called from the main thread.
""",
int(
"shape",
"one of the standard shapes",
"""
#ARROW_CURSOR #IBEAM_CURSOR #CROSSHAIR_CURSOR #POINTING_HAND_CURSOR #RESIZE_EW_CURSOR #RESIZE_NS_CURSOR #RESIZE_NWSE_CURSOR #RESIZE_NESW_CURSOR
#RESIZE_ALL_CURSOR #NOT_ALLOWED_CURSOR
"""
),
returnDoc =
"""
a new cursor ready to use or #NULL if an error occurred. Possible errors include #NOT_INITIALIZED, #INVALID_ENUM, #CURSOR_UNAVAILABLE and
#PLATFORM_ERROR.
""",
since = "version 3.1"
)
void(
"DestroyCursor",
"""
Destroys a cursor previously created with #CreateCursor(). Any remaining cursors will be destroyed by #Terminate().
${note(ul(
"This function must only be called from the main thread.",
"This function must not be called from a callback."
))}
""",
GLFWcursor.p("cursor", "the cursor object to destroy"),
since = "version 3.1"
)
void(
"SetCursor",
"""
Sets the cursor image to be used when the cursor is over the content area of the specified window. The set cursor will only be visible when the
${url("http://www.glfw.org/docs/latest/input.html\\#cursor_mode", "cursor mode")} of the window is #CURSOR_NORMAL.
On some platforms, the set cursor may not be visible unless the window also has input focus.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window to set the system cursor for"),
nullable..GLFWcursor.p("cursor", "the cursor to set, or #NULL to switch back to the default arrow cursor"),
since = "version 3.1"
)
GLFWkeyfun(
"SetKeyCallback",
"""
Sets the key callback of the specified window, which is called when a key is pressed, repeated or released.
The key functions deal with physical keys, with layout independent key tokens named after their values in the standard US keyboard layout. If you want
to input text, use #SetCharCallback() instead.
When a window loses input focus, it will generate synthetic key release events for all pressed keys. You can tell these events from user-generated
events by the fact that the synthetic ones are generated after the focus loss event has been processed, i.e. after the window focus callback has been
called.
The scancode of a key is specific to that platform or sometimes even to that machine. Scancodes are intended to allow users to bind keys that don't have
a GLFW key token. Such keys have {@code key} set to #KEY_UNKNOWN, their state is not saved and so it cannot be queried with #GetKey().
Sometimes GLFW needs to generate synthetic key events, in which case the scancode may be zero.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWkeyfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 1.0"
)
GLFWcharfun(
"SetCharCallback",
"""
Sets the character callback of the specified window, which is called when a Unicode character is input.
The character callback is intended for Unicode text input. As it deals with characters, it is keyboard layout dependent, whereas #SetKeyCallback() is
not. Characters do not map 1:1 to physical keys, as a key may produce zero, one or more characters. If you want to know whether a specific physical key
was pressed or released, see the key callback instead.
The character callback behaves as system text input normally does and will not be called if modifier keys are held down that would prevent normal text
input on that platform, for example a Super (Command) key on macOS or Alt key on Windows.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWcharfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 2.4"
)
GLFWcharmodsfun(
"SetCharModsCallback",
"""
Sets the character with modifiers callback of the specified window, which is called when a Unicode character is input regardless of what modifier keys
are used.
The character with modifiers callback is intended for implementing custom Unicode character input. For regular Unicode text input, see
#SetCharCallback(). Like the character callback, the character with modifiers callback deals with characters and is keyboard layout dependent.
Characters do not map 1:1 to physical keys, as a key may produce zero, one or more characters. If you want to know whether a specific physical key was
pressed or released, see #SetKeyCallback() instead.
This function must only be called from the main thread.
Deprecated: scheduled for removal in version 4.0.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWcharmodsfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 3.1"
)
GLFWmousebuttonfun(
"SetMouseButtonCallback",
"""
Sets the mouse button callback of the specified window, which is called when a mouse button is pressed or released.
When a window loses input focus, it will generate synthetic mouse button release events for all pressed mouse buttons. You can tell these events from
user-generated events by the fact that the synthetic ones are generated after the focus loss event has been processed, i.e. after the window focus
callback has been called.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWmousebuttonfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 1.0"
)
GLFWcursorposfun(
"SetCursorPosCallback",
"""
Sets the cursor position callback of the specified window, which is called when the cursor is moved. The callback is provided with the position, in
screen coordinates, relative to the upper-left corner of the content area of the window.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWcursorposfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 1.0"
)
GLFWcursorenterfun(
"SetCursorEnterCallback",
"""
Sets the cursor boundary crossing callback of the specified window, which is called when the cursor enters or leaves the content area of the window.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWcursorenterfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 3.0"
)
GLFWscrollfun(
"SetScrollCallback",
"""
Sets the scroll callback of the specified window, which is called when a scrolling device is used.
The scroll callback receives all scrolling input, like that from a mouse wheel or a touchpad scrolling area.
This function must only be called from the main thread.
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWscrollfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 2.1"
)
GLFWdropfun(
"SetDropCallback",
"""
Sets the file drop callback of the specified window, which is called when one or more dragged files are dropped on the window.
Because the path array and its strings may have been generated specifically for that event, they are not guaranteed to be valid after the callback has
returned. If you wish to use them after the callback returns, you need to make a deep copy.
Notes:
${ul(
"This function must only be called from the main thread.",
"<b>Wayland</b>: File drop is currently unimplemented."
)}
""",
GLFWwindow.p("window", "the window whose callback to set"),
nullable..GLFWdropfun("cbfun", "the new callback or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set",
since = "version 3.1"
)
intb(
"JoystickPresent",
"""
Returns whether the specified joystick is present.
This function must only be called from the main thread.
""",
int("jid", "joystick to query"),
returnDoc = "#TRUE if the joystick is present, or #FALSE otherwise",
since = "version 3.0"
)
float.const.p(
"GetJoystickAxes",
"""
Returns the values of all axes of the specified joystick. Each element in the array is a value between -1.0 and 1.0.
If the specified joystick is not present this function will return #NULL but will not generate an error. This can be used instead of first calling
#JoystickPresent().
The returned array is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected, this
function is called again for that joystick or the library is terminated.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
AutoSizeResult..int.p(
"count",
"where to store the number of axis values in the returned array. This is set to zero if the joystick is not present or an error occurred."
),
returnDoc = "an array of axis values, or #NULL if the joystick is not present",
since = "version 2.2"
)
unsigned_char.const.p(
"GetJoystickButtons",
"""
Returns the state of all buttons of the specified joystick. Each element in the array is either #PRESS or #RELEASE.
For backward compatibility with earlier versions that did not have #GetJoystickHats(), the button array also includes all hats, each represented as four
buttons. The hats are in the same order as returned by #GetJoystickHats() and are in the order up, right, down and left. To disable these extra
buttons, set the #JOYSTICK_HAT_BUTTONS init hint before initialization.
If the specified joystick is not present this function will return #NULL but will not generate an error. This can be used instead of first calling
#JoystickPresent().
The returned array is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected, this
function is called again for that joystick or the library is terminated.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
AutoSizeResult..int.p(
"count",
"where to store the number of button states in the returned array. This is set to zero if the joystick is not present or an error occurred."
),
returnDoc = "an array of button states, or #NULL if the joystick is not present",
since = "version 2.2"
)
unsigned_char.const.p(
"GetJoystickHats",
"""
Returns the state of all hats of the specified joystick.
This function returns the state of all hats of the specified joystick. Each element in the array is one of the following values:
${codeBlock("""
Name | Value
------------------- | ------------------------------
GLFW_HAT_CENTERED | 0
GLFW_HAT_UP | 1
GLFW_HAT_RIGHT | 2
GLFW_HAT_DOWN | 4
GLFW_HAT_LEFT | 8
GLFW_HAT_RIGHT_UP | GLFW_HAT_RIGHT | GLFW_HAT_UP
GLFW_HAT_RIGHT_DOWN | GLFW_HAT_RIGHT | GLFW_HAT_DOWN
GLFW_HAT_LEFT_UP | GLFW_HAT_LEFT | GLFW_HAT_UP
GLFW_HAT_LEFT_DOWN | GLFW_HAT_LEFT | GLFW_HAT_DOWN
""")}
The diagonal directions are bitwise combinations of the primary (up, right, down and left) directions and you can test for these individually by ANDing
it with the corresponding direction.
${codeBlock("""
if (hats[2] & GLFW_HAT_RIGHT)
{
// State of hat 2 could be right-up, right or right-down
}""")}
If the specified joystick is not present this function will return #NULL but will not generate an error. This can be used instead of first calling
#JoystickPresent().
${note(ul(
"This function must only be called from the main thread.",
"""
The returned array is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected, this
function is called again for that joystick or the library is terminated.
"""
))}
""",
int("jid", "the joystick to query"),
AutoSizeResult..int.p(
"count",
"where to store the number of hat states in the returned array. This is set to zero if the joystick is not present or an error occurred."
),
returnDoc = "an array of hat states, or #NULL if the joystick is not present or an error occurred",
since = "version 3.3"
)
charUTF8.const.p(
"GetJoystickName",
"""
Returns the name, encoded as UTF-8, of the specified joystick.
If the specified joystick is not present this function will return #NULL but will not generate an error. This can be used instead of first calling
#JoystickPresent().
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected, this
function is called again for that joystick or the library is terminated.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
returnDoc = "the UTF-8 encoded name of the joystick, or #NULL if the joystick is not present",
since = "version 3.0"
)
charUTF8.const.p(
"GetJoystickGUID",
"""
Returns the SDL compatible GUID, as a UTF-8 encoded hexadecimal string, of the specified joystick.
The GUID is what connects a joystick to a gamepad mapping. A connected joystick will always have a GUID even if there is no gamepad mapping assigned to
it.
The GUID uses the format introduced in SDL 2.0.5. This GUID tries to uniquely identify the make and model of a joystick but does not identify a
specific unit, e.g. all wired Xbox 360 controllers will have the same GUID on that platform. The GUID for a unit may vary between platforms depending
on what hardware information the platform specific APIs provide.
If the specified joystick is not present this function will return #NULL but will not generate an error. This can be used instead of first calling
#JoystickPresent().
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected or the
library is terminated.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
returnDoc = "the UTF-8 encoded GUID of the joystick, or #NULL if the joystick is not present or an error occurred",
since = "version 3.3"
)
void(
"SetJoystickUserPointer",
"""
Sets the user pointer of the specified joystick.
This function sets the user-defined pointer of the specified joystick. The current value is retained until the joystick is disconnected. The initial
value is #NULL.
This function may be called from the joystick callback, even for a joystick that is being disconnected.
This function may be called from any thread. Access is not synchronized.
""",
int("jid", "the joystick whose pointer to set"),
opaque_p("pointer", "the new value"),
since = "version 3.3"
)
opaque_p(
"GetJoystickUserPointer",
"""
Returns the user pointer of the specified joystick.
This function returns the current value of the user-defined pointer of the specified joystick. The initial value is #NULL.
This function may be called from the joystick callback, even for a joystick that is being disconnected.
This function may be called from any thread. Access is not synchronized.
""",
int("jid", "the joystick whose pointer to set"),
since = "version 3.3"
)
intb(
"JoystickIsGamepad",
"""
Returns whether the specified joystick is both present and has a gamepad mapping.
If the specified joystick is present but does not have a gamepad mapping this function will return {@code false} but will not generate an error. Call
#JoystickPresent() to check if a joystick is present regardless of whether it has a mapping.
This function must only be called from the main thread.
""",
int("jid", "the joystick id to query"),
returnDoc = "{@code true} if a joystick is both present and has a gamepad mapping or {@code false} otherwise",
since = "version 3.3"
)
GLFWjoystickfun(
"SetJoystickCallback",
"""
Sets the joystick configuration callback, or removes the currently set callback. This is called when a joystick is connected to or disconnected from
the system.
For joystick connection and disconnection events to be delivered on all platforms, you need to call one of the event processing functions. Joystick
disconnection may also be detected and the callback called by joystick functions. The function will then return whatever it returns if the joystick is
not present.
This function must only be called from the main thread.
""",
nullable..GLFWjoystickfun("cbfun", "the new callback, or #NULL to remove the currently set callback"),
returnDoc = "the previously set callback, or #NULL if no callback was set or the library had not been initialized",
since = "version 3.2"
)
intb(
"UpdateGamepadMappings",
"""
Adds the specified SDL_GameControllerDB gamepad mappings.
This function parses the specified ASCII encoded string and updates the internal list with any gamepad mappings it finds. This string may contain either
a single gamepad mapping or many mappings separated by newlines. The parser supports the full format of the {@code gamecontrollerdb.txt} source file
including empty lines and comments.
See ${url("http://www.glfw.org/docs/latest/input.html\\#gamepad_mapping", "gamepad_mapping")} for a description of the format.
If there is already a gamepad mapping for a given GUID in the internal list, it will be replaced by the one passed to this function. If the library is
terminated and re-initialized the internal list will revert to the built-in default.
This function must only be called from the main thread.
""",
NullTerminated..char.const.p("string", "the string containing the gamepad mappings"),
returnDoc = "{@code true}, or {@code false} if an error occurred",
since = "version 3.3"
)
charUTF8.const.p(
"GetGamepadName",
"""
Returns the human-readable name of the gamepad from the gamepad mapping assigned to the specified joystick.
If the specified joystick is not present or does not have a gamepad mapping this function will return #NULL but will not generate an error. Call
#JoystickIsGamepad() to check if a joystick is present regardless of whether it has a mapping.
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the specified joystick is disconnected, the
gamepad mappings are updated or the library is terminated.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
returnDoc = "the UTF-8 encoded name of the gamepad, or #NULL if the joystick is not present, does not have a mapping or an error occurred",
since = "version 3.3"
)
intb(
"GetGamepadState",
"""
Retrieves the state of the specified joystick remapped to an Xbox-like gamepad.
If the specified joystick is not present or does not have a gamepad mapping this function will return #FALSE but will not generate an error. Call
#JoystickPresent() to check whether it is present regardless of whether it has a mapping.
The Guide button may not be available for input as it is often hooked by the system or the Steam client.
Not all devices have all the buttons or axes provided by ##GLFWGamepadState. Unavailable buttons and axes will always report #RELEASE and 0.0
respectively.
This function must only be called from the main thread.
""",
int("jid", "the joystick to query"),
GLFWgamepadstate.p("state", "the gamepad input state of the joystick"),
returnDoc = "{@code true} if successful, or {@code false} if no joystick is connected, it has no gamepad mapping or an error occurred",
since = "version 3.3"
)
void(
"SetClipboardString",
"""
Sets the system clipboard to the specified, UTF-8 encoded string.
The specified string is copied before this function returns.
Notes:
${ul(
"This function must only be called from the main thread."
)}
""",
nullable..GLFWwindow.p("window", "deprecated, any valid window or #NULL."),
charUTF8.const.p("string", "a UTF-8 encoded string"),
since = "version 3.0"
)
charUTF8.const.p(
"GetClipboardString",
"""
Returns the contents of the system clipboard, if it contains or is convertible to a UTF-8 encoded string. If the clipboard is empty or if its contents
cannot be converted, #NULL is returned and a #FORMAT_UNAVAILABLE error is generated.
The returned string is allocated and freed by GLFW. You should not free it yourself. It is valid until the next call to #GetClipboardString() or
#SetClipboardString(), or until the library is terminated.
${note(ul(
"This function must only be called from the main thread.",
"The returned string is allocated and freed by GLFW. You should not free it yourself.",
"The returned string is valid only until the next call to #GetClipboardString() or #SetClipboardString()."
))}
""",
nullable..GLFWwindow.p("window", "deprecated, any valid window or #NULL."),
returnDoc = "the contents of the clipboard as a UTF-8 encoded string, or #NULL if an error occurred",
since = "version 3.0"
)
double(
"GetTime",
"""
Returns the value of the GLFW timer. Unless the timer has been set using #SetTime(), the timer measures time elapsed since GLFW was initialized.
The resolution of the timer is system dependent, but is usually on the order of a few micro- or nanoseconds. It uses the highest-resolution monotonic
time source on each operating system.
This function may be called from any thread. Reading and writing of the internal timer offset is not atomic, so it needs to be externally synchronized
with calls to #SetTime().
""",
returnDoc = "the current value, in seconds, or zero if an error occurred",
since = "version 1.0"
)
void(
"SetTime",
"""
Sets the value of the GLFW timer. It then continues to count up from that value. The value must be a positive finite number less than or equal to
18446744073.0, which is approximately 584.5 years.
The upper limit of the timer is calculated as ${code("floor((2<sup>64</sup> - 1) / 10<sup>9</sup>)")} and is due to implementations storing nanoseconds
in 64 bits. The limit may be increased in the future.
This function may be called from any thread. Reading and writing of the internal timer offset is not atomic, so it needs to be externally synchronized
with calls to #GetTime().
""",
double("time", "the new value, in seconds"),
since = "version 2.2"
)
uint64_t(
"GetTimerValue",
"""
Returns the current value of the raw timer.
This function returns the current value of the raw timer, measured in {@code 1 / frequency} seconds. To get the frequency, call #GetTimerFrequency().
This function may be called from any thread.
""",
returnDoc = "the value of the timer, or zero if an error occurred",
since = "version 3.2"
)
uint64_t(
"GetTimerFrequency",
"""
Returns the frequency, in Hz, of the raw timer.
This function may be called from any thread.
""",
returnDoc = "the frequency of the timer, in Hz, or zero if an error occurred",
since = "version 3.2"
)
// [ OpenGL ]
void(
"MakeContextCurrent",
"""
Makes the OpenGL or OpenGL ES context of the specified window current on the calling thread. A context must only be made current on a single thread at
a time and each thread can have only a single current context at a time.
When moving a context between threads, you must make it non-current on the old thread before making it current on the new one.
By default, making a context non-current implicitly forces a pipeline flush. On machines that support
${url("https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_context_flush_control.txt", "GL_KHR_context_flush_control")}, you can control whether
a context performs this flush by setting the #CONTEXT_RELEASE_BEHAVIOR
${url("http://www.glfw.org/docs/latest/window.html\\#window_hints_ctx", "window hint")}.
The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a context will generate a #NO_WINDOW_CONTEXT error.
This function may be called from any thread.
""",
nullable..GLFWwindow.p("window", "the window whose context to make current, or #NULL to detach the current context"),
since = "version 3.0"
)
GLFWwindow.p(
"GetCurrentContext",
"""
Returns the window whose OpenGL or OpenGL ES context is current on the calling thread.
This function may be called from any thread.
""",
returnDoc = "the window whose context is current, or #NULL if no window's context is current",
since = "version 3.0"
)
void(
"SwapBuffers",
"""
Swaps the front and back buffers of the specified window when rendering with OpenGL or OpenGL ES. If the swap interval is greater than zero, the GPU
driver waits the specified number of screen updates before swapping the buffers.
The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a context will generate a #NO_WINDOW_CONTEXT error.
This function does not apply to Vulkan. If you are rendering with Vulkan, {@code vkQueuePresentKHR} instead.
<b>EGL</b>: The context of the specified window must be current on the calling thread.
This function may be called from any thread.
""",
GLFWwindow.p("window", "the window whose buffers to swap"),
since = "version 1.0"
)
void(
"SwapInterval",
"""
Sets the swap interval for the current OpenGL or OpenGL ES context, i.e. the number of screen updates to wait from the time #SwapBuffers() was called
before swapping the buffers and returning. This is sometimes called <i>vertical synchronization</i>, <i>vertical retrace synchronization</i> or just
<i>vsync</i>.
A context that supports either of the
${url("https://www.khronos.org/registry/OpenGL/extensions/EXT/WGL_EXT_swap_control_tear.txt", "WGL_EXT_swap_control_tear")} and
${url("https://www.khronos.org/registry/OpenGL/extensions/EXT/GLX_EXT_swap_control_tear.txt", "GLX_EXT_swap_control_tear")} extensions also accepts
<b>negative</b> swap intervals, which allows the driver to swap immediately even if a frame arrives a little bit late. You can check for these
extensions with #ExtensionSupported(). For more information about swap tearing, see the extension specifications.
A context must be current on the calling thread. Calling this function without a current context will cause a #NO_CURRENT_CONTEXT error.
This function does not apply to Vulkan. If you are rendering with Vulkan, see the present mode of your swapchain instead.
${note(ul(
"This function may be called from any thread.",
"""
This function is not called during window creation, leaving the swap interval set to whatever is the default for that API. This is done because
some swap interval extensions used by GLFW do not allow the swap interval to be reset to zero once it has been set to a non-zero value.
""",
"""
Some GPU drivers do not honor the requested swap interval, either because of a user setting that overrides the application's request or due to bugs
in the driver.
"""
))}
""",
int("interval", "the minimum number of screen updates to wait for until the buffers are swapped by #SwapBuffers()"),
since = "version 1.0"
)
intb(
"ExtensionSupported",
"""
Returns whether the specified ${url("http://www.glfw.org/docs/latest/context.html\\#context_glext", "API extension")} is supported by the current
OpenGL or OpenGL ES context. It searches both for client API extension and context creation API extensions.
A context must be current on the calling thread. Calling this function without a current context will cause a #NO_CURRENT_CONTEXT error.
As this functions retrieves and searches one or more extension strings each call, it is recommended that you cache its results if it is going to be used
frequently. The extension strings will not change during the lifetime of a context, so there is no danger in doing this.
This function does not apply to Vulkan. If you are using Vulkan, see {@code glfwGetRequiredInstanceExtensions},
{@code vkEnumerateInstanceExtensionProperties} and {@code vkEnumerateDeviceExtensionProperties} instead.
This function may be called from any thread.
""",
charASCII.const.p("extension", "the ASCII encoded name of the extension"),
returnDoc = "#TRUE if the extension is available, or #FALSE otherwise",
since = "version 1.0"
)
GLFWglproc(
"GetProcAddress",
"""
Returns the address of the specified OpenGL or OpenGL ES ${url(
"http://www.glfw.org/docs/latest/context.html\\#context_glext",
"core or extension function")
}, if it is supported by the current context.
A context must be current on the calling thread. Calling this function without a current context will cause a #NO_CURRENT_CONTEXT error.
This function does not apply to Vulkan. If you are rendering with Vulkan, {@code glfwGetInstanceProcAddress}, {@code vkGetInstanceProcAddr} and
{@code vkGetDeviceProcAddr} instead.
${note(ul(
"The address of a given function is not guaranteed to be the same between contexts.",
"""
This function may return a non-#NULL address despite the associated version or extension not being available. Always check the context version or
extension string first.
""",
"The returned function pointer is valid until the context is destroyed or the library is terminated.",
"This function may be called from any thread."
))}
""",
charASCII.const.p("procname", "the ASCII encoded name of the function"),
returnDoc = "the address of the function, or #NULL if an error occurred",
since = "version 1.0"
)
}
| bsd-3-clause | 6f0f50b633cb17e9f86373cc09864b88 | 42.573714 | 172 | 0.638349 | 4.693998 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/nbt/NBTFactory.kt | 1 | 18089 | /*
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.nbt
import com.mcmoonlake.api.*
import com.mcmoonlake.api.entity.Entities
import com.mcmoonlake.api.exception.MoonLakeException
import com.mcmoonlake.api.reflect.FuzzyReflect
import com.mcmoonlake.api.reflect.StructureModifier
import com.mcmoonlake.api.reflect.accessor.AccessorConstructor
import com.mcmoonlake.api.reflect.accessor.AccessorField
import com.mcmoonlake.api.reflect.accessor.AccessorMethod
import com.mcmoonlake.api.reflect.accessor.Accessors
import com.mcmoonlake.api.security.base64DString
import com.mcmoonlake.api.security.base64EString
import com.mcmoonlake.api.utility.MinecraftConverters
import com.mcmoonlake.api.utility.MinecraftReflection
import com.mcmoonlake.api.version.MinecraftBukkitVersion
import org.bukkit.Material
import org.bukkit.entity.Entity
import org.bukkit.entity.LivingEntity
import org.bukkit.inventory.ItemStack
import java.io.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object NBTFactory {
@JvmStatic
private val nbtBaseCreateTag: AccessorMethod by lazy {
Accessors.getAccessorMethod(MinecraftReflection.nbtBaseClass, "createTag", true, Byte::class.java) }
@JvmStatic
private val nbtStreamClass: Class<*> by lazy {
MinecraftReflection.getMinecraftClass("NBTCompressedStreamTools") }
@JvmStatic
private val nbtReadLimiterClass: Class<*> by lazy {
MinecraftReflection.getMinecraftClass("NBTReadLimiter") }
@JvmStatic
private val nbtReadLimiterInstance: Any by lazy {
Accessors.getAccessorField(FuzzyReflect.fromClass(nbtReadLimiterClass, true)
.getFieldByType("instance", nbtReadLimiterClass), true).get(null).notNull() }
@JvmStatic
private val nbtStreamRead: AccessorMethod by lazy {
Accessors.getAccessorMethod(FuzzyReflect.fromClass(nbtStreamClass, true)
.getMethodByParameters("read", MinecraftReflection.nbtBaseClass, arrayOf(DataInput::class.java, Int::class.java, nbtReadLimiterClass)), true) }
@JvmStatic
private val nbtStreamWrite: AccessorMethod by lazy {
Accessors.getAccessorMethod(FuzzyReflect.fromClass(nbtStreamClass, true)
.getMethodByParameters("write", Void::class.java, arrayOf(MinecraftReflection.nbtBaseClass, DataOutput::class.java)), true) }
@JvmStatic
private val itemStackModifier: StructureModifier<*> by lazy {
StructureModifier.of(MinecraftReflection.itemStackClass, Object::class.java) }
@JvmStatic
private val itemStackConstructor: AccessorConstructor<out Any> by lazy {
Accessors.getAccessorConstructor(MinecraftReflection.itemStackClass, false, MinecraftReflection.nbtTagCompoundClass) }
@JvmStatic
private val craftItemStackHandle: AccessorField by lazy {
Accessors.getAccessorField(MinecraftReflection.craftItemStackClass, MinecraftReflection.itemStackClass, true) }
@JvmStatic
private val entitySave: AccessorMethod by lazy {
val nbtClazz = MinecraftReflection.nbtTagCompoundClass
if(!currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_9_R2))
Accessors.getAccessorMethod(MinecraftReflection.entityClass, "e", false, nbtClazz)
Accessors.getAccessorMethod(FuzzyReflect.fromClass(MinecraftReflection.entityClass).getMethodByParameters("save", nbtClazz, arrayOf(nbtClazz))) }
@JvmStatic
private val entityRead: AccessorMethod by lazy {
Accessors.getAccessorMethod(MinecraftReflection.entityClass, "f", false, MinecraftReflection.nbtTagCompoundClass) }
@JvmStatic
private val entityLivingSave: AccessorMethod by lazy {
Accessors.getAccessorMethod(MinecraftReflection.entityLivingClass, "a", false, MinecraftReflection.nbtTagCompoundClass) }
@JvmStatic
private val entityLivingRead: AccessorMethod by lazy {
Accessors.getAccessorMethod(MinecraftReflection.entityLivingClass, "b", false, MinecraftReflection.nbtTagCompoundClass) }
@JvmStatic
@JvmName("fromBase")
@Suppress("UNCHECKED_CAST")
fun <T> fromBase(base: NBTBase<T>): NBTWrapper<T> {
return when(base is NBTWrapper) {
true -> base as NBTWrapper
else -> return when(base.type) {
NBTType.TAG_COMPOUND -> {
val compound = ofCompound(base.name)
compound.value = base.value as MutableMap<String, NBTBase<*>>
return compound as NBTWrapper<T>
}
NBTType.TAG_LIST -> {
val list = ofList<T>(base.name)
list.value = base.value as MutableList<NBTBase<T>>
return list as NBTWrapper<T>
}
else -> ofWrapper(base.type, base.name, base.value)
}
}
}
@JvmStatic
@JvmName("fromNMS")
@Suppress("UNCHECKED_CAST")
fun <T> fromNMS(handle: Any, name: String = ""): NBTWrapper<T> {
val element = NBTWrappedElement<T>(handle, name)
return when(element.type) {
NBTType.TAG_COMPOUND -> NBTWrappedCompound(handle, name) as NBTWrapper<T>
NBTType.TAG_LIST -> NBTWrappedList<T>(handle, name) as NBTWrapper<T>
else -> element
}
}
@JvmStatic
@JvmName("of")
fun of(type: NBTType): Any
= nbtBaseCreateTag.invoke(null, type.id.toByte()) as Any
@JvmStatic
@JvmName("ofWrapper")
@Suppress("UNCHECKED_CAST")
fun <T> ofWrapper(type: NBTType, name: String): NBTWrapper<T> {
val handle = of(type)
return when(type) {
NBTType.TAG_COMPOUND -> NBTWrappedCompound(handle, name) as NBTWrapper<T>
NBTType.TAG_LIST -> NBTWrappedList<T>(handle, name) as NBTWrapper<T>
else -> NBTWrappedElement(handle, name)
}
}
@JvmStatic
@JvmName("ofWrapper")
fun <T> ofWrapper(type: NBTType, name: String, value: T): NBTWrapper<T> {
val wrapper = ofWrapper<T>(type, name)
wrapper.value = value
return wrapper
}
@JvmStatic
@JvmName("of")
fun of(name: String, value: String): NBTBase<String>
= ofWrapper(NBTType.TAG_STRING, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Byte): NBTBase<Byte>
= ofWrapper(NBTType.TAG_BYTE, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Short): NBTBase<Short>
= ofWrapper(NBTType.TAG_SHORT, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Int): NBTBase<Int>
= ofWrapper(NBTType.TAG_INT, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Long): NBTBase<Long>
= ofWrapper(NBTType.TAG_LONG, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Float): NBTBase<Float>
= ofWrapper(NBTType.TAG_FLOAT, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: Double): NBTBase<Double>
= ofWrapper(NBTType.TAG_DOUBLE, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: ByteArray): NBTBase<ByteArray>
= ofWrapper(NBTType.TAG_BYTE_ARRAY, name, value)
@JvmStatic
@JvmName("of")
fun of(name: String, value: IntArray): NBTBase<IntArray>
= ofWrapper(NBTType.TAG_INT_ARRAY, name, value)
@JvmStatic
@JvmName("ofCompound")
@JvmOverloads
fun ofCompound(name: String = ""): NBTCompound
= ofWrapper<MutableMap<String, NBTBase<*>>>(NBTType.TAG_COMPOUND, name) as NBTCompound
@JvmStatic
@JvmName("ofList")
@Suppress("UNCHECKED_CAST")
@JvmOverloads
fun <T> ofList(name: String = ""): NBTList<T>
= ofWrapper<MutableList<NBTBase<T>>>(NBTType.TAG_LIST, name) as NBTList<T>
@JvmStatic
@JvmName("readStackTag")
fun readStackTag(itemStack: ItemStack): NBTCompound? {
return when(MinecraftReflection.craftItemStackClass.isInstance(itemStack)) {
true -> getCraftStackTag(itemStack)
else -> getOriginStackTag(itemStack)
}
}
@JvmStatic
@JvmName("readStackTagSafe")
fun readStackTagSafe(itemStack: ItemStack): NBTCompound
= readStackTag(itemStack) ?: ofCompound("tag")
@JvmStatic
@JvmName("writeStackTag")
fun writeStackTag(itemStack: ItemStack, tag: NBTCompound?): ItemStack {
when(MinecraftReflection.craftItemStackClass.isInstance(itemStack)) {
true -> setCraftStackTag(itemStack, tag)
else -> setOriginStackTag(itemStack, tag)
}
return itemStack
}
@JvmStatic
@JvmName("createStack")
@JvmOverloads
fun createStack(type: Material, amount: Int = 1, durability: Int = 0, tag: NBTCompound? = null): ItemStack {
val nbt = ofCompound()
nbt.putString("id", "minecraft:${type.name.toLowerCase()}")
nbt.putByte("Count", amount)
nbt.putShort("Damage", durability)
if(tag != null) nbt.put("tag", tag)
val nmsItemStack = itemStackConstructor.newInstance(fromBase(nbt).handle)
return MinecraftConverters.itemStack.getSpecific(nmsItemStack) as ItemStack
}
@JvmStatic
@JvmName("createStackNBT")
fun createStackNBT(nbt: NBTCompound): ItemStack {
val type = nbt.getString("id").replaceFirst("minecraft:", "", true)
val count = nbt.getByteOrNull("Count") ?: 1
val durability = nbt.getShortOrNull("Damage") ?: 0
val tag = nbt.getCompoundOrNull("tag")
val itemStack = ItemStack(Material.matchMaterial(type), count.toInt(), durability)
return writeStackTag(itemStack, tag)
}
@JvmStatic
@JvmName("readStackNBT")
fun readStackNBT(itemStack: ItemStack): NBTCompound {
val nbt = ofCompound()
val tag = readStackTag(itemStack)
nbt.putString("id", "minecraft:${itemStack.type.name.toLowerCase()}")
nbt.putByte("Count", itemStack.amount)
nbt.putShort("Damage", itemStack.durability)
if(tag != null) nbt.put("tag", tag)
return nbt
}
@JvmStatic
@JvmName("readEntityTag")
fun <T: Entity> readEntityTag(entity: T): NBTCompound {
val handle = of(NBTType.TAG_COMPOUND)
when(entity) {
is LivingEntity -> entityLivingRead.invoke(Entities.asNMSEntity(entity), handle)
else -> entityRead.invoke(Entities.asNMSEntity(entity), handle)
}
return fromNMS<NBTCompound>(handle, "EntityTag") as NBTCompound
}
@JvmStatic
@JvmName("writeEntityTag")
fun <T: Entity> writeEntityTag(entity: T, tag: NBTCompound): T {
val handle = fromBase(tag).handle
when(entity) {
is LivingEntity -> entityLivingSave.invoke(Entities.asNMSEntity(entity), handle)
else -> entitySave.invoke(Entities.asNMSEntity(entity), handle)
}
return entity
}
/** nbt io */
@JvmStatic
@JvmName("writeData")
@Throws(MoonLakeException::class)
fun writeData(base: NBTBase<*>, data: DataOutput) = try {
nbtStreamWrite.invoke(null, fromBase(base).handle, data)
} catch(e: Exception) {
e.throwMoonLake()
}
@JvmStatic
@JvmName("readData")
@Throws(MoonLakeException::class)
fun <T> readData(data: DataInput): NBTWrapper<T>? {
try {
val handle = nbtStreamRead.invoke(null, data, 0, nbtReadLimiterInstance) ?: return null
return fromNMS(handle)
} catch(e: Exception) {
e.throwMoonLake()
}
}
@JvmStatic
@JvmName("readDataCompound")
@Throws(MoonLakeException::class)
fun readDataCompound(data: DataInput): NBTCompound? = try {
readData<NBTCompound>(data) as NBTCompound?
} catch(e: Exception) {
e.throwMoonLake()
}
@JvmStatic
@JvmName("readDataList")
@Throws(MoonLakeException::class)
fun <T> readDataList(data: DataInput): NBTList<T>? = try {
@Suppress("UNCHECKED_CAST")
readData<NBTList<T>>(data) as NBTList<T>?
} catch(e: Exception) {
e.throwMoonLake()
}
@JvmStatic
@JvmName("writeDataCompoundFile")
@Throws(IOException::class)
@JvmOverloads
fun writeDataCompoundFile(compound: NBTCompound, file: File, compress: Boolean = true) {
var stream: FileOutputStream? = null
var output: DataOutputStream? = null
var swallow = true
try {
stream = FileOutputStream(file)
output = if(compress) DataOutputStream(GZIPOutputStream(stream)) else DataOutputStream(stream)
writeData(compound, output)
swallow = false
} finally {
if(output != null) output.ioClose(swallow)
else if(stream != null) stream.ioClose(swallow)
}
}
@JvmStatic
@JvmName("readDataCompoundFile")
@Throws(IOException::class)
@JvmOverloads
fun readDataCompoundFile(file: File, compress: Boolean = true): NBTCompound? {
if(!file.exists() || file.isDirectory)
return null
var stream: FileInputStream? = null
var input: DataInputStream? = null
var swallow = true
try {
stream = FileInputStream(file)
input = if(compress) DataInputStream(GZIPInputStream(stream)) else DataInputStream(stream)
val result = readDataCompound(input)
swallow = false
return result
} finally {
if(input != null) input.ioClose(swallow)
else if(stream != null) stream.ioClose(swallow)
}
}
@JvmStatic
@JvmName("writeDataBase64")
@Throws(MoonLakeException::class)
fun writeDataBase64(base: NBTBase<*>): String {
val stream = ByteArrayOutputStream()
val output = DataOutputStream(stream)
writeData(base, output)
return base64EString(stream.toByteArray())
}
@JvmStatic
@JvmName("readDataBase64")
@Throws(MoonLakeException::class)
fun <T> readDataBase64(value: String): NBTWrapper<T>? {
val stream = ByteArrayInputStream(base64DString(value))
val input = DataInputStream(stream)
return readData(input)
}
@JvmStatic
@JvmName("readDataBase64Compound")
@Throws(MoonLakeException::class)
fun readDataBase64Compound(value: String): NBTCompound? = try {
readDataBase64<NBTCompound>(value) as NBTCompound?
} catch(e: Exception) {
e.throwMoonLake()
}
@JvmStatic
@JvmName("readDataBase64List")
@Throws(MoonLakeException::class)
fun <T> readDataBase64List(value: String): NBTList<T>? = try {
@Suppress("UNCHECKED_CAST")
readDataBase64<NBTList<T>>(value) as NBTList<T>?
} catch(e: Exception) {
e.throwMoonLake()
}
/** implement */
@JvmStatic
@JvmName("getCraftStackTag")
private fun getCraftStackTag(itemStack: ItemStack): NBTCompound? {
val nmsItemStack = craftItemStackHandle.get(itemStack)
val modifier = itemStackModifier.withTarget<Any>(nmsItemStack)
.withType(MinecraftReflection.nbtBaseClass, MinecraftConverters.nbt)
return modifier.read(0) as NBTCompound?
}
@JvmStatic
@JvmName("setCraftStackTag")
private fun setCraftStackTag(itemStack: ItemStack, tag: NBTCompound?) {
val nmsItemStack = craftItemStackHandle.get(itemStack)
val modifier = itemStackModifier.withTarget<Any>(nmsItemStack)
.withType(MinecraftReflection.nbtBaseClass, MinecraftConverters.nbt)
modifier.write(0, tag)
}
@JvmStatic
@JvmName("getOriginStackTag")
private fun getOriginStackTag(itemStack: ItemStack): NBTCompound? {
val itemStackConverter = MinecraftConverters.itemStack
val copyItemStack = itemStackConverter.getSpecific(itemStackConverter.getGeneric(itemStack)) as ItemStack
copyItemStack.itemMeta = itemStack.itemMeta
return getCraftStackTag(copyItemStack)
}
@JvmStatic
@JvmName("setOriginStackTag")
private fun setOriginStackTag(itemStack: ItemStack, tag: NBTCompound?) {
if(tag == null) {
itemStack.itemMeta = null
} else {
val itemStackConverter = MinecraftConverters.itemStack
val copyItemStack = itemStackConverter.getSpecific(itemStackConverter.getGeneric(itemStack)) as ItemStack
setCraftStackTag(copyItemStack, tag)
itemStack.itemMeta = copyItemStack.itemMeta
}
}
}
| gpl-3.0 | 5d587285be04c9a899e93e07b456bb0a | 37.651709 | 159 | 0.671237 | 4.576018 | false | false | false | false |
mdanielwork/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/teamCity.kt | 1 | 4354 | // 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.intellij.build.images.sync
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.entity.ContentType
import java.io.File
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*
internal fun isUnderTeamCity() = BUILD_SERVER != null
private val BUILD_SERVER = System.getProperty("teamcity.serverUrl")
private val BUILD_CONF = System.getProperty("teamcity.buildType.id")
private val BUILD_ID = System.getProperty("teamcity.build.id")
private fun teamCityGet(path: String) = get("$BUILD_SERVER/httpAuth/app/rest/$path") {
teamCityAuth()
}
private fun teamCityPost(path: String, body: String) = post("$BUILD_SERVER/httpAuth/app/rest/$path", body) {
teamCityAuth()
addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.toString())
}
private fun HttpRequestBase.teamCityAuth() {
basicAuth(System.getProperty("pin.builds.user.name"), System.getProperty("pin.builds.user.password"))
}
private val DATE_FORMAT = SimpleDateFormat("yyyyMMdd'T'HHmmsszzz")
internal fun isNotificationRequired(context: Context): Boolean {
val request = "builds?locator=buildType:$BUILD_CONF,count:1"
return if (context.isSuccess()) {
// notify on fail -> success
val previousBuild = teamCityGet(request)
previousBuild.contains("status=\"FAILURE\"")
}
else {
val dayAgo = DATE_FORMAT.format(Calendar.getInstance().let { calendar ->
calendar.add(Calendar.HOUR, -12)
calendar.time
})
// remind of failure once per day
val previousBuild = teamCityGet("$request,sinceDate:${URLEncoder.encode(dayAgo, Charsets.UTF_8.name())}")
previousBuild.contains("count=\"0\"")
}
}
internal val DEFAULT_INVESTIGATOR by lazy {
System.getProperty("intellij.icons.sync.default.investigator")?.takeIf { it.isNotBlank() } ?: error("Specify default investigator")
}
internal class Investigator(val email: String = DEFAULT_INVESTIGATOR,
val commits: Map<File, Collection<CommitInfo>> = emptyMap(),
var isAssigned: Boolean = false)
internal fun isInvestigationAssigned() = teamCityGet("investigations?locator=buildType:$BUILD_CONF").run {
contains("assignee") && !contains("GIVEN_UP")
}
internal fun assignInvestigation(investigator: Investigator, context: Context): Investigator {
try {
val id = teamCityGet("users/email:${investigator.email}/id")
val text = investigator.run {
(if (commits.isNotEmpty()) "commits: ${commits.entries.joinToString {
"${getOriginUrl(it.key)} : ${it.value.map(CommitInfo::hash)}"
}},"
else "") +
(if (context.createdReviews.isNotEmpty()) " reviews created: ${context.createdReviews.map(Review::url)}," else "")
} + " build: ${thisBuildReportableLink()}, see also: https://confluence.jetbrains.com/display/IDEA/Working+with+icons+in+IntelliJ+Platform"
teamCityPost("investigations", """
<investigation state="TAKEN">
<assignee id="$id"/>
<assignment>
<text><![CDATA[$text]]></text>
</assignment>
<scope>
<buildTypes count="1">
<buildType id="$BUILD_CONF"/>
</buildTypes>
</scope>
<target anyProblem="true"/>
<resolution type="whenFixed"/>
</investigation>""".trimIndent())
investigator.isAssigned = true
log("Investigation is assigned to ${investigator.email} with message '$text'")
}
catch (e: Exception) {
log("Unable to assign investigation to ${investigator.email}, ${e.message}")
}
return if (!investigator.isAssigned && investigator.email != DEFAULT_INVESTIGATOR) {
Investigator(DEFAULT_INVESTIGATOR, investigator.commits).also {
assignInvestigation(it, context)
}
}
else investigator
}
internal fun thisBuildReportableLink() =
"${System.getProperty("intellij.icons.report.buildserver")}/viewLog.html?buildId=$BUILD_ID&buildTypeId=$BUILD_CONF"
internal fun triggeredBy() = System.getProperty("teamcity.build.triggeredBy.username")
?.takeIf { it.isNotBlank() }
?.let { teamCityGet("users/username:$it/email") }
?.removeSuffix(System.lineSeparator()) | apache-2.0 | a26c77a2833a68808e61db85528f0598 | 39.700935 | 143 | 0.69706 | 4.13093 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/views/Themes.kt | 1 | 4597 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.ui.views
import org.isoron.platform.gui.Color
import org.isoron.uhabits.core.models.PaletteColor
abstract class Theme {
open val appBackgroundColor = Color(0xf4f4f4)
open val cardBackgroundColor = Color(0xFAFAFA)
open val headerBackgroundColor = Color(0xeeeeee)
open val headerBorderColor = Color(0xcccccc)
open val headerTextColor = Color(0x9E9E9E)
open val highContrastTextColor = Color(0x202020)
open val itemBackgroundColor = Color(0xffffff)
open val lowContrastTextColor = Color(0xe0e0e0)
open val mediumContrastTextColor = Color(0x9E9E9E)
open val statusBarBackgroundColor = Color(0x333333)
open val toolbarBackgroundColor = Color(0xf4f4f4)
open val toolbarColor = Color(0xffffff)
fun color(paletteColor: PaletteColor): Color {
return color(paletteColor.paletteIndex)
}
open fun color(paletteIndex: Int): Color {
return when (paletteIndex) {
0 -> Color(0xD32F2F)
1 -> Color(0xE64A19)
2 -> Color(0xF57C00)
3 -> Color(0xFF8F00)
4 -> Color(0xF9A825)
5 -> Color(0xAFB42B)
6 -> Color(0x7CB342)
7 -> Color(0x388E3C)
8 -> Color(0x00897B)
9 -> Color(0x00ACC1)
10 -> Color(0x039BE5)
11 -> Color(0x1976D2)
12 -> Color(0x303F9F)
13 -> Color(0x5E35B1)
14 -> Color(0x8E24AA)
15 -> Color(0xD81B60)
16 -> Color(0x5D4037)
17 -> Color(0x424242)
18 -> Color(0x757575)
19 -> Color(0x9E9E9E)
else -> Color(0x000000)
}
}
val checkmarkButtonSize = 48.0
val smallTextSize = 10.0
val regularTextSize = 17.0
}
open class LightTheme : Theme()
open class DarkTheme : Theme() {
override val appBackgroundColor = Color(0x212121)
override val cardBackgroundColor = Color(0x303030)
override val headerBackgroundColor = Color(0x212121)
override val headerBorderColor = Color(0xcccccc)
override val headerTextColor = Color(0x9E9E9E)
override val highContrastTextColor = Color(0xF5F5F5)
override val itemBackgroundColor = Color(0xffffff)
override val lowContrastTextColor = Color(0x424242)
override val mediumContrastTextColor = Color(0x9E9E9E)
override val statusBarBackgroundColor = Color(0x333333)
override val toolbarBackgroundColor = Color(0xf4f4f4)
override val toolbarColor = Color(0xffffff)
override fun color(paletteIndex: Int): Color {
return when (paletteIndex) {
0 -> Color(0xEF9A9A)
1 -> Color(0xFFAB91)
2 -> Color(0xFFCC80)
3 -> Color(0xFFECB3)
4 -> Color(0xFFF59D)
5 -> Color(0xE6EE9C)
6 -> Color(0xC5E1A5)
7 -> Color(0x69F0AE)
8 -> Color(0x80CBC4)
9 -> Color(0x80DEEA)
10 -> Color(0x81D4FA)
11 -> Color(0x64B5F6)
12 -> Color(0x9FA8DA)
13 -> Color(0xB39DDB)
14 -> Color(0xCE93D8)
15 -> Color(0xF48FB1)
16 -> Color(0xBCAAA4)
17 -> Color(0xF5F5F5)
18 -> Color(0xE0E0E0)
19 -> Color(0x9E9E9E)
else -> Color(0xFFFFFF)
}
}
}
class PureBlackTheme : DarkTheme() {
override val appBackgroundColor = Color(0x000000)
override val cardBackgroundColor = Color(0x000000)
override val lowContrastTextColor = Color(0x212121)
}
class WidgetTheme : LightTheme() {
override val cardBackgroundColor = Color.TRANSPARENT
override val highContrastTextColor = Color.WHITE
override val mediumContrastTextColor = Color.WHITE.withAlpha(0.50)
override val lowContrastTextColor = Color.WHITE.withAlpha(0.10)
}
| gpl-3.0 | 9b5f14c9fde70bd2a7b8f3a8d497b500 | 34.90625 | 78 | 0.649478 | 3.662151 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/ui/datacollection/DataCollectionFragment.kt | 1 | 3592 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.datacollection
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.widget.ViewPager2
import com.google.android.ground.AbstractActivity
import com.google.android.ground.R
import com.google.android.ground.databinding.DataCollectionFragBinding
import com.google.android.ground.model.submission.Submission
import com.google.android.ground.rx.Loadable
import com.google.android.ground.rx.Schedulers
import com.google.android.ground.ui.common.AbstractFragment
import com.google.android.ground.ui.common.BackPressListener
import com.google.android.ground.ui.common.Navigator
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/** Fragment allowing the user to collect data to complete a task. */
@AndroidEntryPoint
class DataCollectionFragment : AbstractFragment(), BackPressListener {
@Inject lateinit var navigator: Navigator
@Inject lateinit var schedulers: Schedulers
@Inject lateinit var viewPagerAdapterFactory: DataCollectionViewPagerAdapterFactory
private lateinit var viewModel: DataCollectionViewModel
private val args: DataCollectionFragmentArgs by navArgs()
private lateinit var viewPager: ViewPager2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = getViewModel(DataCollectionViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreateView(inflater, container, savedInstanceState)
val binding = DataCollectionFragBinding.inflate(inflater, container, false)
viewPager = binding.root.findViewById(R.id.pager)
viewPager.isUserInputEnabled = false
viewPager.offscreenPageLimit = 1
viewModel.loadSubmissionDetails(args)
viewModel.submission.observe(viewLifecycleOwner) { submission: Loadable<Submission> ->
submission.value().ifPresent {
viewPager.adapter = viewPagerAdapterFactory.create(this, it.job.tasksSorted, viewModel)
}
}
viewModel.currentPosition.observe(viewLifecycleOwner) { viewPager.currentItem = it }
viewModel.currentTaskDataLiveData.observe(viewLifecycleOwner) {
viewModel.currentTaskData = it.orElse(null)
}
binding.viewModel = viewModel
binding.lifecycleOwner = this
(activity as AbstractActivity?)?.setActionBar(binding.dataCollectionToolbar, showTitle = false)
return binding.root
}
override fun onBack(): Boolean =
if (viewPager.currentItem == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
false
} else {
// Otherwise, select the previous step.
viewModel.currentPosition.value = viewModel.currentPosition.value!! - 1
true
}
}
| apache-2.0 | e447950389f949b239e4b9a9f146aa0e | 37.623656 | 99 | 0.773385 | 4.707733 | false | false | false | false |
dahlstrom-g/intellij-community | platform/configuration-store-impl/src/ChooseComponentsToExportDialog.kt | 8 | 8501 | // 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.configurationStore
import com.intellij.ide.util.ElementsChooser
import com.intellij.ide.util.MultiStateElementsChooser
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.FieldPanel
import com.intellij.util.containers.CollectionFactory
import java.awt.Component
import java.awt.event.ActionEvent
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import javax.swing.*
private const val DEFAULT_FILE_NAME = "settings.zip"
private val DEFAULT_PATH = FileUtil.toSystemDependentName(PathManager.getConfigPath() + "/") + DEFAULT_FILE_NAME
private const val KEY_MARKED_NAMES = "export.settings.marked"
private val markedElementNames: Set<String>
get() {
val value = PropertiesComponent.getInstance().getValue(KEY_MARKED_NAMES)
return if (value.isNullOrEmpty()) {
emptySet()
}
else {
CollectionFactory.createSmallMemoryFootprintSet(value.trim { it <= ' ' }.split("|"))
}
}
private fun addToExistingListElement(item: ExportableItem,
itemToContainingListElement: MutableMap<ExportableItem, ComponentElementProperties>,
fileToItem: Map<FileSpec, List<ExportableItem>>): Boolean {
val list = fileToItem[item.fileSpec]
if (list.isNullOrEmpty()) {
return false
}
var file: FileSpec? = null
for (tiedItem in list) {
if (tiedItem === item) {
continue
}
val elementProperties = itemToContainingListElement[tiedItem]
if (elementProperties != null && item.fileSpec !== file) {
LOG.assertTrue(file == null, "Component $item serialize itself into $file and ${item.fileSpec}")
// found
elementProperties.items.add(item)
itemToContainingListElement[item] = elementProperties
file = item.fileSpec
}
}
return file != null
}
internal fun chooseSettingsFile(descriptor: FileChooserDescriptor,
initialPath: String?,
parent: Component?,
onFileChosen: (VirtualFile) -> Unit) {
FileChooser.chooseFile(descriptor, null, parent, getFileOrParent(initialPath), onFileChosen)
}
private fun getFileOrParent(path: String?): VirtualFile? {
if (path != null) {
val oldFile = File(path)
val initialDir = LocalFileSystem.getInstance().findFileByIoFile(oldFile)
return initialDir ?: oldFile.parentFile?.let {
LocalFileSystem.getInstance().findFileByIoFile(it)
}
}
return null
}
internal class ChooseComponentsToExportDialog(fileToComponents: Map<FileSpec, List<ExportableItem>>,
private val isShowFilePath: Boolean,
@NlsContexts.DialogTitle title: String,
@NlsContexts.Label private val description: String) : DialogWrapper(false) {
private val chooser: ElementsChooser<ComponentElementProperties>
private val pathPanel = FieldPanel(ConfigurationStoreBundle.message("editbox.export.settings.to"), null, { browse() }, null)
internal val exportableComponents: Set<ExportableItem>
get() {
val components = CollectionFactory.createSmallMemoryFootprintSet<ExportableItem>()
for (elementProperties in chooser.markedElements) {
components.addAll(elementProperties.items)
}
return components
}
internal val exportFile: Path
get() = Paths.get(pathPanel.text)
init {
val componentToContainingListElement = LinkedHashMap<ExportableItem, ComponentElementProperties>()
for (list in fileToComponents.values) {
for (item in list) {
if (!addToExistingListElement(item, componentToContainingListElement, fileToComponents)) {
val componentElementProperties = ComponentElementProperties()
componentElementProperties.items.add(item)
componentToContainingListElement[item] = componentElementProperties
}
}
}
chooser = ElementsChooser(true)
chooser.setColorUnmarkedElements(false)
val markedElementNames = markedElementNames
for (componentElementProperty in LinkedHashSet(componentToContainingListElement.values)) {
chooser.addElement(componentElementProperty, markedElementNames.isEmpty() || markedElementNames.contains(componentElementProperty.fileName), componentElementProperty)
}
chooser.sort(Comparator.comparing<ComponentElementProperties, String> { it.toString() })
val exportPath = PropertiesComponent.getInstance().getValue("export.settings.path", DEFAULT_PATH)
pathPanel.text = exportPath
pathPanel.changeListener = Runnable { this.updateControls() }
updateControls()
setTitle(title)
init()
}
private fun browse() {
val descriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor().apply {
title = ConfigurationStoreBundle.message("title.export.file.location")
description = ConfigurationStoreBundle.message("prompt.choose.export.settings.file.path")
isHideIgnored = false
withFileFilter { ConfigImportHelper.isSettingsFile(it) }
}
chooseSettingsFile(descriptor, pathPanel.text, window) { file ->
val path = if (file.isDirectory) "${file.path}/$DEFAULT_FILE_NAME" else file.path
pathPanel.text = FileUtil.toSystemDependentName(path)
}
}
private fun updateControls() {
isOKActionEnabled = !pathPanel.text.isNullOrBlank()
}
override fun createLeftSideActions(): Array<Action> {
val selectAll = object : AbstractAction(ConfigurationStoreBundle.message("export.components.list.action.select.all")) {
override fun actionPerformed(e: ActionEvent) {
chooser.setAllElementsMarked(true)
}
}
val selectNone = object : AbstractAction(ConfigurationStoreBundle.message("export.components.list.action.select.none")) {
override fun actionPerformed(e: ActionEvent) {
chooser.setAllElementsMarked(false)
}
}
val invert = object : AbstractAction(ConfigurationStoreBundle.message("export.components.list.action.invert.selection")) {
override fun actionPerformed(e: ActionEvent) {
chooser.invertSelection()
}
}
return arrayOf(selectAll, selectNone, invert)
}
override fun doOKAction() {
PropertiesComponent.getInstance().setValue("export.settings.path", pathPanel.text, DEFAULT_PATH)
val builder = StringBuilder()
if (chooser.hasUnmarkedElements()) {
val marked = chooser.getElements(true)
for (element in marked) {
builder.append(element.fileName)
builder.append("|")
}
}
PropertiesComponent.getInstance().setValue(KEY_MARKED_NAMES, if (builder.isEmpty()) null else builder.toString())
super.doOKAction()
}
override fun getPreferredFocusedComponent(): JTextField? = pathPanel.textField
override fun createNorthPanel() = JLabel(description)
override fun createCenterPanel(): JComponent = chooser
override fun createSouthPanel(): JComponent {
val buttons = super.createSouthPanel()
if (!isShowFilePath) {
return buttons
}
val panel = JPanel(VerticalFlowLayout())
panel.add(pathPanel)
panel.add(buttons)
return panel
}
override fun getDimensionServiceKey() = "#com.intellij.ide.actions.ChooseComponentsToExportDialog"
}
private class ComponentElementProperties : MultiStateElementsChooser.ElementProperties {
val items = CollectionFactory.createSmallMemoryFootprintSet<ExportableItem>()
val fileName: String
get() = items.first().fileSpec.relativePath
override fun toString(): String {
val names = LinkedHashSet<String>()
for (item in items) {
names.add(item.presentableName)
}
return names.joinToString(", ")
}
} | apache-2.0 | 46fac65e2c0f365b46898b2edd5d2673 | 37.645455 | 172 | 0.721092 | 4.991779 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/markerblocks/impl/BlockQuoteMarkerBlock.kt | 2 | 1616 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
public class BlockQuoteMarkerBlock(myConstraints: MarkdownConstraints, marker: ProductionHolder.Marker) : MarkerBlockImpl(myConstraints, marker) {
override fun allowsSubBlocks(): Boolean = true
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = pos.char == '\n'
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOffset ?: -1
}
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
assert(pos.char == '\n')
val nextLineConstraints = MarkdownConstraints.fromBase(pos, constraints)
// That means nextLineConstraints are "shorter" so our blockquote char is absent
if (!nextLineConstraints.extendsPrev(constraints)) {
return MarkerBlock.ProcessingResult.DEFAULT
}
return MarkerBlock.ProcessingResult.PASS
}
override fun getDefaultNodeType(): IElementType {
return MarkdownElementTypes.BLOCK_QUOTE
}
}
| apache-2.0 | aae8270feaa0a6835219015813a7d10e | 40.435897 | 146 | 0.773515 | 5.315789 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/flavours/gfm/StrikeThroughParser.kt | 1 | 2494 | package org.intellij.markdown.flavours.gfm
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil
import org.intellij.markdown.parser.sequentialparsers.TokensCache
import java.util.*
public class StrikeThroughParser : SequentialParser {
override fun parse(tokens: TokensCache, rangesToGlue: Collection<IntRange>): SequentialParser.ParsingResult {
val result = SequentialParser.ParsingResult()
val delegateIndices = ArrayList<Int>()
val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue)
var lastOpenedPos: Int? = null
var i = 0
while (i < indices.size) {
val iterator = tokens.ListIterator(indices, i)
if (iterator.type != GFMTokenTypes.TILDE) {
delegateIndices.add(indices.get(i))
i++
continue
}
if (lastOpenedPos != null
&& isGoodType(iterator.rawLookup(-1))
&& iterator.rawLookup(1) == GFMTokenTypes.TILDE) {
result.withNode(SequentialParser.Node(indices.get(lastOpenedPos)..indices.get(i + 1) + 1,
GFMElementTypes.STRIKETHROUGH));
i += 2
lastOpenedPos = null
continue
}
if (lastOpenedPos == null
&& iterator.rawLookup(1) == GFMTokenTypes.TILDE
&& isGoodType(iterator.rawLookup(2))) {
lastOpenedPos = i
i += 2
continue
}
delegateIndices.add(indices.get(i))
i++
}
if (lastOpenedPos != null) {
for (delta in 0..1) {
delegateIndices.add(indices.get(lastOpenedPos + delta))
}
Collections.sort(delegateIndices)
}
return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices))
}
private fun isGoodType(type: IElementType?): Boolean {
return type != null
&& type != MarkdownTokenTypes.WHITE_SPACE
&& type != MarkdownTokenTypes.EOL
&& type != GFMTokenTypes.TILDE
&& type != MarkdownTokenTypes.HTML_TAG
&& type != MarkdownTokenTypes.HTML_BLOCK_CONTENT;
}
} | apache-2.0 | c4db653f73f353e10750464c110d9132 | 36.80303 | 113 | 0.594627 | 5.306383 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/drawable/MediaBackgroundDrawable.kt | 1 | 2378 | package jp.juggler.subwaytooter.drawable
import android.graphics.*
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import kotlin.math.min
class MediaBackgroundDrawable(
private val tileStep: Int,
private val kind: Kind
) : Drawable() {
enum class Kind(@ColorInt val c1: Int, @ColorInt val c2: Int = 0) {
Black(Color.BLACK),
BlackTile(Color.BLACK, Color.BLACK or 0x202020),
Grey(Color.BLACK or 0x787878),
GreyTile(Color.BLACK or 0x707070, Color.BLACK or 0x808080),
White(Color.WHITE),
WhiteTile(Color.WHITE, Color.BLACK or 0xe0e0e0),
;
fun toIndex() = values().indexOf(this)
companion object {
fun fromIndex(idx: Int) = values().elementAtOrNull(idx) ?: BlackTile
}
}
private val rect = Rect()
private val paint = Paint().apply {
style = Paint.Style.FILL
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}
override fun getOpacity() = when (paint.alpha) {
255 -> PixelFormat.OPAQUE
0 -> PixelFormat.TRANSPARENT
else -> PixelFormat.TRANSLUCENT
}
override fun draw(canvas: Canvas) {
val bounds = this.bounds
val c1 = kind.c1
val c2 = kind.c2
if (c2 == 0) {
paint.color = c1
canvas.drawRect(bounds, paint)
return
}
val xStart = bounds.left
val xRepeat = (bounds.right - bounds.left + tileStep - 1) / tileStep
val yStart = bounds.top
val yRepeat = (bounds.bottom - bounds.top + tileStep - 1) / tileStep
for (y in 0 until yRepeat) {
val ys = yStart + y * tileStep
rect.top = ys
rect.bottom = min(bounds.bottom, ys + tileStep)
for (x in 0 until xRepeat) {
paint.color = when ((x + y).and(1)) {
0 -> c1
else -> c2
}
val xs = xStart + x * tileStep
rect.left = xs
rect.right = min(bounds.right, xs + tileStep)
canvas.drawRect(rect, paint)
}
}
}
}
| apache-2.0 | 2b499396f132cc54ab86d359999ff415 | 27.725 | 80 | 0.541211 | 4.238859 | false | false | false | false |
Vektah/CodeGlance | src/main/java/net/vektah/codeglance/GlancePanel.kt | 1 | 10410 | /*
* Copyright © 2013, Adam Scarr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 net.vektah.codeglance
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.colors.ColorKey
import com.intellij.openapi.editor.event.*
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.JBColor
import net.vektah.codeglance.concurrent.DirtyLock
import net.vektah.codeglance.config.Config
import net.vektah.codeglance.config.ConfigService
import net.vektah.codeglance.render.*
import javax.swing.*
import java.awt.*
import java.awt.event.*
import java.awt.image.BufferedImage
import java.lang.ref.SoftReference
/**
* This JPanel gets injected into editor windows and renders a image generated by GlanceFileRenderer
*/
class GlancePanel(private val project: Project, fileEditor: FileEditor, private val container: JPanel, private val runner: TaskRunner) : JPanel(), VisibleAreaListener {
private val editor = (fileEditor as TextEditor).editor
private var mapRef = SoftReference<Minimap>(null)
private val configService = ServiceManager.getService(ConfigService::class.java)
private var config: Config = configService.state!!
private var lastFoldCount = -1
private var buf: BufferedImage? = null
private val renderLock = DirtyLock()
private val scrollstate = ScrollState()
private val scrollbar = Scrollbar(editor, scrollstate)
// Anonymous Listeners that should be cleaned up.
private val componentListener: ComponentListener
private val documentListener: DocumentListener
private val selectionListener: SelectionListener = SelectionListener { repaint() }
private val isDisabled: Boolean
get() = config.disabled || editor.document.textLength > config.maxFileSize || editor.document.lineCount < config.minLineCount || container.width < config.minWindowWidth
private val onConfigChange = {
updateImage()
updateSize()
[email protected]()
[email protected]()
}
init {
componentListener = object : ComponentAdapter() {
override fun componentResized(componentEvent: ComponentEvent?) {
updateSize()
scrollstate.setVisibleHeight(height)
[email protected]()
[email protected]()
}
}
container.addComponentListener(componentListener)
documentListener = object : DocumentAdapter() {
override fun documentChanged(documentEvent: DocumentEvent?) {
updateImage()
}
}
editor.document.addDocumentListener(documentListener)
configService.onChange(onConfigChange)
editor.scrollingModel.addVisibleAreaListener(this)
editor.selectionModel.addSelectionListener(selectionListener)
updateSize()
updateImage()
isOpaque = false
layout = BorderLayout()
add(scrollbar)
}
/**
* Adjusts the panels size to be a percentage of the total window
*/
private fun updateSize() {
if (isDisabled) {
preferredSize = Dimension(0, 0)
} else {
val size = Dimension(config.width, 0)
preferredSize = size
}
}
// the minimap is held by a soft reference so the GC can delete it at any time.
// if its been deleted and we want it again (active tab) we recreate it.
private fun getOrCreateMap() : Minimap? {
var map = mapRef.get()
if (map == null) {
map = Minimap(configService.state!!)
mapRef = SoftReference<Minimap>(map)
}
return map
}
/**
* Fires off a new task to the worker thread. This should only be called from the ui thread.
*/
private fun updateImage() {
if (isDisabled) return
if (project.isDisposed) return
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return
val map = getOrCreateMap() ?: return
if (!renderLock.acquire()) return
val hl = SyntaxHighlighterFactory.getSyntaxHighlighter(file.language, project, file.virtualFile)
val text = editor.document.text
val folds = Folds(editor.foldingModel.allFoldRegions)
runner.run {
map.update(text, editor.colorsScheme, hl, folds)
scrollstate.setDocumentSize(config.width, map.height)
renderLock.release()
if (renderLock.dirty) {
updateImageSoon()
renderLock.clean()
}
repaint()
}
}
private fun updateImageSoon() = SwingUtilities.invokeLater { updateImage() }
fun paintLast(gfx: Graphics?) {
val g = gfx as Graphics2D
if (buf != null) {
g.drawImage(buf,
0, 0, buf!!.width, buf!!.height,
0, 0, buf!!.width, buf!!.height,
null)
}
paintSelections(g)
scrollbar.paint(gfx)
}
override fun paint(gfx: Graphics?) {
if (renderLock.locked) {
paintLast(gfx)
return
}
val minimap = mapRef.get()
if (minimap == null) {
updateImageSoon()
paintLast(gfx)
return
}
if (buf == null || buf?.width!! < width || buf?.height!! < height) {
buf = BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR)
}
val g = buf!!.createGraphics()
g.composite = AlphaComposite.getInstance(AlphaComposite.CLEAR)
g.fillRect(0, 0, width, height)
g.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER)
if (editor.document.textLength != 0) {
g.drawImage(
minimap.img,
0, 0, scrollstate.documentWidth, scrollstate.drawHeight,
0, scrollstate.visibleStart, scrollstate.documentWidth, scrollstate.visibleEnd,
null
)
}
paintSelections(gfx as Graphics2D)
gfx.drawImage(buf, 0, 0, null)
scrollbar.paint(gfx)
}
private fun paintSelection(g: Graphics2D, startByte: Int, endByte: Int) {
val start = editor.offsetToVisualPosition(startByte)
val end = editor.offsetToVisualPosition(endByte)
val sX = start.column
val sY = (start.line + 1) * config.pixelsPerLine - scrollstate.visibleStart
val eX = end.column
val eY = (end.line + 1) * config.pixelsPerLine - scrollstate.visibleStart
g.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.80f)
g.color = editor.colorsScheme.getColor(ColorKey.createColorKey("SELECTION_BACKGROUND", JBColor.BLUE))
// Single line is real easy
if (start.line == end.line) {
g.fillRect(
sX,
sY,
eX - sX,
config.pixelsPerLine
)
} else {
// Draw the line leading in
g.fillRect(sX, sY, width - sX, config.pixelsPerLine)
// Then the line at the end
g.fillRect(0, eY, eX, config.pixelsPerLine)
if (eY + config.pixelsPerLine != sY) {
// And if there is anything in between, fill it in
g.fillRect(0, sY + config.pixelsPerLine, width, eY - sY - config.pixelsPerLine)
}
}
}
private fun paintSelections(g: Graphics2D) {
paintSelection(g, editor.selectionModel.selectionStart, editor.selectionModel.selectionEnd)
for ((index, start) in editor.selectionModel.blockSelectionStarts.withIndex()) {
paintSelection(g, start, editor.selectionModel.blockSelectionEnds[index])
}
}
override fun visibleAreaChanged(visibleAreaEvent: VisibleAreaEvent) {
// TODO pending http://youtrack.jetbrains.com/issue/IDEABKL-1141 - once fixed this should be a listener
var currentFoldCount = 0
for (fold in editor.foldingModel.allFoldRegions) {
if (!fold.isExpanded) {
currentFoldCount++
}
}
val visibleArea = editor.scrollingModel.visibleArea
val factor = scrollstate.documentHeight.toDouble() / editor.contentComponent.height
scrollstate.setViewportArea((factor * visibleArea.y).toInt(), (factor * visibleArea.height).toInt())
scrollstate.setVisibleHeight(height)
if (currentFoldCount != lastFoldCount) {
updateImage()
}
lastFoldCount = currentFoldCount
updateSize()
repaint()
}
fun onClose() {
container.removeComponentListener(componentListener)
editor.document.removeDocumentListener(documentListener)
editor.selectionModel.removeSelectionListener(selectionListener)
remove(scrollbar)
mapRef.clear()
}
}
| bsd-2-clause | 22de3c8df29982103af5159091c70d76 | 34.404762 | 176 | 0.654722 | 4.866293 | false | true | false | false |
buzmaxx/WODDiary | app/src/main/java/woddiary20/bazaleev/io/woddiary20/storage/cntntprvdr/WODContentProvider.kt | 1 | 5479 | package woddiary20.bazaleev.io.woddiary20.storage.cntntprvdr
import android.content.*
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import java.util.*
/**
* Created by max on 11/17/16.
*/
class WODContentProvider : ContentProvider() {
var database: WODDB? = null
var uriMatcher: UriMatcher? = null
init {
uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
uriMatcher!!.addURI(WODDBConstants.AUTHORITY, WODDBConstants.Exercise.BASE_PATH, WODDBConstants.Exercise.EXERCISE_MATCHER_CODE)
uriMatcher!!.addURI(WODDBConstants.AUTHORITY, WODDBConstants.Set.BASE_PATH, WODDBConstants.Set.SETS_MATCHER_CODE)
uriMatcher!!.addURI(WODDBConstants.AUTHORITY, WODDBConstants.ExerciseSet.BASE_PATH, WODDBConstants.ExerciseSet.EXERCISES_SETS_MATCHER_CODE)
}
override fun onCreate(): Boolean {
database = WODDB(context)
return false
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
val match = uriMatcher!!.match(uri)
val queryBuilder = SQLiteQueryBuilder()
when (match) {
WODDBConstants.Exercise.EXERCISE_MATCHER_CODE -> queryBuilder.tables = WODDBConstants.Exercise.TABLE_NAME
WODDBConstants.Set.SETS_MATCHER_CODE -> queryBuilder.tables = WODDBConstants.Set.TABLE_NAME
WODDBConstants.ExerciseSet.EXERCISES_SETS_MATCHER_CODE -> {
queryBuilder.tables = WODDBConstants.ExerciseSet.EXERCISES_SETS_TABLE_CREATE
queryBuilder.setProjectionMap(WODDBConstants.ExerciseSet.projectionMap)
}
}
val cursor = queryBuilder.query(database!!.readableDatabase, projection, selection, selectionArgs, null, null, sortOrder)
cursor.setNotificationUri(context.contentResolver, uri)
return cursor
}
// SQLiteQuery: SELECT amount, time, exercise_name, exercise_date, reps_count, _order_, exercise_type, exercises._id, exercise_duration FROM exercises LEFT JOIN sets ON sets.exercise_id=exercises._id
override fun getType(uri: Uri): String? {
when (uriMatcher!!.match(uri)) {
WODDBConstants.Exercise.EXERCISE_MATCHER_CODE -> return WODDBConstants.Exercise.CONTENT_TYPE
WODDBConstants.Set.SETS_MATCHER_CODE -> return WODDBConstants.Set.CONTENT_TYPE
}
return null
}
override fun insert(uri: Uri, contentValues: ContentValues?): Uri? {
val writableDatabase = database!!.writableDatabase
var rowUri: Uri? = null
var rowId: Long = -1
var contentUri: Uri? = null
when (uriMatcher!!.match(uri)) {
WODDBConstants.Exercise.EXERCISE_MATCHER_CODE -> {
rowId = writableDatabase.insert(WODDBConstants.Exercise.TABLE_NAME, null, contentValues)
contentUri = WODDBConstants.Exercise.CONTENT_ID_URI_BASE
}
WODDBConstants.Set.SETS_MATCHER_CODE -> {
rowId = writableDatabase.insert(WODDBConstants.Set.TABLE_NAME, null, contentValues)
contentUri = WODDBConstants.Set.CONTENT_ID_URI_BASE
}
}
if (rowId > 0) {
rowUri = ContentUris.withAppendedId(contentUri, rowId)
context.contentResolver.notifyChange(uri, null)
}
return rowUri
}
override fun bulkInsert(uri: Uri?, values: Array<out ContentValues>?): Int {
when (uriMatcher!!.match(uri)) {
WODDBConstants.Exercise.EXERCISE_MATCHER_CODE -> insertValues(values!!, WODDBConstants.Exercise.TABLE_NAME)
WODDBConstants.Set.SETS_MATCHER_CODE -> insertValues(values!!, WODDBConstants.Set.TABLE_NAME)
}
context.contentResolver.notifyChange(uri, null)
return values!!.size
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val writableDatabase = database!!.writableDatabase
var tableName: String = ""
when (uriMatcher!!.match(uri)) {
WODDBConstants.Exercise.EXERCISE_MATCHER_CODE -> {
tableName = WODDBConstants.Exercise.TABLE_NAME
}
WODDBConstants.Set.SETS_MATCHER_CODE -> {
tableName = WODDBConstants.Set.TABLE_NAME
}
}
return writableDatabase.delete(tableName, selection, selectionArgs)
}
override fun update(uri: Uri, contentValues: ContentValues?, s: String?, strings: Array<String>?): Int {
return 0
}
override fun applyBatch(operations: ArrayList<ContentProviderOperation>?): Array<out ContentProviderResult> {
val results: Array<ContentProviderResult>
val db = database!!.writableDatabase
db.beginTransaction()
try {
results = super.applyBatch(operations)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
return results
}
private fun insertValues(values: Array<out ContentValues>, tableName: String) {
val writableDatabase = database!!.writableDatabase
writableDatabase.beginTransaction()
try {
values.forEach {
writableDatabase.insertOrThrow(tableName, null, it)
}
writableDatabase.setTransactionSuccessful()
} finally {
writableDatabase.endTransaction()
}
}
} | apache-2.0 | 0a64f54c91d60bbec01b1f344350d7c2 | 39.895522 | 204 | 0.661435 | 4.949413 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/ClosureAsAnonymousParameterEnhancer.kt | 2 | 2512 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.PsiWildcardType
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSafeCastExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.findCall
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.GroovyInferenceSessionBuilder
import org.jetbrains.plugins.groovy.lang.sam.findSingleAbstractSignature
open class ClosureAsAnonymousParameterEnhancer : AbstractClosureParameterEnhancer() {
override fun getClosureParameterType(expression: GrFunctionalExpression, index: Int): PsiType? {
val type = expectedType(expression) as? PsiClassType ?: return null
val result = type.resolveGenerics()
val clazz = result.element ?: return null
val substitutor = result.substitutor
val sam = findSingleAbstractSignature(clazz) ?: return null
return sam.parameterTypes.getOrNull(index)?.let(substitutor::substitute)?.let(::unwrapBound)
}
private fun expectedType(expression: GrFunctionalExpression): PsiType? {
val parent = expression.parent
if (parent is GrSafeCastExpression) {
return parent.castTypeElement?.type
}
else {
return fromMethodCall(expression)
}
}
private fun fromMethodCall(expression: GrFunctionalExpression): PsiType? {
val call = findCall(expression) ?: return null
val variant = call.advancedResolve() as? GroovyMethodResult ?: return null
val candidate = variant.candidate ?: return null
val mapping = candidate.argumentMapping ?: return null
val expectedType = mapping.expectedType(ExpressionArgument(expression)) ?: return null
val substitutor = GroovyInferenceSessionBuilder(call, candidate, variant.contextSubstitutor)
.skipClosureIn(call)
.resolveMode(false)
.build()
.inferSubst()
return substitutor.substitute(expectedType)
}
private fun unwrapBound(type: PsiType): PsiType? {
return if (type is PsiWildcardType && type.isSuper) {
type.bound
}
else {
type
}
}
}
| apache-2.0 | 43d790a96f9900e57fa578b762578bcb | 42.310345 | 140 | 0.771099 | 4.712946 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodProcessor.kt | 2 | 4126 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.*
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
import com.intellij.psi.scope.JavaScopeProcessorEvent
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import com.intellij.psi.scope.PsiScopeProcessor.Event
import com.intellij.util.SmartList
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.util.elementInfo
import org.jetbrains.plugins.groovy.lang.resolve.*
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.impl.*
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.putAll
class MethodProcessor(
private val name: String,
private val place: PsiElement,
private val arguments: Arguments?,
private val typeArguments: Array<out PsiType>
) : ProcessorWithHints(),
NameHint,
GroovyResolveKind.Hint,
ElementClassHint,
DynamicMembersHint {
init {
hint(NameHint.KEY, this)
hint(GroovyResolveKind.HINT_KEY, this)
hint(ElementClassHint.KEY, this)
hint(DynamicMembersHint.KEY, this)
}
override fun getName(state: ResolveState): String? = name
override fun shouldProcess(kind: GroovyResolveKind): Boolean = kind == GroovyResolveKind.METHOD && acceptMore
override fun shouldProcess(kind: DeclarationKind): Boolean = kind == DeclarationKind.METHOD && acceptMore
override fun shouldProcessMethods(): Boolean = myCandidates.isEmpty()
private val myCandidates = SmartList<GroovyMethodResult>()
private var myApplicable: ApplicabilitiesResult? = null
private val acceptMore: Boolean get() = myApplicable?.first.isNullOrEmpty()
override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (!acceptMore) {
log.warn("Don't pass more methods if processor doesn't want to accept them")
return false
}
if (element !is PsiMethod) {
if (state[sorryCannotKnowElementKind] != true) {
log.error("Unexpected element. ${elementInfo(element)}")
}
return true
}
if (name != getName(state, element)) return true
myCandidates += when {
!element.hasTypeParameters() -> {
// ignore explicit type arguments if there are no type parameters => no inference needed
BaseMethodResolveResult(element, place, state, arguments)
}
typeArguments.isEmpty() -> {
// generic method call without explicit type arguments => needs inference
MethodResolveResult(element, place, state, arguments)
}
else -> {
// generic method call with explicit type arguments => inference happens right here
val substitutor = state[PsiSubstitutor.KEY].putAll(element.typeParameters, typeArguments)
BaseMethodResolveResult(element, place, state.put(PsiSubstitutor.KEY, substitutor), arguments)
}
}
myApplicable = null
return true
}
override fun handleEvent(event: Event, associated: Any?) {
if (JavaScopeProcessorEvent.CHANGE_LEVEL === event && myApplicable == null) {
myApplicable = computeApplicableCandidates()
}
}
private fun computeApplicableCandidates(): Pair<List<GroovyMethodResult>, Boolean> {
return myCandidates
.correctStaticScope()
.findApplicable()
}
val applicableCandidates: List<GroovyMethodResult>?
get() {
val (applicableCandidates, canChooseOverload) = myApplicable ?: computeApplicableCandidates()
if (applicableCandidates.isEmpty()) return null
val filteredBySignature = filterBySignature(applicableCandidates)
if (canChooseOverload) {
return chooseOverloads(filteredBySignature)
}
else {
return filteredBySignature
}
}
val allCandidates: List<GroovyMethodResult> get() = myCandidates
}
| apache-2.0 | 2c4e9555bf1460a61f05878321a5741f | 37.203704 | 140 | 0.73873 | 4.69397 | false | false | false | false |
Zeyad-37/RxRedux | app/src/main/java/com/zeyad/rxredux/screens/list/UserListActivity2.kt | 1 | 13611 | package com.zeyad.rxredux.screens.list
import android.app.ActivityOptions
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.util.Pair
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import com.jakewharton.rxbinding2.support.v7.widget.RxSearchView
import com.jakewharton.rxbinding2.support.v7.widget.scrollEvents
import com.zeyad.gadapter.*
import com.zeyad.gadapter.GenericAdapter.Companion.SECTION_HEADER
import com.zeyad.rxredux.R
import com.zeyad.rxredux.core.view.IBaseActivity
import com.zeyad.rxredux.screens.User
import com.zeyad.rxredux.screens.detail.IntentBundleState
import com.zeyad.rxredux.screens.detail.UserDetailActivity
import com.zeyad.rxredux.screens.detail.UserDetailFragment
import com.zeyad.rxredux.screens.list.viewHolders.EmptyViewHolder
import com.zeyad.rxredux.screens.list.viewHolders.SectionHeaderViewHolder
import com.zeyad.rxredux.screens.list.viewHolders.UserViewHolder
import com.zeyad.rxredux.utils.hasLollipop
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_user_list.*
import kotlinx.android.synthetic.main.user_list.*
import kotlinx.android.synthetic.main.view_progress.*
import org.koin.android.viewmodel.ext.android.getViewModel
import java.util.concurrent.TimeUnit
/**
* An activity representing a list of Repos. This activity has different presentations for handset
* and tablet-size devices. On handsets, the activity presents a list of items, which when touched,
* lead to a [UserDetailActivity] representing item details. On tablets, the activity presents
* the list of items and item details side-by-side using two vertical panes.
*/
class UserListActivity2 : AppCompatActivity(), OnStartDragListener, ActionMode.Callback,
IBaseActivity<UserListIntents, UserListResult, UserListState, UserListEffect, UserListVM> {
override lateinit var intentStream: Observable<UserListIntents>
override lateinit var viewModel: UserListVM
override lateinit var viewState: UserListState
private lateinit var itemTouchHelper: ItemTouchHelper
private lateinit var usersAdapter: GenericRecyclerViewAdapter
private var actionMode: ActionMode? = null
private var currentFragTag: String = ""
private var twoPane: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
onCreateImpl(savedInstanceState)
Log.d("UserListActivity2", "we are here!")
}
override fun initialStateProvider(): UserListState = EmptyState()
override fun isViewStateInitialized(): Boolean = ::viewState.isInitialized
override fun onSaveInstanceState(outState: Bundle) {
onSaveInstanceStateImpl(outState, viewState)
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
onRestoreInstanceStateImpl(savedInstanceState)
}
override fun initialize() {
viewModel = getViewModel()
intentStream = Observable.empty()
}
override fun setupUI(isNew: Boolean) {
setContentView(R.layout.activity_user_list)
setSupportActionBar(toolbar)
toolbar.title = title
setupRecyclerView()
twoPane = findViewById<View>(R.id.user_detail_container) != null
}
override fun onResume() {
super.onResume()
if (viewState is EmptyState) {
viewModel.intents.onNext(GetPaginatedUsersIntent(0))
}
}
override fun bindState(successState: UserListState) {
usersAdapter.setDataList(successState.list, successState.callback)
}
override fun bindEffect(effectBundle: UserListEffect) = Unit
override fun toggleLoadingViews(isLoading: Boolean, intent: UserListIntents?) {
linear_layout_loader.bringToFront()
linear_layout_loader.visibility = if (isLoading) View.VISIBLE else View.GONE
}
override fun bindError(errorMessage: String, intent: UserListIntents?, cause: Throwable) {
// showErrorSnackBar(errorMessage, user_list, Snackbar.LENGTH_LONG)
}
private fun setupRecyclerView() {
usersAdapter = object : GenericRecyclerViewAdapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GenericViewHolder<*> {
return when (viewType) {
SECTION_HEADER -> SectionHeaderViewHolder(layoutInflater
.inflate(R.layout.section_header_layout, parent, false))
R.layout.empty_view -> EmptyViewHolder(layoutInflater
.inflate(R.layout.empty_view, parent, false))
R.layout.user_item_layout -> UserViewHolder(layoutInflater
.inflate(R.layout.user_item_layout, parent, false))
else -> throw IllegalArgumentException("Could not find view of type $viewType")
}
}
}
usersAdapter.setAreItemsClickable(true)
usersAdapter.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClicked(position: Int, itemInfo: ItemInfo<*>, holder: GenericViewHolder<*>) {
if (actionMode != null) {
toggleItemSelection(position)
} else if (itemInfo.data is User) {
val userModel = itemInfo.data as User
val userDetailState = IntentBundleState(userModel)
var pair: Pair<View, String>? = null
var secondPair: Pair<View, String>? = null
if (hasLollipop()) {
val userViewHolder = holder as UserViewHolder
val avatar = userViewHolder.getAvatar()
pair = Pair.create(avatar, avatar.transitionName)
val textViewTitle = userViewHolder.getTextViewTitle()
secondPair = Pair.create(textViewTitle, textViewTitle.transitionName)
}
if (twoPane) {
if (currentFragTag.isNotBlank()) {
removeFragment(currentFragTag)
}
val orderDetailFragment = UserDetailFragment.newInstance(userDetailState)
currentFragTag = orderDetailFragment.javaClass.simpleName + userModel.id
addFragment(R.id.user_detail_container, orderDetailFragment, currentFragTag,
pair!!, secondPair!!)
} else {
if (hasLollipop()) {
val options = ActivityOptions
.makeSceneTransitionAnimation(this@UserListActivity2, pair,
secondPair).toBundle()
startActivity(UserDetailActivity
.getCallingIntent(this@UserListActivity2, userDetailState), options)
} else {
startActivity(UserDetailActivity.getCallingIntent(this@UserListActivity2, userDetailState))
}
}
}
}
})
usersAdapter.setOnItemLongClickListener(object : OnItemLongClickListener {
override fun onItemLongClicked(position: Int, itemInfo: ItemInfo<*>, holder: GenericViewHolder<*>): Boolean {
if (usersAdapter.isSelectionAllowed) {
actionMode = startSupportActionMode(this@UserListActivity2)
toggleItemSelection(position)
}
return true
}
})
user_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
user_list.adapter = usersAdapter
usersAdapter.setAllowSelection(true)
// fastScroller.setRecyclerView(userRecycler)
intentStream = intentStream.mergeWith(user_list.scrollEvents()
.map { recyclerViewScrollEvent ->
GetPaginatedUsersIntent(
if (ScrollEventCalculator.isAtScrollEnd(recyclerViewScrollEvent))
viewState.lastId
else -1)
}
.filter { it.lastId != -1L }
.throttleLast(200, TimeUnit.MILLISECONDS, Schedulers.computation())
.debounce(300, TimeUnit.MILLISECONDS, Schedulers.computation())
.doOnNext { Log.d("NextPageIntent", UserListActivity.FIRED) })
.mergeWith(usersAdapter.itemSwipeObservable
.map { itemInfo -> DeleteUsersIntent(listOf((itemInfo.data as User).login)) }
.doOnEach { Log.d("DeleteIntent", UserListActivity.FIRED) })
itemTouchHelper = ItemTouchHelper(SimpleItemTouchHelperCallback(usersAdapter))
itemTouchHelper.attachToRecyclerView(user_list)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.list_menu, menu)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = menu.findItem(R.id.menu_search).actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.setOnCloseListener {
viewModel.intents.onNext(GetPaginatedUsersIntent(viewState.lastId))
false
}
intentStream = intentStream.mergeWith(RxSearchView.queryTextChanges(searchView)
.filter { charSequence -> charSequence.toString().isNotEmpty() }
.throttleLast(100, TimeUnit.MILLISECONDS, Schedulers.computation())
.debounce(200, TimeUnit.MILLISECONDS, Schedulers.computation())
.map { query -> SearchUsersIntent(query.toString()) }
.distinctUntilChanged()
.doOnEach { Log.d("SearchIntent", FIRED) })
return super.onCreateOptionsMenu(menu)
}
private fun toggleItemSelection(position: Int) {
usersAdapter.toggleSelection(position)
val count = usersAdapter.selectedItemCount
if (count == 0) {
actionMode?.finish()
} else {
actionMode?.title = count.toString()
actionMode?.invalidate()
}
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.selected_list_menu, menu)
menu.findItem(R.id.delete_item).setOnMenuItemClickListener {
viewModel.intents.onNext(DeleteUsersIntent(Observable.fromIterable(usersAdapter.selectedItems)
.map<String> { itemInfo -> (itemInfo.data as User).login }.toList()
.blockingGet()))
true
}
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
menu.findItem(R.id.delete_item).setVisible(true).isEnabled = true
toolbar.visibility = View.GONE
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return item.itemId == R.id.delete_item
}
override fun onDestroyActionMode(mode: ActionMode) {
try {
usersAdapter.clearSelection()
} catch (e: Exception) {
Log.e("onDestroyActionMode", e.message, e)
}
actionMode = null
toolbar.visibility = View.VISIBLE
}
override fun onStartDrag(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
itemTouchHelper.startDrag(viewHolder)
}
fun getImageViewAvatar(): ImageView = imageView_avatar
/**
* Adds a [Fragment] to this activity's layout.
*
* @param containerViewId The container view to where add the fragment.
* @param fragment The fragment to be added.
*/
@SafeVarargs
fun addFragment(containerViewId: Int, fragment: Fragment, currentFragTag: String?,
vararg sharedElements: Pair<View, String>) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
for (pair in sharedElements) {
fragmentTransaction.addSharedElement(pair.first, pair.second)
}
if (currentFragTag == null || currentFragTag.isEmpty()) {
fragmentTransaction.addToBackStack(fragment.tag)
} else {
fragmentTransaction.addToBackStack(currentFragTag)
}
fragmentTransaction.add(containerViewId, fragment, fragment.tag).commit()
}
private fun removeFragment(tag: String) {
supportFragmentManager.findFragmentByTag(tag)?.let {
supportFragmentManager.beginTransaction().remove(it).commit()
}
}
companion object {
const val FIRED = "fired!"
fun getCallingIntent(context: Context): Intent {
return Intent(context, UserListActivity2::class.java)
}
}
}
| apache-2.0 | 8908a0de4864727f5f2264b8b782164b | 43.773026 | 121 | 0.657116 | 5.379842 | false | false | false | false |
apollographql/apollo-android | apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/api/CacheKeyResolver.kt | 1 | 3364 | package com.apollographql.apollo3.cache.normalized.api
import com.apollographql.apollo3.api.CompiledField
import com.apollographql.apollo3.api.CompiledListType
import com.apollographql.apollo3.api.CompiledNamedType
import com.apollographql.apollo3.api.CompiledNotNullType
import com.apollographql.apollo3.api.Executable
import com.apollographql.apollo3.api.isComposite
import kotlin.jvm.JvmSuppressWildcards
/**
* A [CacheResolver] that resolves objects and list of objects and fallbacks to the default resolver for scalar fields.
* It is intended to simplify the usage of [CacheResolver] when no special handling is needed for scalar fields.
*
* Override [cacheKeyForField] to compute a cache key for a field of composite type.
* Override [listOfCacheKeysForField] to compute a list of cache keys for a field of 'list-of-composite' type.
*
* For simplicity, this only handles one level of list. Implement [CacheResolver] if you need arbitrary nested lists of objects.
*/
abstract class CacheKeyResolver : CacheResolver {
/**
* Return the computed the cache key for a composite field.
*
* If the field is of object type, you can get the object typename with `field.type.leafType().name`
* If the field is of interface type, the concrete object typename is not predictable and the returned [CacheKey] must be unique
* in the whole schema as it cannot be namespaced by the typename anymore.
*
* If the returned [CacheKey] is null, the resolver will use the default handling and use any previously cached value.
*/
abstract fun cacheKeyForField(field: CompiledField, variables: Executable.Variables): CacheKey?
/**
* For a field that contains a list of objects, [listOfCacheKeysForField ] returns a list of [CacheKey]s where each [CacheKey] identifies an object.
*
* If the field is of object type, you can get the object typename with `field.type.leafType().name`
* If the field is of interface type, the concrete object typename is not predictable and the returned [CacheKey] must be unique
* in the whole schema as it cannot be namespaced by the typename anymore.
*
* If an individual [CacheKey] is null, the resulting object will be null in the response.
* If the returned list of [CacheKey]s is null, the resolver will use the default handling and use any previously cached value.
*/
open fun listOfCacheKeysForField(field: CompiledField, variables: Executable.Variables): List<CacheKey?>? = null
final override fun resolveField(
field: CompiledField,
variables: Executable.Variables,
parent: Map<String, @JvmSuppressWildcards Any?>,
parentId: String,
): Any? {
var type = field.type
if (type is CompiledNotNullType) {
type = type.ofType
}
if (type is CompiledNamedType && type.isComposite()) {
val result = cacheKeyForField(field, variables)
if (result != null) {
return result
}
}
if (type is CompiledListType) {
type = type.ofType
if (type is CompiledNotNullType) {
type = type.ofType
}
if (type is CompiledNamedType && type.isComposite()) {
val result = listOfCacheKeysForField(field, variables)
if (result != null) {
return result
}
}
}
return DefaultCacheResolver.resolveField(field, variables, parent, parentId)
}
}
| mit | a73de5eb6177687227d1bb6e376eb692 | 43.263158 | 150 | 0.729191 | 4.545946 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinStdlibCache.kt | 1 | 12811 | // 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.projectStructure
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.DumbModeAccessType
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.messages.MessageBusConnection
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.vfilefinder.KotlinStdlibIndex
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
// TODO(kirpichenkov): works only for JVM (see KT-44552)
interface KotlinStdlibCache {
fun isStdlib(libraryInfo: LibraryInfo): Boolean
fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean
fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo?
companion object {
fun getInstance(project: Project): KotlinStdlibCache =
if (IdeBuiltInsLoadingState.isFromClassLoader) {
Disabled
} else {
project.getService(KotlinStdlibCache::class.java)
?: error("Failed to load service ${KotlinStdlibCache::class.java.name}")
}
val Disabled = object : KotlinStdlibCache {
override fun isStdlib(libraryInfo: LibraryInfo) = false
override fun isStdlibDependency(libraryInfo: LibraryInfo) = false
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? = null
}
}
}
internal class KotlinStdlibCacheImpl(private val project: Project) : KotlinStdlibCache, Disposable {
companion object {
private const val KOTLIN_JAVA_RUNTIME_NAME = "KotlinJavaRuntime"
private val noStdlibDependency = StdlibDependency(null)
}
@JvmInline
private value class StdlibDependency(val libraryInfo: LibraryInfo?)
private val stdlibCache = StdLibCache()
private val stdlibDependencyCache = StdlibDependencyCache()
private val moduleStdlibDependencyCache = ModuleStdlibDependencyCache()
init {
Disposer.register(this, stdlibCache)
Disposer.register(this, stdlibDependencyCache)
Disposer.register(this, moduleStdlibDependencyCache)
}
private class LibraryScope(
project: Project,
private val directories: Set<VirtualFile>
) : DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
private val fileSystems = directories.mapTo(hashSetOf(), VirtualFile::getFileSystem)
override fun contains(file: VirtualFile): Boolean = file.fileSystem in fileSystems && VfsUtilCore.isUnder(file, directories)
override fun toString() = "All files under: $directories"
}
private fun libraryScopeContainsIndexedFilesForNames(libraryInfo: LibraryInfo, names: Collection<FqName>): Boolean {
val libraryScope = LibraryScope(project, libraryInfo.library.getFiles(OrderRootType.CLASSES).toSet())
return names.any { name ->
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
FileBasedIndex.getInstance().getContainingFilesIterator(KotlinStdlibIndex.KEY, name, libraryScope).hasNext()
})
}
}
private fun libraryScopeContainsIndexedFilesForName(libraryInfo: LibraryInfo, name: FqName) =
libraryScopeContainsIndexedFilesForNames(libraryInfo, listOf(name))
private fun isFatJar(libraryInfo: LibraryInfo) = libraryInfo.getLibraryRoots().size > 1
private fun isKotlinJavaRuntime(libraryInfo: LibraryInfo) = libraryInfo.library.name == KOTLIN_JAVA_RUNTIME_NAME
override fun isStdlib(libraryInfo: LibraryInfo): Boolean = stdlibCache[libraryInfo]
override fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean = stdlibDependencyCache[libraryInfo]
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? {
ProgressManager.checkCanceled()
val stdlibDependency = moduleStdlibDependencyCache.get(module)
return stdlibDependency.libraryInfo
}
override fun dispose() = Unit
private sealed class BaseStdLibCache(project: Project) :
SynchronizedFineGrainedEntityCache<LibraryInfo, Boolean>(project, cleanOnLowMemory = true),
LibraryInfoListener {
override fun subscribe() {
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(LibraryInfoListener.TOPIC, this)
}
override fun checkKeyValidity(key: LibraryInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateKeys(libraryInfos)
}
}
private inner class StdLibCache : BaseStdLibCache(project) {
override fun calculate(key: LibraryInfo): Boolean =
libraryScopeContainsIndexedFilesForName(key, KotlinStdlibIndex.KOTLIN_STDLIB_NAME) &&
(!isFatJar(key) || isKotlinJavaRuntime(key))
}
private inner class StdlibDependencyCache : BaseStdLibCache(project) {
override fun calculate(key: LibraryInfo): Boolean =
libraryScopeContainsIndexedFilesForNames(key, KotlinStdlibIndex.STANDARD_LIBRARY_DEPENDENCY_NAMES) &&
(!isFatJar(key) || isKotlinJavaRuntime(key))
}
private inner class ModuleStdlibDependencyCache : Disposable {
private val libraryCache = LibraryCache()
private val moduleCache = ModuleCache()
init {
Disposer.register(this, libraryCache)
Disposer.register(this, moduleCache)
}
fun get(key: IdeaModuleInfo): StdlibDependency = when (key) {
is LibraryInfo -> libraryCache[key]
is SdkInfo, is NotUnderContentRootModuleInfo -> noStdlibDependency
else -> moduleCache[key]
}
override fun dispose() = Unit
private abstract inner class AbstractCache<Key : IdeaModuleInfo> :
SynchronizedFineGrainedEntityCache<Key, StdlibDependency>(project, cleanOnLowMemory = true),
LibraryInfoListener {
override fun subscribe() {
val connection = project.messageBus.connect(this)
connection.subscribe(LibraryInfoListener.TOPIC, this)
subscribe(connection)
}
protected open fun subscribe(connection: MessageBusConnection) {
}
protected fun Key.findStdLib(): LibraryInfo? {
val dependencies = if (this is LibraryInfo) {
if (isStdlib(this)) return this
LibraryDependenciesCache.getInstance(project).getLibraryDependencies(this).libraries
} else {
dependencies()
}
return dependencies.firstNotNullOfOrNull { it.safeAs<LibraryInfo>()?.takeIf(::isStdlib) }
}
protected fun LibraryInfo?.toStdlibDependency(): StdlibDependency {
if (this != null) {
return StdlibDependency(this)
}
val flag = runReadAction {
when {
project.isDisposed -> null
DumbService.isDumb(project) -> true
else -> false
}
}
return when (flag) {
null -> throw ProcessCanceledException()
true -> throw IndexNotReadyException.create()
else -> noStdlibDependency
}
}
override fun checkValueValidity(value: StdlibDependency) {
value.libraryInfo?.checkValidity()
}
}
private inner class LibraryCache : AbstractCache<LibraryInfo>() {
override fun calculate(key: LibraryInfo): StdlibDependency = key.findStdLib().toStdlibDependency()
fun putExtraValues(map: Map<LibraryInfo, StdlibDependency>) {
putAll(map)
}
override fun checkKeyValidity(key: LibraryInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateEntries({ k, v -> k in libraryInfos || v.libraryInfo in libraryInfos })
}
}
private inner class ModuleCache : AbstractCache<IdeaModuleInfo>(), WorkspaceModelChangeListener {
override fun subscribe(connection: MessageBusConnection) {
connection.subscribe(WorkspaceModelTopics.CHANGED, this)
}
override fun calculate(key: IdeaModuleInfo): StdlibDependency {
val moduleSourceInfo = key.safeAs<ModuleSourceInfo>()
val stdLib = moduleSourceInfo?.module?.moduleWithLibrariesScope?.let index@{ scope ->
val stdlibManifests = DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
FileBasedIndex.getInstance().getContainingFiles(
KotlinStdlibIndex.KEY,
KotlinStdlibIndex.KOTLIN_STDLIB_NAME,
scope
)
})
val projectFileIndex = ProjectFileIndex.getInstance(project)
val libraryInfoCache = LibraryInfoCache.getInstance(project)
for (manifest in stdlibManifests) {
val orderEntries = projectFileIndex.getOrderEntriesForFile(manifest)
for (entry in orderEntries) {
val library = entry.safeAs<LibraryOrderEntry>()?.library.safeAs<LibraryEx>() ?: continue
val libraryInfos = libraryInfoCache[library]
return@index libraryInfos.find(::isStdlib) ?: continue
}
}
null
} ?: key.findStdLib()
return stdLib.toStdlibDependency()
}
override fun postProcessNewValue(key: IdeaModuleInfo, value: StdlibDependency) {
if (key !is ModuleSourceInfo) return
val result = hashMapOf<LibraryInfo, StdlibDependency>()
// all module dependencies have same stdlib as module itself
key.dependencies().forEach {
if (it is LibraryInfo) {
result[it] = value
}
}
libraryCache.putExtraValues(result)
}
override fun checkKeyValidity(key: IdeaModuleInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateEntries({ _, v -> v.libraryInfo in libraryInfos }, validityCondition = { _, v -> v.libraryInfo != null })
}
override fun changed(event: VersionedStorageChange) {
event.getChanges(ModuleEntity::class.java).ifEmpty { return }
invalidate(writeAccessRequired = true)
}
}
}
}
fun LibraryInfo.isCoreKotlinLibrary(project: Project): Boolean = isKotlinStdlib(project) || isKotlinStdlibDependency(project)
fun LibraryInfo.isKotlinStdlib(project: Project): Boolean = KotlinStdlibCache.getInstance(project).isStdlib(this)
fun LibraryInfo.isKotlinStdlibDependency(project: Project): Boolean = KotlinStdlibCache.getInstance(project).isStdlibDependency(this) | apache-2.0 | 1190e152eb4e7fd967f545471d4dbb43 | 42.430508 | 133 | 0.66357 | 5.873911 | false | false | false | false |
raybritton/json-query | lib/src/main/kotlin/com/raybritton/jsonquery/parsing/query/QueryBuilder.kt | 1 | 11436 | package com.raybritton.jsonquery.parsing.query
import com.raybritton.jsonquery.SyntaxException
import com.raybritton.jsonquery.ext.joinStringOr
import com.raybritton.jsonquery.ext.toSegments
import com.raybritton.jsonquery.models.*
import com.raybritton.jsonquery.models.Target
import com.raybritton.jsonquery.parsing.tokens.Operator
/**
* Used by QueryParser to build the query
*
* It checks that values set correctly
*
*/
internal class QueryBuilder(val queryString: String) {
var method: Query.Method? = null
set(value) {
checkMethodNotSet()
field = value
}
var target: Target? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Target already set: $field")
}
if (value is Target.TargetQuery) {
if (value.query.method != Query.Method.SELECT) {
throw SyntaxException("Only SELECT queries can be nested")
}
}
if (value is Target.TargetField) {
checkJsonTargetIsValid(value.value)
}
field = value
}
var describeProjection: String? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Projection already set: $field")
}
checkJsonPathIsValid(value!!, "DESCRIBE")
field = value
}
var selectProjection: SelectProjection? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Projection already set: $field")
}
checkMath()
when (value) {
is SelectProjection.SingleField -> checkJsonPathIsValid(value.field, "SELECT")
is SelectProjection.MultipleFields -> value.fields.forEach { checkJsonPathIsValid(it.first, "SELECT") }
}
field = value
}
var where: Where? = null
set(value) {
checkMethod("WHERE", Query.Method.SELECT, Query.Method.DESCRIBE)
if (value!!.projection is WhereProjection.Field) {
checkJsonPathIsValid((value.projection as WhereProjection.Field).value, "WHERE")
}
field = value
}
var searchOperator: Operator? = null
set(value) {
if (field != null) {
throw SyntaxException("Search operator already set: $field")
}
field = value
}
var targetRange: SearchQuery.TargetRange? = null
set(value) {
checkMethod(value!!.name, Query.Method.SEARCH)
if (field != null) {
throw SyntaxException("Search target range already set: $field")
}
field = value
}
var searchValue: Value<*>? = null
set(value) {
if (field != null) {
throw SyntaxException("Search value already set: $field")
}
field = value
}
var limit: Int? = null
set(value) {
checkMethod("LIMIT", Query.Method.SELECT, Query.Method.DESCRIBE)
if (field != null) {
throw SyntaxException("Limit already set: $field")
}
field = value
}
var offset: Int? = null
set(value) {
checkMethod("OFFSET", Query.Method.SELECT, Query.Method.DESCRIBE)
if (field != null) {
throw SyntaxException("Offset already set: $field")
}
field = value
}
var orderBy: ElementFieldProjection? = null
set(value) {
checkMethod("ORDER BY", Query.Method.SELECT)
if (field != null) {
throw SyntaxException("Order already set: $field")
}
if (value is ElementFieldProjection.Field) {
checkJsonPathIsValid(value.value, "ORDER BY")
}
checkMath()
field = value
}
var isDistinct: Boolean? = null
set(value) {
checkMethodSet()
if (selectProjection is SelectProjection.Math) {
throw SyntaxException("Can not use DISTINCT and MIN, MAX, SUM or COUNT together")
}
checkMath()
field = value
}
var isCaseSensitive: Boolean? = null
set(value) {
checkMethodSet()
if (method == Query.Method.SELECT || method == Query.Method.DESCRIBE) {
if (where == null) {
throw SyntaxException("In SELECT or DESCRIBE: CASE SENSITIVE is only allowed after WHERE")
}
}
field = value
}
var isWithValues: Boolean? = null
set(value) {
checkMethod("WITH VALUES", Query.Method.SEARCH)
checkMath()
field = value
}
var isWithKeys: Boolean? = null
set(value) {
checkMethod("WITH KEYS", Query.Method.DESCRIBE)
field = value
}
var isByElement: Boolean? = null
set(value) {
checkMethod("BY ELEMENT", Query.Method.SELECT)
field = value
}
var isAsJson: Boolean? = null
set(value) {
checkIsFalse("AS JSON", "KEYS", isOnlyPrintKeys)
checkIsFalse("AS JSON", "VALUES", isOnlyPrintValues)
checkMethod("AS JSON", Query.Method.SELECT)
checkMath()
field = value
}
var isPrettyPrinted: Boolean? = null
set(value) {
checkMethod("PRETTY", Query.Method.SELECT, Query.Method.DESCRIBE)
if (isAsJson != true) {
throw SyntaxException("In SELECT: PRETTY is only allowed after AS JSON")
}
field = value
}
var isOnlyPrintKeys: Boolean? = null
set(value) {
checkIsFalse("KEYS", "AS JSON", isAsJson)
checkIsFalse("KEYS", "VALUES", isOnlyPrintValues)
checkMethod("KEYS", Query.Method.SELECT)
checkMath()
field = value
}
var isOnlyPrintValues: Boolean? = null
set(value) {
checkIsFalse("VALUES", "AS JSON", isAsJson)
checkIsFalse("VALUES", "KEYS", isOnlyPrintKeys)
checkMethod("VALUES", Query.Method.SELECT)
checkMath()
field = value
}
var isOrderByDesc: Boolean? = null
set(value) {
checkMethod("VALUES", Query.Method.SELECT)
if (orderBy == null) {
throw SyntaxException("DESC is only allowed after ORDER BY")
}
field = value
}
fun build(): Query {
if (method == null) {
throw SyntaxException("No SELECT, DESCRIBE or SEARCH method found")
}
if (target == null) {
throw SyntaxException("No target found")
}
val flags = Query.Flags(
isDistinct = (isDistinct == true),
isCaseSensitive = (isCaseSensitive == true),
isAsJson = (isAsJson == true),
isByElement = (isByElement == true),
isOnlyPrintKeys = (isOnlyPrintKeys == true),
isOnlyPrintValues = (isOnlyPrintValues == true),
isPrettyPrinted = (isPrettyPrinted == true),
isWithKeys = (isWithKeys == true),
isWithValues = (isWithValues == true),
isOrderByDesc = (isOrderByDesc == true)
)
var searchQuery: SearchQuery? = null
var selectQuery: SelectQuery? = null
var describeQuery: DescribeQuery? = null
when (method!!) {
Query.Method.SELECT -> {
selectQuery = SelectQuery(selectProjection, limit, offset, orderBy)
}
Query.Method.DESCRIBE -> {
describeQuery = DescribeQuery(describeProjection, limit, offset)
}
Query.Method.SEARCH -> {
if (targetRange == null) {
throw SyntaxException("No target range found")
}
if (searchOperator == null) {
throw SyntaxException("No operator found")
}
if (searchValue == null) {
throw SyntaxException("No value found")
}
searchQuery = SearchQuery(targetRange!!, searchOperator!!, searchValue!!)
}
}
return Query(queryString, method!!, target!!, flags, where, searchQuery, selectQuery, describeQuery)
}
private fun checkMath() {
if (selectProjection is SelectProjection.Math) {
if (isDistinct == true) {
throw SyntaxException("Can not use DISTINCT and MIN, MAX, SUM or COUNT together")
}
if (orderBy != null) {
throw SyntaxException("Can not use ORDER BY and MIN, MAX, SUM or COUNT together")
}
if (isOnlyPrintKeys != null) {
throw SyntaxException("Can not use KEYS and MIN, MAX, SUM or COUNT together")
}
if (isOnlyPrintValues != null) {
throw SyntaxException("Can not use VALUES and MIN, MAX, SUM or COUNT together")
}
if (isAsJson != null) {
throw SyntaxException("Can not use VALUES and MIN, MAX, SUM or COUNT together")
}
}
}
private fun checkJsonTargetIsValid(path: String) {
if (path.isEmpty()) throw SyntaxException("Json target is empty", SyntaxException.ExtraInfo.JSON_TARGET)
if (path == ".") return
if (path.endsWith(".")) throw SyntaxException("Json target ends with .", SyntaxException.ExtraInfo.JSON_TARGET)
if (path.toSegments().any { it.isEmpty() }) throw SyntaxException("Json target contains blank segments", SyntaxException.ExtraInfo.JSON_TARGET)
}
private fun checkJsonPathIsValid(path: String, type: String) {
if (path.isEmpty()) throw SyntaxException("Json path is empty", SyntaxException.ExtraInfo.JSON_PATH)
if (path.startsWith(".")) throw SyntaxException("Json path for $type starts with .", SyntaxException.ExtraInfo.JSON_PATH)
if (path.endsWith(".")) throw SyntaxException("Json path for $type ends with .", SyntaxException.ExtraInfo.JSON_PATH)
if (path.toSegments().any { it.isEmpty() }) throw SyntaxException("Json path for $type contains blank segments", SyntaxException.ExtraInfo.JSON_PATH)
}
private fun checkIsFalse(field: String, flag: String, flagValue: Boolean?) {
if (flagValue == true) {
throw SyntaxException("$field can not be used with $flag")
}
}
private fun checkMethod(keyword: String, vararg allowedMethods: Query.Method) {
checkMethodSet()
if (!allowedMethods.contains(method)) {
throw SyntaxException("$keyword only works with ${allowedMethods.joinStringOr()}")
}
}
private fun checkMethodSet() {
if (method == null) {
throw SyntaxException("Method (SELECT, DESCRIBE or SEARCH) must be first")
}
}
private fun checkMethodNotSet() {
if (method != null) {
throw SyntaxException("Method can only be set once, already set to $method")
}
}
} | apache-2.0 | 566f23d24ac7e2c8c521b30a3220a4a9 | 34.299383 | 157 | 0.554302 | 5.057939 | false | false | false | false |
allotria/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt | 2 | 1009 | // 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.grazie
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import java.nio.file.Path
internal object GraziePlugin {
const val id = "tanvd.grazi"
object LanguageTool {
const val version = "5.2"
const val url = "https://resources.jetbrains.com/grazie/model/language-tool"
}
private val descriptor: IdeaPluginDescriptor
get() = PluginManagerCore.getPlugin(PluginId.getId(id))!!
val group: String
get() = GrazieBundle.message("grazie.group.name")
val name: String
get() = GrazieBundle.message("grazie.name")
val isBundled: Boolean
get() = descriptor.isBundled
val classLoader: ClassLoader
get() = descriptor.pluginClassLoader
val libFolder: Path
get() = descriptor.pluginPath.resolve("lib")
}
| apache-2.0 | efe663bef1fc0b74badc0aef6c0e9e48 | 28.676471 | 140 | 0.745292 | 4.152263 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.