repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
team401/SnakeSkin | SnakeSkin-CTRE/src/main/kotlin/org/snakeskin/component/impl/HardwareTalonSrxDevice.kt | 1 | 4163 | package org.snakeskin.component.impl
import com.ctre.phoenix.motorcontrol.ControlMode
import com.ctre.phoenix.motorcontrol.DemandType
import com.ctre.phoenix.motorcontrol.can.TalonSRX
import org.snakeskin.component.CTREFeedforwardScalingMode
import org.snakeskin.component.ITalonSrxDevice
import org.snakeskin.component.provider.IFollowableProvider
import org.snakeskin.measure.distance.angular.AngularDistanceMeasureRadians
import org.snakeskin.measure.velocity.angular.AngularVelocityMeasureRadiansPerSecond
import org.snakeskin.runtime.SnakeskinRuntime
class HardwareTalonSrxDevice(val device: TalonSRX, sensorTicksPerRevolution: Double = 4096.0, val ffMode: CTREFeedforwardScalingMode = CTREFeedforwardScalingMode.ScaleVbusSystem) : ITalonSrxDevice {
private val sensorTicksPerRadian = sensorTicksPerRevolution / (2.0 * Math.PI)
private fun scaleFfVolts(voltage: Double): Double {
return when (ffMode) {
CTREFeedforwardScalingMode.Scale12V -> voltage / 12.0
CTREFeedforwardScalingMode.ScaleVbusSystem -> {
val vbus = SnakeskinRuntime.voltage
return voltage / vbus
}
CTREFeedforwardScalingMode.ScaleVbusDevice -> {
val vbus = device.busVoltage
voltage / vbus
}
}
}
override fun follow(master: IFollowableProvider) {
when (master) {
is HardwareTalonSrxDevice -> device.follow(master.device)
is HardwareVictorSpxDevice -> device.follow(master.device)
}
}
override fun unfollow() {
//CTRE devices unfollow when a 0.0 percent output command is sent
device.set(ControlMode.PercentOutput, 0.0)
}
override fun setPercentOutput(percentOut: Double) {
device.set(ControlMode.PercentOutput, percentOut)
}
override fun getPercentOutput(): Double {
return device.motorOutputPercent
}
override fun getOutputVoltage(): Double {
return device.motorOutputVoltage
}
override fun getInputVoltage(): Double {
return device.busVoltage
}
override fun stop() {
setPercentOutput(0.0)
}
override fun getAngularPosition(): AngularDistanceMeasureRadians {
val ticks = device.selectedSensorPosition.toDouble()
return AngularDistanceMeasureRadians(ticks / sensorTicksPerRadian)
}
override fun setAngularPosition(angle: AngularDistanceMeasureRadians) {
val ticks = (angle.value * sensorTicksPerRadian).toInt()
device.selectedSensorPosition = ticks
}
override fun getAngularVelocity(): AngularVelocityMeasureRadiansPerSecond {
val ticks = device.selectedSensorVelocity.toDouble()
return AngularVelocityMeasureRadiansPerSecond((ticks / sensorTicksPerRadian) * 10.0) //Multiply by 10 to convert deciseconds (100 ms) to seconds
}
override fun getOutputCurrent(): Double {
return device.statorCurrent
}
override fun setAngularPositionSetpoint(setpoint: AngularDistanceMeasureRadians, ffVolts: Double) {
val ticks = setpoint.value * sensorTicksPerRadian
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.Position, ticks, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun setAngularVelocitySetpoint(setpoint: AngularVelocityMeasureRadiansPerSecond, ffVolts: Double) {
val ticksPer100Ms = (setpoint.value * sensorTicksPerRadian) / 10.0 //Divide by 10 to convert seconds to deciseconds (100 ms)
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.Velocity, ticksPer100Ms, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun setProfiledSetpoint(setpoint: AngularDistanceMeasureRadians, ffVolts: Double) {
val ticks = setpoint.value * sensorTicksPerRadian
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.MotionMagic, ticks, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun invert(invert: Boolean) {
device.inverted = invert
}
override fun invertInput(invert: Boolean) {
device.setSensorPhase(invert)
}
} | gpl-3.0 | 21c38bdfeeb793a38237a1de8ca3a3f8 | 38.283019 | 198 | 0.722316 | 4.30062 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/commandframework/CommandExecutor.kt | 1 | 6637 | package me.aberrantfox.hotbot.commandframework
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import me.aberrantfox.hotbot.commandframework.commands.utility.macros
import me.aberrantfox.hotbot.commandframework.parsing.*
import me.aberrantfox.hotbot.dsls.command.Command
import me.aberrantfox.hotbot.dsls.command.CommandEvent
import me.aberrantfox.hotbot.dsls.command.CommandsContainer
import me.aberrantfox.hotbot.extensions.jda.*
import me.aberrantfox.hotbot.logging.BotLogger
import me.aberrantfox.hotbot.permissions.PermissionManager
import me.aberrantfox.hotbot.services.CommandRecommender
import me.aberrantfox.hotbot.services.Configuration
import me.aberrantfox.hotbot.services.MService
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.Message
import net.dv8tion.jda.core.entities.MessageChannel
import net.dv8tion.jda.core.entities.User
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent
import net.dv8tion.jda.core.hooks.ListenerAdapter
import me.aberrantfox.hotbot.commandframework.parsing.ConversionResult.*
class CommandExecutor(val config: Configuration,
val container: CommandsContainer,
val jda: JDA,
val log: BotLogger,
val manager: PermissionManager,
val mService: MService) : ListenerAdapter() {
override fun onGuildMessageReceived(e: GuildMessageReceivedEvent) {
handleInvocation(e.channel, e.message, e.author, true)
}
override fun onPrivateMessageReceived(e: PrivateMessageReceivedEvent) {
handleInvocation(e.channel, e.message, e.author, false)
}
private fun handleInvocation(channel: MessageChannel, message: Message, author: User, invokedInGuild: Boolean) =
launch(CommonPool) {
if (!(isUsableCommand(message, channel.id, author))) return@launch
val (commandName, actualArgs) = cleanCommandMessage(message.contentRaw, config)
if (!(canPerformCommand(channel, message, author))) return@launch
val command = container[commandName]
val macro = macros.firstOrNull { it.name == commandName }
when {
command != null -> {
invokeCommand(command, commandName, actualArgs, message, author, invokedInGuild)
log.cmd("${author.descriptor()} -- invoked $commandName in ${channel.name}")
}
macro != null -> {
channel.sendMessage(macro.message).queue()
log.cmd("${author.descriptor()} -- invoked $commandName in ${channel.name}")
}
else -> {
val recommended = CommandRecommender.recommendCommand(commandName)
channel.sendMessage("I don't know what ${commandName.replace("@", "")} is, perhaps you meant $recommended?").queue()
}
}
if (invokedInGuild) handleDelete(message, config.serverInformation.prefix)
}
private fun invokeCommand(command: Command, name: String, actual: List<String>, message: Message, author: User, invokedInGuild: Boolean) {
val channel = message.channel
if( !(manager.canUseCommand(author, name)) ) {
channel.sendMessage("Did you really think I would let you do that? :thinking:").queue()
return
}
getArgCountError(actual, command)?.let {
channel.sendMessage(it).queue()
return
}
val event = CommandEvent(config, jda, channel, author, message, jda.getGuildById(config.serverInformation.guildid), manager, container, mService, actual)
val conversionResult = convertArguments(actual, command.expectedArgs.toList(), event)
when(conversionResult) {
is Results -> event.args = conversionResult.results.requireNoNulls()
is Error -> {
event.safeRespond(conversionResult.error)
return
}
}
executeCommand(command, event, invokedInGuild)
}
private fun executeCommand(command: Command, event: CommandEvent, invokedInGuild: Boolean) {
if(isDoubleInvocation(event.message, event.config.serverInformation.prefix)) {
event.message.addReaction("\uD83D\uDC40").queue()
}
if (command.parameterCount == 0) {
command.execute(event)
return
}
if (command.requiresGuild && !invokedInGuild) {
event.respond("This command must be invoked in a guild channel, and not through PM")
} else {
command.execute(event)
}
}
private fun isUsableCommand(message: Message, channel: String, author: User): Boolean {
if (message.contentRaw.length > 1500) return false
if (config.security.lockDownMode && author.id != config.serverInformation.ownerID) return false
if (!(message.isCommandInvocation(config))) return false
if (config.security.ignoredIDs.contains(channel) || config.security.ignoredIDs.contains(author.id)) return false
if (author.isBot) return false
return true
}
private fun canPerformCommand(channel: MessageChannel, message: Message, user: User): Boolean {
if (!manager.canPerformAction(user, config.permissionedActions.commandMention) && message.mentionsSomeone()) {
channel.sendMessage("Your permission level is below the required level to use a command mention.").queue()
return false
}
if (!manager.canPerformAction(user, config.permissionedActions.sendInvite) && message.containsInvite()) {
channel.sendMessage("Ayyy lmao. Nice try, try that again. I dare you. :rllynow:").queue()
return false
}
if (!manager.canPerformAction(user, config.permissionedActions.sendURL) && message.containsURL()) {
channel.sendMessage("Your permission level is below the required level to use a URL in a command.").queue()
return false
}
return true
}
private fun handleDelete(message: Message, prefix: String) =
if (!isDoubleInvocation(message, prefix)) {
message.deleteIfExists()
} else Unit
private fun isDoubleInvocation(message: Message, prefix: String) = message.contentRaw.startsWith(prefix + prefix)
}
| mit | b0868d387711ad2f75da8dda0d0c4e54 | 41.819355 | 161 | 0.658731 | 4.792058 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKExternalConversion.kt | 1 | 4026 | // 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.nj2k.externalCodeProcessing
import com.intellij.psi.*
import org.jetbrains.kotlin.j2k.AccessorKind
import org.jetbrains.kotlin.j2k.usageProcessing.AccessorToPropertyProcessing
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.cast
internal sealed class JKExternalConversion : Comparable<JKExternalConversion> {
abstract val usage: PsiElement
abstract fun apply()
private val depth by lazy(LazyThreadSafetyMode.NONE) { usage.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
private val offset by lazy(LazyThreadSafetyMode.NONE) { usage.textRange.startOffset }
override fun compareTo(other: JKExternalConversion): Int {
val depth1 = depth
val depth2 = other.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left
// so that right-side of assignments is not invalidated by processing of the left one
return -offset.compareTo(other.offset)
}
}
internal class AccessorToPropertyKotlinExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
AccessorToPropertyProcessing.processUsage(usage, name, accessorKind)
}
}
internal class AccessorToPropertyJavaExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val methodCall = usage.parent as? PsiMethodCallExpression ?: return
val factory = PsiElementFactory.getInstance(usage.project)
val propertyAccess = factory.createReferenceExpression(usage.qualifierExpression)
val newExpression = when (accessorKind) {
AccessorKind.GETTER -> propertyAccess
AccessorKind.SETTER -> {
val value = methodCall.argumentList.expressions.singleOrNull() ?: return
factory.createAssignment(propertyAccess, value)
}
}
methodCall.replace(newExpression)
}
private fun PsiElementFactory.createReferenceExpression(qualifier: PsiExpression?): PsiReferenceExpression =
createExpressionFromText(qualifier?.let { "qualifier." }.orEmpty() + name, usage).cast<PsiReferenceExpression>().apply {
qualifierExpression?.replace(qualifier ?: return@apply)
}
private fun PsiElementFactory.createAssignment(target: PsiExpression, value: PsiExpression): PsiAssignmentExpression =
createExpressionFromText("x = 1", usage).cast<PsiAssignmentExpression>().apply {
lExpression.replace(target)
rExpression!!.replace(value)
}
}
internal class PropertyRenamedKotlinExternalUsageConversion(
private val newName: String,
override val usage: KtElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is KtSimpleNameExpression) return
val factory = KtPsiFactory(usage)
usage.getReferencedNameElement().replace(factory.createExpression(newName))
}
}
internal class PropertyRenamedJavaExternalUsageConversion(
private val newName: String,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val factory = PsiElementFactory.getInstance(usage.project)
usage.referenceNameElement?.replace(factory.createExpressionFromText(newName, usage))
}
}
| apache-2.0 | 89f9465a37e357888bf8a5a17bf144c1 | 40.081633 | 128 | 0.731744 | 5.007463 | false | false | false | false |
Fantast/project-euler | src/main/euler/solved/Task_539.kt | 1 | 4400 | package solved
import tasks.AbstractTask
import tasks.Tester
import utils.MyMath
import utils.log.Logger
import java.math.BigInteger
//Answer : 426334056
class Task_539 : AbstractTask() {
override fun solving() {
println(S(1000000000000000000))
println(S(1000000000000000000) % bi(987654321))
}
fun P(n: Long): Long {
if (n == 1L) {
return 1L;
}
return 2*(f(n/2) + e(n/2))
}
fun S(n: Long): BigInteger {
return fs(n) + es(n);
}
fun e(n: Long): Long {
if (n == 1L) {
return 1L;
}
val s2: Long;
val bits = 64 - java.lang.Long.numberOfLeadingZeros(n)
if (bits % 2 == 0) {
val ss = (1L shl bits) - 1L;
s2 = -(ss and 0b0101010101010101010101010101010101010101010101010101010101010101L);
} else {
val ss = (1L shl bits) - 1L;
s2 = (ss and 0b010101010101010101010101010101010101010101010101010101010101010L) + 1L;
}
return s2;
}
fun f(n: Long): Long {
if (n == 1L) {
return 0L;
}
val bits = 64 - java.lang.Long.numberOfLeadingZeros(n)
val s1 = n and 0b0101010101010101010101010101010101010101010101010101010101010101L;
val last = 1L shl (bits - 1);
return s1 + (if (bits % 2 == 0) last else -last);
}
fun fs(nn: Long): BigInteger {
assert(nn % 2L == 0L); //for convinience
val n = nn / 2L;
var s = bi(0);
for (bit in 0..61) {
val ds = (1L shl bit)
var cnt = 0L;
if (bit % 2 != 0) {
val maxn = (1L shl (bit + 1)) - 1;
val minn = (1L shl bit);
if (minn > n) {
cnt = 0;
} else {
cnt = Math.min(n, maxn) - minn + 1;
}
} else {
for (bits in (bit+1)..63) {
if (bits % 2 == 0 || (bits >= bit + 3)) {
val maxn = (1L shl bits) - 1;
val minn = (1L shl (bits - 1)) + (1L shl bit);
if (minn > n) {
// cnt += 0;
} else if (maxn <= n) {
cnt += 1L shl (bits - 2);
} else {
val leftParts = (n - (1L shl (bits - 1))) shr (bit + 1);
val hasBit = MyMath.isBitSet(n, bit);
val rightParts = n % (1L shl bit)
if (hasBit) {
//numbers that has the same prefix as n
cnt += rightParts + 1
}
if (leftParts != 0L) {
//fit numbers below n
cnt += leftParts * (1L shl bit);
}
}
}
}
}
s += bi(cnt) * bi(ds);
}
s = s * bi(4L) - bi(2*f(n))
return s;
}
fun es(nn: Long): BigInteger {
assert(nn % 2L == 0L); //for convinience
val n = nn / 2L;
var s = bi(1); // for 1 bit
for (bits in 2..61) {
val pmax = (1L shl bits) - 1L
val pmin = (1L shl (bits - 1))
if (pmin > n) {
break;
}
val cnt = Math.min(pmax, n) - pmin + 1L;
val s2: Long;
if (bits % 2 == 0) {
val ss = (1L shl bits) - 1L;
s2 = -(ss and 0b0101010101010101010101010101010101010101010101010101010101010101L);
} else {
val ss = (1L shl bits) - 1L;
s2 = (ss and 0b010101010101010101010101010101010101010101010101010101010101010L) + 1L;
}
s += bi(cnt) * bi(s2);
}
s = s * bi(4L) - bi(2*e(n)) + bi(1)
return s;
}
fun P0(n: Long): Long {
if (n == 1L) {
return 1L;
}
val nn = n / 2;
return 2 * (nn + 1 - P(nn));
}
companion object {
@JvmStatic fun main(args: Array<String>) {
Logger.init("default.log")
Tester.test(Task_539())
Logger.close()
}
}
} | mit | 87f62770839b3da02853872db7ec2282 | 26.335404 | 102 | 0.407045 | 3.697479 | false | false | false | false |
StPatrck/edac | app/src/main/java/com/phapps/elitedangerous/companion/data/repos/ProfileRepository.kt | 1 | 12282 | package com.phapps.elitedangerous.companion.data.repos
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.phapps.elitedangerous.companion.EdacApp
import com.phapps.elitedangerous.companion.EdacExecutors
import com.phapps.elitedangerous.companion.api.ApiResponse
import com.phapps.elitedangerous.companion.api.edc.EdcService
import com.phapps.elitedangerous.companion.api.edc.dtos.EdcProfileDto
import com.phapps.elitedangerous.companion.data.doa.CommanderDao
import com.phapps.elitedangerous.companion.data.doa.ShipDao
import com.phapps.elitedangerous.companion.data.doa.StarSystemDao
import com.phapps.elitedangerous.companion.data.entities.*
import com.phapps.elitedangerous.companion.domain.Resource
import com.phapps.elitedangerous.companion.ext.withRanks
import com.phapps.elitedangerous.companion.ext.withRanksAndProgress
import com.phapps.elitedangerous.companion.util.SharedPrefsHelper
import com.phapps.elitedangerous.edsm.EdsmClient
import com.phapps.elitedangerous.edsm.callbacks.GetCommanderRanksCallbacks
import com.phapps.elitedangerous.edsm.dto.CommanderDto
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import timber.log.Timber
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProfileRepository @Inject constructor(private var executors: EdacExecutors,
private var commanderDao: CommanderDao, private var shipDao: ShipDao,
private var systemDao: StarSystemDao, private var prefs: SharedPrefsHelper) :
IProfileRepository {
override fun getProfile(name: String,
forceRefresh: Boolean): LiveData<Resource<CommanderProfile>> {
return object : WebBoundResource<CommanderProfile, EdcProfileDto>(executors) {
override fun loadFromDb(): LiveData<CommanderProfile> {
return commanderDao.getCommanderByName(name)
}
override fun shouldFetch(data: CommanderProfile?): Boolean {
if (data == null) return true
val now = Date().time
return forceRefresh || now >= calculateStaleDate(data.lastUpdatedTimestamp)
}
override fun createCall(): LiveData<ApiResponse<EdcProfileDto>> {
val liveData = MutableLiveData<ApiResponse<EdcProfileDto>>()
launch {
liveData.postValue(EdcService(EdacApp.instance).getProfile())
}
return liveData
}
override fun saveCallResult(response: EdcProfileDto) {
val newProfile = CommanderProfile().also { it ->
with(response) {
it.id = commander.id
it.name = name
it.credits = commander.credits
it.debt = commander.debt
it.alive = commander.alive
it.currentShipId = commander.currentShipId
it.lastUpdatedTimestamp = Date().time
it.ranks = runBlocking { createRanks(it) }
}
}
val ships = mutableListOf<Ship>()
val stations = mutableListOf<Station>()
val systems = mutableListOf<StarSystem>()
val moduleSlots = mutableListOf<ModuleSlot>()
// The current ship is the only ship populated with full details
ships.add(Ship().also { ship ->
with(response.ship) {
newProfile.currentShipName = this.name
ship.id = this.id
ship.name = this.name
ship.free = this.free
ship.stationId = this.station.id
ship.starSystemId = this.starsystem.id
ship.oxygenRemaining = this.oxygenRemaining
ship.cockpitBreached = this.cockpitBreached
ship.alive = this.alive
this.health?.let {
ship.hullHealth = it.hull
ship.shieldHealth = it.shield
ship.shieldUp = it.shieldup
ship.integrity = it.integrity
ship.paintwork = it.paintwork
}
ship.hullValue = this.value.hull
ship.modulesValue = this.value.hull
ship.cargoValue = this.value.cargo
ship.totalValue = this.value.total
ship.unloanedValue = this.value.unloaned
this.modules?.let { map ->
for (entry in map) {
moduleSlots.add(ModuleSlot().also { ms ->
ms.name = entry.key
})
}
}
}
})
// List of owned ships does not include all ship details.
if (response.ships.isNotEmpty()) {
for (dto in response.ships) {
if (dto.id != response.ship.id) {
ships.add(Ship().also { ship ->
with(dto) {
ship.id = this.id
ship.name = this.name
ship.free = this.free
ship.stationId = this.station.id
with(this.station) {
stations.add(Station().also { s ->
s.name = this.name
s.id = this.id
})
}
ship.starSystemId = this.starsystem.id
with(this.starsystem) {
systems.add(StarSystem().also { s ->
s.id = this.id
s.name = this.name
s.address = this.systemaddress.toString()
})
}
ship.alive = this.alive
}
})
}
}
}
val starport = Starport().also { s ->
with(response.lastStarport) {
s.id = this.id
s.name = this.name
s.faction = this.faction
s.minorFaction = this.minorfaction
s.services = StarportServices().also { services ->
with(this.services) {
services.dock = this.dock == "ok"
services.contacts = this.contacts == "ok"
services.cartographers = this.exploration == "ok"
services.refuel = this.refuel == "ok"
services.repair = this.repair == "ok"
services.outfitting = this.outfitting == "ok"
services.crewLounge = this.crewlounge == "ok"
services.powerPlay = this.powerplay == "ok"
services.searchAndRescue = this.searchrescue == "ok"
services.engineer = this.engineer == "ok"
}
}
}
}
commanderDao.insert(newProfile)
systemDao.insert(*stations.toTypedArray())
systemDao.insert(*systems.toTypedArray())
systemDao.insert(starport)
shipDao.insert(*ships.toTypedArray())
}
}.asLiveData()
}
private suspend fun createRanks(commanderProfile: CommanderProfile): Ranks {
var ranks = Ranks.withRanks(commanderProfile.ranks.combatRank,
commanderProfile.ranks.traderRank, commanderProfile.ranks.explorerRank,
commanderProfile.ranks.cqcRank, commanderProfile.ranks.federationRank,
commanderProfile.ranks.empireRank, commanderProfile.ranks.crime,
commanderProfile.ranks.power, commanderProfile.ranks.service)
async {
EdsmClient.getInstance().getCommanderRanks(commanderProfile.name, prefs.getEdsmApiKey(),
object : GetCommanderRanksCallbacks {
override fun onSuccess(commander: CommanderDto) {
Timber.d("commander = $commander")
var combatProgress = commanderProfile.ranks.combatProgress
var tradeProgress = commanderProfile.ranks.traderProgress
var exploreProgress = commanderProfile.ranks.explorerProgress
var cqcProgress = commanderProfile.ranks.cqcProgress
var empireProgress = commanderProfile.ranks.empireProgress
var federationProgress = commanderProfile.ranks.federationProgress
if (commander.ranks != null) {
if (commanderProfile.ranks.combatRank == commander.ranks.combat) {
combatProgress = commander.progress.combat
}
if (commanderProfile.ranks.traderRank == commander.ranks.trade) {
tradeProgress = commander.ranks.trade
}
if (commanderProfile.ranks.explorerRank == commander.ranks.explore) {
exploreProgress = commander.progress.explore
}
if (commanderProfile.ranks.cqcProgress == commander.ranks.cqc) {
cqcProgress = commander.progress.cqc
}
if (commanderProfile.ranks.empireRank == commander.ranks.empire) {
empireProgress = commander.progress.empire
}
if (commanderProfile.ranks.federationRank == commander.ranks.federation) {
federationProgress = commander.progress.federation
}
}
ranks = Ranks.withRanksAndProgress(
Pair(commanderProfile.ranks.combatRank, combatProgress),
Pair(commanderProfile.ranks.traderRank, tradeProgress),
Pair(commanderProfile.ranks.explorerRank, exploreProgress),
Pair(commanderProfile.ranks.cqcRank, cqcProgress),
Pair(commanderProfile.ranks.federationRank, federationProgress),
Pair(commanderProfile.ranks.empireRank, empireProgress),
commanderProfile.ranks.crime, commanderProfile.ranks.power,
commanderProfile.ranks.service)
}
override fun onFail(message: String) {
Timber.w("Error fetching rank details from EDSM: $message")
}
override fun onError() {
Timber.w("Unable to communicate with EDSM servers to fetch Ranks.")
}
})
}.await()
return ranks
}
}
| gpl-3.0 | 2288d36bc79f6fe62fcf0a511a36a876 | 46.789883 | 106 | 0.495603 | 5.779765 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/CachingGithubUserAvatarLoader.kt | 2 | 3061 | // 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.github.util
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.LowMemoryWatcher
import com.intellij.util.ImageLoader
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.GithubUser
import java.awt.Image
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.Supplier
class CachingGithubUserAvatarLoader(private val progressManager: ProgressManager) : Disposable {
private val LOG = logger<CachingGithubUserAvatarLoader>()
private val executor = AppExecutorUtil.getAppExecutorService()
private val progressIndicator: EmptyProgressIndicator = NonReusableEmptyProgressIndicator()
private val avatarCache = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build<GithubUser, CompletableFuture<Image?>>()
init {
LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this)
}
fun requestAvatar(requestExecutor: GithubApiRequestExecutor, user: GithubUser): CompletableFuture<Image?> {
val indicator = progressIndicator
// store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale)
val imageSize = MAXIMUM_ICON_SIZE * 6
return avatarCache.get(user) {
val url = user.avatarUrl
if (url == null) CompletableFuture.completedFuture(null)
else CompletableFuture.supplyAsync(Supplier {
try {
progressManager.runProcess(Computable { loadAndDownscale(requestExecutor, indicator, url, imageSize) }, indicator)
}
catch (e: ProcessCanceledException) {
null
}
}, executor)
}
}
private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: EmptyProgressIndicator,
url: String, maximumSize: Int): Image? {
try {
val image = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url))
return if (image.getWidth(null) <= maximumSize && image.getHeight(null) <= maximumSize) image
else ImageLoader.scaleImage(image, maximumSize)
}
catch (e: ProcessCanceledException) {
return null
}
catch (e: Exception) {
LOG.info("Error loading image from $url", e)
return null
}
}
override fun dispose() {
progressIndicator.cancel()
}
companion object {
private const val MAXIMUM_ICON_SIZE = 40
}
} | apache-2.0 | ffdcb57afde83344071d4091eba6485f | 38.25641 | 140 | 0.755962 | 4.881978 | false | false | false | false |
mdanielwork/intellij-community | platform/credential-store/src/NativeCredentialStoreWrapper.kt | 1 | 4634 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.google.common.cache.CacheBuilder
import com.intellij.credentialStore.keePass.InMemoryCredentialStore
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.util.containers.ContainerUtil
import java.util.concurrent.TimeUnit
internal val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup("Password Safe", NotificationDisplayType.STICKY_BALLOON, true), NotificationType.ERROR)
}
// used only for native keychains, not for KeePass, so, postponedCredentials and other is not overhead if KeePass is used
private class NativeCredentialStoreWrapper(private val store: CredentialStore) : CredentialStore {
private val fallbackStore = lazy { InMemoryCredentialStore() }
private val queueProcessor = QueueProcessor<() -> Unit> { it() }
private val postponedCredentials = InMemoryCredentialStore()
private val postponedRemovedCredentials = ContainerUtil.newConcurrentSet<CredentialAttributes>()
private val deniedItems = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<CredentialAttributes, Boolean>()
override fun get(attributes: CredentialAttributes): Credentials? {
if (postponedRemovedCredentials.contains(attributes)) {
return null
}
postponedCredentials.get(attributes)?.let {
return it
}
if (deniedItems.getIfPresent(attributes) != null) {
LOG.warn("User denied access to $attributes")
return null
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
val value = store.get(attributes)
if (value === ACCESS_TO_KEY_CHAIN_DENIED) {
deniedItems.put(attributes, true)
}
return value
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
LOG.runAndLogException {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
return
}
if (credentials == null) {
postponedRemovedCredentials.add(attributes)
}
else {
postponedCredentials.set(attributes, credentials)
}
queueProcessor.add {
try {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
}
finally {
if (!postponedRemovedCredentials.remove(attributes)) {
postponedCredentials.set(attributes, null)
}
}
}
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = "Credentials are remembered until ${ApplicationNamesInfo.getInstance().fullProductName} is closed."
if (SystemInfo.isLinux) {
message += "\nPlease install required package libsecret-1-0: sudo apt-get install libsecret-1-0 gnome-keyring"
}
NOTIFICATION_MANAGER.notify("Cannot Access Native Keychain", message)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (isMacOsCredentialStoreSupported) {
return NativeCredentialStoreWrapper(KeyChainCredentialStore())
}
return null
}
}
private class LinuxSecretCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (SystemInfo.isLinux) {
return NativeCredentialStoreWrapper(SecretCredentialStore("com.intellij.credentialStore.Credential"))
}
return null
}
} | apache-2.0 | bb61a8b59e87b4d21a420eb00822e1a0 | 34.930233 | 140 | 0.723781 | 4.827083 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/BackendKeyFilter.kt | 1 | 3783 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.metric
import com.spotify.heroic.common.OptionalLimit
import java.util.*
data class BackendKeyFilter(
val start: Optional<Start> = Optional.empty(),
val end: Optional<End> = Optional.empty(),
val limit: OptionalLimit = OptionalLimit.empty()
) {
fun withStart(start: Start): BackendKeyFilter = BackendKeyFilter(Optional.of(start), end, limit)
fun withEnd(end: End): BackendKeyFilter = BackendKeyFilter(start, Optional.of(end), limit)
fun withLimit(limit: OptionalLimit): BackendKeyFilter = BackendKeyFilter(start, end, limit)
companion object {
/**
* Match keys strictly greater than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly greater than the given key.
*/
@JvmStatic fun gt(key: BackendKey): GT = GT(key)
}
interface Start
interface End
/**
* Match keys strictly greater than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly greater than the given key.
*/
data class GT(val key: BackendKey): Start
/**
* Match keys greater or equal to the given key.
*
* @param key The key to match against.
* @return A {@link BackendKeyFilter} matching if a key is greater or equal to the given key.
*/
data class GTE(val key: BackendKey): Start
/**
* Match keys larger or equal to the given percentage.
*
* @param percentage The percentage to match against, should be a value between {@code [0, 1]}.
* @return A {@link BackendKeyFilter} matching if a key is larger or equal to the given
* percentage.
*/
data class GTEPercentage(val percentage: Float): Start
/**
* Match keys larger or equal to the given token.
*
* @param token The token to match against.
* @return A {@link BackendKeyFilter} matching if a key is larger or equal to the given token.
*/
data class GTEToken(val token: Long): Start
/**
* Match keys strictly smaller than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly smaller than the given key.
*/
data class LT(val key: BackendKey): End
/**
* Match keys smaller than the given percentage.
*
* @param percentage The percentage to match against, should be a value between {@code [0, 1]}
* @return A {@link BackendKeyFilter} matching if a key is smaller than a given percentage.
*/
data class LTPercentage(val percentage: Float): End
/**
* Match keys smaller than the given token.
*
* @param token The token to match against.
* @return A {@link BackendKeyFilter} matching if a key is smaller than the given token.
*/
data class LTToken(val token: Long): End
} | apache-2.0 | 431315c8fba12446c9faa18c76014b37 | 33.715596 | 100 | 0.678826 | 4.203333 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassImportAliasAllUsages.0.kt | 5 | 1067 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtImportAlias
// OPTIONS: usages, constructorUsages
package client
import server.Server as Srv<caret>
import server.Server
class Client(name: String = Server.NAME) : Srv() {
var nextServer: Server? = Server()
val name = Server.NAME
/**
* [Srv] parameter
*/
fun foo(s: Srv) {
val server: Server = s
println("Server: $server")
}
fun getNextServer2(): Server? {
return nextServer
}
override fun work() {
super<Server>.work()
println("Client")
}
companion object : Server() {
}
}
object ClientObject : Server() {
}
abstract class Servers : Iterator<Server> {
}
fun Iterator<Server>.f(p: Iterator<Server>): Iterator<Server> = this
fun Client.bar(s: Server = Server()) {
foo(s)
}
fun Client.hasNextServer(): Boolean {
return getNextServer2() != null
}
fun Any.asServer(): Server? {
when (this) {
is Server -> println("Server!")
}
return if (this is Server) this as Server else this as? Server
}
| apache-2.0 | cee4fd1432a2dfdc899f1634524752be | 17.719298 | 68 | 0.615745 | 3.666667 | false | false | false | false |
KrzysztofBogdan/Kodeks_formater | src/main/kotlin/pl/codeweaver/kodeks/formater/MarkdownTableFormatter.kt | 1 | 6013 | package pl.codeweaver.kodeks.formater
import javax.script.Invocable
import javax.script.ScriptEngineManager
object MarkdownTableFormatter {
fun format(value: String): String {
val runtime = ScriptEngineManager().getEngineByName("javascript");
runtime.eval(jsCode)
runtime.eval("""
function format_table(value) {
var mtf = new MarkdownTableFormatter();
mtf.format_table(value)
return mtf.output_table;
}
""")
if (runtime is Invocable) {
return runtime.invokeFunction("format_table", value) as String;
} else {
throw RuntimeException("ScriptEngine is not Invocable")
}
}
}
// https://github.com/alanwsmith/markdown_table_formatter
private val jsCode = """
function MarkdownTableFormatter() {
// Setup instance variables.
this.cells = new Array();
this.column_widths = new Array();
this.output_table = "";
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.add_missing_cell_columns = function() {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.column_widths.length; col_i < col_l; col_i = col_i + 1) {
if (typeof this.cells[row_i][col_i] === 'undefined') {
this.cells[row_i][col_i] = '';
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.format_table = function(table) {
this.import_table(table);
this.get_column_widths();
this.add_missing_cell_columns();
this.pad_cells_for_output();
// Header
this.output_table = "| ";
this.output_table += this.cells[0].join(" | ");
this.output_table += " |\n";
// Separator
this.output_table += "|-";
this.output_table += this.cells[1].join("-|-");
this.output_table += "-|\n";
for (var row_i = 2, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
this.output_table += "| ";
this.output_table += this.cells[row_i].join(" | ");
this.output_table += " |\n";
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.get_column_widths = function() {
this.column_widths = new Array();
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.cells[row_i].length; col_i < col_l; col_i = col_i + 1) {
if (typeof this.column_widths[col_i] === 'undefined') {
this.column_widths[col_i] = this.cells[row_i][col_i].length;
}
else if (this.column_widths[col_i] < this.cells[row_i][col_i].length) {
this.column_widths[col_i] = this.cells[row_i][col_i].length;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.import_table = function(table) {
var table_rows = table.split("\n");
// Remove leading empty lines
while (table_rows[0].indexOf('|') == -1) {
table_rows.shift();
}
for (var row_i = 0, row_l = table_rows.length; row_i < row_l; row_i = row_i + 1) {
// TODO: Set up the indexes so that empty lines at either the top or bottom will
// be removed. Right now, this is only helpful for empty lines at the bottom.
if(table_rows[row_i].indexOf('|') == -1) {
continue;
}
this.cells[row_i] = new Array();
var row_columns = table_rows[row_i].split("\|");
for (var col_i = 0, col_l = row_columns.length; col_i < col_l; col_i = col_i + 1) {
this.cells[row_i][col_i] = row_columns[col_i]
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/^\s+/g,"");
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/\s+$/g,"");
// If it's the separator row, parse down the dashes
// Only do this if it matches to avoid adding a
// dash in an empty column and messing with the column widths.
if (row_i == 1) {
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/-+/g,"-");
}
}
}
// Remove leading and trailing rows if they are empty.
this.get_column_widths();
if (this.column_widths[0] == 0) {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
this.cells[row_i].shift();
}
}
this.get_column_widths();
// check to see if the last item in column widths is empty
if (this.column_widths[ (this.column_widths.length - 1) ] == 0) {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
// Only remove the row if it is in the proper last slot.
if (this.cells[row_i].length == this.column_widths.length) {
this.cells[row_i].pop();
}
}
}
this.get_column_widths();
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.pad_cells_for_output = function() {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.cells[row_i].length; col_i < col_l; col_i = col_i + 1) {
// Handle anything that's not the separator row
if (row_i != 1) {
while(this.cells[row_i][col_i].length < this.column_widths[col_i]) {
this.cells[row_i][col_i] += " ";
}
}
// Handle the separator row.
else {
while(this.cells[row_i][col_i].length < this.column_widths[col_i]) {
this.cells[row_i][col_i] += "-";
}
}
}
}
}
""" | mit | 2c64556d695d65161da5cc0711b81d8b | 31.160428 | 98 | 0.5079 | 3.479745 | false | false | false | false |
pflammertsma/cryptogram | app/src/main/java/com/pixplicity/cryptogram/activities/CryptogramActivity.kt | 1 | 51352 | package com.pixplicity.cryptogram.activities
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.ProgressDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.drawable.AnimatedVectorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.InputType
import android.util.Log
import android.util.SparseBooleanArray
import android.view.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.GravityCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.getkeepsafe.taptargetview.TapTarget
import com.getkeepsafe.taptargetview.TapTargetView
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.common.images.ImageManager
import com.google.android.gms.games.Games
import com.google.android.gms.games.GamesActivityResultCodes
import com.google.android.gms.games.snapshot.SnapshotMetadata
import com.google.android.gms.games.snapshot.Snapshots
import com.google.android.material.button.MaterialButton
import com.google.firebase.Timestamp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PlayGamesAuthProvider
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.pixplicity.cryptogram.BuildConfig
import com.pixplicity.cryptogram.CryptogramApp
import com.pixplicity.cryptogram.R
import com.pixplicity.cryptogram.adapters.PuzzleAdapter
import com.pixplicity.cryptogram.db.PuzzleStateDao
import com.pixplicity.cryptogram.events.PuzzleEvent
import com.pixplicity.cryptogram.events.PuzzlesEvent
import com.pixplicity.cryptogram.events.RemoteConfigEvent
import com.pixplicity.cryptogram.models.Puzzle
import com.pixplicity.cryptogram.models.PuzzleState
import com.pixplicity.cryptogram.utils.*
import com.pixplicity.cryptogram.utils.BillingUtils.DONATIONS_ENABLED
import com.pixplicity.cryptogram.views.CryptogramView
import com.pixplicity.easyprefs.library.Prefs
import com.skydoves.balloon.ArrowOrientation
import com.skydoves.balloon.BalloonAnimation
import com.skydoves.balloon.createBalloon
import com.squareup.otto.Subscribe
import kotlinx.android.synthetic.main.activity_cryptogram.*
import kotlinx.android.synthetic.main.in_drawer.*
import kotlinx.android.synthetic.main.in_statistics.*
import net.soulwolf.widget.ratiolayout.widget.RatioFrameLayout
import java.util.*
class CryptogramActivity : BaseActivity() {
companion object {
private val TAG = CryptogramActivity::class.java.simpleName
private const val RC_UNUSED = 1000
private const val RC_PLAY_GAMES = 1001
private const val RC_SAVED_GAMES = 1002
private const val ONBOARDING_PAGES = 2
const val EXTRA_LAUNCH_SETTINGS = "launch_settings"
}
private var keyboardView: View? = null
private lateinit var puzzleAdapter: PuzzleAdapter
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth: FirebaseAuth
private val db = Firebase.firestore
private var lastConnectionError: Int = 0
private var freshInstall: Boolean = false
private var activityVisible = false
set(value) {
field = value
// Also persist it
CryptogramApp.activityVisible = value
}
private lateinit var puzzleState: PuzzleState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cryptogram)
// Create the GoogleSignIn client with access to Games
googleSignInClient = GoogleSignIn.getClient(this, SignInUtil.getOptions(this, googleSignIn = true))
googleSignInClient.silentSignIn().addOnCompleteListener { task ->
updateGooglePlayGames()
if (task.isSuccessful) {
task.result?.serverAuthCode?.let { authCode ->
val credential = PlayGamesAuthProvider.getCredential(authCode)
auth.currentUser?.linkWithCredential(credential)?.addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = task.result?.user
Log.d(TAG, "linkWithCredential: success; user=${user?.uid}")
} else {
Log.w(TAG, "linkWithCredential: failure", task.exception)
// Instead just log in as that user
auth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential: success; user UID: ${auth.currentUser?.uid}")
} else {
// TODO Handle sign in failure more gracefully
Log.w(TAG, "signInWithCredential: failure", task.exception)
}
}
}
}
}
}
}
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
if (auth.currentUser == null) {
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, hold on to signed-in user's information
Log.d(TAG, "signInAnonymously: success; user UID: ${auth.currentUser?.uid}")
} else {
// TODO Handle sign in failure more gracefully
Log.w(TAG, "signInAnonymously: failure", task.exception)
}
}
} else {
Log.d(TAG, "user UID: ${auth.currentUser?.uid}")
}
RatingsBooster.init(this)
refreshPuzzles()
vg_cryptogram.setCryptogramView(cryptogram)
cryptogram.setOnHighlightListener(object : CryptogramView.OnHighlightListener {
private val mHighlightShown = SparseBooleanArray()
override fun onHighlight(type: Int, point: PointF) {
if (mHighlightShown.get(type, false)) {
return
}
if (PrefsUtils.getHighlighted(type)) {
return
}
mHighlightShown.put(type, true)
when (type) {
PrefsUtils.TYPE_HIGHLIGHT_HYPHENATION -> showHighlight(type, createTapTargetFromPoint(
point,
getString(R.string.highlight_hyphenation_title),
getString(R.string.highlight_hyphenation_description)),
1200
)
}
}
})
if (PrefsUtils.useSystemKeyboard) {
keyboardView?.visibility = View.GONE
} else {
if (keyboardView == null) {
vs_keyboard.layoutResource = when (PrefsUtils.keyboardLayout) {
KeyboardLayouts.LAYOUT_QWERTY -> R.layout.in_keyboard_qwerty
KeyboardLayouts.LAYOUT_QWERTZ -> R.layout.in_keyboard_qwertz
KeyboardLayouts.LAYOUT_AZERTY -> R.layout.in_keyboard_azerty
KeyboardLayouts.LAYOUT_ABC -> R.layout.in_keyboard_abc
}
keyboardView = vs_keyboard.inflate()
}
keyboardView?.visibility = View.VISIBLE
cryptogram.setKeyboardView(keyboardView)
}
val intent = intent
if (intent != null) {
if (intent.getBooleanExtra(EXTRA_LAUNCH_SETTINGS, false)) {
startActivity(SettingsActivity.create(this))
}
}
if (UpdateManager.consumeEnabledShowUsedLetters()) {
showHighlight(-1, TapTarget.forToolbarOverflow(
viewToolbar,
getString(R.string.highlight_used_letters_title),
getString(R.string.highlight_used_letters_description)),
1200
)
}
vg_google_play_games.setOnClickListener {
onClickGooglePlayGames()
}
bt_next.setOnClickListener {
nextPuzzle()
}
bt_flag.setOnClickListener {
FlaggingUtil.showDialog(this, PrefsUtils.theme.isDark, db, PuzzleProvider.getInstance(this).current, auth.currentUser)
}
bt_star.setOnClickListener {
PuzzleProvider.getInstance(this).current?.apply {
// Toggle puzzle state
puzzleState.starred = !puzzleState.starred
// Update record
PuzzleStateDao.set(puzzleState)
}
}
bt_covid.setOnClickListener {
AlertDialog.Builder(this)
.setMessage(R.string.covid_19_prevention)
.setPositiveButton(R.string.covid_19_learn_more) { _, _ ->
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://g.co/kgs/i6Pdqv")).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
} catch (e: Exception) {
}
}
.show()
}
RemoteConfig.refreshRemoteConfig()
}
override fun onStart() {
super.onStart()
activityVisible = true
EventProvider.bus.register(this)
val puzzleProvider = PuzzleProvider.getInstance(this)
val puzzle = puzzleProvider.current
puzzle?.onResume()
showHintView(puzzle)
if (hasOnBoardingPages()) {
showOnboarding(0)
} else {
onGameplayReady()
if (!PrefsUtils.notificationsPuzzlesSet) {
// Ask to enable notifications
AlertDialog.Builder(this)
.setTitle(R.string.enable_notifications_title)
.setMessage(R.string.enable_notifications_message)
.setPositiveButton(R.string.enable_notifications_yes) { _, _ ->
PrefsUtils.notificationsPuzzles = true
}
.setNegativeButton(R.string.enable_notifications_no) { _, _ ->
PrefsUtils.notificationsPuzzles = false
}
.show()
}
}
updateGooglePlayGames()
}
override fun onResume() {
super.onResume()
val puzzleProvider = PuzzleProvider.getInstance(this)
puzzleProvider.current?.let {
onPuzzleChanged(it, true, layoutChange = true)
}
}
override fun onStop() {
super.onStop()
activityVisible = false
val puzzleProvider = PuzzleProvider.getInstance(this)
val puzzle = puzzleProvider.current
puzzle?.onPause()
EventProvider.bus.unregister(this)
}
override fun onBackPressed() {
if (viewDrawerLayout != null && viewDrawerLayout!!.isDrawerOpen(GravityCompat.START)) {
viewDrawerLayout!!.closeDrawer(GravityCompat.START)
return
}
if (keyboardView != null && keyboardView!!.isShown) {
cryptogram.hideSoftInput()
return
}
super.onBackPressed()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
when (requestCode) {
RC_PLAY_GAMES -> {
when (resultCode) {
RESULT_OK -> {
// Logged in
Log.d(TAG, "user UID: ${auth.currentUser?.uid}")
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, null)
}
GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED -> {
// Logged out
googleSignInClient.signOut()
}
RESULT_CANCELED -> {
// Canceled; do nothing
}
else -> {
// Assume some error
showGmsError(resultCode)
}
}
updateGooglePlayGames()
loadGame(intent)
}
RC_SAVED_GAMES -> {
loadGame(intent)
if (viewDrawerLayout != null) {
viewDrawerLayout!!.closeDrawers()
}
}
}
}
private fun loadGame(intent: Intent?) {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (intent != null && account != null) {
val snapshotsClient = Games.getSnapshotsClient(this, account)
if (intent.hasExtra(Snapshots.EXTRA_SNAPSHOT_METADATA)) {
// TODO replace with a better UI
// Load a snapshot
val pd = ProgressDialog(this)
pd.setMessage(getString(R.string.saved_game_loading))
pd.setCancelable(false)
pd.show()
intent.getParcelableExtra<SnapshotMetadata>(Snapshots.EXTRA_SNAPSHOT_METADATA)?.let { snapshotMetadata ->
PuzzleProvider.getInstance(this).load(this, snapshotsClient, snapshotMetadata,
object : SavegameManager.OnLoadResult {
override fun onLoadSuccess() {
PuzzleProvider.getInstance(this@CryptogramActivity).current?.let {
onPuzzleChanged(it, false)
showSnackbar(getString(R.string.saved_game_loaded))
}
pd.dismiss()
}
override fun onLoadFailure(reason: String) {
showSnackbar(getString(R.string.saved_game_load_failed, reason))
pd.dismiss()
}
})
}
} else if (intent.hasExtra(Snapshots.EXTRA_SNAPSHOT_NEW)) {
PuzzleProvider.getInstance(this).save(this, snapshotsClient,
object : SavegameManager.OnSaveResult {
override fun onSaveSuccess() {
showSnackbar(getString(R.string.saved_game_saved))
}
override fun onSaveFailure(reason: String) {
showSnackbar(getString(R.string.saved_game_save_failed, reason))
}
})
}
}
}
private fun hasOnBoardingPages(): Boolean {
return PrefsUtils.onboarding < ONBOARDING_PAGES - 1
}
private fun createTapTargetFromPoint(point: PointF, title: String,
description: String): TapTarget {
val viewRect = Rect()
cryptogram.getGlobalVisibleRect(viewRect)
val targetX = (point.x + viewRect.left).toInt()
val targetY = (point.y + viewRect.top).toInt()
val targetRadius = 48
return TapTarget.forBounds(Rect(targetX - targetRadius, targetY - targetRadius, targetX + targetRadius, targetY + targetRadius),
title, description)
}
private fun showHighlight(type: Int, tapTarget: TapTarget, delayMillis: Int) {
Handler().postDelayed({
val showTime = System.currentTimeMillis()
TapTargetView.showFor(
this@CryptogramActivity,
tapTarget
.titleTextColor(R.color.white)
.descriptionTextColor(R.color.white)
.outerCircleColor(R.color.highlight_color)
.cancelable(true)
.tintTarget(false)
.transparentTarget(true),
object : TapTargetView.Listener() {
override fun onTargetClick(view: TapTargetView) {
dismiss(view)
}
override fun onOuterCircleClick(view: TapTargetView?) {
dismiss(view)
}
override fun onTargetCancel(view: TapTargetView) {
dismiss(view)
}
private fun dismiss(view: TapTargetView?) {
if (type >= 0 && System.currentTimeMillis() - showTime >= 1500) {
// Ensure that the user saw the message
PrefsUtils.setHighlighted(type, true)
}
view!!.dismiss(false)
}
})
}, delayMillis.toLong())
}
private fun showOnboarding(page: Int) {
if (!activityVisible) {
// Do nothing if activity was paused
return
}
val titleStringResId: Int
val textStringResId: Int
var actionStringResId = R.string.intro_next
val video: VideoUtils.Video
when (page) {
0 -> {
titleStringResId = R.string.intro1_title
textStringResId = R.string.intro1_text
video = VideoUtils.VIDEO_INSTRUCTION
}
1 -> {
titleStringResId = R.string.intro2_title
textStringResId = R.string.intro2_text
actionStringResId = R.string.intro_done
video = VideoUtils.VIDEO_HELP
}
ONBOARDING_PAGES -> {
onGameplayReady()
return
}
else -> {
onGameplayReady()
return
}
}
val onboarding = PrefsUtils.onboarding
if (onboarding == -1) {
freshInstall = true
}
if (onboarding >= page) {
showOnboarding(page + 1)
return
}
val customView = LayoutInflater.from(this).inflate(R.layout.dialog_intro, null)
val tvIntro = customView.findViewById<TextView>(R.id.tv_intro)
tvIntro.setText(textStringResId)
val vgRatio = customView.findViewById<RatioFrameLayout>(R.id.vg_ratio)
val player = VideoUtils.setup(this, vgRatio, video)
MaterialDialog.Builder(this)
.title(titleStringResId)
.customView(customView, false)
.cancelable(false)
.positiveText(actionStringResId)
.showListener { _ ->
player?.start()
}
.onAny { _, _ ->
PrefsUtils.onboarding = page
showOnboarding(page + 1)
}
.show()
}
private fun onClickGooglePlayGames() {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
// Connected; show gameplay options
val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_google_play_games, null)
val dialog = AlertDialog.Builder(this)
.setView(dialogView)
.show()
val btLeaderboards = dialogView.findViewById<Button>(R.id.bt_leaderboards)
btLeaderboards.setOnClickListener { _ ->
dialog.dismiss()
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(CryptogramApp.CONTENT_LEADERBOARDS, null)
Games.getLeaderboardsClient(this, account).getLeaderboardIntent(getString(R.string.leaderboard_scoreboard)).addOnSuccessListener {
try {
startActivityForResult(
it,
RC_UNUSED)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btAchievements = dialogView.findViewById<Button>(R.id.bt_achievements)
btAchievements.setOnClickListener { _ ->
dialog.dismiss()
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(CryptogramApp.CONTENT_ACHIEVEMENTS, null)
Games.getAchievementsClient(this, account).achievementsIntent.addOnSuccessListener {
try {
startActivityForResult(it, RC_UNUSED)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btRestoreSavedGames = dialogView.findViewById<Button>(R.id.bt_restore_saved_games)
btRestoreSavedGames.setOnClickListener { _ ->
dialog.dismiss()
val maxNumberOfSavedGamesToShow = 5
val task = Games.getSnapshotsClient(this, account).getSelectSnapshotIntent(
getString(R.string.google_play_games_saved_games_window_title), true, true, maxNumberOfSavedGamesToShow)
task.addOnFailureListener { e ->
FirebaseCrashlytics.getInstance().recordException(e)
}
task.addOnSuccessListener {
try {
startActivityForResult(it, RC_SAVED_GAMES)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btSignOut = dialogView.findViewById<Button>(R.id.bt_sign_out)
btSignOut.setOnClickListener { _ ->
dialog.dismiss()
googleSignInClient.signOut()
updateGooglePlayGames()
}
} else {
// Start the sign-in flow
startActivityForResult(googleSignInClient.signInIntent, RC_PLAY_GAMES)
}
}
private fun refreshPuzzles() {
rv_drawer.layoutManager = LinearLayoutManager(this)
puzzleAdapter = PuzzleAdapter(this, object : PuzzleAdapter.OnItemClickListener {
override fun onItemClick(position: Int) {
if (viewDrawerLayout != null) {
viewDrawerLayout!!.closeDrawers()
}
PuzzleProvider.getInstance(this@CryptogramActivity)[position]?.let {
onPuzzleChanged(it, false)
}
}
})
rv_drawer.adapter = puzzleAdapter
}
private fun updateCryptogram(puzzle: Puzzle?, layoutChange: Boolean = false) {
if (puzzle != null) {
// Pause the previous puzzle
cryptogram.puzzle?.onPause()
// Resume the current puzzle
puzzle.onResume()
val provider = PuzzleProvider.getInstance(this)
provider.setCurrentId(puzzle.id)
// Update UI
rv_drawer.scrollToPosition(provider.currentIndex)
tv_error.visibility = View.GONE
vg_cryptogram.visibility = View.VISIBLE
// Apply the puzzle to the CryptogramView
cryptogram.puzzle = puzzle
// Show other puzzle details
val author = puzzle.author
if (!PrefsUtils.showAuthor && !puzzle.isCompleted || author == null) {
tv_author.visibility = View.GONE
} else {
tv_author.visibility = View.VISIBLE
tv_author.text = getString(R.string.quote, author)
}
val topic = puzzle.topic
if (!PrefsUtils.showTopic && !puzzle.isCompleted || topic == null) {
tv_topic.visibility = View.GONE
} else {
tv_topic.visibility = View.VISIBLE
tv_topic.text = getString(R.string.topic, topic)
}
if (puzzle.isInstruction || puzzle.isNoScore) {
setToolbarSubtitle(puzzle.getTitle(this))
} else {
setToolbarSubtitle(getString(
R.string.puzzle_number,
puzzle.number))
}
// Invoke various events
showPuzzleState(puzzle, layoutChange = layoutChange)
} else {
tv_error.visibility = View.VISIBLE
vg_cryptogram.visibility = View.GONE
setToolbarSubtitle(null)
}
}
private fun onGameplayReady() {
cryptogram.requestFocus()
if (UpdateManager.consumeScoreExcludesExcessInputs()) {
MaterialDialog.Builder(this)
.title(R.string.scoring_changed_title)
.content(R.string.scoring_changed_message)
.cancelable(false)
.positiveText(R.string.ok)
.show()
}
}
private fun showPuzzleState(puzzle: Puzzle, layoutChange: Boolean = false) {
// Update the HintView as the puzzle updates
puzzleAdapter.notifyDataSetChanged()
if (puzzle.isCompleted) {
if (PrefsUtils.randomize) {
bt_next.setText(R.string.continue_to_puzzle_random)
} else {
bt_next.setText(R.string.continue_to_puzzle_sequential)
}
vg_stats.apply {
// Show the stats
visibility = View.VISIBLE
animate()
.translationY(0f)
.alpha(1f)
.setListener(null)
iv_check.visibility = View.VISIBLE
}
// C-19 information message
bt_covid.visibility = if (puzzle.number == Puzzle.PUZZLE_UNIQUE_COVID) View.VISIBLE else View.GONE
// Orient buttons to make space for stats if needed
if (layoutChange) {
ConstraintSet().apply {
clone(vg_stats)
if (PrefsUtils.showScore) {
connect(R.id.bt_star, ConstraintSet.TOP, R.id.bt_flag, ConstraintSet.BOTTOM, 8.px)
connect(R.id.bt_star, ConstraintSet.END, R.id.vg_stats, ConstraintSet.END, 0)
} else {
connect(R.id.bt_star, ConstraintSet.TOP, R.id.vg_stats, ConstraintSet.TOP, 0)
connect(R.id.bt_star, ConstraintSet.END, R.id.bt_flag, ConstraintSet.START, 8.px)
}
applyTo(vg_stats)
}
}
vg_solved.visibility =
if (PrefsUtils.showScore || PrefsUtils.showSolveTime || puzzle.isNoScore) View.GONE else View.VISIBLE
val durationMs = puzzle.durationMs
if (!PrefsUtils.showSolveTime || durationMs <= 0) {
vg_stats_time.visibility = View.GONE
} else {
vg_stats_time.visibility = View.VISIBLE
tv_stats_time.text = StringUtils.getDurationString(durationMs)
}
var reveals = -1
var score: Float? = null
if (PrefsUtils.showScore) {
reveals = puzzle.reveals
score = puzzle.score
}
if (reveals < 0) {
vg_stats_reveals.visibility = View.GONE
} else {
vg_stats_reveals.visibility = View.VISIBLE
tv_stats_reveals.text = getString(R.string.stats_reveals_value, reveals, resources.getQuantityString(R.plurals.stats_reveals_chars, reveals))
}
if (score != null) {
vg_stats_practice.visibility = View.GONE
vg_stats_score.visibility = View.VISIBLE
tv_stats_score.text = String.format(
Locale.ENGLISH,
"%.1f%%",
score * 100)
} else {
vg_stats_score.visibility = View.GONE
vg_stats_practice.visibility = if (puzzle.isNoScore) View.VISIBLE else View.GONE
}
if (CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.ALLOW_USER_FLAGGING) && !puzzle.isNoScore) {
bt_flag.visibility = View.VISIBLE
} else {
bt_flag.visibility = View.GONE
}
bt_star.visibility = if (puzzle.isNoScore) View.GONE else View.VISIBLE
} else {
bt_covid.visibility = View.GONE
if (vg_stats.isShown) {
vg_stats.apply {
animate()
.translationY(height.toFloat())
.alpha(0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
visibility = View.GONE
}
})
}
}
}
showHintView(puzzle)
puzzle.apply {
bt_star.isEnabled = false
(PuzzleStateDao.get(id.toLong())).observe(this@CryptogramActivity, Observer {
puzzleState = it.firstOrNull() ?: PuzzleState(id.toLong(), false)
puzzleState.apply {
(bt_star as MaterialButton).setIconResource(if (starred) R.drawable.ic_star else R.drawable.ic_star_border)
}
bt_star.isEnabled = true
})
}
}
private fun showHintView(puzzle: Puzzle?) {
hint.visibility = if (puzzle != null && !puzzle.isCompleted
&& PrefsUtils.showUsedChars && PrefsUtils.useSystemKeyboard)
View.VISIBLE
else
View.GONE
}
fun onPuzzleChanged(puzzle: Puzzle, delayEvent: Boolean, layoutChange: Boolean = false) {
updateCryptogram(puzzle, layoutChange = layoutChange)
if (delayEvent) {
EventProvider.postEventDelayed(PuzzleEvent.PuzzleProgressEvent(puzzle), 200)
} else {
EventProvider.postEvent(PuzzleEvent.PuzzleProgressEvent(puzzle))
}
cryptogram.onPuzzleResume()
}
@Subscribe
fun onPuzzleProgress(event: PuzzleEvent.PuzzleProgressEvent) {
event.puzzle?.let {
showPuzzleState(it)
}
}
@Subscribe
fun onPuzzleStarted(event: PuzzleEvent.PuzzleStartedEvent) {
// Submit any achievements
AchievementProvider.onCryptogramStart()
cryptogram.onPuzzleResume()
}
@Subscribe
fun onPuzzleReset(event: PuzzleEvent.PuzzleResetEvent) {
updateCryptogram(event.puzzle)
}
@Subscribe
fun onPuzzleCompleted(event: PuzzleEvent.PuzzleCompletedEvent) {
updateCryptogram(event.puzzle)
cryptogram.onPuzzleCompleted()
// TODO animate finish vector
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && iv_check.drawable is AnimatedVectorDrawable) {
(iv_check.drawable as AnimatedVectorDrawable).apply {
iv_check.visibility = View.INVISIBLE
iv_check.postDelayed({
iv_check.visibility = View.VISIBLE
start()
}, 1000)
}
}
if (!FirebaseCrashlytics.getInstance().didCrashOnPreviousExecution()) {
// Increment the trigger for displaying the rating dialog
RatingsBooster.incrementAndPrompt()
}
// Conditional behavior after X triggers
val provider = PuzzleProvider.getInstance(this)
var count = 0L
for (c in provider.all) {
if (!c.isInstruction && c.isCompleted) {
count++
}
}
val suggestDonationCount = PrefsUtils.suggestDonationCount
if (DONATIONS_ENABLED && count >= suggestDonationCount) {
// Prompt for donations only if user hasn't already donated
val purchases = PrefsUtils.purchases
PrefsUtils.suggestDonationCount = count + BillingUtils.DONATION_SUGGESTION_FREQUENCY
if (purchases == null) {
// Query purchases
BillingUtils.updatePurchases(this)
} else if (purchases.isEmpty()) {
BillingUtils.suggestDonation(this)
} else {
AchievementProvider.onDonated()
}
}
// Show prompts for frustrated users
if (bt_flag.isShown && !PrefsUtils.highlightedFrustrationFlag && CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.FRUSTRATION_HINT)) {
val createBalloon = createBalloon(this) {
setArrowSize(12)
setCornerRadius(4f)
setPadding(8)
setArrowPosition(0.88f)
setArrowOrientation(ArrowOrientation.BOTTOM)
setText(getString(R.string.highlight_frustration_flag))
setTextColor(getColorFromAttr(R.attr.textColorOnPrimary))
setBackgroundColor(getColorFromAttr(R.attr.colorPrimaryDark))
setBalloonAnimation(BalloonAnimation.FADE)
setLifecycleOwner(lifecycleOwner)
dismissWhenTouchOutside = true
dismissWhenClicked = true
}
bt_flag.postDelayed({
createBalloon.showAlignTop(bt_flag)
}, 500)
bt_flag.postDelayed({
// Only stop showing this if it was visible for a moment
if (createBalloon.isShowing) {
PrefsUtils.highlightedFrustrationFlag = true
}
}, 1300)
}
// Using the Google sign in
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
// Attach view for popups
Games.getGamesClient(this, account).setViewForPopups(drawer_layout)
// Submit score
LeaderboardProvider.submit(Games.getLeaderboardsClient(this, account))
// Submit any achievements
AchievementProvider.onCryptogramCompleted(this, Games.getAchievementsClient(this, account))
// Attempt to save the game to Google Play Saved Games
provider.save(this, Games.getSnapshotsClient(this, account), null)
} else if (BuildConfig.DEBUG) {
// Check achievements for offline
AchievementProvider.onCryptogramCompleted(this, null)
}
}
@Subscribe
fun onPuzzleKeyboardInput(event: PuzzleEvent.KeyboardInputEvent) {
val keyCode = event.keyCode
cryptogram.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
keyCode, 0))
cryptogram.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_UP,
keyCode, 0))
}
@Subscribe
fun onRemoteConfigPush(event: RemoteConfigEvent.Push) {
if (BuildConfig.DEBUG) {
Toast.makeText(this, "Remote configuration changing…", Toast.LENGTH_SHORT).show()
}
}
@Subscribe
fun onRemoteConfigChanged(event: RemoteConfigEvent.Change) {
if (event.updated) {
updateCryptogram(cryptogram.puzzle)
}
}
@Subscribe
fun onPuzzlesChanged(event: PuzzlesEvent.Change) {
if (event.newPuzzles > 0) {
showSnackbar(event.message, autoDismiss = false)
}
refreshPuzzles()
updateCryptogram(cryptogram.puzzle)
}
override fun onDrawerOpened(drawerView: View?) {}
override fun onDrawerClosed(drawerView: View?) {}
override fun onDrawerMoving() {
cryptogram.hideSoftInput()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_cryptogram, menu)
menu.findItem(R.id.action_reveal_puzzle).apply {
isVisible = BuildConfig.DEBUG
}
menu.findItem(R.id.action_donate).apply {
isVisible = DONATIONS_ENABLED
}
menu.findItem(R.id.action_admin).apply {
isVisible = BuildConfig.DEBUG
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (super.onOptionsItemSelected(item)) {
return true
}
val puzzle = cryptogram.puzzle
when (item.itemId) {
R.id.action_next -> {
nextPuzzle()
return true
}
R.id.action_reveal_letter -> {
if (puzzle == null || !cryptogram.hasSelectedCharacter()) {
showSnackbar(getString(R.string.reveal_letter_instruction))
} else {
if (PrefsUtils.neverAskRevealLetter) {
revealLetter()
} else {
MaterialDialog.Builder(this)
.content(R.string.reveal_letter_confirmation)
.checkBoxPromptRes(R.string.never_ask_again, false, null)
.positiveText(R.string.reveal)
.onPositive { dialog, _ ->
PrefsUtils.neverAskRevealLetter = dialog.isPromptCheckBoxChecked
revealLetter()
}
.negativeText(R.string.cancel)
.show()
}
}
return true
}
R.id.action_reveal_mistakes -> {
puzzle?.let {
if (PrefsUtils.neverAskRevealMistakes) {
revealMistakes(it)
} else {
MaterialDialog.Builder(this)
.content(R.string.reveal_mistakes_confirmation)
.checkBoxPromptRes(R.string.never_ask_again, false, null)
.positiveText(R.string.reveal)
.onPositive { dialog, _ ->
PrefsUtils.neverAskRevealMistakes = dialog.isPromptCheckBoxChecked
revealMistakes(it)
}
.negativeText(R.string.cancel)
.show()
}
}
return true
}
R.id.action_reveal_puzzle -> {
if (BuildConfig.DEBUG) {
puzzle?.revealPuzzle()
cryptogram.redraw()
} else {
throw IllegalStateException("Only applicable to debug builds")
}
return true
}
R.id.action_reset -> {
if (puzzle != null) {
AlertDialog.Builder(this)
.setMessage(R.string.reset_puzzle)
.setPositiveButton(R.string.reset) { _, _ ->
puzzle.reset(true)
cryptogram.reset()
showPuzzleState(puzzle)
onPuzzleChanged(puzzle, false)
}
.setNegativeButton(R.string.cancel) { _, _ -> }
.show()
}
return true
}
R.id.action_go_to -> {
if (puzzle == null) {
if (viewDrawerLayout != null) {
viewDrawerLayout!!.openDrawer(GravityCompat.START)
}
} else {
var prefilledText: String? = null
val currentId = puzzle.number
if (currentId > 0) {
prefilledText = currentId.toString()
}
MaterialDialog.Builder(this)
.content(R.string.go_to_puzzle_content)
.inputType(InputType.TYPE_CLASS_NUMBER)
.input(null, prefilledText) { dialog, input ->
val button = dialog.getActionButton(DialogAction.POSITIVE)
try {
button.isEnabled = Integer.parseInt(input.toString()) > 0
} catch (ignored: NumberFormatException) {
button.isEnabled = false
}
}
.alwaysCallInputCallback()
.showListener { dialogInterface ->
val dialog = dialogInterface as MaterialDialog
dialog.inputEditText!!.selectAll()
}
.onPositive { dialog, _ ->
val input = dialog.inputEditText!!.text
try {
val puzzleNumber = Integer.parseInt(input.toString())
val provider = PuzzleProvider
.getInstance(this@CryptogramActivity)
val newPuzzle = provider.getByNumber(puzzleNumber)
if (newPuzzle == null) {
showSnackbar(getString(R.string.puzzle_nonexistant, puzzleNumber))
} else {
onPuzzleChanged(newPuzzle, false)
}
} catch (ignored: NumberFormatException) {
}
}.show()
}
return true
}
R.id.action_share -> {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
val text = if (puzzle != null && puzzle.isCompleted) {
getString(
R.string.share_full,
puzzle.text,
puzzle.author,
getString(R.string.share_url))
} else {
getString(
R.string.share_partial,
if (puzzle == null)
getString(R.string.author_unknown)
else
puzzle.author,
getString(R.string.share_url))
}
intent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(intent, getString(R.string.share)))
// Analytics
val puzzleId = puzzle?.id?.toString()
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.LEVEL, puzzleId)
bundle.putString(FirebaseAnalytics.Param.CONTENT, text)
CryptogramApp.instance.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE, bundle)
return true
}
R.id.action_stats -> {
// Make sure to save the puzzle first
puzzle?.save()
// Now show the stats
StatisticsUtils.showDialog(this);
return true
}
R.id.action_settings -> {
startActivity(SettingsActivity.create(this))
return true
}
R.id.action_how_to_play -> {
startActivity(HowToPlayActivity.create(this))
return true
}
R.id.action_gameplay_tips -> {
startActivity(TipsActivity.create(this))
return true
}
R.id.action_about -> {
startActivity(AboutActivity.create(this))
return true
}
R.id.action_donate -> {
startActivity(DonateActivity.create(this))
return true
}
R.id.action_admin -> {
startActivity(AdminActivity.create(this))
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun revealLetter() {
val c = cryptogram.caretChar
cryptogram.revealCharacterMapping(c)
if (CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.SUBMIT_REVEALS)) {
// Submit which character was revealed for analytics
auth.currentUser?.let { user ->
cryptogram.puzzle?.let { puzzle ->
val reveals = mutableMapOf<String, Any>(Pair(c.toString(), true))
reveals["timestamp"] = Timestamp(Date())
db.collection("users").document(user.uid)
.collection("reveals").document(puzzle.id.toString())
.set(reveals, SetOptions.merge())
.addOnSuccessListener {
Log.d(TAG, "DocumentSnapshot written")
}
.addOnFailureListener { e ->
Log.w(TAG, "DocumentSnapshot failed writing", e)
}
}
}
}
}
private fun revealMistakes(puzzle: Puzzle) {
if (puzzle.revealMistakes() == 0) {
showSnackbar(getString(R.string.reveal_mistakes_none))
} else {
// Show those mistakes
cryptogram.redraw()
}
}
private fun nextPuzzle() {
val puzzle = PuzzleProvider.getInstance(this).next
puzzle.let {
if (it == null) {
val customView = LayoutInflater.from(this).inflate(R.layout.dialog_game_completed, null)
MaterialDialog.Builder(this)
.customView(customView, false)
.cancelable(false)
.positiveText(android.R.string.ok)
.show()
} else {
onPuzzleChanged(it, false)
}
}
}
private fun updateGooglePlayGames() {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
val playerTask = Games.getPlayersClient(this, account).currentPlayer
playerTask.addOnFailureListener {
bt_google_play_games.visibility = View.VISIBLE
iv_google_play_games_avatar.visibility = View.GONE
tv_google_play_games.visibility = View.VISIBLE
tv_google_play_games_name.visibility = View.GONE
vg_google_play_games_actions.visibility = View.GONE
}
playerTask.addOnSuccessListener { p ->
val displayName: String
val imageUri: Uri?
if (p != null) {
displayName = p.displayName
imageUri = if (p.hasHiResImage()) p.hiResImageUri else p.iconImageUri
//bannerUri = p.getBannerImageLandscapeUri();
} else {
// Set the greeting appropriately on main menu
displayName = account.displayName
?: getString(R.string.google_play_games_player_unknown)
imageUri = account.photoUrl
}
Log.w(TAG, "onConnected(): current player is $displayName")
bt_google_play_games.visibility = View.GONE
iv_google_play_games_avatar.visibility = View.VISIBLE
ImageManager.create(this).loadImage(iv_google_play_games_avatar, imageUri, R.drawable.im_avatar)
tv_google_play_games.visibility = View.GONE
tv_google_play_games_name.visibility = View.VISIBLE
tv_google_play_games_name.text = displayName
vg_google_play_games_actions.visibility = View.VISIBLE
}
} else {
bt_google_play_games.visibility = View.VISIBLE
iv_google_play_games_avatar.visibility = View.GONE
tv_google_play_games.visibility = View.VISIBLE
tv_google_play_games_name.visibility = View.GONE
vg_google_play_games_actions.visibility = View.GONE
}
}
private fun showGmsError(errorCode: Int) {
if (isFinishing) {
return
}
AlertDialog.Builder(this)
.setMessage(getString(R.string.google_play_games_connection_failure, lastConnectionError, errorCode))
.setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
}
| mit | bf072ee80541ee34542cfde01d105b0f | 40.612642 | 157 | 0.5326 | 5.337283 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/lesson/view/LessonController.kt | 1 | 4413 | package org.secfirst.umbrella.feature.lesson.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.bluelinelabs.conductor.RouterTransaction
import com.xwray.groupie.ExpandableGroup
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.lesson_view.*
import kotlinx.android.synthetic.main.lesson_view.view.*
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.database.lesson.Lesson
import org.secfirst.umbrella.data.database.lesson.Subject
import org.secfirst.umbrella.data.database.segment.Markdown
import org.secfirst.umbrella.feature.base.view.BaseController
import org.secfirst.umbrella.feature.difficulty.view.DifficultyController
import org.secfirst.umbrella.feature.lesson.DaggerLessonComponent
import org.secfirst.umbrella.feature.lesson.interactor.LessonBaseInteractor
import org.secfirst.umbrella.feature.lesson.presenter.LessonBasePresenter
import org.secfirst.umbrella.feature.segment.view.controller.HostSegmentController
import org.secfirst.umbrella.misc.AboutController
import javax.inject.Inject
class LessonController : BaseController(), LessonView {
@Inject
internal lateinit var presenter: LessonBasePresenter<LessonView, LessonBaseInteractor>
private val lessonClick: (Subject) -> Unit = this::onLessonClicked
private val groupClick: (Lesson) -> Unit = this::onGroupClicked
private val groupAdapter = GroupAdapter<ViewHolder>()
private var isRecycledView = false
companion object {
private const val RECYCLER_STATE = "recycle_state"
}
override fun onInject() {
DaggerLessonComponent.builder()
.application(UmbrellaApplication.instance)
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.lesson_view, container, false)
presenter.onAttach(this)
presenter.submitLoadAllLesson()
view.lessonRecyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = groupAdapter
}
setUpToolbar(view)
return view
}
override fun showAllLesson(lessons: List<Lesson>) {
if (!isRecycledView) {
lessons.forEach { lesson ->
val hasChild = lesson.topics.isNotEmpty()
val lessonGroup = LessonGroup(lesson,
hasChild, groupClick)
val groups = ExpandableGroup(lessonGroup)
if (hasChild) groups.add(LessonDecorator())
lesson.topics.forEach { subject ->
groups.add(LessonItem(subject, lessonClick))
}
if (hasChild) groups.add(LessonDecorator())
groupAdapter.add(groups)
}
lessonRecyclerView?.apply { adapter = groupAdapter }
}
}
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
outState.putBoolean(RECYCLER_STATE, true)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
isRecycledView = savedViewState.getBoolean(RECYCLER_STATE)
}
private fun setUpToolbar(view: View) {
view.lessonToolbar.let {
mainActivity.setSupportActionBar(it)
mainActivity.supportActionBar?.title = context.getString(R.string.lesson_title)
}
}
private fun onLessonClicked(subject: Subject) = presenter.submitSelectLesson(subject)
private fun onGroupClicked(lesson: Lesson) = presenter.submitSelectHead(lesson)
override fun startSegment(markdownIds: ArrayList<String>, enableFilter: Boolean) =
router.pushController(RouterTransaction.with(HostSegmentController(markdownIds, enableFilter)))
override fun startDifficultyController(subject: Subject) =
router.pushController(RouterTransaction.with(DifficultyController(subject.id)))
override fun startSegmentAlone(markdown: Markdown) =
router.pushController(RouterTransaction.with(AboutController(markdown)))
} | gpl-3.0 | 1cb691d1425fb0b6c83eba954a82f0d1 | 38.765766 | 110 | 0.721278 | 4.860132 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/test/java/co/smartreceipts/android/identity/widget/account/AccountPresenterTest.kt | 2 | 3909 | package co.smartreceipts.android.identity.widget.account
import co.smartreceipts.android.identity.apis.organizations.Organization
import co.smartreceipts.android.identity.apis.organizations.OrganizationModel
import co.smartreceipts.core.identity.store.EmailAddress
import co.smartreceipts.android.purchases.model.InAppPurchase
import co.smartreceipts.android.purchases.subscriptions.RemoteSubscription
import co.smartreceipts.android.widget.model.UiIndicator
import com.nhaarman.mockitokotlin2.*
import io.reactivex.Observable
import io.reactivex.Single
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.util.*
@RunWith(RobolectricTestRunner::class)
class AccountPresenterTest {
companion object {
private const val EMAIL = "[email protected]"
}
// Class under test
private lateinit var presenter: AccountPresenter
private val view = mock<AccountView>()
private val interactor = mock<AccountInteractor>()
private val organizationModel = mock<OrganizationModel>()
private val organization = mock<Organization>()
@Before
fun setUp() {
whenever(view.applySettingsClicks).thenReturn(Observable.never())
whenever(view.logoutButtonClicks).thenReturn(Observable.never())
whenever(view.uploadSettingsClicks).thenReturn(Observable.never())
whenever(interactor.getEmail()).thenReturn(EmailAddress(EMAIL))
whenever(interactor.getOrganizations()).thenReturn(Single.just(Collections.emptyList()))
whenever(interactor.getOcrRemainingScansStream()).thenReturn(Observable.just(5))
whenever(interactor.getSubscriptionsStream()).thenReturn(Observable.empty())
whenever(organizationModel.organization).thenReturn(organization)
presenter = AccountPresenter(view, interactor)
}
@Test
fun presentEmailTest() {
presenter.subscribe()
verify(view).presentEmail(eq(EmailAddress(EMAIL)))
}
@Test
fun presentNoOrganization() {
presenter.subscribe()
verify(view, times(2)).presentOrganizations(any())
verify(view).presentOrganizations(UiIndicator.loading())
verify(view).presentOrganizations(UiIndicator.idle())
verify(interactor, times(1)).getOrganizations()
}
@Test
fun presentOrganizations() {
val organizationModel = mock<OrganizationModel>()
whenever(interactor.getOrganizations()).thenReturn(Single.just(listOf(organizationModel)))
whenever(organizationModel.organization).thenReturn(mock<Organization>())
presenter.subscribe()
verify(view, times(2)).presentOrganizations(any())
verify(view).presentOrganizations(UiIndicator.loading())
verify(view).presentOrganizations(UiIndicator.success(listOf(organizationModel)))
verify(interactor, times(1)).getOrganizations()
}
@Test
fun presentOcrScansTest() {
presenter.subscribe()
verify(view).presentOcrScans(5)
}
@Test
fun presentSubscriptions() {
val subscriptions = listOf(RemoteSubscription(45, InAppPurchase.SmartReceiptsPlus, Date()))
whenever(interactor.getSubscriptionsStream()).thenReturn(Observable.just(subscriptions))
presenter.subscribe()
verify(view).presentSubscriptions(subscriptions)
}
@Test
fun applySettingsClickTest() {
whenever(view.applySettingsClicks).thenReturn(Observable.just(organizationModel))
presenter.subscribe()
verify(interactor).applyOrganizationSettings(organizationModel.organization)
}
@Test
fun uploadSettingsClickTest() {
whenever(view.uploadSettingsClicks).thenReturn(Observable.just(organizationModel))
presenter.subscribe()
verify(interactor).uploadOrganizationSettings(organizationModel.organization)
}
} | agpl-3.0 | 4955fd7659a9f66bd52f92629915e766 | 31.857143 | 99 | 0.737529 | 4.843866 | false | true | false | false |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/diff/editor/DiffEditorProvider.kt | 1 | 1926 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.editor
import com.intellij.openapi.fileEditor.AsyncFileEditorProvider
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
class DiffEditorProvider : AsyncFileEditorProvider, DumbAware {
override fun accept(project: Project, file: VirtualFile): Boolean {
return file is DiffVirtualFile
}
override fun createEditorAsync(project: Project, file: VirtualFile): AsyncFileEditorProvider.Builder {
val builder = (file as DiffVirtualFile).createProcessorAsync(project)
return object : AsyncFileEditorProvider.Builder() {
override fun build() = DiffRequestProcessorEditor(file, builder.build())
}
}
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
val builder = (file as DiffVirtualFile).createProcessorAsync(project)
return DiffRequestProcessorEditor(file, builder.build())
}
override fun disposeEditor(editor: FileEditor) {
Disposer.dispose(editor)
}
override fun getEditorTypeId(): String = "DiffEditor"
override fun getPolicy(): FileEditorPolicy = FileEditorPolicy.HIDE_DEFAULT_EDITOR
}
| apache-2.0 | 4ddd3a768197915daca96b11e03c6dcb | 38.306122 | 104 | 0.776739 | 4.448037 | false | false | false | false |
vitaliy555/stdkotlin | src/ii_collections/_15_AllAnyAndOtherPredicates.kt | 1 | 1212 | package ii_collections
fun example2(list: List<Int>) {
val isZero: (Int) -> Boolean = { it == 0 }
val hasZero: Boolean = list.any(isZero)
val allZeros: Boolean = list.all(isZero)
val numberOfZeros: Int = list.count(isZero)
val firstPositiveNumber: Int? = list.firstOrNull { it > 0 }
}
fun Customer.isFrom(city: City): Boolean {
// Return true if the customer is from the given city
return this.city==city
}
fun Shop.checkAllCustomersAreFrom(city: City): Boolean {
// Return true if all customers are from the given city
return this.customers.all { it.city==city }
}
fun Shop.hasCustomerFrom(city: City): Boolean {
// Return true if there is at least one customer from the given city
// todoCollectionTask()
return this.customers.any { it.city==city}
}
fun Shop.countCustomersFrom(city: City): Int {
// Return the number of customers from the given city
// todoCollectionTask()
return this.customers.count { it.city==city }
}
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city, or null if there is none
// todoCollectionTask()
return this.customers.firstOrNull { it.city==city }
}
| mit | 6808406e5ff32b84e7567f5385c7fccf | 27.857143 | 78 | 0.693069 | 3.811321 | false | false | false | false |
breandan/idear | src/main/java/org/openasr/idear/actions/recognition/FindUsagesActionRecognizer.kt | 2 | 2753 | package org.openasr.idear.actions.recognition
import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.psi.PsiElement
import com.intellij.usages.*
import org.openasr.idear.ide.IDEService
import org.openasr.idear.psi.PsiUtil.findContainingClass
import org.openasr.idear.psi.PsiUtil.findElementUnderCaret
import org.openasr.idear.tts.TTSService
import java.util.*
//runs only selected configuration
class FindUsagesActionRecognizer : ActionRecognizer {
override fun isMatching(sentence: String) = "find" in sentence
override fun getActionInfo(sentence: String, dataContext: DataContext): ActionCallInfo {
val aci = ActionCallInfo("FindUsages")
// Ok, that's lame
val words = listOf(*sentence.split("\\W+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
val wordsSet = HashSet(words)
val editor = IDEService.getEditor(dataContext)
val project = IDEService.getProject(dataContext)
if (editor == null || project == null) return aci
val klass = editor.findElementUnderCaret()!!.findContainingClass() ?: return aci
var targets = arrayOf<PsiElement>()
var targetName: String? = null
var subject: String? = null
if ("field" in wordsSet) {
subject = "field"
targetName = extractNameOf("field", words)
if (targetName.isEmpty()) return aci
targets = arrayOf(klass.findFieldByName(targetName, /*checkBases*/ true)!!)
} else if ("method" in wordsSet) {
subject = "method"
targetName = extractNameOf("method", words)
if (targetName.isEmpty()) return aci
targets = arrayOf(*klass.findMethodsByName(targetName, /*checkBases*/ true))
}
// TODO(kudinkin): need to cure this pain someday
aci.actionEvent = AnActionEvent(null,
SimpleDataContext.getSimpleContext(UsageView.USAGE_TARGETS_KEY.name, prepare(targets[0]), dataContext),
ActionPlaces.UNKNOWN, Presentation(), ActionManager.getInstance(), 0)
// TODO(kudinkin): move it to appropriate place
TTSService.say("Looking for usages of the $subject $targetName")
return aci
}
private fun prepare(target: PsiElement): Array<UsageTarget> = arrayOf(PsiElement2UsageTargetAdapter(target))
private fun extractNameOf(pivot: String, sentence: List<String>): String {
val target = StringBuilder()
for (i in sentence.indexOf(pivot) + 1 until sentence.size) {
target.append(sentence[i])
}
return target.toString()
}
}
| apache-2.0 | 59e7a9d9adee912f38935ed7a55ec375 | 35.706667 | 119 | 0.681075 | 4.520525 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/map/LoadGeoJsonFeaturesUseCase.kt | 1 | 2554 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.map
import android.content.Context
import android.text.TextUtils
import com.google.android.gms.maps.GoogleMap
import com.google.maps.android.data.geojson.GeoJsonFeature
import com.google.maps.android.data.geojson.GeoJsonLayer
import com.google.maps.android.ktx.utils.geojson.geoJsonLayer
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.UseCase
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Inject
/** Parameters for this use case. */
typealias LoadGeoJsonParams = Pair<GoogleMap, Int>
/** Data loaded by this use case. */
data class GeoJsonData(
val geoJsonLayer: GeoJsonLayer,
val featureMap: Map<String, GeoJsonFeature>
)
/** Use case that loads a GeoJsonLayer and its features. */
class LoadGeoJsonFeaturesUseCase @Inject constructor(
@ApplicationContext private val context: Context,
@IoDispatcher dispatcher: CoroutineDispatcher
) : UseCase<LoadGeoJsonParams, GeoJsonData>(dispatcher) {
override suspend fun execute(parameters: LoadGeoJsonParams): GeoJsonData {
val (googleMap, markersRes) = parameters
val layer = geoJsonLayer(
map = googleMap,
resourceId = markersRes,
context = context
)
processGeoJsonLayer(layer, context)
return GeoJsonData(layer, buildFeatureMap(layer))
}
private fun buildFeatureMap(layer: GeoJsonLayer): Map<String, GeoJsonFeature> {
val featureMap: MutableMap<String, GeoJsonFeature> = mutableMapOf()
layer.features.forEach {
val id = it.id
if (!TextUtils.isEmpty(id)) {
// Marker can map to multiple room IDs
for (part in id.split(",")) {
featureMap[part] = it
}
}
}
return featureMap
}
}
| apache-2.0 | 36a2a45ebd30f147b146e1d00baf6020 | 35.485714 | 83 | 0.710258 | 4.358362 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/ir/OperationBasedModelGroupBuilder.kt | 1 | 16804 | package com.apollographql.apollo3.compiler.ir
import com.apollographql.apollo3.api.BPossibleTypes
import com.apollographql.apollo3.api.BTerm
import com.apollographql.apollo3.api.BVariable
import com.apollographql.apollo3.api.BooleanExpression
import com.apollographql.apollo3.api.and
import com.apollographql.apollo3.ast.GQLField
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.GQLFragmentSpread
import com.apollographql.apollo3.ast.GQLInlineFragment
import com.apollographql.apollo3.ast.GQLNamedType
import com.apollographql.apollo3.ast.GQLNonNullType
import com.apollographql.apollo3.ast.GQLSelection
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.transformation.mergeTrivialInlineFragments
import com.apollographql.apollo3.compiler.capitalizeFirstLetter
import com.apollographql.apollo3.compiler.codegen.CodegenLayout.Companion.lowerCamelCaseIgnoringNonLetters
import com.apollographql.apollo3.compiler.codegen.CodegenLayout.Companion.modelName
import com.apollographql.apollo3.compiler.decapitalizeFirstLetter
import com.apollographql.apollo3.compiler.escapeKotlinReservedWord
internal class OperationBasedModelGroupBuilder(
private val schema: Schema,
private val allFragmentDefinitions: Map<String, GQLFragmentDefinition>,
private val fieldMerger: FieldMerger,
private val compat: Boolean
) : ModelGroupBuilder {
private val insertFragmentSyntheticField = compat
private val collectAllInlineFragmentFields = compat
private val mergeTrivialInlineFragments = compat
private fun resolveNameClashes(usedNames: MutableSet<String>, modelName: String): String {
if (!compat) {
return modelName
}
var i = 0
var name = modelName
while (usedNames.contains(name)) {
i++
name = "$modelName$i"
}
usedNames.add(name)
return name
}
override fun buildOperationData(selections: List<GQLSelection>, rawTypeName: String, operationName: String): IrModelGroup {
val info = IrFieldInfo(
responseName = "data",
description = null,
type = IrNonNullType(IrModelType(MODEL_UNKNOWN)),
deprecationReason = null,
gqlType = GQLNonNullType(type = GQLNamedType(name = rawTypeName))
)
val mergedSelections = if (mergeTrivialInlineFragments) {
selections.mergeTrivialInlineFragments(schema, rawTypeName)
} else {
selections
}
val usedNames = mutableSetOf<String>()
return buildField(
path = "${MODEL_OPERATION_DATA}.$operationName",
info = info,
selections = mergedSelections.map { SelectionWithParent(it, rawTypeName) },
condition = BooleanExpression.True,
usedNames = usedNames,
).toModelGroup()!!
}
override fun buildFragmentInterface(fragmentName: String): IrModelGroup? {
return null
}
override fun buildFragmentData(fragmentName: String): IrModelGroup {
val fragmentDefinition = allFragmentDefinitions[fragmentName]!!
/**
* XXX: because we want the model to be named after the fragment (and not data), we use
* fragmentName below. This means the id for the very first model is going to be
* FragmentName.FragmentName unlike operations where it's OperationName.Data
*/
val info = IrFieldInfo(
responseName = fragmentName,
description = null,
type = IrNonNullType(IrModelType(MODEL_UNKNOWN)),
deprecationReason = null,
gqlType = GQLNonNullType(type = fragmentDefinition.typeCondition)
)
val mergedSelections = if (mergeTrivialInlineFragments) {
fragmentDefinition.selectionSet.selections.mergeTrivialInlineFragments(schema, fragmentDefinition.typeCondition.name)
} else {
fragmentDefinition.selectionSet.selections
}
val usedNames = mutableSetOf<String>()
return buildField(
path = "${MODEL_FRAGMENT_DATA}.$fragmentName",
info = info,
selections = mergedSelections.map { SelectionWithParent(it, fragmentDefinition.typeCondition.name) },
condition = BooleanExpression.True,
usedNames = usedNames,
).toModelGroup()!!
}
/**
* A grouping key for fragments
*/
private data class InlineFragmentKey(val typeCondition: String, val condition: BooleanExpression<BVariable>)
private fun BooleanExpression<BVariable>.toName(): String = when (this) {
is BooleanExpression.True -> "True"
is BooleanExpression.False -> "False"
is BooleanExpression.And -> this.operands.joinToString("And") { it.toName() }
is BooleanExpression.Or -> this.operands.joinToString("Or") { it.toName() }
is BooleanExpression.Not -> "Not${this.operand.toName()}"
is BooleanExpression.Element -> this.value.name.capitalizeFirstLetter()
else -> error("")
}
private fun InlineFragmentKey.toName(): String = buildString {
append(typeCondition.capitalizeFirstLetter())
if (condition != BooleanExpression.True) {
append("If")
append(condition.toName())
}
}
private class SelectionWithParent(val selection: GQLSelection, val parent: String)
/**
* @param kind the [IrKind] used to identify the resulting model
* @param path the path up to but not including this field
* @param info information about this field
* @param selections the sub-selections of this fields. If [collectAllInlineFragmentFields] is true, might contain parent fields that
* might not all be on the same parent type. Hence [SelectionWithParent]
* @param condition the condition for this field. Might be a mix of include directives and type conditions
* @param usedNames the used names for 2.x compat name conflicts resolution
* @param modelName the modelName to use for this field
*/
private fun buildField(
path: String,
info: IrFieldInfo,
selections: List<SelectionWithParent>,
condition: BooleanExpression<BTerm>,
usedNames: MutableSet<String>,
): OperationField {
if (selections.isEmpty()) {
return OperationField(
info = info,
condition = condition,
fieldSet = null,
hide = false,
)
}
val selfPath = path + "." + info.responseName
/**
* Merge fragments with the same type condition and include directive to avoid name clashes
*
* We don't merge inline fragments with different include directives as nested fields would all have to become nullable:
*
* ```
* {
* ... on Droid @include(if: $a) {
* primaryFunction
* friend {
* firstName
* }
* }
* ... on Droid @include(if: $b) {
* friend {
* lastName
* }
* }
* }
* ```
*
* Merging these would yield
*
* ```
* class onDroid(val primaryFunction: String?, val friend: Friend)
* class Friend(val firstName: String?, val lastName: String?)
* ```
*
* While this is technically doable, it goes against mapping to the operation 1:1 and also makes invalid states representable
* (for an example both firstName = null and lastName = null)
*
*/
val inlineFragmentsFields = selections.filter { it.selection is GQLInlineFragment }
.groupBy {
(it.selection as GQLInlineFragment).typeCondition.name
}.entries.flatMap {
val typeCondition = it.key
// If there is only one fragment, no need to disambiguate it
val nameNeedsCondition = it.value.size > 1
val inlineFragmentsWithSameTypeCondition = it.value.map { it.selection as GQLInlineFragment }
/**
* Because fragments are not merged regardless of [collectAllInlineFragmentFields], all inline fragments
* should have the same parentType here
*/
val parentTypeCondition = it.value.first().parent
inlineFragmentsWithSameTypeCondition.groupBy { it.directives.toBooleanExpression() }
.entries.map { entry ->
val prefix = if (collectAllInlineFragmentFields) "as" else "on"
val name = if (nameNeedsCondition) {
InlineFragmentKey(typeCondition, entry.key).toName()
} else {
InlineFragmentKey(typeCondition, BooleanExpression.True).toName()
}
val possibleTypes = schema.possibleTypes(typeCondition)
var childCondition: BooleanExpression<BTerm> = if (typeCondition == parentTypeCondition) {
BooleanExpression.True
} else {
BooleanExpression.Element(BPossibleTypes(possibleTypes))
}
childCondition = entry.key.and(childCondition).simplify()
var type: IrType = IrModelType(MODEL_UNKNOWN)
if (childCondition == BooleanExpression.True) {
type = IrNonNullType(type)
}
val childInfo = IrFieldInfo(
responseName = "$prefix$name",
description = "Synthetic field for inline fragment on $typeCondition",
deprecationReason = null,
type = type,
gqlType = null
)
var childSelections = entry.value.flatMap {
it.selectionSet.selections.map { SelectionWithParent(it, typeCondition) }
}
if (collectAllInlineFragmentFields) {
childSelections = selections.filter { it.selection is GQLField } + childSelections
}
buildField(
path = selfPath,
info = childInfo,
selections = childSelections,
condition = childCondition,
usedNames = usedNames,
)
}
}
/**
* Merge fragment spreads, regardless of the type condition
*
* Since they all have the same shape, it's ok, contrary to inline fragments above
*/
val fragmentSpreadFields = selections.filter { it.selection is GQLFragmentSpread }
.groupBy {
(it.selection as GQLFragmentSpread).name
}.values.map { values ->
val fragmentSpreadsWithSameName = values.map { it.selection as GQLFragmentSpread }
val first = fragmentSpreadsWithSameName.first()
val fragmentDefinition = allFragmentDefinitions[first.name]!!
val typeCondition = fragmentDefinition.typeCondition.name
/**
* Because fragments are not merged regardless of [collectAllInlineFragmentFields], all inline fragments
* should have the same parentType here
*/
val parentTypeCondition = values.first().parent
val possibleTypes = schema.possibleTypes(typeCondition)
var childCondition: BooleanExpression<BTerm> = if (typeCondition != parentTypeCondition) {
BooleanExpression.Element(BPossibleTypes(possibleTypes))
} else {
BooleanExpression.True
}
/**
* That's more involved than the inline fragment case because fragment spreads have different @include/@skip directives get merged together
*/
childCondition = BooleanExpression.Or(fragmentSpreadsWithSameName.map { it.directives.toBooleanExpression() }.toSet())
.simplify()
.and(childCondition)
.simplify()
val fragmentModelPath = "${MODEL_FRAGMENT_DATA}.${first.name}.${first.name}"
var type: IrType = IrModelType(fragmentModelPath)
if (childCondition == BooleanExpression.True) {
type = IrNonNullType(type)
}
val childInfo = IrFieldInfo(
responseName = first.name.decapitalizeFirstLetter().escapeKotlinReservedWord(),
description = "Synthetic field for '${first.name}'",
deprecationReason = null,
type = type,
gqlType = null
)
val p = if (insertFragmentSyntheticField) {
"$selfPath.$FRAGMENTS_SYNTHETIC_FIELD"
} else {
selfPath
}
buildField(
path = p,
info = childInfo,
selections = emptyList(), // Don't create a model for fragments spreads
condition = childCondition,
usedNames = usedNames,
)
}
/**
* Add the "Fragments" synthetic field for compat codegen
*/
val fragmentsFields = if (insertFragmentSyntheticField && fragmentSpreadFields.isNotEmpty()) {
val childPath = "$selfPath.$FRAGMENTS_SYNTHETIC_FIELD"
val fragmentsFieldInfo = IrFieldInfo(
responseName = FRAGMENTS_SYNTHETIC_FIELD,
description = "Synthetic field for grouping fragments",
deprecationReason = null,
type = IrNonNullType(IrModelType(childPath)),
gqlType = null
)
val fragmentsFieldSet = OperationFieldSet(
id = childPath,
// No need to resolve the nameclashes here, "Fragments" are never flattened
modelName = modelName(fragmentsFieldInfo),
fields = listOf(hiddenTypenameField) + fragmentSpreadFields
)
listOf(
OperationField(
info = fragmentsFieldInfo,
condition = BooleanExpression.True,
fieldSet = fragmentsFieldSet,
hide = false
)
)
} else {
fragmentSpreadFields
}
val modelName = resolveNameClashes(usedNames, modelName(info))
/**
* Merge fields with the same response name in the selectionSet
* This comes last so that it mimics the 2.x behaviour of nameclash resolution
*/
val fieldsWithParent = selections.mapNotNull {
if (it.selection is GQLField) {
FieldWithParent(it.selection, it.parent)
} else {
null
}
}
val fields = fieldMerger.merge(fieldsWithParent).map { mergedField ->
val childInfo = mergedField.info.maybeNullable(mergedField.condition != BooleanExpression.True)
buildField(
path = selfPath,
info = childInfo,
selections = mergedField.selections.map { SelectionWithParent(it, mergedField.rawTypeName) },
condition = BooleanExpression.True,
usedNames = usedNames,
)
}
val fieldSet = OperationFieldSet(
id = selfPath,
modelName = modelName,
fields = fields + inlineFragmentsFields + fragmentsFields
)
val patchedInfo = info.copy(
type = info.type.replacePlaceholder(fieldSet.id),
responseName = if (info.gqlType == null) {
lowerCamelCaseIgnoringNonLetters(setOf(modelName))
} else {
info.responseName
}
)
return OperationField(
info = patchedInfo,
condition = condition,
fieldSet = fieldSet,
hide = false
)
}
companion object {
const val FRAGMENTS_SYNTHETIC_FIELD = "fragments"
private val hiddenTypenameField by lazy {
val info = IrFieldInfo(
responseName = "__typename",
description = null,
deprecationReason = null,
type = IrNonNullType(IrScalarType("String")),
gqlType = GQLNamedType(name = "String")
)
OperationField(
info = info,
condition = BooleanExpression.True,
fieldSet = null,
hide = true
)
}
}
}
private class OperationField(
val info: IrFieldInfo,
val condition: BooleanExpression<BTerm>,
val fieldSet: OperationFieldSet?,
val hide: Boolean,
) {
val isSynthetic: Boolean
get() = info.gqlType == null
}
private data class OperationFieldSet(
val id: String,
val modelName: String,
val fields: List<OperationField>,
)
private fun OperationField.toModelGroup(): IrModelGroup? {
if (fieldSet == null) {
return null
}
val model = fieldSet.toModel()
return IrModelGroup(
models = listOf(model),
baseModelId = model.id
)
}
private fun OperationFieldSet.toModel(): IrModel {
return IrModel(
modelName = modelName,
id = id,
properties = fields.map { it.toProperty() },
accessors = emptyList(),
implements = emptyList(),
isFallback = false,
isInterface = false,
modelGroups = fields.mapNotNull { it.toModelGroup() },
possibleTypes = emptySet(),
typeSet = emptySet(),
)
}
private fun OperationField.toProperty(): IrProperty {
return IrProperty(
info = info,
override = false,
condition = condition,
requiresBuffering = fieldSet?.fields?.any { it.isSynthetic } ?: false,
hidden = hide
)
}
| mit | c1da221daa53e8eae1568746244eb3dd | 33.935551 | 149 | 0.645085 | 4.838468 | false | false | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/models/Medium.kt | 1 | 3980 | package com.simplemobiletools.gallery.pro.models
import android.content.Context
import androidx.room.*
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.pro.helpers.*
import java.io.File
import java.io.Serializable
import java.util.*
@Entity(tableName = "media", indices = [(Index(value = ["full_path"], unique = true))])
data class Medium(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "filename") var name: String,
@ColumnInfo(name = "full_path") var path: String,
@ColumnInfo(name = "parent_path") var parentPath: String,
@ColumnInfo(name = "last_modified") var modified: Long,
@ColumnInfo(name = "date_taken") var taken: Long,
@ColumnInfo(name = "size") var size: Long,
@ColumnInfo(name = "type") var type: Int,
@ColumnInfo(name = "video_duration") var videoDuration: Int,
@ColumnInfo(name = "is_favorite") var isFavorite: Boolean,
@ColumnInfo(name = "deleted_ts") var deletedTS: Long,
@ColumnInfo(name = "media_store_id") var mediaStoreId: Long,
@Ignore var gridPosition: Int = 0 // used at grid view decoration at Grouping enabled
) : Serializable, ThumbnailItem() {
constructor() : this(null, "", "", "", 0L, 0L, 0L, 0, 0, false, 0L, 0L, 0)
companion object {
private const val serialVersionUID = -6553149366975655L
}
fun isWebP() = name.isWebP()
fun isGIF() = type == TYPE_GIFS
fun isImage() = type == TYPE_IMAGES
fun isVideo() = type == TYPE_VIDEOS
fun isRaw() = type == TYPE_RAWS
fun isSVG() = type == TYPE_SVGS
fun isPortrait() = type == TYPE_PORTRAITS
fun isApng() = name.isApng()
fun isHidden() = name.startsWith('.')
fun isHeic() = name.toLowerCase().endsWith(".heic") || name.toLowerCase().endsWith(".heif")
fun getBubbleText(sorting: Int, context: Context, dateFormat: String, timeFormat: String) = when {
sorting and SORT_BY_NAME != 0 -> name
sorting and SORT_BY_PATH != 0 -> path
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate(context, dateFormat, timeFormat)
sorting and SORT_BY_RANDOM != 0 -> name
else -> taken.formatDate(context)
}
fun getGroupingKey(groupBy: Int): String {
return when {
groupBy and GROUP_BY_LAST_MODIFIED_DAILY != 0 -> getDayStartTS(modified, false)
groupBy and GROUP_BY_LAST_MODIFIED_MONTHLY != 0 -> getDayStartTS(modified, true)
groupBy and GROUP_BY_DATE_TAKEN_DAILY != 0 -> getDayStartTS(taken, false)
groupBy and GROUP_BY_DATE_TAKEN_MONTHLY != 0 -> getDayStartTS(taken, true)
groupBy and GROUP_BY_FILE_TYPE != 0 -> type.toString()
groupBy and GROUP_BY_EXTENSION != 0 -> name.getFilenameExtension().toLowerCase()
groupBy and GROUP_BY_FOLDER != 0 -> parentPath
else -> ""
}
}
fun getIsInRecycleBin() = deletedTS != 0L
private fun getDayStartTS(ts: Long, resetDays: Boolean): String {
val calendar = Calendar.getInstance(Locale.ENGLISH).apply {
timeInMillis = ts
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if (resetDays) {
set(Calendar.DAY_OF_MONTH, 1)
}
}
return calendar.timeInMillis.toString()
}
fun getSignature(): String {
val lastModified = if (modified > 1) {
modified
} else {
File(path).lastModified()
}
return "$path-$lastModified-$size"
}
fun getKey() = ObjectKey(getSignature())
fun toFileDirItem() = FileDirItem(path, name, false, 0, size, modified, mediaStoreId)
}
| gpl-3.0 | 86118cdbf2873fd9872dd836bddd6bbd | 34.855856 | 102 | 0.636181 | 3.968096 | false | false | false | false |
HITGIF/SchoolPower | app/src/main/java/com/carbonylgroup/schoolpower/data/SortableTerm.kt | 1 | 848 | /**
* Copyright (C) 2019 SchoolPower Studio
*/
package com.carbonylgroup.schoolpower.data
class SortableTerm(raw: String) {
private var raw: String = ""
private var letter: String = ""
private var index: Int = 0
init {
this.raw = raw
this.letter = raw.substring(0, 1)
this.index = raw.substring(1, 2).toInt()
}
fun getValue(): Int {
return valueOfLetter(letter) * index
}
fun getRaw(): String {
return raw
}
private fun valueOfLetter(letter: String): Int {
// This is so that S1 > T4/Q4, Y1 > S2, X1 > Y1
// Don't know what's X, assume it's greater than Y here :P
return when (letter) {
"T" -> 1
"Q" -> 1
"S" -> 5
"Y" -> 11
"X" -> 12
else -> 0
}
}
}
| apache-2.0 | 796850fa838e029f41682f72421801ab | 20.74359 | 66 | 0.502358 | 3.670996 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/EditFeedDialog.kt | 1 | 4107 | package com.nononsenseapps.feeder.ui.compose.feed
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeightIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
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.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeletableFeed
import com.nononsenseapps.feeder.ui.compose.minimumTouchSize
import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme
import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder
import com.nononsenseapps.feeder.ui.compose.utils.PreviewThemes
import com.nononsenseapps.feeder.ui.compose.utils.immutableListHolderOf
@Composable
fun EditFeedDialog(
feeds: ImmutableHolder<List<DeletableFeed>>,
onDismiss: () -> Unit,
onEdit: (Long) -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
confirmButton = {
// Button(onClick = onOk) {
// Text(text = stringResource(id = R.string.ok))
// }
},
dismissButton = {
Button(onClick = onDismiss) {
Text(text = stringResource(id = android.R.string.cancel))
}
},
title = {
Text(
text = stringResource(id = R.string.edit_feed),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(vertical = 8.dp)
)
},
text = {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
) {
items(feeds.item) { feed ->
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.requiredHeightIn(min = minimumTouchSize)
.clickable {
onEdit(feed.id)
onDismiss()
}
.semantics(mergeDescendants = true) {}
) {
RadioButton(
selected = false,
onClick = {
onEdit(feed.id)
onDismiss()
},
modifier = Modifier.clearAndSetSemantics { }
)
Spacer(modifier = Modifier.width(32.dp))
Text(
text = feed.title,
style = MaterialTheme.typography.titleMedium
)
}
}
}
}
)
}
@Composable
@PreviewThemes
private fun preview() {
FeederTheme {
EditFeedDialog(
feeds = immutableListHolderOf(
DeletableFeed(1, "A Feed"),
DeletableFeed(2, "Another Feed")
),
onDismiss = {},
onEdit = {}
)
}
}
| gpl-3.0 | e516a3c68d83bbbbddb3197698fa784d | 35.669643 | 73 | 0.574872 | 5.306202 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/viewmodel/ClientConnectionViewModel.kt | 1 | 3120 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.database.model.UClientAddress
import org.monora.uprotocol.client.android.protocol.NoAddressException
import org.monora.uprotocol.core.CommunicationBridge
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.ConnectionFactory
import javax.inject.Inject
@HiltViewModel
class ClientConnectionViewModel @Inject internal constructor(
val connectionFactory: ConnectionFactory,
val persistenceProvider: PersistenceProvider,
var clientRepository: ClientRepository,
) : ViewModel() {
private var job: Job? = null
val state = MutableLiveData<ConnectionState>()
fun start(client: UClient, address: UClientAddress?): Job = job ?: viewModelScope.launch(Dispatchers.IO) {
val addresses = address?.let { listOf(it.inetAddress) } ?: clientRepository.getAddresses(client.clientUid).map {
it.inetAddress
}
try {
if (addresses.isEmpty()) {
throw NoAddressException()
}
state.postValue(ConnectionState.Connecting())
val bridge = CommunicationBridge.Builder(
connectionFactory, persistenceProvider, addresses
).apply {
setClearBlockedStatus(true)
setClientUid(client.clientUid)
}
state.postValue(ConnectionState.Connected(bridge.connect()))
} catch (e: Exception) {
state.postValue(ConnectionState.Error(e))
} finally {
job = null
}
}.also { job = it }
}
sealed class ConnectionState(val isConnecting: Boolean = false, val isError: Boolean = false) {
class Connected(val bridge: CommunicationBridge) : ConnectionState()
class Error(val e: Exception) : ConnectionState(isError = true)
class Connecting : ConnectionState(isConnecting = true)
} | gpl-2.0 | df749dd028db1ce1dff96ddc74ce8c7b | 38 | 120 | 0.730042 | 4.676162 | false | false | false | false |
agoda-com/Kakao | sample/src/main/kotlin/com/agoda/sample/DrawableListActivity.kt | 1 | 2208 | package com.agoda.sample
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.ListView
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class DrawableListActivity : AppCompatActivity() {
val drawableIds = listOf(DrawableResource(R.drawable.ic_android_black_24dp),
DrawableResource(R.drawable.ic_sentiment_very_satisfied_black_24dp),
DrawableResource(R.drawable.ic_android_black_24dp, android.R.color.holo_red_dark))
val list: ListView by lazy { findViewById<ListView>(R.id.drawableList) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_drawable_list)
list.adapter = object : BaseAdapter() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View
val vh = if (convertView != null) {
view = convertView
convertView.tag as ViewHolder
} else {
view = layoutInflater.inflate(R.layout.item_image, null)
ViewHolder(view.findViewById(R.id.imgView)).apply { view.tag = this }
}
drawableIds[position].run {
vh.imageView.setImageResource(resId)
tint?.let {
vh.imageView.setColorFilter(
ContextCompat.getColor(vh.imageView.context, it),
android.graphics.PorterDuff.Mode.SRC_IN)
}
}
return view
}
override fun getItem(position: Int) = drawableIds[position]
override fun getItemId(position: Int) = position.toLong()
override fun getCount() = drawableIds.size
}
}
class ViewHolder(val imageView: ImageView)
data class DrawableResource(@DrawableRes val resId: Int, val tint: Int? = null)
}
| apache-2.0 | 51fb34e29f6709ebb99eafb627a8f8f0 | 36.423729 | 111 | 0.612319 | 4.961798 | false | false | false | false |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/service/AddressService.kt | 1 | 3919 | package com.antonio.samir.meteoritelandingsspots.service
import android.util.Log
import com.antonio.samir.meteoritelandingsspots.data.Result
import com.antonio.samir.meteoritelandingsspots.data.local.MeteoriteLocalRepository
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import com.antonio.samir.meteoritelandingsspots.util.DefaultDispatcherProvider
import com.antonio.samir.meteoritelandingsspots.util.DispatcherProvider
import com.antonio.samir.meteoritelandingsspots.util.GeoLocationUtilInterface
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import org.apache.commons.lang3.StringUtils
import java.util.*
/**
* Evaluate convert this class to work manager
*/
@ExperimentalCoroutinesApi
class AddressService(
private val meteoriteLocalRepository: MeteoriteLocalRepository,
private val geoLocationUtil: GeoLocationUtilInterface,
private val dispatchers: DispatcherProvider = DefaultDispatcherProvider()
) : AddressServiceInterface {
private val TAG = AddressService::class.java.simpleName
override fun recoveryAddress(): Flow<Result<Float>> = meteoriteLocalRepository.meteoritesWithOutAddress()
.onEach { recoverAddress(it) }
.flowOn(dispatchers.default())
.map {
getReturn(it)
}
private suspend fun getReturn(it: List<Meteorite>): Result<Float> {
return if (!it.isNullOrEmpty()) {
val meteoritesWithoutAddressCount = meteoriteLocalRepository.getMeteoritesWithoutAddressCount()
val meteoritesCount = meteoriteLocalRepository.getMeteoritesCount()
val progress = (1 - (meteoritesWithoutAddressCount.toFloat() / meteoritesCount)) * 100
Result.InProgress(progress)
} else {
Result.Success(100f)
}
}
private suspend fun recoverAddress(list: List<Meteorite>) = withContext(dispatchers.default()) {
list.onEach { meteorite ->
try {
meteorite.address = getAddressFromMeteorite(meteorite)
} catch (e: Exception) {
Log.e(TAG, "Fail to retrieve address", e)
}
}
meteoriteLocalRepository.updateAll(list)
}
override suspend fun recoverAddress(meteorite: Meteorite) = withContext(dispatchers.default()) {
meteorite.address = getAddressFromMeteorite(meteorite)
meteoriteLocalRepository.update(meteorite)
}
private fun getAddressFromMeteorite(meteorite: Meteorite): String {
val recLat = meteorite.reclat
val recLong = meteorite.reclong
var metAddress = " "
if (recLat != null && recLong != null) {
val address = getAddress(recLat.toDouble(), recLong.toDouble())
metAddress = address ?: " "
}
return metAddress
}
private fun getAddress(recLat: Double, recLong: Double): String? {
var addressString: String? = null
val address = geoLocationUtil.getAddress(recLat, recLong)
if (address != null) {
val finalAddress = ArrayList<String>()
val city = address.locality
if (StringUtils.isNoneEmpty(city)) {
finalAddress.add(city)
}
val state = address.adminArea
if (StringUtils.isNoneEmpty(state)) {
finalAddress.add(state)
}
val countryName = address.countryName
if (StringUtils.isNoneEmpty(countryName)) {
finalAddress.add(countryName)
}
if (finalAddress.isNotEmpty()) {
addressString = finalAddress.joinToString(", ")
}
}
return addressString
}
}
| mit | ea7b1f46b06456526600adb4d0afa655 | 35.626168 | 109 | 0.675172 | 5.017926 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/ElementAnnotator.kt | 3 | 9081 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.util.TextRange
import com.intellij.psi.MultiRangeReference
import com.intellij.psi.PsiElement
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtReferenceExpression
internal class ElementAnnotator(
private val element: PsiElement,
private val shouldSuppressUnusedParameter: (KtParameter) -> Boolean
) {
fun registerDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) = diagnostics.groupBy { it.factory }
.forEach {
registerSameFactoryDiagnosticsAnnotations(
holder,
it.value,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
private fun registerSameFactoryDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
setUpAnnotations(
holder,
diagnostics,
presentationInfo,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
fun registerDiagnosticsQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>
) = diagnostics.groupBy { it.factory }
.forEach { registerDiagnosticsSameFactoryQuickFixes(it.value, highlightInfoByDiagnostic) }
private fun registerDiagnosticsSameFactoryQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
val fixesMap = createFixesMap(diagnostics) ?: return
diagnostics.forEach {
val highlightInfo = highlightInfoByDiagnostic[it] ?: return
presentationInfo.applyFixes(fixesMap, it, highlightInfo)
}
}
private fun presentationInfo(diagnostics: Collection<Diagnostic>): AnnotationPresentationInfo? {
if (diagnostics.isEmpty() || !diagnostics.any { it.isValid }) return null
val diagnostic = diagnostics.first()
// hack till the root cause #KT-21246 is fixed
if (isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic)) return null
val factory = diagnostic.factory
assert(diagnostics.all { it.psiElement == element && it.factory == factory })
val ranges = diagnostic.textRanges
val presentationInfo: AnnotationPresentationInfo = when (factory.severity) {
Severity.ERROR -> {
when (factory) {
in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS -> {
val referenceExpression = element as KtReferenceExpression
val reference = referenceExpression.mainReference
if (reference is MultiRangeReference) {
AnnotationPresentationInfo(
ranges = reference.ranges.map { it.shiftRight(referenceExpression.textOffset) },
highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
} else {
AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL)
}
}
Errors.ILLEGAL_ESCAPE -> AnnotationPresentationInfo(
ranges, textAttributes = KotlinHighlightingColors.INVALID_STRING_ESCAPE
)
Errors.REDECLARATION -> AnnotationPresentationInfo(
ranges = listOf(diagnostic.textRanges.first()), nonDefaultMessage = ""
)
else -> {
AnnotationPresentationInfo(
ranges,
highlightType = if (factory == Errors.INVISIBLE_REFERENCE)
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
else
null
)
}
}
}
Severity.WARNING -> {
if (factory == Errors.UNUSED_PARAMETER && shouldSuppressUnusedParameter(element as KtParameter)) {
return null
}
AnnotationPresentationInfo(
ranges,
textAttributes = when (factory) {
Errors.DEPRECATION -> CodeInsightColors.DEPRECATED_ATTRIBUTES
Errors.UNUSED_ANONYMOUS_PARAMETER -> CodeInsightColors.WEAK_WARNING_ATTRIBUTES
else -> null
},
highlightType = when (factory) {
in Errors.UNUSED_ELEMENT_DIAGNOSTICS, Errors.UNUSED_DESTRUCTURED_PARAMETER_ENTRY ->
ProblemHighlightType.LIKE_UNUSED_SYMBOL
Errors.UNUSED_ANONYMOUS_PARAMETER -> ProblemHighlightType.WEAK_WARNING
else -> null
}
)
}
Severity.INFO -> AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.INFORMATION)
}
return presentationInfo
}
private fun setUpAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
data: AnnotationPresentationInfo,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val fixesMap =
createFixesMap(diagnostics, noFixes)
data.processDiagnostics(holder, diagnostics, highlightInfoByDiagnostic, highlightInfoByTextRange, fixesMap, calculatingInProgress)
}
private fun createFixesMap(
diagnostics: Collection<Diagnostic>,
noFixes: Boolean = false
): MultiMap<Diagnostic, IntentionAction>? = if (noFixes) {
null
} else {
try {
createQuickFixes(diagnostics)
} catch (e: Exception) {
if (e is ControlFlowException) {
throw e
}
LOG.error(e)
MultiMap()
}
}
private fun isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic: Diagnostic): Boolean {
val factory = diagnostic.factory
if (factory != Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS && factory != Errors.FIR_COMPILED_CLASS) return false
val module = element.module ?: return false
val moduleFacetSettings = KotlinFacetSettingsProvider.getInstance(element.project)?.getSettings(module) ?: return false
return when (factory) {
Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useIR) &&
!moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useOldBackend)
Errors.FIR_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useFir)
else -> error(factory)
}
}
companion object {
val LOG = Logger.getInstance(ElementAnnotator::class.java)
}
}
| apache-2.0 | d0e9f8ab82a7914bdd15d190ee3f0fcc | 41.834906 | 158 | 0.638256 | 6.301874 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt | 3 | 8390 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.rename.inplace.MyLookupExpression
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class MapPlatformClassToKotlinFix(
element: KtReferenceExpression,
private val platformClass: ClassDescriptor,
private val possibleClasses: Collection<ClassDescriptor>
) : KotlinQuickFixAction<KtReferenceExpression>(element) {
override fun getText(): String {
val platformClassQualifiedName = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(platformClass.defaultType)
val singleClass = possibleClasses.singleOrNull()
return if (singleClass != null)
KotlinBundle.message(
"change.all.usages.of.0.in.this.file.to.1",
platformClassQualifiedName,
DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(singleClass.defaultType)
)
else
KotlinBundle.message("change.all.usages.of.0.in.this.file.to.a.kotlin.class", platformClassQualifiedName)
}
override fun getFamilyName() = KotlinBundle.message("change.to.kotlin.class")
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val bindingContext = file.analyzeWithContent()
val imports = ArrayList<KtImportDirective>()
val usages = ArrayList<KtUserType>()
for (diagnostic in bindingContext.diagnostics) {
if (diagnostic.factory !== Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN) continue
val refExpr = getImportOrUsageFromDiagnostic(diagnostic) ?: continue
if (resolveToClass(refExpr, bindingContext) != platformClass) continue
val import = refExpr.getStrictParentOfType<KtImportDirective>()
if (import != null) {
imports.add(import)
} else {
usages.add(refExpr.getStrictParentOfType<KtUserType>() ?: continue)
}
}
imports.forEach { it.delete() }
if (usages.isEmpty()) {
// if we are not going to replace any usages, there's no reason to continue at all
return
}
val replacedElements = replaceUsagesWithFirstClass(project, usages)
if (possibleClasses.size > 1 && editor != null) {
val possibleTypes = LinkedHashSet<String>()
for (klass in possibleClasses) {
possibleTypes.add(klass.name.asString())
}
buildAndShowTemplate(project, editor, file, replacedElements, possibleTypes)
}
}
private fun replaceUsagesWithFirstClass(project: Project, usages: List<KtUserType>): List<PsiElement> {
val replacementClass = possibleClasses.first()
val replacementClassName = replacementClass.name.asString()
val replacedElements = ArrayList<PsiElement>()
for (usage in usages) {
val typeArguments = usage.typeArgumentList
val typeArgumentsString = typeArguments?.text ?: ""
val replacementType = KtPsiFactory(project).createType(replacementClassName + typeArgumentsString)
val replacementTypeElement = replacementType.typeElement!!
val replacedElement = usage.replace(replacementTypeElement)
val replacedExpression = replacedElement.firstChild
assert(replacedExpression is KtSimpleNameExpression) // assumption: the Kotlin class requires no imports
replacedElements.add(replacedExpression)
}
return replacedElements
}
private val PRIMARY_USAGE = "PrimaryUsage"
private val OTHER_USAGE = "OtherUsage"
private fun buildAndShowTemplate(
project: Project, editor: Editor, file: PsiFile,
replacedElements: Collection<PsiElement>, options: LinkedHashSet<String>
) {
PsiDocumentManager.getInstance(project).commitAllDocuments()
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
val primaryReplacedExpression = replacedElements.iterator().next()
val caretModel = editor.caretModel
val oldOffset = caretModel.offset
caretModel.moveToOffset(file.node.startOffset)
val builder = TemplateBuilderImpl(file)
val expression = MyLookupExpression(
primaryReplacedExpression.text,
options,
null,
null,
false,
KotlinBundle.message("choose.an.appropriate.kotlin.class")
)
builder.replaceElement(primaryReplacedExpression, PRIMARY_USAGE, expression, true)
for (replacedExpression in replacedElements) {
if (replacedExpression === primaryReplacedExpression) continue
builder.replaceElement(replacedExpression, OTHER_USAGE, PRIMARY_USAGE, false)
}
TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
caretModel.moveToOffset(oldOffset)
}
})
}
companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtReferenceExpression, Companion.Data>() {
data class Data(
val platformClass: ClassDescriptor,
val possibleClasses: Collection<ClassDescriptor>
)
override fun getElementOfInterest(diagnostic: Diagnostic): KtReferenceExpression? = getImportOrUsageFromDiagnostic(diagnostic)
override fun extractFixData(element: KtReferenceExpression, diagnostic: Diagnostic): Data? {
val context = element.analyze(BodyResolveMode.PARTIAL)
val platformClass = resolveToClass(element, context) ?: return null
val possibleClasses = Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN.cast(diagnostic).a
return Data(platformClass, possibleClasses)
}
override fun createFix(originalElement: KtReferenceExpression, data: Data): IntentionAction? {
return MapPlatformClassToKotlinFix(originalElement, data.platformClass, data.possibleClasses)
}
private fun resolveToClass(referenceExpression: KtReferenceExpression, context: BindingContext): ClassDescriptor? {
return referenceExpression.mainReference.resolveToDescriptors(context).firstIsInstanceOrNull<ClassDescriptor>()
}
private fun getImportOrUsageFromDiagnostic(diagnostic: Diagnostic): KtReferenceExpression? {
val import = diagnostic.psiElement.getNonStrictParentOfType<KtImportDirective>()
return if (import != null) {
import.importedReference?.getQualifiedElementSelector() as? KtReferenceExpression
} else {
(diagnostic.psiElement.getNonStrictParentOfType<KtUserType>() ?: return null).referenceExpression
}
}
}
}
| apache-2.0 | 665f2b29753afa47eb395f55f31c2448 | 45.611111 | 158 | 0.718355 | 5.392031 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt | 2 | 16569 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.references.ReferenceAccess
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinIdeaAnalysisBundle.lazyMessage("replace.overloaded.operator.with.function.call"),
) {
companion object {
fun replaceExplicitInvokeCallWithImplicit(qualifiedExpression: KtDotQualifiedExpression): KtExpression? {
/*
* `a.b.invoke<>(){}` -> `a.b<>(){}`
* `a.b<>(){}.invoke<>(){}` -> `a.b<>(){}<>(){}`
* `b.invoke<>(){}` -> `b<>(){}`
* `b<>(){}.invoke<>(){}` -> `b<>(){}<>(){}`
* `invoke<>(){}` -> not applicable
*/
val callExpression = qualifiedExpression.selectorExpression.safeAs<KtCallExpression>()?.copied() ?: return null
val calleExpression = callExpression.calleeExpression as KtNameReferenceExpression
val receiverExpression = qualifiedExpression.receiverExpression
val selectorInReceiver = receiverExpression.safeAs<KtDotQualifiedExpression>()?.selectorExpression
return if (selectorInReceiver is KtNameReferenceExpression) {
calleExpression.rawReplace(selectorInReceiver.copied())
selectorInReceiver.rawReplace(callExpression)
qualifiedExpression.replaced(receiverExpression)
} else {
if ((receiverExpression is KtCallExpression || receiverExpression is KtDotQualifiedExpression) &&
callExpression.valueArgumentList == null && callExpression.typeArgumentList == null) {
calleExpression.replace(receiverExpression)
} else {
calleExpression.rawReplace(receiverExpression)
}
qualifiedExpression.replaced(callExpression)
}
}
private fun isApplicableUnary(element: KtUnaryExpression, caretOffset: Int): Boolean {
if (element.baseExpression == null) return false
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
return when (opRef.getReferencedNameElementType()) {
KtTokens.PLUS, KtTokens.MINUS, KtTokens.EXCL -> true
KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> !isUsedAsExpression(element)
else -> false
}
}
// TODO: replace to `element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))` after fix KT-25682
private fun isUsedAsExpression(element: KtExpression): Boolean {
val parent = element.parent
return if (parent is KtBlockExpression) parent.lastBlockStatementOrThis() == element && parentIsUsedAsExpression(parent.parent)
else parentIsUsedAsExpression(parent)
}
private fun parentIsUsedAsExpression(element: PsiElement): Boolean = when (val parent = element.parent) {
is KtLoopExpression, is KtFile -> false
is KtIfExpression, is KtWhenExpression -> (parent as KtExpression).isUsedAsExpression(parent.analyze(BodyResolveMode.PARTIAL_WITH_CFA))
else -> true
}
private fun isApplicableBinary(element: KtBinaryExpression, caretOffset: Int): Boolean {
if (element.left == null || element.right == null) return false
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
return when (opRef.getReferencedNameElementType()) {
KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL, KtTokens.DIV, KtTokens.PERC, KtTokens.RANGE,
KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ,
KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ
-> true
KtTokens.EQEQ, KtTokens.EXCLEQ -> listOf(element.left, element.right).none { it?.node?.elementType == KtNodeTypes.NULL }
KtTokens.EQ -> element.left is KtArrayAccessExpression
else -> false
}
}
private fun isApplicableArrayAccess(element: KtArrayAccessExpression, caretOffset: Int): Boolean {
val lbracket = element.leftBracket ?: return false
val rbracket = element.rightBracket ?: return false
val access = element.readWriteAccess(useResolveForReadWrite = true)
if (access == ReferenceAccess.READ_WRITE) return false // currently not supported
return lbracket.textRange.containsOffset(caretOffset) || rbracket.textRange.containsOffset(caretOffset)
}
private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean {
val lbrace = (element.valueArgumentList?.leftParenthesis
?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace
?: return false) as PsiElement
if (!lbrace.textRange.containsOffset(caretOffset)) return false
val resolvedCall = element.resolveToCall(BodyResolveMode.FULL)
val descriptor = resolvedCall?.resultingDescriptor
if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) {
if (element.parent is KtDotQualifiedExpression &&
element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString()
) return false
return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty()
}
return false
}
private fun convertUnary(element: KtUnaryExpression): KtExpression {
val operatorName = when (element.operationReference.getReferencedNameElementType()) {
KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> return convertUnaryWithAssignFix(element)
KtTokens.PLUS -> OperatorNameConventions.UNARY_PLUS
KtTokens.MINUS -> OperatorNameConventions.UNARY_MINUS
KtTokens.EXCL -> OperatorNameConventions.NOT
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern("$0.$1()", element.baseExpression!!, operatorName)
return element.replace(transformed) as KtExpression
}
private fun convertUnaryWithAssignFix(element: KtUnaryExpression): KtExpression {
val operatorName = when (element.operationReference.getReferencedNameElementType()) {
KtTokens.PLUSPLUS -> OperatorNameConventions.INC
KtTokens.MINUSMINUS -> OperatorNameConventions.DEC
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern("$0 = $0.$1()", element.baseExpression!!, operatorName)
return element.replace(transformed) as KtExpression
}
//TODO: don't use creation by plain text
private fun convertBinary(element: KtBinaryExpression): KtExpression {
val op = element.operationReference.getReferencedNameElementType()
val left = element.left!!
val right = element.right!!
if (op == KtTokens.EQ) {
if (left is KtArrayAccessExpression) {
convertArrayAccess(left)
}
return element
}
val context = element.analyze(BodyResolveMode.PARTIAL)
val functionCandidate = element.getResolvedCall(context)
val functionName = functionCandidate?.candidateDescriptor?.name.toString()
val elemType = context.getType(left)
@NonNls
val pattern = when (op) {
KtTokens.PLUS -> "$0.plus($1)"
KtTokens.MINUS -> "$0.minus($1)"
KtTokens.MUL -> "$0.times($1)"
KtTokens.DIV -> "$0.div($1)"
KtTokens.PERC -> "$0.rem($1)"
KtTokens.RANGE -> "$0.rangeTo($1)"
KtTokens.IN_KEYWORD -> "$1.contains($0)"
KtTokens.NOT_IN -> "!$1.contains($0)"
KtTokens.PLUSEQ -> if (functionName == "plusAssign") "$0.plusAssign($1)" else "$0 = $0.plus($1)"
KtTokens.MINUSEQ -> if (functionName == "minusAssign") "$0.minusAssign($1)" else "$0 = $0.minus($1)"
KtTokens.MULTEQ -> if (functionName == "timesAssign") "$0.timesAssign($1)" else "$0 = $0.times($1)"
KtTokens.DIVEQ -> if (functionName == "divAssign") "$0.divAssign($1)" else "$0 = $0.div($1)"
KtTokens.PERCEQ -> {
val remSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem)
if (remSupported && functionName == "remAssign") "$0.remAssign($1)"
else if (functionName == "modAssign") "$0.modAssign($1)"
else if (remSupported) "$0 = $0.rem($1)"
else "$0 = $0.mod($1)"
}
KtTokens.EQEQ -> if (elemType?.isMarkedNullable != false) "$0?.equals($1) ?: ($1 == null)" else "$0.equals($1)"
KtTokens.EXCLEQ -> if (elemType?.isMarkedNullable != false) "!($0?.equals($1) ?: ($1 == null))" else "!$0.equals($1)"
KtTokens.GT -> "$0.compareTo($1) > 0"
KtTokens.LT -> "$0.compareTo($1) < 0"
KtTokens.GTEQ -> "$0.compareTo($1) >= 0"
KtTokens.LTEQ -> "$0.compareTo($1) <= 0"
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern(pattern, left, right)
return element.replace(transformed) as KtExpression
}
private fun convertArrayAccess(element: KtArrayAccessExpression): KtExpression {
var expressionToReplace: KtExpression = element
val transformed = KtPsiFactory(element).buildExpression {
appendExpression(element.arrayExpression)
appendFixedText(".")
if (isAssignmentLeftSide(element)) {
val parent = element.parent
expressionToReplace = parent as KtBinaryExpression
appendFixedText("set(")
appendExpressions(element.indexExpressions)
appendFixedText(",")
appendExpression(parent.right)
} else {
appendFixedText("get(")
appendExpressions(element.indexExpressions)
}
appendFixedText(")")
}
return expressionToReplace.replace(transformed) as KtExpression
}
private fun isAssignmentLeftSide(element: KtArrayAccessExpression): Boolean {
val parent = element.parent
return parent is KtBinaryExpression &&
parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left
}
//TODO: don't use creation by plain text
private fun convertCall(element: KtCallExpression): KtExpression {
val callee = element.calleeExpression!!
val receiver = element.parent?.safeAs<KtQualifiedExpression>()?.receiverExpression
val isAnonymousFunctionWithReceiver = receiver != null && callee.deparenthesize() is KtNamedFunction
val argumentsList = element.valueArgumentList
val argumentString = argumentsList?.text?.removeSurrounding("(", ")") ?: ""
val argumentsWithReceiverIfNeeded = if (isAnonymousFunctionWithReceiver) {
val receiverText = receiver?.text ?: ""
val delimiter = if (receiverText.isNotEmpty() && argumentString.isNotEmpty()) ", " else ""
receiverText + delimiter + argumentString
} else {
argumentString
}
val funcLitArgs = element.lambdaArguments
val calleeText = callee.text
val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + "($argumentsWithReceiverIfNeeded)"
val transformed = KtPsiFactory(element).createExpression(transformation)
val callExpression = transformed.getCalleeExpressionIfAny()?.parent as? KtCallExpression
if (callExpression != null && funcLitArgs.isNotEmpty()) {
funcLitArgs.forEach { callExpression.add(it) }
if (argumentsWithReceiverIfNeeded.isEmpty()) {
callExpression.valueArgumentList?.delete()
}
}
val elementToReplace = if (isAnonymousFunctionWithReceiver) element.parent else callee.parent
return elementToReplace.replace(transformed) as KtExpression
}
fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> {
var elementToBeReplaced = element
if (element is KtArrayAccessExpression && isAssignmentLeftSide(element)) {
elementToBeReplaced = element.parent as KtExpression
}
val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true)
val result = when (element) {
is KtUnaryExpression -> convertUnary(element)
is KtBinaryExpression -> convertBinary(element)
is KtArrayAccessExpression -> convertArrayAccess(element)
is KtCallExpression -> convertCall(element)
else -> throw IllegalArgumentException(element.toString())
}
commentSaver.restore(result)
val callName = findCallName(result) ?: error("No call name found in ${result.text}")
return result to callName
}
private fun findCallName(result: KtExpression): KtSimpleNameExpression? = when (result) {
is KtBinaryExpression -> {
if (KtPsiUtil.isAssignment(result))
findCallName(result.right!!)
else
findCallName(result.left!!)
}
is KtUnaryExpression -> result.baseExpression?.let { findCallName(it) }
is KtParenthesizedExpression -> result.expression?.let { findCallName(it) }
else -> result.getQualifiedElementSelector() as KtSimpleNameExpression?
}
}
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean = when (element) {
is KtUnaryExpression -> isApplicableUnary(element, caretOffset)
is KtBinaryExpression -> isApplicableBinary(element, caretOffset)
is KtArrayAccessExpression -> isApplicableArrayAccess(element, caretOffset)
is KtCallExpression -> isApplicableCall(element, caretOffset)
else -> false
}
override fun applyTo(element: KtExpression, editor: Editor?) {
convert(element)
}
}
| apache-2.0 | 9c867cc0a6efc4fc173a85b99ae28e98 | 51.268139 | 158 | 0.638964 | 5.61661 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/gridLayoutTestAction/GridLayoutTestAction.kt | 5 | 15867 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.gridLayoutTestAction
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.dsl.gridLayout.*
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import javax.swing.*
import javax.swing.border.Border
import kotlin.random.Random
internal class GridLayoutTestAction : DumbAwareAction("Show GridLayout Test") {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
object : DialogWrapper(e.project, null, true, IdeModalityType.IDE, false) {
init {
title = "GridLayout Test"
init()
}
override fun createContentPaneBorder(): Border? {
return null
}
override fun createCenterPanel(): JComponent {
val result = JBTabbedPane()
result.minimumSize = Dimension(300, 200)
result.preferredSize = Dimension(800, 600)
result.addTab("TODO", createTodoPanel())
result.addTab(
"NoResizableCells", createTabPanel("No resizable cells",
createPanelLabels(3, 4) { _, _, _ -> null })
)
result.addTab("ResizableCell[1, 1]", createResizableCell11Panel())
result.addTab("CellAlignments", createCellAlignmentsPanel())
result.addTab("SubGrid", createSubGridPanel())
result.addTab("JointCells", createJointCellsPanel())
result.addTab("Gaps", createGapsPanel())
result.addTab("Col/row gaps", createColRowGapsPanel())
result.addTab("VisualPaddings", createVisualPaddingsPanel())
result.addTab("Baseline", createBaselinePanel())
result.addTab("SizeGroup", SizeGroupPanel().panel)
return result
}
}.show()
}
fun createTodoPanel(): JPanel {
val result = JPanel()
val todo = listOf(
"Implement cells which occupies all remaining columns",
"Resize non resizable cells when there is no enough space",
"Tests",
"visualPaddings can depend on component size? E.g. checkBox",
"SubGrids: visibility, visualPaddings"
)
result.add(
JLabel("<html>TODO list<br><br>&bull " + todo.joinToString("<br>&bull "))
)
return result
}
fun createBaselinePanel(): JPanel {
fun RowsGridBuilder.label(verticalAlign: VerticalAlign, size: Int): RowsGridBuilder {
val label = JLabel("${verticalAlign.name} $size")
label.font = label.font.deriveFont(size.toFloat())
cell(label, verticalAlign = verticalAlign)
return this
}
fun RowsGridBuilder.title(text: String): RowsGridBuilder {
val label = JLabel(text)
label.preferredSize = Dimension(150, 40)
label.verticalAlignment = SwingConstants.TOP
cell(label, verticalAlign = VerticalAlign.FILL)
return this
}
val panel = JPanel(GridLayout())
val builder = RowsGridBuilder(panel)
.defaultBaselineAlign(true)
builder
.title("Vertical align: TOP")
.label(VerticalAlign.TOP, 14)
.label(VerticalAlign.TOP, 10)
.label(VerticalAlign.TOP, 16)
.row()
.title("Vertical align: CENTER")
.label(VerticalAlign.CENTER, 12)
.label(VerticalAlign.CENTER, 14)
.label(VerticalAlign.CENTER, 16)
.row()
.title("Vertical align: BOTTOM")
.label(VerticalAlign.BOTTOM, 12)
.label(VerticalAlign.BOTTOM, 10)
.label(VerticalAlign.BOTTOM, 16)
.row()
.title("Vertical align: mixed")
.label(VerticalAlign.TOP, 12)
.label(VerticalAlign.CENTER, 10)
.label(VerticalAlign.BOTTOM, 14)
.label(VerticalAlign.CENTER, 16)
.label(VerticalAlign.TOP, 14)
.label(VerticalAlign.BOTTOM, 10)
.row()
builder
.subGridBuilder(width = 7)
.title("sub-panels")
.label(VerticalAlign.CENTER, 14)
.subGridBuilder(verticalAlign = VerticalAlign.CENTER)
.label(VerticalAlign.CENTER, 12)
.subGridBuilder(verticalAlign = VerticalAlign.CENTER)
.label(VerticalAlign.CENTER, 16)
.label(VerticalAlign.CENTER, 10)
return createTabPanel("Labels are aligned by baseline", panel)
}
fun createVisualPaddingsPanel(): JPanel {
val layoutManager = GridLayout()
val rootGrid = layoutManager.rootGrid
rootGrid.resizableColumns.add(1)
rootGrid.resizableRows.add(2)
val panel = JPanel(layoutManager)
fillGridByLabels(panel, rootGrid, 3, 4) { grid, x, y ->
if (x == 0 && y == 1) {
Constraints(grid, x, y, visualPaddings = Gaps(10, 10, 10, 10))
}
else if (x == 1 && y == 2) {
Constraints(
grid, x, y, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL,
visualPaddings = Gaps(10, 10, 10, 10)
)
}
else {
null
}
}
return createTabPanel("Every second cell has own Gaps", panel)
}
fun createGapsPanel(): JPanel {
val panel = createPanelLabels(4, 4) { grid, x, y ->
Constraints(
grid,
x,
y,
horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL,
gaps = if ((x + y) % 2 == 0) Gaps.EMPTY else Gaps(y * 20, x * 20, y * 30, x * 30)
)
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.addAll(0..HorizontalAlign.values().size)
grid.resizableRows.addAll(0..VerticalAlign.values().size)
return createTabPanel("Every second cell has own Gaps", panel)
}
fun createColRowGapsPanel(): JPanel {
val layoutManager = GridLayout()
val grid = layoutManager.rootGrid
grid.resizableColumns.addAll(0..4)
grid.resizableRows.addAll(0..3)
grid.columnsGaps.addAll((0..4).map { HorizontalGaps(it * 20, it * 20 + 10) })
grid.rowsGaps.addAll((0..3).map { VerticalGaps(it * 5 + 5, it * 5 + 15) })
val panel = JPanel(layoutManager)
fillGridByCompoundLabels(panel, grid)
return createTabPanel("Different distances between columns/rows", panel)
}
fun createJointCellsPanel(): JPanel {
val layoutManager = GridLayout()
val grid = layoutManager.rootGrid
grid.resizableColumns.add(1)
grid.resizableRows.add(1)
val panel = JPanel(layoutManager)
fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) {
panel.addLabel(
Constraints(
grid, x, y, width = width, height = height,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
}
addLabel(0, 0, height = 2)
addLabel(1, 0, width = 3)
addLabel(4, 0, height = 3)
addLabel(1, 1)
val constraints = Constraints(
grid, 2, 1, width = 2, height = 2,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
panel.add(
JLabel(
"<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${
constraintsToHtmlString(
constraints
)
}"
),
constraints
)
addLabel(0, 2, width = 2, height = 2)
addLabel(2, 3, width = 3)
return createTabPanel("Cells have different shapes", panel)
}
fun createCellAlignmentsPanel(): JPanel {
val panel = createPanelLabels(HorizontalAlign.values().size, VerticalAlign.values().size) { grid, x, y ->
Constraints(
grid,
x,
y,
horizontalAlign = HorizontalAlign.values()[x],
verticalAlign = VerticalAlign.values()[y]
)
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.addAll(0..HorizontalAlign.values().size)
grid.resizableRows.addAll(0..VerticalAlign.values().size)
return createTabPanel("Cells size is equal, component layouts have different alignments", panel)
}
fun createResizableCell11Panel(): JPanel {
val panel = createPanelLabels(3, 4) { grid, x, y ->
if (x == 1 && y == 1)
Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL)
else
null
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.add(1)
grid.resizableRows.add(1)
return createTabPanel("One column and row are resizable", panel)
}
fun createSubGridPanel(): JPanel {
val layoutManager = GridLayout()
layoutManager.rootGrid.resizableColumns.add(1)
layoutManager.rootGrid.resizableRows.add(1)
val panel = JPanel(layoutManager)
val subGrid = layoutManager.addLayoutSubGrid(
Constraints(
layoutManager.rootGrid, 1, 1,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
subGrid.resizableColumns.add(1)
subGrid.resizableRows.add(1)
fillGridByLabels(panel, subGrid, 3, 3) { grid, x, y ->
if (x == 1 && y == 1)
Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL)
else
null
}
RowsGridBuilder(panel)
.cell(label(0, 0))
.cell(label(1, 0))
.cell(label(2, 0))
.row()
.cell(label(0, 1))
.skip()
.cell(label(2, 1))
.row()
.cell(label(0, 2))
.cell(label(1, 2))
.cell(label(2, 2))
return createTabPanel("cell[1, 1] contains another grid inside", panel)
}
fun createPanelLabels(
width: Int,
height: Int,
constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints?
): JPanel {
val layoutManager = GridLayout()
val result = JPanel(layoutManager)
fillGridByLabels(result, layoutManager.rootGrid, width, height, constraintFactory)
return result
}
fun fillGridByLabels(
container: JComponent,
grid: Grid,
width: Int,
height: Int,
constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints?
) {
for (x in 0 until width) {
for (y in 0 until height) {
val constraints =
constraintFactory.invoke(grid, x, y) ?: Constraints(grid, x, y)
container.addLabel(constraints, longLabel = x == y)
}
}
}
fun fillGridByCompoundLabels(
container: JComponent,
grid: Grid
) {
fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) {
container.addLabel(
Constraints(
grid, x, y, width = width, height = height,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
}
addLabel(0, 0, height = 2)
addLabel(1, 0, width = 3)
addLabel(4, 0, height = 3)
addLabel(1, 1)
val constraints = Constraints(
grid, 2, 1, width = 2, height = 2,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
container.add(
JLabel(
"<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${
constraintsToHtmlString(
constraints
)
}"
),
constraints
)
addLabel(0, 2, width = 2, height = 2)
addLabel(2, 3, width = 3)
}
fun label(constraints: Constraints, longLabel: Boolean = false): JLabel {
val text = if (longLabel) "Very very very very very long label" else "Label"
return JLabel("<html>$text<br>${constraintsToHtmlString(constraints)}")
}
fun constraintsToHtmlString(constraints: Constraints): String {
var result = "x = ${constraints.x}, y = ${constraints.y}<br>" +
"width = ${constraints.width}, height = ${constraints.height}<br>" +
"hAlign = ${constraints.horizontalAlign}, vAlign = ${constraints.verticalAlign}<br>"
if (constraints.gaps != Gaps.EMPTY) {
result += "gaps = ${constraints.gaps}<br>"
}
if (constraints.visualPaddings != Gaps.EMPTY) {
result += "visualPaddings = ${constraints.visualPaddings}<br>"
}
return result
}
fun label(x: Int, y: Int, longLabel: Boolean = false): JLabel {
val text = if (longLabel) "Very very very very very long label" else "Label"
return JLabel("$text [x = $x, y = $y]")
}
fun JComponent.addLabel(constraints: Constraints, longLabel: Boolean = false) {
val label = label(constraints, longLabel)
add(label, constraints)
}
}
private fun gridToHtmlString(grid: Grid): String {
val result = mutableListOf<String>()
if (grid.resizableColumns.isNotEmpty()) {
result.add("resizableColumns = ${grid.resizableColumns.joinToString()}")
}
if (grid.resizableRows.isNotEmpty()) {
result.add("resizableRows = ${grid.resizableRows.joinToString()}")
}
if (grid.columnsGaps.isNotEmpty()) {
result.add("<br>columnsGaps = ${grid.columnsGaps.joinToString()}")
}
if (grid.rowsGaps.isNotEmpty()) {
result.add("<br>rowsGaps = ${grid.rowsGaps.joinToString()}")
}
return result.joinToString()
}
fun createTabPanel(title: String, content: JComponent): JPanel {
val layoutManager = GridLayout()
val rootGrid = layoutManager.rootGrid
val result = JPanel(layoutManager)
rootGrid.resizableColumns.add(0)
rootGrid.resizableRows.add(1)
val label = JLabel("<html>$title<br>${gridToHtmlString((content.layout as GridLayout).rootGrid)}")
label.background = Color.LIGHT_GRAY
label.isOpaque = true
result.add(label, Constraints(rootGrid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL))
result.add(
content, Constraints(
rootGrid, 0, 1, verticalAlign = VerticalAlign.FILL,
horizontalAlign = HorizontalAlign.FILL
)
)
val controlGrid = layoutManager.addLayoutSubGrid(
Constraints(
rootGrid,
1,
1,
verticalAlign = VerticalAlign.FILL
)
)
createControls(result, content, controlGrid)
return result
}
private fun createControls(container: JComponent, content: JComponent, grid: Grid) {
val cbHighlight = JCheckBox("Highlight components")
cbHighlight.addActionListener {
for (component in content.components) {
if (component is JLabel) {
component.background = if (cbHighlight.isSelected) Color(Random.nextInt()) else null
component.isOpaque = cbHighlight.isSelected
}
}
}
cbHighlight.doClick()
val list = JBList(content.components.filterIsInstance<JLabel>())
val btnHide = JButton("Hide")
val btnShow = JButton("Show")
list.cellRenderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val label = value as JLabel
val result = super.getListCellRendererComponent(
list,
label.text,
index,
isSelected,
cellHasFocus
) as DefaultListCellRenderer
result.foreground = if (label.isVisible) Color.BLACK else Color.LIGHT_GRAY
return result
}
}
btnHide.addActionListener {
list.selectedValuesList.forEach { it.isVisible = false }
list.updateUI()
}
btnShow.addActionListener {
list.selectedValuesList.forEach { it.isVisible = true }
list.updateUI()
}
grid.resizableColumns.addAll(0..1)
grid.resizableRows.add(0)
container.add(
JScrollPane(list), Constraints(
grid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL
)
)
container.add(btnHide, Constraints(grid, 0, 1, horizontalAlign = HorizontalAlign.CENTER))
container.add(btnShow, Constraints(grid, 1, 1, horizontalAlign = HorizontalAlign.CENTER))
container.add(cbHighlight, Constraints(grid, 0, 2, width = 2))
}
| apache-2.0 | 4284a5e1453e39e03d4210c8bdb6667d | 31.447853 | 120 | 0.653873 | 4.124513 | false | false | false | false |
skroll/kt-acollections | src/main/kotlin/org/skroll/acollections/AbstractList.kt | 1 | 5988 | package org.skroll.acollections
import java.util.NoSuchElementException
import java.util.RandomAccess
/**
* This class provides a skeletal implementation of the [List] interface
* to minimize the effort required to implement this interface backed by a
* "random access" data store (such as an array).
*
* For sequential access data (such as a linked list), [AbstractSequentialList]
* should be used in preference to this class.
*/
public abstract class AbstractList<E> : AbstractCollection<E>(), List<E> {
override fun indexOf(element: E): Int {
val it = listIterator()
while (it.hasNext()) {
if (it.next() == element)
return it.previousIndex()
}
return -1
}
override fun lastIndexOf(element: E): Int {
val it = listIterator(size)
while (it.hasPrevious()) {
if (it.previous() == element)
return it.nextIndex()
}
return -1
}
/**
* Returns an iterator over the elements in this list (in proper sequence).
*
* This implementation merely returns a list iterator over the list.
*
* @return an iterator over the elements in this list (in proper sequence)
*/
override fun iterator(): Iterator<E> = Itr()
override fun listIterator(): ListIterator<E> = listIterator(0)
override fun listIterator(index: Int): ListIterator<E> {
rangeCheckForAdd(index)
return ListItr(index)
}
open inner class Itr(protected var cursor: Int) : Iterator<E> {
protected var lastRet = -1
constructor() : this(0)
override fun hasNext(): Boolean = cursor != size
override fun next(): E {
try {
val i = cursor
val next = get(i)
lastRet = i
cursor = i + 1
return next
} catch (e: IndexOutOfBoundsException) {
throw NoSuchElementException()
}
}
}
inner class ListItr(index: Int) : Itr(index), ListIterator<E> {
override fun hasPrevious(): Boolean = cursor != 0
override fun previous(): E {
try {
val i = cursor - 1
val previous = get(i)
lastRet = i
cursor = i
return previous
} catch (unused: IndexOutOfBoundsException) {
throw NoSuchElementException()
}
}
override fun nextIndex(): Int = cursor
override fun previousIndex(): Int = cursor - 1
}
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return if (this is RandomAccess) RandomAccessSubList<E>(this, fromIndex, toIndex) else SubList(this, fromIndex, toIndex)
}
override fun equals(other: Any?): Boolean {
if (other === this)
return true
if (other !is List<*>)
return false
val e1 = listIterator()
val e2 = other.listIterator()
while (e1.hasNext() && e2.hasNext()) {
if (e1.next() != e2.next())
return false
}
return !(e1.hasNext() || e2.hasNext())
}
override fun hashCode(): Int {
var hashCode = 1
for (e in this)
hashCode = 31 * hashCode + (e?.hashCode() ?: 0)
return hashCode
}
private fun rangeCheckForAdd(index: Int) {
if (index < 0 || index > size)
throw IndexOutOfBoundsException("Index: $index, Size: $size")
}
}
private open class SubList<E>(private val list: AbstractList<E>, fromIndex: Int, toIndex: Int) : AbstractList<E>() {
private val offset = fromIndex
private val subSize: Int
init {
if (fromIndex < 0)
throw IndexOutOfBoundsException("fromIndex = $fromIndex")
if (toIndex > list.size)
throw IndexOutOfBoundsException("toIndex = $toIndex")
if (fromIndex > toIndex)
throw IllegalAccessException("fromIndex($fromIndex) > toIndex($toIndex)")
subSize = toIndex - fromIndex
}
override val size: Int
get() = subSize
override fun get(index: Int): E {
rangeCheck(index)
return list[index + offset]
}
override fun iterator() = listIterator()
override fun listIterator(index: Int): ListIterator<E> {
rangeCheckForAdd(index)
return object : ListIterator<E> {
val i = list.listIterator(index + offset)
override fun hasNext(): Boolean = nextIndex() < subSize
override fun next(): E {
if (hasNext())
return i.next()
else
throw NoSuchElementException()
}
override fun hasPrevious(): Boolean = previousIndex() >= 0
override fun previous(): E {
if (hasPrevious())
return i.previous()
else
throw NoSuchElementException()
}
override fun nextIndex(): Int = i.nextIndex() - offset
override fun previousIndex(): Int = i.previousIndex() - offset
}
}
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return SubList(this, fromIndex, toIndex)
}
private fun rangeCheck(index: Int) {
if (index < 0 || index >= subSize)
throw IndexOutOfBoundsException(outOfBoundsMsg(index))
}
private fun rangeCheckForAdd(index: Int) {
if (index < 0 || index > subSize)
throw IndexOutOfBoundsException(outOfBoundsMsg(index))
}
private fun outOfBoundsMsg(index: Int) = "Index: $index, Size: $subSize"
}
private class RandomAccessSubList<E>(list: AbstractList<E>, fromIndex: Int, toIndex: Int) : SubList<E>(list, fromIndex, toIndex), RandomAccess {
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return RandomAccessSubList(this, fromIndex, toIndex)
}
} | mit | 26068a4634abff3750e865558bf2851d | 30.031088 | 144 | 0.573146 | 4.714961 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt | 1 | 904 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL
aapsLogger.debug(LTag.PUMPCOMM, "Canceling temp basal")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "BASAL__CANCEL_TEMPORARY_BASAL"
}
} | agpl-3.0 | cb1de8af19dc19b7677f8b43a6537d79 | 29.166667 | 81 | 0.670354 | 4.453202 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/generator/GlslGenerator.kt | 1 | 23580 | package de.fabmax.kool.modules.ksl.generator
import de.fabmax.kool.modules.ksl.lang.*
import de.fabmax.kool.modules.ksl.model.KslState
/**
* Default GLSL shader code generator, generates glsl in version 300 es, which works for WebGL and OpenGL 3.3+
*/
open class GlslGenerator : KslGenerator() {
protected var glslVersionStr = "#version 300 es"
var blockIndent = " "
override fun generateProgram(program: KslProgram): GlslGeneratorOutput {
return GlslGeneratorOutput(generateVertexSrc(program.vertexStage), generateFragmentSrc(program.fragmentStage))
}
override fun constFloatVecExpression(vararg values: KslExpression<KslTypeFloat1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "vec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constIntVecExpression(vararg values: KslExpression<KslTypeInt1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "ivec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constUintVecExpression(vararg values: KslExpression<KslTypeUint1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "uvec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constBoolVecExpression(vararg values: KslExpression<KslTypeBool1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "bvec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constMatExpression(vararg columns: KslVectorExpression<*, KslTypeFloat1>): String {
if (columns.size !in 2..4) {
throw IllegalArgumentException("invalid number of columns: ${columns.size} (must be between 2 and 4)")
}
return "mat${columns.size}(${columns.joinToString { it.generateExpression(this) }})"
}
override fun castExpression(castExpr: KslExpressionCast<*>): String {
return "${glslTypeName(castExpr.expressionType)}(${castExpr.value.generateExpression(this)})"
}
override fun <B: KslBoolType> compareExpression(expression: KslExpressionCompare<B>): String {
val lt = expression.left.generateExpression(this)
val rt = expression.right.generateExpression(this)
return if (expression.left.expressionType is KslVector<*>) {
when (expression.operator) {
KslCompareOperator.Equal -> "equal($lt, $rt)"
KslCompareOperator.NotEqual -> "notEqual($lt, $rt)"
KslCompareOperator.Less -> "lessThan($lt, $rt)"
KslCompareOperator.LessEqual -> "lessThanEqual($lt, $rt)"
KslCompareOperator.Greater -> "greaterThan($lt, $rt)"
KslCompareOperator.GreaterEqual -> "greaterThanEqual($lt, $rt)"
}
} else {
"($lt ${expression.operator.opString} $rt)"
}
}
override fun sampleColorTexture(sampleTexture: KslSampleColorTexture<*>): String {
val sampler = sampleTexture.sampler.generateExpression(this)
val coord = if (sampleTexture.sampler.expressionType is KslTypeSampler1d && sampleTexture.coord.expressionType is KslTypeFloat1) {
// for better OpenGL ES compatibility 1d textures actually are 2d textures...
"vec2(${sampleTexture.coord.generateExpression(this)}, 0.5)"
} else {
sampleTexture.coord.generateExpression(this)
}
return if (sampleTexture.lod != null) {
"textureLod(${sampler}, ${coord}, ${sampleTexture.lod.generateExpression(this)})"
} else {
"texture(${sampler}, ${coord})"
}
}
override fun sampleDepthTexture(sampleTexture: KslSampleDepthTexture<*>): String {
return "texture(${sampleTexture.sampler.generateExpression(this)}, ${sampleTexture.coord.generateExpression(this)})"
}
override fun textureSize(textureSize: KslTextureSize<*, *>): String {
return "textureSize(${textureSize.sampler.generateExpression(this)}, ${textureSize.lod.generateExpression(this)})"
}
override fun texelFetch(expression: KslTexelFetch<*>): String {
val sampler = expression.sampler.generateExpression(this)
val coords = expression.coord.generateExpression(this)
val lod = expression.lod?.generateExpression(this)
return "texelFetch($sampler, $coords, ${lod ?: 0})"
}
private fun generateVertexSrc(vertexStage: KslVertexStage): String {
val src = StringBuilder()
src.appendLine("""
$glslVersionStr
precision highp sampler3D;
/*
* ${vertexStage.program.name} - generated vertex shader
*/
""".trimIndent())
src.appendLine()
src.generateUbos(vertexStage)
src.generateUniformSamplers(vertexStage)
src.generateAttributes(vertexStage.attributes.values.filter { it.inputRate == KslInputRate.Instance }, "instance attributes")
src.generateAttributes(vertexStage.attributes.values.filter { it.inputRate == KslInputRate.Vertex }, "vertex attributes")
src.generateInterStageOutputs(vertexStage)
src.generateFunctions(vertexStage)
src.appendLine("void main() {")
src.appendLine(generateScope(vertexStage.main, blockIndent))
src.appendLine("}")
return src.toString()
}
private fun generateFragmentSrc(fragmentStage: KslFragmentStage): String {
val src = StringBuilder()
src.appendLine("""
$glslVersionStr
precision highp float;
precision highp sampler2DShadow;
precision highp sampler3D;
/*
* ${fragmentStage.program.name} - generated fragment shader
*/
""".trimIndent())
src.appendLine()
src.generateUbos(fragmentStage)
src.generateUniformSamplers(fragmentStage)
src.generateInterStageInputs(fragmentStage)
src.generateOutputs(fragmentStage.outColors)
src.generateFunctions(fragmentStage)
src.appendLine("void main() {")
src.appendLine(generateScope(fragmentStage.main, blockIndent))
src.appendLine("}")
return src.toString()
}
protected open fun StringBuilder.generateUniformSamplers(stage: KslShaderStage) {
val samplers = stage.getUsedSamplers()
if (samplers.isNotEmpty()) {
appendLine("// texture samplers")
for (u in samplers) {
val arraySuffix = if (u.value is KslArray<*>) { "[${u.arraySize}]" } else { "" }
appendLine("uniform ${glslTypeName(u.expressionType)} ${u.value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateUbos(stage: KslShaderStage) {
val ubos = stage.getUsedUbos()
if (ubos.isNotEmpty()) {
appendLine("// uniform buffer objects")
for (ubo in ubos) {
// if isShared is true, the underlying buffer is externally provided without the buffer layout
// being queried via OpenGL API -> use standardized std140 layout
val layoutPrefix = if (ubo.isShared) { "layout(std140) " } else { "" }
appendLine("${layoutPrefix}uniform ${ubo.name} {")
for (u in ubo.uniforms.values) {
val arraySuffix = if (u.value is KslArray<*>) { "[${u.arraySize}]" } else { "" }
appendLine(" highp ${glslTypeName(u.expressionType)} ${u.value.name()}${arraySuffix};")
}
appendLine("};")
}
appendLine()
}
}
protected open fun StringBuilder.generateAttributes(attribs: List<KslVertexAttribute<*>>, info: String) {
if (attribs.isNotEmpty()) {
appendLine("// $info")
attribs.forEach { a ->
appendLine("layout(location=${a.location}) in ${glslTypeName(a.expressionType)} ${a.value.name()};")
}
appendLine()
}
}
protected open fun StringBuilder.generateInterStageOutputs(vertexStage: KslVertexStage) {
if (vertexStage.interStageVars.isNotEmpty()) {
appendLine("// custom vertex stage outputs")
vertexStage.interStageVars.forEach { interStage ->
val value = interStage.input
val arraySuffix = if (value is KslArray<*>) { "[${value.arraySize}]" } else { "" }
appendLine("${interStage.interpolation.glsl()} out ${glslTypeName(value.expressionType)} ${value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateInterStageInputs(fragmentStage: KslFragmentStage) {
if (fragmentStage.interStageVars.isNotEmpty()) {
appendLine("// custom fragment stage inputs")
fragmentStage.interStageVars.forEach { interStage ->
val value = interStage.output
val arraySuffix = if (value is KslArray<*>) { "[${value.arraySize}]" } else { "" }
appendLine("${interStage.interpolation.glsl()} in ${glslTypeName(value.expressionType)} ${value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateOutputs(outputs: List<KslStageOutput<*>>) {
if (outputs.isNotEmpty()) {
appendLine("// stage outputs")
outputs.forEach { output ->
val loc = if (output.location >= 0) "layout(location=${output.location}) " else ""
appendLine("${loc}out ${glslTypeName(output.expressionType)} ${output.value.name()};")
}
appendLine()
}
}
private fun StringBuilder.generateFunctions(stage: KslShaderStage) {
if (stage.functions.isNotEmpty()) {
val funcList = stage.functions.values.toMutableList()
sortFunctions(funcList)
funcList.forEach { func ->
appendLine("${glslTypeName(func.returnType)} ${func.name}(${func.parameters.joinToString { p -> "${glslTypeName(p.expressionType)} ${p.stateName}" }}) {")
appendLine(generateScope(func.body, blockIndent))
appendLine("}")
appendLine()
}
}
}
override fun opDeclareVar(op: KslDeclareVar): String {
val initExpr = op.initExpression?.let { " = ${it.generateExpression(this)}" } ?: ""
val state = op.declareVar
return "${glslTypeName(state.expressionType)} ${state.name()}${initExpr};"
}
override fun opDeclareArray(op: KslDeclareArray): String {
val initExpr = op.elements.joinToString { it.generateExpression(this) }
val array = op.declareVar
val typeName = glslTypeName(array.expressionType.elemType)
return "$typeName ${array.name()}[${array.arraySize}] = ${typeName}[](${initExpr});"
}
override fun opAssign(op: KslAssign<*>): String {
return "${op.assignTarget.generateAssignable(this)} = ${op.assignExpression.generateExpression(this)};"
}
override fun opAugmentedAssign(op: KslAugmentedAssign<*>): String {
return "${op.assignTarget.generateAssignable(this)} ${op.augmentationMode.opChar}= ${op.assignExpression.generateExpression(this)};"
}
override fun opIf(op: KslIf): String {
val txt = StringBuilder("if (${op.condition.generateExpression(this)}) {\n")
txt.appendLine(generateScope(op.body, blockIndent))
txt.append("}")
op.elseIfs.forEach { elseIf ->
txt.appendLine(" else if (${elseIf.first.generateExpression(this)}) {")
txt.appendLine(generateScope(elseIf.second, blockIndent))
txt.append("}")
}
if (op.elseBody.isNotEmpty()) {
txt.appendLine(" else {")
txt.appendLine(generateScope(op.elseBody, blockIndent))
txt.append("}")
}
return txt.toString()
}
override fun opFor(op: KslLoopFor<*>): String {
return StringBuilder("for (; ")
.append(op.whileExpression.generateExpression(this)).append("; ")
.append(op.loopVar.generateAssignable(this)).append(" += ").append(op.incExpr.generateExpression(this))
.appendLine(") {")
.appendLine(generateScope(op.body, blockIndent))
.append("}")
.toString()
}
override fun opWhile(op: KslLoopWhile): String {
return StringBuilder("while (${op.whileExpression.generateExpression(this)}) {\n")
.appendLine(generateScope(op.body, blockIndent))
.append("}")
.toString()
}
override fun opDoWhile(op: KslLoopDoWhile): String {
return StringBuilder("do {\n")
.appendLine(generateScope(op.body, blockIndent))
.append("} while (${op.whileExpression.generateExpression(this)});")
.toString()
}
override fun opBreak(op: KslLoopBreak) = "break;"
override fun opContinue(op: KslLoopContinue) = "continue;"
override fun opDiscard(op: KslDiscard): String = "discard;"
override fun opReturn(op: KslReturn): String = "return ${op.returnValue.generateExpression(this)};"
override fun opBlock(op: KslBlock): String {
val txt = StringBuilder("{ // block: ${op.opName}\n")
txt.appendLine(generateScope(op.body, blockIndent))
txt.append("}")
return txt.toString()
}
private fun generateArgs(args: List<KslExpression<*>>, expectedArgs: Int): String {
check(args.size == expectedArgs)
return args.joinToString { it.generateExpression(this) }
}
override fun invokeFunction(func: KslInvokeFunction<*>) = "${func.function.name}(${generateArgs(func.args, func.args.size)})"
override fun builtinAbs(func: KslBuiltinAbsScalar<*>) = "abs(${generateArgs(func.args, 1)})"
override fun builtinAbs(func: KslBuiltinAbsVector<*, *>) = "abs(${generateArgs(func.args, 1)})"
override fun builtinAtan2(func: KslBuiltinAtan2Scalar) = "atan(${generateArgs(func.args, 2)})"
override fun builtinAtan2(func: KslBuiltinAtan2Vector<*>) = "atan(${generateArgs(func.args, 2)})"
override fun builtinCeil(func: KslBuiltinCeilScalar) = "ceil(${generateArgs(func.args, 1)})"
override fun builtinCeil(func: KslBuiltinCeilVector<*>) = "ceil(${generateArgs(func.args, 1)})"
override fun builtinClamp(func: KslBuiltinClampScalar<*>) = "clamp(${generateArgs(func.args, 3)})"
override fun builtinClamp(func: KslBuiltinClampVector<*, *>) = "clamp(${generateArgs(func.args, 3)})"
override fun builtinCross(func: KslBuiltinCross) = "cross(${generateArgs(func.args, 2)})"
override fun builtinDegrees(func: KslBuiltinDegreesScalar) = "degrees(${generateArgs(func.args, 1)})"
override fun builtinDegrees(func: KslBuiltinDegreesVector<*>) = "degrees(${generateArgs(func.args, 1)})"
override fun builtinDistance(func: KslBuiltinDistanceScalar<*>) = "distance(${generateArgs(func.args, 2)})"
override fun builtinDot(func: KslBuiltinDot<*>) = "dot(${generateArgs(func.args, 2)})"
override fun builtinExp(func: KslBuiltinExpScalar) = "exp(${generateArgs(func.args, 1)})"
override fun builtinExp(func: KslBuiltinExpVector<*>) = "exp(${generateArgs(func.args, 1)})"
override fun builtinExp2(func: KslBuiltinExp2Scalar) = "exp2(${generateArgs(func.args, 1)})"
override fun builtinExp2(func: KslBuiltinExp2Vector<*>) = "exp2(${generateArgs(func.args, 1)})"
override fun builtinFaceForward(func: KslBuiltinFaceForward<*>) = "faceforward(${generateArgs(func.args, 3)})"
override fun builtinFloor(func: KslBuiltinFloorScalar) = "floor(${generateArgs(func.args, 1)})"
override fun builtinFloor(func: KslBuiltinFloorVector<*>) = "floor(${generateArgs(func.args, 1)})"
override fun builtinFma(func: KslBuiltinFmaScalar) = "fma(${generateArgs(func.args, 3)})"
override fun builtinFma(func: KslBuiltinFmaVector<*>) = "fma(${generateArgs(func.args, 3)})"
override fun builtinFract(func: KslBuiltinFractScalar) = "fract(${generateArgs(func.args, 1)})"
override fun builtinFract(func: KslBuiltinFractVector<*>) = "fract(${generateArgs(func.args, 1)})"
override fun builtinInverseSqrt(func: KslBuiltinInverseSqrtScalar) = "inversesqrt(${generateArgs(func.args, 1)})"
override fun builtinInverseSqrt(func: KslBuiltinInverseSqrtVector<*>) = "inversesqrt(${generateArgs(func.args, 1)})"
override fun builtinLength(func: KslBuiltinLength<*>) = "length(${generateArgs(func.args, 1)})"
override fun builtinLog(func: KslBuiltinLogScalar) = "log(${generateArgs(func.args, 1)})"
override fun builtinLog(func: KslBuiltinLogVector<*>) = "log(${generateArgs(func.args, 1)})"
override fun builtinLog2(func: KslBuiltinLog2Scalar) = "log2(${generateArgs(func.args, 1)})"
override fun builtinLog2(func: KslBuiltinLog2Vector<*>) = "log2(${generateArgs(func.args, 1)})"
override fun builtinMax(func: KslBuiltinMaxScalar<*>) = "max(${generateArgs(func.args, 2)})"
override fun builtinMax(func: KslBuiltinMaxVector<*, *>) = "max(${generateArgs(func.args, 2)})"
override fun builtinMin(func: KslBuiltinMinScalar<*>) = "min(${generateArgs(func.args, 2)})"
override fun builtinMin(func: KslBuiltinMinVector<*, *>) = "min(${generateArgs(func.args, 2)})"
override fun builtinMix(func: KslBuiltinMixScalar) = "mix(${generateArgs(func.args, 3)})"
override fun builtinMix(func: KslBuiltinMixVector<*>) = "mix(${generateArgs(func.args, 3)})"
override fun builtinNormalize(func: KslBuiltinNormalize<*>) = "normalize(${generateArgs(func.args, 1)})"
override fun builtinReflect(func: KslBuiltinReflect<*>) = "reflect(${generateArgs(func.args, 2)})"
override fun builtinRefract(func: KslBuiltinRefract<*>) = "refract(${generateArgs(func.args, 3)})"
override fun builtinRound(func: KslBuiltinRoundScalar) = "round(${generateArgs(func.args, 1)})"
override fun builtinRound(func: KslBuiltinRoundVector<*>) = "round(${generateArgs(func.args, 1)})"
override fun builtinSign(func: KslBuiltinSignScalar<*>) = "sign(${generateArgs(func.args, 1)})"
override fun builtinSign(func: KslBuiltinSignVector<*, *>) = "sign(${generateArgs(func.args, 1)})"
override fun builtinPow(func: KslBuiltinPowScalar) = "pow(${generateArgs(func.args, 2)})"
override fun builtinPow(func: KslBuiltinPowVector<*>) = "pow(${generateArgs(func.args, 2)})"
override fun builtinRadians(func: KslBuiltinRadiansScalar) = "radians(${generateArgs(func.args, 1)})"
override fun builtinRadians(func: KslBuiltinRadiansVector<*>) = "radians(${generateArgs(func.args, 1)})"
override fun builtinSmoothStep(func: KslBuiltinSmoothStepScalar) = "smoothstep(${generateArgs(func.args, 3)})"
override fun builtinSmoothStep(func: KslBuiltinSmoothStepVector<*>) = "smoothstep(${generateArgs(func.args, 3)})"
override fun builtinSqrt(func: KslBuiltinSqrtScalar) = "sqrt(${generateArgs(func.args, 1)})"
override fun builtinSqrt(func: KslBuiltinSqrtVector<*>) = "sqrt(${generateArgs(func.args, 1)})"
override fun builtinStep(func: KslBuiltinStepScalar) = "step(${generateArgs(func.args, 2)})"
override fun builtinStep(func: KslBuiltinStepVector<*>) = "step(${generateArgs(func.args, 2)})"
override fun builtinTrigonometry(func: KslBuiltinTrigonometryScalar) = "${func.name}(${generateArgs(func.args, 1)})"
override fun builtinTrigonometry(func: KslBuiltinTrigonometryVector<*>) = "${func.name}(${generateArgs(func.args, 1)})"
override fun builtinTrunc(func: KslBuiltinTruncScalar) = "trunc(${generateArgs(func.args, 1)})"
override fun builtinTrunc(func: KslBuiltinTruncVector<*>) = "trunc(${generateArgs(func.args, 1)})"
override fun builtinDeterminant(func: KslBuiltinDeterminant<*, *>) = "determinant(${generateArgs(func.args, 1)})"
override fun builtinTranspose(func: KslBuiltinTranspose<*, *>) = "transpose(${generateArgs(func.args, 1)})"
protected fun KslInterStageInterpolation.glsl(): String {
return when (this) {
KslInterStageInterpolation.Smooth -> "smooth"
KslInterStageInterpolation.Flat -> "flat"
KslInterStageInterpolation.NoPerspective -> "noperspective"
}
}
override fun KslState.name(): String {
return when (stateName) {
KslVertexStage.NAME_IN_VERTEX_INDEX -> "gl_VertexID"
KslVertexStage.NAME_IN_INSTANCE_INDEX -> "gl_InstanceID"
KslVertexStage.NAME_OUT_POSITION -> "gl_Position"
KslVertexStage.NAME_OUT_POINT_SIZE -> "gl_PointSize"
KslFragmentStage.NAME_IN_FRAG_POSITION -> "gl_FragCoord"
KslFragmentStage.NAME_IN_IS_FRONT_FACING -> "gl_FrontFacing"
KslFragmentStage.NAME_OUT_DEPTH -> "gl_FragDepth"
else -> stateName
}
}
protected fun glslTypeName(type: KslType): String {
return when (type) {
KslTypeVoid -> "void"
KslTypeBool1 -> "bool"
KslTypeBool2 -> "bvec2"
KslTypeBool3 -> "bvec3"
KslTypeBool4 -> "bvec4"
KslTypeFloat1 -> "float"
KslTypeFloat2 -> "vec2"
KslTypeFloat3 -> "vec3"
KslTypeFloat4 -> "vec4"
KslTypeInt1 -> "int"
KslTypeInt2 -> "ivec2"
KslTypeInt3 -> "ivec3"
KslTypeInt4 -> "ivec4"
KslTypeUint1 -> "uint"
KslTypeUint2 -> "uvec2"
KslTypeUint3 -> "uvec3"
KslTypeUint4 -> "uvec4"
KslTypeMat2 -> "mat2"
KslTypeMat3 -> "mat3"
KslTypeMat4 -> "mat4"
KslTypeColorSampler1d -> "sampler2D" // in WebGL2, 1d textures are not supported, simply use 2d instead (with height = 1px)
KslTypeColorSampler2d -> "sampler2D"
KslTypeColorSampler3d -> "sampler3D"
KslTypeColorSamplerCube -> "samplerCube"
KslTypeColorSampler2dArray -> "sampler2DArray"
KslTypeColorSamplerCubeArray -> "samplerCubeArray"
KslTypeDepthSampler2d -> "sampler2DShadow"
KslTypeDepthSamplerCube -> "samplerCubeShadow"
KslTypeDepthSampler2dArray -> "sampler2DArrayShadow"
KslTypeDepthSamplerCubeArray -> "samplerCubeArrayShadow"
is KslTypeArray<*> -> glslTypeName(type.elemType)
}
}
class GlslGeneratorOutput(val vertexSrc: String, val fragmentSrc: String) : GeneratorOutput {
private fun linePrefix(line: Int): String {
var num = "$line"
while (num.length < 3) {
num = " $num"
}
return "$num "
}
fun dump() {
println("### vertex shader:")
vertexSrc.lineSequence().forEachIndexed { i, line -> println("${linePrefix(i)}${line}") }
println("### fragment shader:")
fragmentSrc.lineSequence().forEachIndexed { i, line -> println("${linePrefix(i)}${line}") }
}
}
} | apache-2.0 | 0ec307fb2e923ae04cf3cec4adf78427 | 49.065817 | 170 | 0.642282 | 4.331374 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/AddOnViewHolderViewModel.kt | 1 | 9774 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.R
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.models.Country
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.RewardUtils
import com.kickstarter.libs.utils.extensions.negate
import com.kickstarter.models.Project
import com.kickstarter.models.Reward
import com.kickstarter.models.RewardsItem
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.viewholders.RewardViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.math.RoundingMode
interface AddOnViewHolderViewModel {
interface Inputs {
/** Configure with the current [ProjectData] and [Reward].
* @param projectData we get the Project for currency
* @param reward the actual reward, add on, no reward loading on the ViewHolder
*/
fun configureWith(projectData: ProjectData, reward: Reward)
}
interface Outputs {
/** Emits `true` if the title for addons should be hidden, `false` otherwise. */
fun isAddonTitleGone(): Observable<Boolean>
/** Emits the reward's minimum converted to the user's preference */
fun conversion(): Observable<String>
/** Emits `true` if the conversion should be hidden, `false` otherwise. */
fun conversionIsGone(): Observable<Boolean>
/** Emits the reward's description when `isNoReward` is true. */
fun descriptionForNoReward(): Observable<Int>
/** Emits the reward's description. */
fun descriptionForReward(): Observable<String?>
/** Emits the minimum pledge amount in the project's currency. */
fun minimumAmountTitle(): Observable<String>
/** Emits the reward's items. */
fun rewardItems(): Observable<List<RewardsItem>>
/** Emits `true` if the items section should be hidden, `false` otherwise. */
fun rewardItemsAreGone(): Observable<Boolean>
/** Emits the reward's title when `isReward` is true. */
fun titleForReward(): Observable<String?>
/** Emits the reward's title when `noReward` is true. */
fun titleForNoReward(): Observable<Int>
/** Emits a pait with the add on title and the quantity in order to build the stylized title */
fun titleForAddOn(): Observable<Pair<String, Int>>
/** Emits a boolean that determines if the local PickUp section should be hidden **/
fun localPickUpIsGone(): Observable<Boolean>
/** Emits the String with the Local Pickup Displayable name **/
fun localPickUpName(): Observable<String>
}
/**
* Logic to handle the UI for `Reward`, `No Reward` and `Add On`
* Configuring the View for [AddOnViewHolder]
* - No interaction with the user just displaying information
* - Loading in [AddOnViewHolder] -> [RewardAndAddOnsAdapter] -> [BackingFragment]
*/
class ViewModel(@NonNull environment: Environment) : ActivityViewModel<RewardViewHolder>(environment), Inputs, Outputs {
private val ksCurrency = requireNotNull(environment.ksCurrency())
private val isAddonTitleGone = BehaviorSubject.create<Boolean>()
private val projectDataAndReward = PublishSubject.create<Pair<ProjectData, Reward>>()
private val conversion = BehaviorSubject.create<String>()
private val conversionIsGone = BehaviorSubject.create<Boolean>()
private val descriptionForNoReward = BehaviorSubject.create<Int>()
private val titleForNoReward = BehaviorSubject.create<Int>()
private val descriptionForReward = BehaviorSubject.create<String?>()
private val minimumAmountTitle = PublishSubject.create<String>()
private val rewardItems = BehaviorSubject.create<List<RewardsItem>>()
private val rewardItemsAreGone = BehaviorSubject.create<Boolean>()
private val titleForReward = BehaviorSubject.create<String?>()
private val titleForAddOn = BehaviorSubject.create<Pair<String, Int>>()
private val titleIsGone = BehaviorSubject.create<Boolean>()
private val localPickUpIsGone = BehaviorSubject.create<Boolean>()
private val localPickUpName = BehaviorSubject.create<String>()
private val optimizely = environment.optimizely()
val inputs: Inputs = this
val outputs: Outputs = this
init {
val reward = this.projectDataAndReward
.map { it.second }
val projectAndReward = this.projectDataAndReward
.map { Pair(it.first.project(), it.second) }
projectAndReward
.map { buildCurrency(it.first, it.second) }
.compose(bindToLifecycle())
.subscribe(this.minimumAmountTitle)
projectAndReward
.map { it.first }
.map { it.currency() == it.currentCurrency() }
.compose(bindToLifecycle())
.subscribe(this.conversionIsGone)
projectAndReward
.map { getCurrency(it) }
.compose(bindToLifecycle())
.subscribe(this.conversion)
reward
.filter { RewardUtils.isReward(it) }
.map { it.description() }
.compose(bindToLifecycle())
.subscribe(this.descriptionForReward)
reward
.filter { !it.isAddOn() && RewardUtils.isNoReward(it) }
.compose(bindToLifecycle())
.subscribe {
this.descriptionForNoReward.onNext(R.string.Thanks_for_bringing_this_project_one_step_closer_to_becoming_a_reality)
this.titleForNoReward.onNext(R.string.You_pledged_without_a_reward)
}
reward
.filter { RewardUtils.isItemized(it) }
.map { if (it.isAddOn()) it.addOnsItems() else it.rewardsItems() }
.compose(bindToLifecycle())
.subscribe(this.rewardItems)
reward
.map { RewardUtils.isItemized(it) }
.map { it.negate() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.rewardItemsAreGone)
reward
.filter { !it.isAddOn() && RewardUtils.isReward(it) }
.map { it.title() }
.compose(bindToLifecycle())
.subscribe(this.titleForReward)
reward
.map { !it.isAddOn() }
.compose(bindToLifecycle())
.subscribe(this.titleIsGone)
reward
.filter { it.isAddOn() && it.quantity()?.let { q -> q > 0 } ?: false }
.map { reward -> parametersForTitle(reward) }
.compose(bindToLifecycle())
.subscribe(this.titleForAddOn)
reward
.filter { !RewardUtils.isShippable(it) }
.map {
RewardUtils.isLocalPickup(it)
}
.compose(bindToLifecycle())
.subscribe {
this.localPickUpIsGone.onNext(!it)
}
reward
.filter { !RewardUtils.isShippable(it) }
.filter { RewardUtils.isLocalPickup(it) }
.map { it.localReceiptLocation()?.displayableName() }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe(this.localPickUpName)
}
private fun getCurrency(it: Pair<Project, Reward>) =
this.ksCurrency.format(it.second.convertedMinimum(), it.first, true, RoundingMode.HALF_UP, true)
private fun buildCurrency(project: Project, reward: Reward): String {
val completeCurrency = ksCurrency.format(reward.minimum(), project, RoundingMode.HALF_UP)
val country = Country.findByCurrencyCode(project.currency()) ?: ""
return completeCurrency.removePrefix(country.toString())
}
private fun parametersForTitle(reward: Reward?): Pair<String, Int> {
val title = reward?.title()?.let { it } ?: ""
val quantity = reward?.quantity()?.let { it } ?: -1
return Pair(title, quantity)
}
override fun configureWith(projectData: ProjectData, reward: Reward) = this.projectDataAndReward.onNext(Pair.create(projectData, reward))
override fun isAddonTitleGone(): Observable<Boolean> = this.isAddonTitleGone
override fun conversion(): Observable<String> = this.conversion
override fun conversionIsGone(): Observable<Boolean> = this.conversionIsGone
override fun descriptionForNoReward(): Observable<Int> = this.descriptionForNoReward
override fun titleForNoReward(): Observable<Int> = this.titleForNoReward
override fun descriptionForReward(): Observable<String?> = this.descriptionForReward
override fun minimumAmountTitle(): Observable<String> = this.minimumAmountTitle
override fun rewardItems(): Observable<List<RewardsItem>> = this.rewardItems
override fun rewardItemsAreGone(): Observable<Boolean> = this.rewardItemsAreGone
override fun titleForReward(): Observable<String?> = this.titleForReward
override fun titleForAddOn(): Observable<Pair<String, Int>> = this.titleForAddOn
override fun localPickUpIsGone(): Observable<Boolean> = localPickUpIsGone
override fun localPickUpName(): Observable<String> = localPickUpName
}
}
| apache-2.0 | 32ea75b6ecd5cb06e9b3af3ebae7ab90 | 40.948498 | 145 | 0.635154 | 4.966463 | false | false | false | false |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt | 2 | 4918 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.p3c.idea.quickfix.DecorateInspectionGadgetsFix
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.HardcodedMethodConstants
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import com.siyeh.ig.psiutils.TypeUtils
import com.siyeh.ig.style.LiteralAsArgToStringEqualsInspection
import org.jetbrains.annotations.NonNls
/**
*
* Batch QuickFix Supported
* @author caikang
* @date 2017/02/27
*/
class AliEqualsAvoidNullInspection : LiteralAsArgToStringEqualsInspection, AliBaseInspection {
constructor()
/**
* For Javassist
*/
constructor(any: Any?) : this()
override fun ruleName(): String {
return "EqualsAvoidNullRule"
}
override fun getDisplayName(): String {
return RuleInspectionUtils.getRuleMessage(ruleName())
}
override fun buildErrorString(vararg infos: Any?): String {
val methodName = infos[0] as String
return String.format(P3cBundle.getMessage("com.alibaba.p3c.idea.inspection.rule.AliEqualsAvoidNull.errMsg"),
methodName)
}
override fun getShortName(): String {
return "AliEqualsAvoidNull"
}
override fun getStaticDescription(): String? {
return RuleInspectionUtils.getRuleStaticDescription(ruleName())
}
override fun getDefaultLevel(): HighlightDisplayLevel {
return RuleInspectionUtils.getHighlightDisplayLevel(ruleName())
}
override fun buildVisitor(): BaseInspectionVisitor {
return LiteralAsArgToEqualsVisitor()
}
private class LiteralAsArgToEqualsVisitor : BaseInspectionVisitor() {
override fun visitMethodCallExpression(
expression: PsiMethodCallExpression) {
super.visitMethodCallExpression(expression)
val methodExpression = expression.methodExpression
@NonNls val methodName = methodExpression.referenceName
if (HardcodedMethodConstants.EQUALS != methodName && HardcodedMethodConstants.EQUALS_IGNORE_CASE != methodName) {
return
}
val argList = expression.argumentList
val args = argList.expressions
if (args.size != 1) {
return
}
val argument = args[0]
val argumentType = argument.type ?: return
if (argument !is PsiLiteralExpression && !isConstantField(argument)) {
return
}
if (!TypeUtils.isJavaLangString(argumentType)) {
return
}
val target = methodExpression.qualifierExpression
if (target is PsiLiteralExpression || isConstantField(argument)) {
return
}
registerError(argument, methodName)
}
private fun isConstantField(argument: PsiExpression): Boolean {
if (argument !is PsiReferenceExpression) {
return false
}
val psiField = argument.resolve() as? PsiField ?: return false
val modifierList = psiField.modifierList ?: return false
return modifierList.hasModifierProperty("final") && modifierList.hasModifierProperty("static")
}
}
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val fix = super.buildFix(*infos) ?: return null
return DecorateInspectionGadgetsFix(fix,
P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.AliEqualsAvoidNull"))
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? {
return buildFix(psiElement)
}
override fun manualParsePsiElement(psiFile: PsiFile, manager: InspectionManager, start: Int, end: Int): PsiElement {
return psiFile.findElementAt(start)!!.parent.parent
}
}
| apache-2.0 | e95c2bd8177eb293d50e2f30a8f1740d | 35.977444 | 125 | 0.696015 | 5.013252 | false | false | false | false |
Setekh/corvus-android-essentials | app/src/main/java/eu/corvus/essentials/core/tasks.kt | 1 | 3751 | package eu.corvus.essentials.core
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
/**
* Created by Vlad Cazacu on 05.05.2017.
*/
class Promise<T> {
var isSuccessful = false
var isCanceled = false
var future: Future<*>? = null
set(value) {
if(isCanceled)
value?.cancel(true)
field = value
}
internal val successHandlers = LinkedList<ResultCallbackHolder<T>>()
internal val failHandlers = LinkedList<ResultCallbackHolder<Throwable>>()
internal var alwaysHandler: ResultCallbackHolder<Unit>? = null
fun cancel(mayInterruptIfRunning: Boolean) {
isCanceled = true
future?.cancel(mayInterruptIfRunning)
}
fun doSuccess(returns: T) {
isSuccessful = true
successHandlers.forEach {
if(it.isUi)
threads.uiHandler.post { it.resultHandler.invoke(true, returns) }
else
it.resultHandler.invoke(true, returns)
}
}
fun doFail(returns: Throwable) {
isSuccessful = false
failHandlers.forEach {
if(it.isUi)
threads.uiHandler.post { it.resultHandler.invoke(false, returns) }
else
it.resultHandler.invoke(false, returns)
}
}
class ResultCallbackHolder<in E>(val isUi: Boolean, val resultHandler: (Boolean, E) -> Unit)
fun doFinally() {
successHandlers.clear()
failHandlers.clear()
val alwaysHandler = alwaysHandler ?: return
this.alwaysHandler = null
if(alwaysHandler.isUi)
threads.uiHandler.post { alwaysHandler.resultHandler.invoke(isSuccessful, Unit) }
else
alwaysHandler.resultHandler.invoke(isSuccessful, Unit)
}
fun get(): T {
if(isCanceled)
throw InterruptedException("Task interrupted!")
return future!!.get() as T
}
}
fun <V> task(body: () -> V): Promise<V> {
val promise = Promise<V>()
val futureTask = FutureTask<V>(Callable {
var value: V? = null
try {
val v = body.invoke()
value = v
promise.doSuccess(v)
} catch (e: Exception) {
promise.doFail(e)
} finally {
promise.doFinally()
}
value
})
promise.future = futureTask
threads.uiHandler.post { // on the next loop
threads.executionService.submit(futureTask)
}
return promise
}
infix fun <T> Promise<T>.success(callback: ((T) -> Unit)) : Promise<T> {
successHandlers += Promise.ResultCallbackHolder(false, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.fail(callback: ((Throwable) -> Unit)) : Promise<T> {
failHandlers += Promise.ResultCallbackHolder(false, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.successUi(callback: ((T) -> Unit)) : Promise<T> {
successHandlers += Promise.ResultCallbackHolder(true, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.failUi(callback: ((Throwable) -> Unit)) : Promise<T> {
failHandlers += Promise.ResultCallbackHolder(true, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.finally(callback: ((Boolean) -> Unit)) : Promise<T> {
alwaysHandler = Promise.ResultCallbackHolder(false, { success, _ -> callback.invoke(success) })
return this
}
infix fun <T> Promise<T>.finallyUi(callback: ((Boolean) -> Unit)) : Promise<T> {
alwaysHandler = Promise.ResultCallbackHolder(true, { success, _ -> callback.invoke(success) })
return this
}
| apache-2.0 | d68e271da3b3c55feb978fc5604149cc | 27.853846 | 102 | 0.620101 | 4.121978 | false | false | false | false |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/productInfo/ProductInfoGenerator.kt | 1 | 2848 | // 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.intellij.build.impl.productInfo
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.BuiltinModulesFileData
internal const val PRODUCT_INFO_FILE_NAME = "product-info.json"
@OptIn(ExperimentalSerializationApi::class)
internal val jsonEncoder by lazy {
Json {
prettyPrint = true
prettyPrintIndent = " "
encodeDefaults = false
explicitNulls = false
}
}
/**
* Generates product-info.json file containing meta-information about product installation.
*/
internal fun generateMultiPlatformProductJson(relativePathToBin: String,
builtinModules: BuiltinModulesFileData?,
launch: List<ProductInfoLaunchData>,
context: BuildContext): String {
val appInfo = context.applicationInfo
val json = ProductInfoData(
name = appInfo.productName,
version = appInfo.fullVersion,
versionSuffix = appInfo.versionSuffix,
buildNumber = context.buildNumber,
productCode = appInfo.productCode,
dataDirectoryName = context.systemSelector,
svgIconPath = if (appInfo.svgRelativePath == null) null else "$relativePathToBin/${context.productProperties.baseFileName}.svg",
launch = launch,
customProperties = context.productProperties.generateCustomPropertiesForProductInfo(),
bundledPlugins = builtinModules?.bundledPlugins ?: emptyList(),
fileExtensions = builtinModules?.fileExtensions ?: emptyList(),
modules = builtinModules?.modules ?: emptyList(),
)
return jsonEncoder.encodeToString(serializer(), json)
}
/**
* Describes format of JSON file containing meta-information about a product installation. Must be consistent with 'product-info.schema.json' file.
*/
@Serializable
data class ProductInfoData(
val name: String,
val version: String,
val versionSuffix: String?,
val buildNumber: String,
val productCode: String,
val dataDirectoryName: String,
val svgIconPath: String?,
val launch: List<ProductInfoLaunchData> = emptyList(),
val customProperties: List<CustomProperty> = emptyList(),
val bundledPlugins: List<String>,
val modules: List<String>,
val fileExtensions: List<String>,
)
@Serializable
data class ProductInfoLaunchData(
val os: String,
val launcherPath: String,
val javaExecutablePath: String?,
val vmOptionsFilePath: String,
val startupWmClass: String? = null,
)
@Serializable
data class CustomProperty(
val key: String,
val value: String,
) | apache-2.0 | 6c6c2604d24ea28eb6835e55b89434b9 | 34.17284 | 147 | 0.73736 | 4.893471 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt | 2 | 18568 | // 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.j2k
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.inspections.*
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix
import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.mapToIndex
object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar {
private val myProcessings = ArrayList<J2kPostProcessing>()
override val processings: Collection<J2kPostProcessing>
get() = myProcessings
private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>()
override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!!
init {
myProcessings.add(RemoveExplicitTypeArgumentsProcessing())
myProcessings.add(RemoveRedundantOverrideVisibilityProcessing())
registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection())
myProcessings.add(FixObjectStringConcatenationProcessing())
myProcessings.add(ConvertToStringTemplateProcessing())
myProcessings.add(UsePropertyAccessSyntaxProcessing())
myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(RemoveRedundantSamAdaptersProcessing())
myProcessings.add(RemoveRedundantCastToNullableProcessing())
registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection())
myProcessings.add(UseExpressionBodyProcessing())
registerInspectionBasedProcessing(UnnecessaryVariableInspection())
registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection())
registerIntentionBasedProcessing(FoldIfToReturnIntention()) {
it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody()
}
registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) {
it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments(
it
) as KtReturnExpression).returnedExpression.isTrivialStatementBody()
}
registerInspectionBasedProcessing(IfThenToSafeAccessInspection())
registerInspectionBasedProcessing(IfThenToElvisInspection(true))
registerInspectionBasedProcessing(SimplifyNegatedBinaryExpressionInspection())
registerInspectionBasedProcessing(ReplaceGetOrSetInspection())
registerInspectionBasedProcessing(AddOperatorModifierInspection())
registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention())
registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention())
registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention())
registerIntentionBasedProcessing(DestructureIntention())
registerInspectionBasedProcessing(SimplifyAssertNotNullInspection())
registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention())
registerInspectionBasedProcessing(JavaMapForEachInspection())
registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection())
registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ ->
val expression = RemoveUselessCastFix.invoke(element)
val variable = expression.parent as? KtProperty
if (variable != null && expression == variable.initializer && variable.isLocal) {
val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull()
if (ref != null && ref.element is KtSimpleNameExpression) {
ref.element.replace(expression)
variable.delete()
}
}
}
registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic ->
val fix = RemoveModifierFix.createRemoveProjectionFactory(true).createActions(diagnostic).single() as RemoveModifierFix
fix.invoke()
}
registerDiagnosticBasedProcessingFactory(
Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION
) { element: KtSimpleNameExpression, _: Diagnostic ->
val property = element.mainReference.resolve() as? KtProperty
if (property == null) {
null
} else {
{
if (!property.isVar) {
property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword())
}
}
}
}
registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ ->
val exclExclExpr = element.parent as KtUnaryExpression
val baseExpression = exclExclExpr.baseExpression!!
val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) {
exclExclExpr.replace(baseExpression)
}
}
processingsToPriorityMap.putAll(myProcessings.mapToIndex())
}
private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing(
intention: TIntention,
noinline additionalChecker: (TElement) -> Boolean = { true }
) {
myProcessings.add(object : J2kPostProcessing {
// Intention can either need or not need write action
override val writeActionNeeded = intention.startInWriteAction()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (intention.applicabilityRange(tElement) == null) return null
if (!additionalChecker(tElement)) return null
return {
if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change
intention.applyTo(element, null)
}
}
}
})
}
private inline fun
<reified TElement : KtElement,
TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing(
inspection: TInspection,
acceptInformationLevel: Boolean = false
) {
myProcessings.add(object : J2kPostProcessing {
// Inspection can either need or not need write action
override val writeActionNeeded = inspection.startFixInWriteAction
private fun isApplicable(element: TElement): Boolean {
if (!inspection.isApplicable(element)) return false
return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION
}
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (!isApplicable(tElement)) return null
return {
if (isApplicable(tElement)) { // check availability of the inspection again because something could change
inspection.applyTo(tElement)
}
}
}
})
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fix: (TElement, Diagnostic) -> Unit
) {
registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic ->
{
fix(
element,
diagnostic
)
}
}
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)?
) {
myProcessings.add(object : J2kPostProcessing {
// ???
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null
return fixFactory(element as TElement, diagnostic)
}
})
}
private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo(
element,
approximateFlexible = true
)
) return null
return {
if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) {
element.delete()
}
}
}
}
private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val modifier = element.visibilityModifierType() ?: return null
return { element.setVisibility(modifier) }
}
}
private class ConvertToStringTemplateProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = ConvertToStringTemplateIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert(
element
)
) {
return { intention.applyTo(element, null) }
} else {
return null
}
}
}
private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = UsePropertyAccessSyntaxIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val propertyName = intention.detectPropertyNameToUse(element) ?: return null
return { intention.applyTo(element, propertyName, reformat = true) }
}
}
private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
if (expressions.isEmpty()) return null
return {
RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
.forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) }
}
}
}
private class UseExpressionBodyProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtPropertyAccessor) return null
val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false)
if (!inspection.isActiveFor(element)) return null
return {
if (inspection.isActiveFor(element)) {
inspection.simplify(element, false)
}
}
}
}
private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpressionWithTypeRHS) return null
val context = element.analyze()
val leftType = context.getType(element.left) ?: return null
val rightType = context.get(BindingContext.TYPE, element.right) ?: return null
if (!leftType.isMarkedNullable && rightType.isMarkedNullable) {
return {
val type = element.right?.typeElement as? KtNullableType
type?.replace(type.innerType!!)
}
}
return null
}
}
private class FixObjectStringConcatenationProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpression ||
element.operationToken != KtTokens.PLUS ||
diagnostics.forElement(element.operationReference).none {
it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER
|| it.factory == Errors.NONE_APPLICABLE
}
)
return null
val bindingContext = element.analyze()
val rightType = element.right?.getType(bindingContext) ?: return null
if (KotlinBuiltIns.isString(rightType)) {
return {
val factory = KtPsiFactory(element)
element.left!!.replace(factory.buildExpression {
appendFixedText("(")
appendExpression(element.left)
appendFixedText(").toString()")
})
}
}
return null
}
}
private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNINITIALIZED_VARIABLE }
) return null
val resolved = element.mainReference.resolve() ?: return null
if (resolved.isAncestor(element, strict = true)) {
if (resolved is KtVariableDeclaration && resolved.hasInitializer()) {
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) {
return { element.replaced(KtPsiFactory(element).createThisExpression()) }
}
}
}
return null
}
}
private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNRESOLVED_REFERENCE }
) return null
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null
if (variable.nameAsName == element.getReferencedNameAsName() &&
variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject
) {
return { element.replaced(KtPsiFactory(element).createThisExpression()) }
}
return null
}
}
} | apache-2.0 | 4d43f69d6d0465bc44a1a85a55262d34 | 45.538847 | 158 | 0.671586 | 6.374185 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddJvmNameAnnotationFix.kt | 1 | 3474 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.psi.*
class AddJvmNameAnnotationFix(element: KtElement, private val jvmName: String) : KotlinQuickFixAction<KtElement>(element) {
override fun getText(): String = if (element is KtAnnotationEntry) {
KotlinBundle.message("fix.change.jvm.name")
} else {
KotlinBundle.message("fix.add.annotation.text.self", JvmFileClassUtil.JVM_NAME.shortName())
}
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
when (element) {
is KtAnnotationEntry -> {
val argList = element.valueArgumentList
val newArgList = KtPsiFactory(element).createCallArguments("(\"$jvmName\")")
if (argList != null) {
argList.replace(newArgList)
} else {
element.addAfter(newArgList, element.lastChild)
}
}
is KtFunction ->
element.addAnnotation(JvmFileClassUtil.JVM_NAME, annotationInnerText = "\"$jvmName\"")
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val function = diagnostic.psiElement as? KtNamedFunction ?: return null
val functionName = function.name ?: return null
val containingDeclaration = function.parent ?: return null
val nameValidator = NewDeclarationNameValidator(
containingDeclaration,
function,
NewDeclarationNameValidator.Target.FUNCTIONS_AND_CLASSES
)
val receiverTypeElements = function.receiverTypeReference?.typeElements()?.joinToString("") { it.text } ?: ""
val jvmName = KotlinNameSuggester.suggestNameByName(functionName + receiverTypeElements, nameValidator)
return AddJvmNameAnnotationFix(function.findAnnotation(JvmFileClassUtil.JVM_NAME) ?: function, jvmName)
}
private fun KtTypeReference.typeElements(): List<KtTypeElement> {
val typeElements = mutableListOf<KtTypeElement>()
fun collect(typeReference: KtTypeReference?) {
val typeElement = typeReference?.typeElement ?: return
val typeArguments = typeElement.typeArgumentsAsTypes
if (typeArguments.isEmpty()) {
typeElements.add(typeElement)
} else {
typeArguments.forEach { collect(it) }
}
}
typeElement?.typeArgumentsAsTypes?.forEach { collect(it) }
return typeElements
}
}
}
| apache-2.0 | f08272ef6a08ffbb0cfb0d52b015cc75 | 45.945946 | 158 | 0.667818 | 5.523052 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/main/java/androidx/graphics/opengl/GLRenderer.kt | 3 | 32918 | /*
* 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.graphics.opengl
import android.graphics.SurfaceTexture
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLSurface
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.TextureView
import androidx.annotation.WorkerThread
import androidx.graphics.opengl.egl.EGLConfigAttributes
import androidx.graphics.opengl.egl.EGLManager
import androidx.graphics.opengl.egl.EGLSpec
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
/**
* Class responsible for coordination of requests to render into surfaces using OpenGL.
* This creates a backing thread to handle EGL dependencies and draw leveraging OpenGL across
* multiple [android.view.Surface] instances that can be attached and detached throughout
* the lifecycle of an application. Usage of this class is recommended to be done on the UI thread.
*
* @param eglSpecFactory Callback invoked to determine the EGL spec version to use
* for EGL management. This is invoked on the GL Thread
* @param eglConfigFactory Callback invoked to determine the appropriate EGLConfig used
* to create the EGL context. This is invoked on the GL Thread
*/
// GL is the industry standard for referencing OpenGL vs Gl (lowercase l)
@Suppress("AcronymName")
class GLRenderer(
eglSpecFactory: () -> EGLSpec = { EGLSpec.V14 },
eglConfigFactory: EGLManager.() -> EGLConfig = {
// 8 bit channels should always be supported
loadConfig(EGLConfigAttributes.RGBA_8888)
?: throw IllegalStateException("Unable to obtain config for 8 bit EGL " +
"configuration")
}
) {
/**
* Factory method to determine which [EGLSpec] the underlying [EGLManager] implementation uses
*/
private val mEglSpecFactory: () -> EGLSpec = eglSpecFactory
/**
* Factory method used to create the corresponding EGLConfig used to create the EGLRenderer used
* by [EGLManager]
*/
private val mEglConfigFactory: EGLManager.() -> EGLConfig = eglConfigFactory
/**
* GLThread used to manage EGL dependencies, create EGLSurfaces and draw content
*/
private var mGLThread: GLThread? = null
/**
* Collection of [RenderTarget] instances that are managed by the GLRenderer
*/
private val mRenderTargets = ArrayList<RenderTarget>()
/**
* Collection of callbacks to be invoked when the EGL dependencies are initialized
* or torn down
*/
private val mEglContextCallback = HashSet<EGLContextCallback>()
/**
* Removes the corresponding [RenderTarget] from management of the GLThread.
* This destroys the EGLSurface associated with this surface and subsequent requests
* to render into the surface with the provided token are ignored.
*
* If the [cancelPending] flag is set to true, any queued request
* to render that has not started yet is cancelled. However, if this is invoked in the
* middle of the frame being rendered, it will continue to process the current frame.
*
* Additionally if this flag is false, all pending requests to render will be processed
* before the [RenderTarget] is detached.
*
* Note the detach operation will only occur if the GLRenderer is started, that is if
* [isRunning] returns true. Otherwise this is a no-op. GLRenderer will automatically detach all
* [RenderTarget] instances as part of its teardown process.
*/
@JvmOverloads
fun detach(
target: RenderTarget,
cancelPending: Boolean,
@WorkerThread onDetachComplete: ((RenderTarget) -> Unit)? = null
) {
if (mRenderTargets.contains(target)) {
mGLThread?.detachSurface(target.token, cancelPending) {
// WorkerThread
target.release()
target.onDetach.invoke()
onDetachComplete?.invoke(target)
}
mRenderTargets.remove(target)
}
}
/**
* Determines if the GLThread has been started. That is [start] has been invoked
* on this GLRenderer instance without a corresponding call to [stop].
*/
fun isRunning(): Boolean = mGLThread != null
/**
* Starts the GLThread. After this method is called, consumers can attempt
* to attach [android.view.Surface] instances through [attach] as well as
* schedule content to be drawn through [requestRender]
*
* @param name Optional name to provide to the GLThread
*
* @throws IllegalStateException if EGLConfig with desired attributes cannot be created
*/
@JvmOverloads
fun start(
name: String = "GLThread",
) {
if (mGLThread == null) {
GLThread.log("starting thread...")
mGLThread = GLThread(
name,
mEglSpecFactory,
mEglConfigFactory
).apply {
start()
if (!mEglContextCallback.isEmpty()) {
// Add a copy of the current collection as new entries to mEglContextCallback
// could be mistakenly added multiple times.
this.addEGLCallbacks(ArrayList<EGLContextCallback>(mEglContextCallback))
}
}
}
}
/**
* Mark the corresponding surface session with the given token as dirty
* to schedule a call to [RenderCallback#onDrawFrame].
* If there is already a queued request to render into the provided surface with
* the specified token, this request is ignored.
*
* Note the render operation will only occur if the GLRenderer is started, that is if
* [isRunning] returns true. Otherwise this is a no-op.
*
* @param target RenderTarget to be re-rendered
* @param onRenderComplete Optional callback invoked on the backing thread after the frame has
* been rendered.
*/
@JvmOverloads
fun requestRender(target: RenderTarget, onRenderComplete: ((RenderTarget) -> Unit)? = null) {
val token = target.token
val callbackRunnable = if (onRenderComplete != null) {
Runnable {
onRenderComplete.invoke(target)
}
} else {
null
}
mGLThread?.requestRender(token, callbackRunnable)
}
/**
* Resize the corresponding surface associated with the RenderTarget to the specified
* width and height and re-render. This will destroy the EGLSurface created by
* [RenderCallback.onSurfaceCreated] and invoke it again with the updated dimensions.
* An optional callback is invoked on the backing thread after the resize operation
* is complete.
*
* Note the resize operation will only occur if the GLRenderer is started, that is if
* [isRunning] returns true. Otherwise this is a no-op.
*
* @param target RenderTarget to be resized
* @param width Updated width of the corresponding surface
* @param height Updated height of the corresponding surface
* @param onResizeComplete Optional callback invoked on the backing thread when the resize
* operation is complete
*/
@JvmOverloads
fun resize(
target: RenderTarget,
width: Int,
height: Int,
onResizeComplete: ((RenderTarget) -> Unit)? = null
) {
val token = target.token
val callbackRunnable = if (onResizeComplete != null) {
Runnable {
onResizeComplete.invoke(target)
}
} else {
null
}
mGLThread?.resizeSurface(token, width, height, callbackRunnable)
}
/**
* Stop the corresponding GL thread. This destroys all EGLSurfaces as well
* as any other EGL dependencies. All queued requests that have not been processed
* yet are cancelled.
*
* Note the stop operation will only occur if the GLRenderer was previously started, that is
* [isRunning] returns true. Otherwise this is a no-op.
*
* @param cancelPending If true all pending requests and cancelled and the backing thread is
* torn down immediately. If false, all pending requests are processed first before tearing
* down the backing thread. Subsequent requests made after this call are ignored.
* @param onStop Optional callback invoked on the backing thread after it is torn down.
*/
@JvmOverloads
fun stop(cancelPending: Boolean, onStop: ((GLRenderer) -> Unit)? = null) {
GLThread.log("stopping thread...")
// Make a copy of the render targets to call cleanup operations on to avoid potential
// concurrency issues.
// This method will clear the existing collection and we do not want to potentially tear
// down a target that was attached after a subsequent call to start if the tear down
// callback execution is delayed if previously pending requests have not been cancelled
// (i.e. cancelPending is false)
val renderTargets = ArrayList(mRenderTargets)
mGLThread?.tearDown(cancelPending) {
// No need to call target.detach as this callback is invoked after
// the dependencies are cleaned up
for (target in renderTargets) {
target.release()
target.onDetach.invoke()
}
onStop?.invoke(this@GLRenderer)
}
mGLThread = null
mRenderTargets.clear()
}
/**
* Add an [EGLContextCallback] to receive callbacks for construction and
* destruction of EGL dependencies.
*
* These callbacks are invoked on the backing thread.
*/
@Suppress("AcronymName")
fun registerEGLContextCallback(callback: EGLContextCallback) {
mEglContextCallback.add(callback)
mGLThread?.addEGLCallback(callback)
}
/**
* Remove [EGLContextCallback] to no longer receive callbacks for construction and
* destruction of EGL dependencies.
*
* These callbacks are invoked on the backing thread
*/
@Suppress("AcronymName")
fun unregisterEGLContextCallback(callback: EGLContextCallback) {
mEglContextCallback.remove(callback)
mGLThread?.removeEGLCallback(callback)
}
/**
* Callbacks invoked when the GL dependencies are created and destroyed.
* These are logical places to setup and tear down any dependencies that are used
* for drawing content within a frame (ex. compiling shaders)
*/
@Suppress("AcronymName")
interface EGLContextCallback {
/**
* Callback invoked on the backing thread after EGL dependencies are initialized.
* This is guaranteed to be invoked before any instance of
* [RenderCallback.onSurfaceCreated] is called.
* This will be invoked lazily before the first request to [GLRenderer.requestRender]
*/
// Suppressing CallbackMethodName due to b/238939160
@Suppress("AcronymName", "CallbackMethodName")
@WorkerThread
fun onEGLContextCreated(eglManager: EGLManager)
/**
* Callback invoked on the backing thread before EGL dependencies are about to be torn down.
* This is invoked after [GLRenderer.stop] is processed.
*/
// Suppressing CallbackMethodName due to b/238939160
@Suppress("AcronymName", "CallbackMethodName")
@WorkerThread
fun onEGLContextDestroyed(eglManager: EGLManager)
}
@JvmDefaultWithCompatibility
/**
* Interface used for creating an [EGLSurface] with a user defined configuration
* from the provided surface as well as a callback used to render content into the surface
* for a given frame
*/
interface RenderCallback {
/**
* Used to create a corresponding [EGLSurface] from the provided
* [android.view.Surface] instance. This enables consumers to configure
* the corresponding [EGLSurface] they wish to render into.
* The [EGLSurface] created here is guaranteed to be the current surface
* before [onDrawFrame] is called. That is, implementations of onDrawFrame
* do not need to call eglMakeCurrent on this [EGLSurface].
*
* This method is invoked on the GL thread.
*
* The default implementation will create a window surface with EGL_WIDTH and EGL_HEIGHT
* set to [width] and [height] respectively.
* Implementations can override this method to provide additional [EGLConfigAttributes]
* for this surface (ex. [EGL14.EGL_SINGLE_BUFFER].
*
* Implementations can return null to indicate the default surface should be used.
* This is helpful in situations where content is to be rendered within a frame buffer
* object instead of to an [EGLSurface]
*
* @param spec EGLSpec used to create the corresponding EGLSurface
* @param config EGLConfig used to create the corresponding EGLSurface
* @param surface [android.view.Surface] used to create an EGLSurface from
* @param width Desired width of the surface to create
* @param height Desired height of the surface to create
*/
@WorkerThread
fun onSurfaceCreated(
spec: EGLSpec,
config: EGLConfig,
surface: Surface,
width: Int,
height: Int
): EGLSurface? =
// Always default to creating an EGL window surface
// Despite having access to the width and height here, do not explicitly
// pass in EGLConfigAttributes specifying the EGL_WIDTH and EGL_HEIGHT parameters
// as those are not accepted parameters for eglCreateWindowSurface but they are
// for other EGL Surface factory methods such as eglCreatePBufferSurface
// See accepted parameters here:
// https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglCreateWindowSurface.xhtml
// and here
// https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglCreatePbufferSurface.xhtml
spec.eglCreateWindowSurface(config, surface, null)
/**
* Callback used to issue OpenGL drawing commands into the [EGLSurface]
* created in [onSurfaceCreated]. This [EGLSurface] is guaranteed to
* be current before this callback is invoked and [EGLManager.swapAndFlushBuffers]
* will be invoked afterwards. If additional scratch [EGLSurface]s are used
* here it is up to the implementation of this method to ensure that the proper
* surfaces are made current and the appropriate swap buffers call is made
*
* This method is invoked on the backing thread
*
* @param eglManager Handle to EGL dependencies
*/
@WorkerThread
fun onDrawFrame(eglManager: EGLManager)
}
/**
* Adds the [android.view.Surface] to be managed by the GLThread.
* A corresponding [EGLSurface] is created on the GLThread as well as a callback
* for rendering into the surface through [RenderCallback].
* Unlike the other [attach] methods that consume a [SurfaceView] or [TextureView],
* this method does not handle any lifecycle callbacks associated with the target surface.
* Therefore it is up to the consumer to properly setup/teardown resources associated with
* this surface.
*
* @param surface Target surface to be managed by the backing thread
* @param width Desired width of the [surface]
* @param height Desired height of the [surface]
* @param renderer Callbacks used to create a corresponding [EGLSurface] from the
* given surface as well as render content into the created [EGLSurface]
* @return [RenderTarget] used for subsequent requests to communicate
* with the provided Surface (ex. [requestRender] or [detach]).
*
* @throws IllegalStateException If this method was called when the GLThread has not started
* (i.e. start has not been called)
*/
fun attach(surface: Surface, width: Int, height: Int, renderer: RenderCallback): RenderTarget {
val thread = mGLThread
if (thread != null) {
val token = sToken.getAndIncrement()
thread.attachSurface(token, surface, width, height, renderer)
return RenderTarget(token, this).also { mRenderTargets.add(it) }
} else {
throw IllegalStateException("GLThread not started, did you forget to call start?")
}
}
/**
* Creates a new [RenderTarget] without a corresponding [android.view.Surface].
* This avoids creation of an [EGLSurface] which is useful in scenarios where only
* rendering to a frame buffer object is required.
*
* @param width Desired width of the [RenderTarget]
* @param height Desired height of the [RenderTarget]
* @param renderer Callbacks used to issue OpenGL commands to the [RenderTarget]
* @return [RenderTarget] used for subsequent requests to render through
* [RenderTarget.requestRender] or to remove itself from the [GLRenderer] through
* [RenderTarget.detach]
*
* @throws IllegalStateException If this method was called when the GLThread has not started
* (i.e. start has not been called)
*/
fun createRenderTarget(width: Int, height: Int, renderer: RenderCallback): RenderTarget {
val thread = mGLThread
if (thread != null) {
val token = sToken.getAndIncrement()
thread.attachSurface(
token,
null,
width,
height,
renderer
)
return RenderTarget(token, this).also { mRenderTargets.add(it) }
} else {
throw IllegalStateException("GLThread not started, did you forget to call start?")
}
}
/**
* Adds the [android.view.Surface] provided by the given [SurfaceView] to be managed by the
* backing thread.
*
* A corresponding [EGLSurface] is created on the GLThread as well as a callback
* for rendering into the surface through [RenderCallback].
*
* This method automatically configures a [SurfaceHolder.Callback] used to attach the
* [android.view.Surface] when the underlying [SurfaceHolder] that contains the surface is
* available. Similarly this surface will be detached from [GLRenderer] when the surface provided
* by the [SurfaceView] is destroyed (i.e. [SurfaceHolder.Callback.surfaceDestroyed] is called.
*
* If the [android.view.Surface] is already available by the time this method is invoked,
* it is attached synchronously.
*
* @param surfaceView SurfaceView that provides the surface to be rendered by the backing thread
* @param renderer callbacks used to create a corresponding [EGLSurface] from the
* given surface as well as render content into the created [EGLSurface]
* @return [RenderTarget] used for subsequent requests to communicate
* with the provided Surface (ex. [requestRender] or [detach]).
*
* @throws IllegalStateException If this method was called when the GLThread has not started
* (i.e. start has not been called)
*/
fun attach(surfaceView: SurfaceView, renderer: RenderCallback): RenderTarget {
val thread = mGLThread
if (thread != null) {
val token = sToken.getAndIncrement()
val holder = surfaceView.holder
val callback = object : SurfaceHolder.Callback2 {
var isAttached = false
/**
* Optional condition that maybe used if we are issuing a blocking call to render
* in [SurfaceHolder.Callback2.surfaceRedrawNeeded]
* In this case we need to signal the condition of either the request to render
* has completed, or if the RenderTarget has been detached and the pending
* render request is cancelled.
*/
@Volatile var renderLatch: CountDownLatch? = null
/**
* [CountDownLatch] used when issuing a blocking call to
* [SurfaceHolder.Callback.surfaceDestroyed]
* In this case we need to signal the condition of either the request to detach
* has completed in case the GLRenderer has been forcefully stopped via
* [GLRenderer.stop] with the cancel pending flag set to true.
*/
val detachLatch: CountDownLatch = CountDownLatch(1)
val renderTarget = RenderTarget(token, this@GLRenderer) @WorkerThread {
isAttached = false
// SurfaceHolder.add/remove callback is thread safe
holder.removeCallback(this)
// Countdown in case we have been detached while waiting for a render
// to be completed
renderLatch?.countDown()
detachLatch.countDown()
}
override fun surfaceRedrawNeeded(p0: SurfaceHolder) {
// If the [RenderTarget] has already been detached then skip rendering
if (detachLatch.count > 0) {
val latch = CountDownLatch(1).also { renderLatch = it }
// Request a render and block until the rendering is complete
// surfaceRedrawNeeded is invoked on older API levels and is replaced with
// surfaceRedrawNeededAsync for newer API levels which is non-blocking
renderTarget.requestRender @WorkerThread {
latch.countDown()
}
latch.await()
renderLatch = null
}
}
override fun surfaceRedrawNeededAsync(
holder: SurfaceHolder,
drawingFinished: Runnable
) {
renderTarget.requestRender {
drawingFinished.run()
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
// NO-OP wait until surfaceChanged which is guaranteed to be called and also
// provides the appropriate width height of the surface
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int
) {
if (!isAttached) {
thread.attachSurface(token, holder.surface, width, height, renderer)
isAttached = true
} else {
renderTarget.resize(width, height)
}
renderTarget.requestRender()
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
// Issue a request to detech the [RenderTarget]. Even if it was
// previously detached this request is a no-op and the corresponding
// [CountDownLatch] will signal when the [RenderTarget] detachment is complete
// or instantaneously if it was already detached
renderTarget.detach(true)
detachLatch.await()
}
}
holder.addCallback(callback)
if (holder.surface != null && holder.surface.isValid) {
thread.attachSurface(
token,
holder.surface,
surfaceView.width,
surfaceView.height,
renderer
)
}
mRenderTargets.add(callback.renderTarget)
return callback.renderTarget
} else {
throw IllegalStateException("GLThread not started, did you forget to call start?")
}
}
/**
* Adds the [android.view.Surface] provided by the given [TextureView] to be managed by the
* backing thread.
*
* A corresponding [EGLSurface] is created on the GLThread as well as a callback
* for rendering into the surface through [RenderCallback].
*
* This method automatically configures a [TextureView.SurfaceTextureListener] used to create a
* [android.view.Surface] when the underlying [SurfaceTexture] is available.
* Similarly this surface will be detached from [GLRenderer] if the underlying [SurfaceTexture]
* is destroyed (i.e. [TextureView.SurfaceTextureListener.onSurfaceTextureDestroyed] is called.
*
* If the [SurfaceTexture] is already available by the time this method is called, then it is
* attached synchronously.
*
* @param textureView TextureView that provides the surface to be rendered into on the GLThread
* @param renderer callbacks used to create a corresponding [EGLSurface] from the
* given surface as well as render content into the created [EGLSurface]
* @return [RenderTarget] used for subsequent requests to communicate
* with the provided Surface (ex. [requestRender] or [detach]).
*
* @throws IllegalStateException If this method was called when the GLThread has not started
* (i.e. start has not been called)
*/
fun attach(textureView: TextureView, renderer: RenderCallback): RenderTarget {
val thread = mGLThread
if (thread != null) {
val token = sToken.getAndIncrement()
val detachLatch = CountDownLatch(1)
val renderTarget = RenderTarget(token, this) @WorkerThread {
textureView.handler?.post {
textureView.surfaceTextureListener = null
}
detachLatch.countDown()
}
textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(
surfaceTexture: SurfaceTexture,
width: Int,
height: Int
) {
thread.attachSurface(token, Surface(surfaceTexture), width, height, renderer)
}
override fun onSurfaceTextureSizeChanged(
texture: SurfaceTexture,
width: Int,
height: Int
) {
renderTarget.resize(width, height)
renderTarget.requestRender()
}
override fun onSurfaceTextureDestroyed(p0: SurfaceTexture): Boolean {
// Issue a request to detech the [RenderTarget]. Even if it was
// previously detached this request is a no-op and the corresponding
// [CountDownLatch] will signal when the [RenderTarget] detachment is complete
// or instantaneously if it was already detached
renderTarget.detach(true)
detachLatch.await()
return true
}
override fun onSurfaceTextureUpdated(p0: SurfaceTexture) {
// NO-OP
}
}
if (textureView.isAvailable) {
thread.attachSurface(
token,
Surface(textureView.surfaceTexture),
textureView.width,
textureView.height,
renderer
)
}
mRenderTargets.add(renderTarget)
return renderTarget
} else {
throw IllegalStateException("GLThread not started, did you forget to call start?")
}
}
/**
* Handle to a [android.view.Surface] that is given to [GLRenderer] to handle
* rendering.
*/
class RenderTarget internal constructor(
internal val token: Int,
glManager: GLRenderer,
@WorkerThread internal val onDetach: () -> Unit = {}
) {
@Volatile
private var mManager: GLRenderer? = glManager
internal fun release() {
mManager = null
}
/**
* Request that this [RenderTarget] should have its contents redrawn.
* This consumes an optional callback that is invoked on the backing thread when
* the rendering is completed.
*
* Note the render operation will only occur if the RenderTarget is attached, that is
* [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that
* created this RenderTarget is stopped, this is a no-op.
*
* @param onRenderComplete Optional callback called on the backing thread when
* rendering is finished
*/
@JvmOverloads
fun requestRender(@WorkerThread onRenderComplete: ((RenderTarget) -> Unit)? = null) {
mManager?.requestRender(this@RenderTarget, onRenderComplete)
}
/**
* Determines if the current RenderTarget is attached to GLRenderer.
* This is true until [detach] has been called. If the RenderTarget is no longer
* in an attached state (i.e. this returns false). Subsequent calls to [requestRender]
* will be ignored.
*/
fun isAttached(): Boolean = mManager != null
/**
* Resize the RenderTarget to the specified width and height.
* This will destroy the EGLSurface created by [RenderCallback.onSurfaceCreated]
* and invoke it again with the updated dimensions.
* An optional callback is invoked on the backing thread after the resize operation
* is complete
*
* Note the resize operation will only occur if the RenderTarget is attached, that is
* [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that
* created this RenderTarget is stopped, this is a no-op.
*
* @param width New target width to resize the RenderTarget
* @param height New target height to resize the RenderTarget
* @param onResizeComplete Optional callback invoked after the resize is complete
*/
@JvmOverloads
fun resize(
width: Int,
height: Int,
@WorkerThread onResizeComplete: ((RenderTarget) -> Unit)? = null
) {
mManager?.resize(this, width, height, onResizeComplete)
}
/**
* Removes the corresponding [RenderTarget] from management of the GLThread.
* This destroys the EGLSurface associated with this surface and subsequent requests
* to render into the surface with the provided token are ignored.
*
* If the [cancelPending] flag is set to true, any queued request
* to render that has not started yet is cancelled. However, if this is invoked in the
* middle of the frame being rendered, it will continue to process the current frame.
*
* Additionally if this flag is false, all pending requests to render will be processed
* before the [RenderTarget] is detached.
*
* This is a convenience method around [GLRenderer.detach]
*
* Note the detach operation will only occur if the RenderTarget is attached, that is
* [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that
* created this RenderTarget is stopped, this is a no-op.
*/
@JvmOverloads
fun detach(cancelPending: Boolean, onDetachComplete: ((RenderTarget) -> Unit)? = null) {
mManager?.detach(this, cancelPending, onDetachComplete)
}
}
companion object {
/**
* Counter used to issue unique identifiers for surfaces that are managed by GLRenderer
*/
private val sToken = AtomicInteger()
}
}
| apache-2.0 | abc670906662cea9bfac13c3670a2d6d | 43.363881 | 101 | 0.631326 | 5.302513 | false | false | false | false |
androidx/androidx | navigation/navigation-dynamic-features-runtime/src/main/java/androidx/navigation/dynamicfeatures/DynamicInstallManager.kt | 3 | 7696 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.dynamicfeatures
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.annotation.RestrictTo
import androidx.lifecycle.MutableLiveData
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDestination
import androidx.navigation.Navigator
import androidx.navigation.dynamicfeatures.DynamicGraphNavigator.DynamicNavGraph
import androidx.navigation.get
import com.google.android.play.core.splitcompat.SplitCompat
import com.google.android.play.core.splitinstall.SplitInstallException
import com.google.android.play.core.splitinstall.SplitInstallHelper
import com.google.android.play.core.splitinstall.SplitInstallManager
import com.google.android.play.core.splitinstall.SplitInstallRequest
import com.google.android.play.core.splitinstall.SplitInstallSessionState
import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener
import com.google.android.play.core.splitinstall.model.SplitInstallErrorCode
import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus
/**
* Install manager for dynamic features.
*
* Enables installation of dynamic features for both installed and instant apps.
*/
public open class DynamicInstallManager(
private val context: Context,
private val splitInstallManager: SplitInstallManager
) {
internal companion object {
internal fun terminateLiveData(
status: MutableLiveData<SplitInstallSessionState>
) {
// Best effort leak prevention, will only work for active observers
check(!status.hasActiveObservers()) {
"This DynamicInstallMonitor will not " +
"emit any more status updates. You should remove all " +
"Observers after null has been emitted."
}
}
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun performInstall(
backStackEntry: NavBackStackEntry,
extras: DynamicExtras?,
moduleName: String
): NavDestination? {
if (extras?.installMonitor != null) {
requestInstall(moduleName, extras.installMonitor)
return null
} else {
val progressArgs = Bundle().apply {
putInt(Constants.DESTINATION_ID, backStackEntry.destination.id)
putBundle(Constants.DESTINATION_ARGS, backStackEntry.arguments)
}
val dynamicNavGraph = DynamicNavGraph.getOrThrow(backStackEntry.destination)
val navigator: Navigator<*> =
dynamicNavGraph.navigatorProvider[dynamicNavGraph.navigatorName]
if (navigator is DynamicGraphNavigator) {
navigator.navigateToProgressDestination(dynamicNavGraph, progressArgs)
return null
} else {
throw IllegalStateException(
"You must use a DynamicNavGraph to perform a module installation."
)
}
}
}
/**
* @param module The module to install.
* @return Whether the requested module needs installation.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun needsInstall(module: String): Boolean {
return !splitInstallManager.installedModules.contains(module)
}
private fun requestInstall(
module: String,
installMonitor: DynamicInstallMonitor
) {
check(!installMonitor.isUsed) {
// We don't want an installMonitor in an undefined state or used by another install
"You must pass in a fresh DynamicInstallMonitor " +
"in DynamicExtras every time you call navigate()."
}
val status = installMonitor.status as MutableLiveData<SplitInstallSessionState>
installMonitor.isInstallRequired = true
val request = SplitInstallRequest
.newBuilder()
.addModule(module)
.build()
splitInstallManager
.startInstall(request)
.addOnSuccessListener { sessionId ->
installMonitor.sessionId = sessionId
installMonitor.splitInstallManager = splitInstallManager
if (sessionId == 0) {
// The feature is already installed, emit synthetic INSTALLED state.
status.value = SplitInstallSessionState.create(
sessionId,
SplitInstallSessionStatus.INSTALLED,
SplitInstallErrorCode.NO_ERROR,
/* bytesDownloaded */ 0,
/* totalBytesToDownload */ 0,
listOf(module),
emptyList()
)
terminateLiveData(status)
} else {
val listener = SplitInstallListenerWrapper(
context, status,
installMonitor
)
splitInstallManager.registerListener(listener)
}
}
.addOnFailureListener { exception ->
Log.i(
"DynamicInstallManager",
"Error requesting install of $module: ${exception.message}"
)
installMonitor.exception = exception
status.value = SplitInstallSessionState.create(
/* sessionId */ 0,
SplitInstallSessionStatus.FAILED,
if (exception is SplitInstallException)
exception.errorCode
else
SplitInstallErrorCode.INTERNAL_ERROR,
/* bytesDownloaded */ 0,
/* totalBytesToDownload */ 0,
listOf(module),
emptyList()
)
terminateLiveData(status)
}
}
private class SplitInstallListenerWrapper(
private val context: Context,
private val status: MutableLiveData<SplitInstallSessionState>,
private val installMonitor: DynamicInstallMonitor
) : SplitInstallStateUpdatedListener {
override fun onStateUpdate(
splitInstallSessionState: SplitInstallSessionState
) {
if (splitInstallSessionState.sessionId() == installMonitor.sessionId) {
if (splitInstallSessionState.status() == SplitInstallSessionStatus.INSTALLED) {
SplitCompat.install(context)
// Enable immediate usage of dynamic feature modules in an instant app context.
SplitInstallHelper.updateAppInfo(context)
}
status.value = splitInstallSessionState
if (splitInstallSessionState.hasTerminalStatus()) {
installMonitor.splitInstallManager!!.unregisterListener(this)
terminateLiveData(status)
}
}
}
}
}
| apache-2.0 | 7a8ae2d0709f0374d861cc6d904a472b | 39.293194 | 99 | 0.626949 | 5.621622 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/staggeredgrid/LazyStaggeredGridState.kt | 3 | 17677 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.staggeredgrid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.lazy.layout.LazyAnimateScrollScope
import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider
import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState
import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState.PrefetchHandle
import androidx.compose.foundation.lazy.layout.animateScrollToItem
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.layout.Remeasurement
import androidx.compose.ui.layout.RemeasurementModifier
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import kotlin.math.abs
/**
* Creates a [LazyStaggeredGridState] that is remembered across composition.
*
* Calling this function with different parameters on recomposition WILL NOT recreate or change
* the state.
* Use [LazyStaggeredGridState.scrollToItem] or [LazyStaggeredGridState.animateScrollToItem] to
* adjust position instead.
*
* @param initialFirstVisibleItemIndex initial position for
* [LazyStaggeredGridState.firstVisibleItemIndex]
* @param initialFirstVisibleItemScrollOffset initial value for
* [LazyStaggeredGridState.firstVisibleItemScrollOffset]
* @return created and memoized [LazyStaggeredGridState] with given parameters.
*/
@ExperimentalFoundationApi
@Composable
fun rememberLazyStaggeredGridState(
initialFirstVisibleItemIndex: Int = 0,
initialFirstVisibleItemScrollOffset: Int = 0
): LazyStaggeredGridState =
rememberSaveable(saver = LazyStaggeredGridState.Saver) {
LazyStaggeredGridState(
initialFirstVisibleItemIndex,
initialFirstVisibleItemScrollOffset
)
}
/**
* Hoisted state object controlling [LazyVerticalStaggeredGrid] or [LazyHorizontalStaggeredGrid].
* In most cases, it should be created via [rememberLazyStaggeredGridState].
*/
@ExperimentalFoundationApi
class LazyStaggeredGridState private constructor(
initialFirstVisibleItems: IntArray,
initialFirstVisibleOffsets: IntArray,
) : ScrollableState {
/**
* @param initialFirstVisibleItemIndex initial value for [firstVisibleItemIndex]
* @param initialFirstVisibleItemOffset initial value for [firstVisibleItemScrollOffset]
*/
constructor(
initialFirstVisibleItemIndex: Int = 0,
initialFirstVisibleItemOffset: Int = 0
) : this(
intArrayOf(initialFirstVisibleItemIndex),
intArrayOf(initialFirstVisibleItemOffset)
)
/**
* Index of the first visible item across all staggered grid lanes.
*
* This property is observable and when use it in composable function it will be recomposed on
* each scroll, potentially causing performance issues.
*/
val firstVisibleItemIndex: Int
get() = scrollPosition.indices.minOfOrNull {
// index array can contain -1, indicating lane being empty (cell number > itemCount)
// if any of the lanes are empty, we always on 0th item index
if (it == -1) 0 else it
} ?: 0
/**
* Current offset of the item with [firstVisibleItemIndex] relative to the container start.
*
* This property is observable and when use it in composable function it will be recomposed on
* each scroll, potentially causing performance issues.
*/
val firstVisibleItemScrollOffset: Int
get() = scrollPosition.offsets.run {
if (isEmpty()) 0 else this[scrollPosition.indices.indexOfMinValue()]
}
/** holder for current scroll position **/
internal val scrollPosition = LazyStaggeredGridScrollPosition(
initialFirstVisibleItems,
initialFirstVisibleOffsets,
::fillNearestIndices
)
/**
* Layout information calculated during last layout pass, with information about currently
* visible items and container parameters.
*
* This property is observable and when use it in composable function it will be recomposed on
* each scroll, potentially causing performance issues.
*/
val layoutInfo: LazyStaggeredGridLayoutInfo get() = layoutInfoState.value
/** backing state for [layoutInfo] **/
private val layoutInfoState: MutableState<LazyStaggeredGridLayoutInfo> =
mutableStateOf(EmptyLazyStaggeredGridLayoutInfo)
/** storage for lane assignments for each item for consistent scrolling in both directions **/
internal val spans = LazyStaggeredGridSpans()
override var canScrollForward: Boolean by mutableStateOf(false)
private set
override var canScrollBackward: Boolean by mutableStateOf(false)
private set
/** implementation of [LazyAnimateScrollScope] scope required for [animateScrollToItem] **/
private val animateScrollScope = LazyStaggeredGridAnimateScrollScope(this)
private var remeasurement: Remeasurement? = null
internal val remeasurementModifier = object : RemeasurementModifier {
override fun onRemeasurementAvailable(remeasurement: Remeasurement) {
[email protected] = remeasurement
}
}
/**
* Only used for testing to disable prefetching when needed to test the main logic.
*/
/*@VisibleForTesting*/
internal var prefetchingEnabled: Boolean = true
/** prefetch state used for precomputing items in the direction of scroll **/
internal val prefetchState: LazyLayoutPrefetchState = LazyLayoutPrefetchState()
/** state controlling the scroll **/
private val scrollableState = ScrollableState { -onScroll(-it) }
/** scroll to be consumed during next/current layout pass **/
internal var scrollToBeConsumed = 0f
private set
/* @VisibleForTesting */
internal var measurePassCount = 0
/** states required for prefetching **/
internal var isVertical = false
internal var laneWidthsPrefixSum: IntArray = IntArray(0)
private var prefetchBaseIndex: Int = -1
private val currentItemPrefetchHandles = mutableMapOf<Int, PrefetchHandle>()
/** state required for implementing [animateScrollScope] **/
internal var density: Density = Density(1f, 1f)
internal val laneCount get() = laneWidthsPrefixSum.size
/**
* [InteractionSource] that will be used to dispatch drag events when this
* list is being dragged. If you want to know whether the fling (or animated scroll) is in
* progress, use [isScrollInProgress].
*/
val interactionSource get(): InteractionSource = mutableInteractionSource
/** backing field mutable field for [interactionSource] **/
internal val mutableInteractionSource = MutableInteractionSource()
/**
* Call this function to take control of scrolling and gain the ability to send scroll events
* via [ScrollScope.scrollBy]. All actions that change the logical scroll position must be
* performed within a [scroll] block (even if they don't call any other methods on this
* object) in order to guarantee that mutual exclusion is enforced.
*
* If [scroll] is called from elsewhere, this will be canceled.
*/
override suspend fun scroll(
scrollPriority: MutatePriority,
block: suspend ScrollScope.() -> Unit
) {
scrollableState.scroll(scrollPriority, block)
}
/**
* Whether this [scrollableState] is currently scrolling by gesture, fling or programmatically or
* not.
*/
override val isScrollInProgress: Boolean
get() = scrollableState.isScrollInProgress
/** Main scroll callback which adjusts scroll delta and remeasures layout **/
private fun onScroll(distance: Float): Float {
if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) {
return 0f
}
check(abs(scrollToBeConsumed) <= 0.5f) {
"entered drag with non-zero pending scroll: $scrollToBeConsumed"
}
scrollToBeConsumed += distance
// scrollToBeConsumed will be consumed synchronously during the forceRemeasure invocation
// inside measuring we do scrollToBeConsumed.roundToInt() so there will be no scroll if
// we have less than 0.5 pixels
if (abs(scrollToBeConsumed) > 0.5f) {
val preScrollToBeConsumed = scrollToBeConsumed
remeasurement?.forceRemeasure()
if (prefetchingEnabled) {
notifyPrefetch(preScrollToBeConsumed - scrollToBeConsumed)
}
}
// here scrollToBeConsumed is already consumed during the forceRemeasure invocation
if (abs(scrollToBeConsumed) <= 0.5f) {
// We consumed all of it - we'll hold onto the fractional scroll for later, so report
// that we consumed the whole thing
return distance
} else {
val scrollConsumed = distance - scrollToBeConsumed
// We did not consume all of it - return the rest to be consumed elsewhere (e.g.,
// nested scrolling)
scrollToBeConsumed = 0f // We're not consuming the rest, give it back
return scrollConsumed
}
}
/**
* Instantly brings the item at [index] to the top of layout viewport, offset by [scrollOffset]
* pixels.
*
* @param index the index to which to scroll. MUST NOT be negative.
* @param scrollOffset the offset where the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a reversed list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
suspend fun scrollToItem(
/* @IntRange(from = 0) */
index: Int,
scrollOffset: Int = 0
) {
scroll {
snapToItemInternal(index, scrollOffset)
}
}
/**
* Animate (smooth scroll) to the given item.
*
* @param index the index to which to scroll. MUST NOT be negative.
* @param scrollOffset the offset that the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
suspend fun animateScrollToItem(
/* @IntRange(from = 0) */
index: Int,
scrollOffset: Int = 0
) {
animateScrollScope.animateScrollToItem(index, scrollOffset)
}
internal fun ScrollScope.snapToItemInternal(index: Int, scrollOffset: Int) {
val visibleItem = layoutInfo.findVisibleItem(index)
if (visibleItem != null) {
val currentOffset = if (isVertical) visibleItem.offset.y else visibleItem.offset.x
val delta = currentOffset + scrollOffset
scrollBy(delta.toFloat())
} else {
scrollPosition.requestPosition(index, scrollOffset)
remeasurement?.forceRemeasure()
}
}
/**
* Maintain scroll position for item based on custom key if its index has changed.
*/
internal fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyLayoutItemProvider) {
scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider)
}
override fun dispatchRawDelta(delta: Float): Float =
scrollableState.dispatchRawDelta(delta)
/** Start prefetch of the items based on provided delta **/
private fun notifyPrefetch(delta: Float) {
val info = layoutInfoState.value
if (info.visibleItemsInfo.isNotEmpty()) {
val scrollingForward = delta < 0
val prefetchIndex = if (scrollingForward) {
info.visibleItemsInfo.last().index
} else {
info.visibleItemsInfo.first().index
}
if (prefetchIndex == prefetchBaseIndex) {
// Already prefetched based on this index
return
}
prefetchBaseIndex = prefetchIndex
val prefetchHandlesUsed = mutableSetOf<Int>()
var targetIndex = prefetchIndex
for (lane in laneWidthsPrefixSum.indices) {
val previousIndex = targetIndex
// find the next item for each line and prefetch if it is valid
targetIndex = if (scrollingForward) {
spans.findNextItemIndex(previousIndex, lane)
} else {
spans.findPreviousItemIndex(previousIndex, lane)
}
if (
targetIndex !in (0 until info.totalItemsCount) ||
previousIndex == targetIndex
) {
return
}
prefetchHandlesUsed += targetIndex
if (targetIndex in currentItemPrefetchHandles) {
continue
}
val crossAxisSize = laneWidthsPrefixSum[lane] -
if (lane == 0) 0 else laneWidthsPrefixSum[lane - 1]
val constraints = if (isVertical) {
Constraints.fixedWidth(crossAxisSize)
} else {
Constraints.fixedHeight(crossAxisSize)
}
currentItemPrefetchHandles[targetIndex] = prefetchState.schedulePrefetch(
index = targetIndex,
constraints = constraints
)
}
clearLeftoverPrefetchHandles(prefetchHandlesUsed)
}
}
private fun clearLeftoverPrefetchHandles(prefetchHandlesUsed: Set<Int>) {
val iterator = currentItemPrefetchHandles.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (entry.key !in prefetchHandlesUsed) {
entry.value.cancel()
iterator.remove()
}
}
}
private fun cancelPrefetchIfVisibleItemsChanged(info: LazyStaggeredGridLayoutInfo) {
val items = info.visibleItemsInfo
if (prefetchBaseIndex != -1 && items.isNotEmpty()) {
if (prefetchBaseIndex !in items.first().index..items.last().index) {
prefetchBaseIndex = -1
currentItemPrefetchHandles.values.forEach { it.cancel() }
currentItemPrefetchHandles.clear()
}
}
}
/** updates state after measure pass **/
internal fun applyMeasureResult(result: LazyStaggeredGridMeasureResult) {
scrollToBeConsumed -= result.consumedScroll
canScrollBackward = result.canScrollBackward
canScrollForward = result.canScrollForward
layoutInfoState.value = result
cancelPrefetchIfVisibleItemsChanged(result)
scrollPosition.updateFromMeasureResult(result)
measurePassCount++
}
private fun fillNearestIndices(itemIndex: Int, laneCount: Int): IntArray {
// reposition spans if needed to ensure valid indices
spans.ensureValidIndex(itemIndex + laneCount)
val span = spans.getSpan(itemIndex)
val targetLaneIndex =
if (span == LazyStaggeredGridSpans.Unset) 0 else minOf(span, laneCount)
val indices = IntArray(laneCount)
// fill lanes before starting index
var currentItemIndex = itemIndex
for (lane in (targetLaneIndex - 1) downTo 0) {
indices[lane] = spans.findPreviousItemIndex(currentItemIndex, lane)
if (indices[lane] == -1) {
indices.fill(-1, toIndex = lane)
break
}
currentItemIndex = indices[lane]
}
indices[targetLaneIndex] = itemIndex
// fill lanes after starting index
currentItemIndex = itemIndex
for (lane in (targetLaneIndex + 1) until laneCount) {
indices[lane] = spans.findNextItemIndex(currentItemIndex, lane)
currentItemIndex = indices[lane]
}
return indices
}
companion object {
/**
* The default implementation of [Saver] for [LazyStaggeredGridState]
*/
val Saver = listSaver<LazyStaggeredGridState, IntArray>(
save = { state ->
listOf(
state.scrollPosition.indices,
state.scrollPosition.offsets
)
},
restore = {
LazyStaggeredGridState(it[0], it[1])
}
)
}
} | apache-2.0 | 1dc04e51663b36e959fd4f445217ee92 | 38.371938 | 101 | 0.672512 | 5.203709 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt | 1 | 19124 | // 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.j2k
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.RemoveUnnecessaryParenthesesIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsights.impl.base.KotlinInspectionFacade
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.inspections.*
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase
import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix
import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.mapToIndex
object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar {
private val myProcessings = ArrayList<J2kPostProcessing>()
override val processings: Collection<J2kPostProcessing>
get() = myProcessings
private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>()
override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!!
init {
myProcessings.add(RemoveExplicitTypeArgumentsProcessing())
myProcessings.add(RemoveRedundantOverrideVisibilityProcessing())
registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection())
myProcessings.add(FixObjectStringConcatenationProcessing())
myProcessings.add(ConvertToStringTemplateProcessing())
myProcessings.add(UsePropertyAccessSyntaxProcessing())
myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(RemoveRedundantSamAdaptersProcessing())
myProcessings.add(RemoveRedundantCastToNullableProcessing())
registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection())
myProcessings.add(UseExpressionBodyProcessing())
registerInspectionBasedProcessing(UnnecessaryVariableInspection())
registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection())
registerIntentionBasedProcessing(FoldIfToReturnIntention()) {
it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody()
}
registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) {
it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments(
it
) as KtReturnExpression).returnedExpression.isTrivialStatementBody()
}
registerInspectionBasedProcessing(IfThenToSafeAccessInspection())
registerInspectionBasedProcessing(IfThenToElvisInspection(true))
registerInspectionBasedProcessing(KotlinInspectionFacade.instance.simplifyNegatedBinaryExpression)
registerInspectionBasedProcessing(ReplaceGetOrSetInspection())
registerInspectionBasedProcessing(AddOperatorModifierInspection())
registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention())
registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention())
registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention())
registerIntentionBasedProcessing(DestructureIntention())
registerInspectionBasedProcessing(SimplifyAssertNotNullInspection())
registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention())
registerInspectionBasedProcessing(JavaMapForEachInspection())
registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection())
registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ ->
val expression = RemoveUselessCastFix.invoke(element)
val variable = expression.parent as? KtProperty
if (variable != null && expression == variable.initializer && variable.isLocal) {
val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull()
if (ref != null && ref.element is KtSimpleNameExpression) {
ref.element.replace(expression)
variable.delete()
}
}
}
registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic ->
val fix = RemoveModifierFixBase.createRemoveProjectionFactory(true)
.asKotlinIntentionActionsFactory()
.createActions(diagnostic).single() as RemoveModifierFixBase
fix.invoke()
}
registerDiagnosticBasedProcessingFactory(
Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION
) { element: KtSimpleNameExpression, _: Diagnostic ->
val property = element.mainReference.resolve() as? KtProperty
if (property == null) {
null
} else {
{
if (!property.isVar) {
property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword())
}
}
}
}
registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ ->
val exclExclExpr = element.parent as KtUnaryExpression
val baseExpression = exclExclExpr.baseExpression!!
val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) {
exclExclExpr.replace(baseExpression)
}
}
processingsToPriorityMap.putAll(myProcessings.mapToIndex())
}
private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing(
intention: TIntention,
noinline additionalChecker: (TElement) -> Boolean = { true }
) {
myProcessings.add(object : J2kPostProcessing {
// Intention can either need or not need write action
override val writeActionNeeded = intention.startInWriteAction()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (intention.applicabilityRange(tElement) == null) return null
if (!additionalChecker(tElement)) return null
return {
if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change
intention.applyTo(element, null)
}
}
}
})
}
private inline fun
<reified TElement : KtElement,
TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing(
inspection: TInspection,
acceptInformationLevel: Boolean = false
) {
myProcessings.add(object : J2kPostProcessing {
// Inspection can either need or not need write action
override val writeActionNeeded = inspection.startFixInWriteAction
private fun isApplicable(element: TElement): Boolean {
if (!inspection.isApplicable(element)) return false
return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION
}
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (!isApplicable(tElement)) return null
return {
if (isApplicable(tElement)) { // check availability of the inspection again because something could change
inspection.applyTo(tElement)
}
}
}
})
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fix: (TElement, Diagnostic) -> Unit
) {
registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic ->
{
fix(
element,
diagnostic
)
}
}
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)?
) {
myProcessings.add(object : J2kPostProcessing {
// ???
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null
return fixFactory(element as TElement, diagnostic)
}
})
}
private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo(
element,
approximateFlexible = true
)
) return null
return {
if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) {
element.delete()
}
}
}
}
private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val modifier = element.visibilityModifierType() ?: return null
return { element.setVisibility(modifier) }
}
}
private class ConvertToStringTemplateProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = ConvertToStringTemplateIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert(
element
)
) {
return { intention.applyTo(element, null) }
} else {
return null
}
}
}
private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = UsePropertyAccessSyntaxIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val propertyName = intention.detectPropertyNameToUse(element) ?: return null
return { intention.applyTo(element, propertyName, reformat = true) }
}
}
private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
if (expressions.isEmpty()) return null
return {
RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
.forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) }
}
}
}
private class UseExpressionBodyProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtPropertyAccessor) return null
val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false)
if (!inspection.isActiveFor(element)) return null
return {
if (inspection.isActiveFor(element)) {
inspection.simplify(element, false)
}
}
}
}
private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpressionWithTypeRHS) return null
val context = element.analyze()
val leftType = context.getType(element.left) ?: return null
val rightType = context.get(BindingContext.TYPE, element.right) ?: return null
if (!leftType.isMarkedNullable && rightType.isMarkedNullable) {
return {
val type = element.right?.typeElement as? KtNullableType
type?.replace(type.innerType!!)
}
}
return null
}
}
private class FixObjectStringConcatenationProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpression ||
element.operationToken != KtTokens.PLUS ||
diagnostics.forElement(element.operationReference).none {
it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER
|| it.factory == Errors.NONE_APPLICABLE
}
)
return null
val bindingContext = element.analyze()
val rightType = element.right?.getType(bindingContext) ?: return null
if (KotlinBuiltIns.isString(rightType)) {
return {
val factory = KtPsiFactory(element)
element.left!!.replace(factory.buildExpression {
appendFixedText("(")
appendExpression(element.left)
appendFixedText(").toString()")
})
}
}
return null
}
}
private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNINITIALIZED_VARIABLE }
) return null
val resolved = element.mainReference.resolve() ?: return null
if (resolved.isAncestor(element, strict = true)) {
if (resolved is KtVariableDeclaration && resolved.hasInitializer()) {
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) {
return { element.replaced(KtPsiFactory(element).createThisExpression()) }
}
}
}
return null
}
}
private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNRESOLVED_REFERENCE }
) return null
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null
if (variable.nameAsName == element.getReferencedNameAsName() &&
variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject
) {
return { element.replaced(KtPsiFactory(element).createThisExpression()) }
}
return null
}
}
} | apache-2.0 | eb12a927655fe1a05d2b73e30127190d | 46.105911 | 158 | 0.676794 | 6.33245 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerState.kt | 5 | 4759 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.fileEditor.impl.EditorsSplitters
import com.intellij.openapi.observable.properties.AtomicProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
interface ToolWindowManagerState : PersistentStateComponent<Element> {
var layout: DesktopLayout
val noStateLoaded: Boolean
val oldLayout: DesktopLayout?
var layoutToRestoreLater: DesktopLayout?
val recentToolWindows: LinkedList<String>
val scheduledLayout: AtomicProperty<DesktopLayout?>
val isEditorComponentActive: Boolean
var frame: ProjectFrameHelper?
}
private const val EDITOR_ELEMENT = "editor"
private const val ACTIVE_ATTR_VALUE = "active"
private const val LAYOUT_TO_RESTORE = "layout-to-restore"
private const val RECENT_TW_TAG = "recentWindows"
@ApiStatus.Internal
@State(name = "ToolWindowManager", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class ToolWindowManagerStateImpl(private val project: Project) : ToolWindowManagerState {
private val isNewUi = ExperimentalUI.isNewUI()
override var layout = DesktopLayout()
override var noStateLoaded = false
private set
override var oldLayout: DesktopLayout? = null
private set
override var layoutToRestoreLater: DesktopLayout? = null
override val recentToolWindows = LinkedList<String>()
override val scheduledLayout = AtomicProperty<DesktopLayout?>(null)
private val focusManager: IdeFocusManager
get() = IdeFocusManager.getInstance(project)!!
override val isEditorComponentActive: Boolean
get() {
ApplicationManager.getApplication().assertIsDispatchThread()
return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null
}
override var frame: ProjectFrameHelper? = null
override fun getState(): Element? {
if (frame == null) {
return null
}
val element = Element("state")
if (isEditorComponentActive) {
element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true"))
}
// save layout of tool windows
writeLayout(layout, element, isV2 = isNewUi)
oldLayout?.let {
writeLayout(it, element, isV2 = !isNewUi)
}
layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let {
element.addContent(it)
}
if (recentToolWindows.isNotEmpty()) {
val recentState = Element(RECENT_TW_TAG)
recentToolWindows.forEach {
recentState.addContent(Element("value").addContent(it))
}
element.addContent(recentState)
}
return element
}
override fun loadState(state: Element) {
var layoutIsScheduled = false
for (element in state.children) {
if (JDOMUtil.isEmpty(element)) {
// make sure that layoutIsScheduled is not set if empty layout for some reason is provided
continue
}
when (element.name) {
DesktopLayout.TAG -> {
val layout = DesktopLayout()
layout.readExternal(element, isNewUi = false)
if (isNewUi) {
oldLayout = layout
}
else {
scheduledLayout.set(layout)
layoutIsScheduled = true
}
}
"layoutV2" -> {
val layout = DesktopLayout()
layout.readExternal(element, isNewUi = true)
if (isNewUi) {
scheduledLayout.set(layout)
layoutIsScheduled = true
}
else {
oldLayout = layout
}
}
LAYOUT_TO_RESTORE -> {
layoutToRestoreLater = DesktopLayout().also { it.readExternal(element, isNewUi) }
}
RECENT_TW_TAG -> {
recentToolWindows.clear()
element.content.forEach {
recentToolWindows.add(it.value)
}
}
}
}
if (!layoutIsScheduled) {
noStateLoaded()
}
}
override fun noStateLoaded() {
noStateLoaded = true
}
private fun writeLayout(layout: DesktopLayout, parent: Element, isV2: Boolean) {
parent.addContent(layout.writeExternal(if (isV2) "layoutV2" else DesktopLayout.TAG) ?: return)
}
} | apache-2.0 | a366893692a1e949163389d13f9a9a01 | 31.827586 | 120 | 0.702669 | 4.602515 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/ControlFlowUtils.kt | 2 | 1987 | // 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.codeinsight.utils
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
/**
* Consider a property initialization `val f: (Int) -> Unit = { println(it) }`. The type annotation `(Int) -> Unit` in this case is required
* in order for the code to type check because otherwise the compiler cannot infer the type of `it`.
*/
tailrec fun KtCallableDeclaration.isExplicitTypeReferenceNeededForTypeInference(typeRef: KtTypeReference? = typeReference): Boolean {
if (this !is KtDeclarationWithInitializer) return false
val initializer = initializer
if (initializer == null || typeRef == null) return false
if (initializer !is KtLambdaExpression && initializer !is KtNamedFunction) return false
val typeElement = typeRef.typeElement ?: return false
if (typeRef.hasModifier(KtTokens.SUSPEND_KEYWORD)) return true
return when (typeElement) {
is KtFunctionType -> {
if (typeElement.receiver != null) return true
if (typeElement.returnTypeReference?.typeElement?.typeArgumentsAsTypes?.isNotEmpty() == true) return true
if (typeElement.parameters.isEmpty()) return false
val valueParameters = when (initializer) {
is KtLambdaExpression -> initializer.valueParameters
is KtNamedFunction -> initializer.valueParameters
else -> emptyList()
}
valueParameters.isEmpty() || valueParameters.any { it.typeReference == null }
}
is KtUserType -> {
val typeAlias = typeElement.referenceExpression?.mainReference?.resolve() as? KtTypeAlias ?: return false
return isExplicitTypeReferenceNeededForTypeInference(typeAlias.getTypeReference())
}
else -> false
}
} | apache-2.0 | ca50c4c74c17a8f97ae7d31f3b99af2c | 52.72973 | 140 | 0.703573 | 5.414169 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/RP_Debug_PageBecameStale.kt | 1 | 2380 | package alraune
import alraune.operations.*
import pieces100.*
import vgrechka.*
import java.io.File
class RP_Debug_PageBecameStale : RemoteProcedureBase<RP_Debug_PageBecameStale.Params>(RP_Debug_PageBecameStale.Params::class) {
class Params {
var initialContent by notNullOnce<String>()
var currentContent by notNullOnce<String>()
}
override fun dance() {
checkIsLocalDebug_elseBitch()
rctx0.al.suspiciouslyLargeXStreamedServantsAllowed = true
clog("--- initialContent = ${args.initialContent.substring(0, 50)}")
clog("--- currentContent = ${args.currentContent.substring(0, 50)}")
// 9d5550db-2fdb-4c90-a04c-67937b9b6c8d
val button = button().id(nextJsIdent()).add("Staleness diff")
btfEval("""
${'$'}(document.body).append(${jsStringLiteral(button.render())})
${jsOnDomidClick_prevent(button.attrs.id, jsCallBackendServantHandle(freakingServant(::serveStalenessDiffButtonClick)))}
""")
}
fun serveStalenessDiffButtonClick() {
fun fart(content: String): String {
val file = AlDebug.tempFile(uuid())
stripIgnoredStuffForPageSha1ing(content) pipe TextPile::prettyPrintHtml pipe {file.writeText(it)}
return file.path
}
btfEval("console.log('So, you are now stale, little motherfucker?')")
runLocalMergeTool_noBlock(fart(args.initialContent), fart(args.currentContent))
}
object Test1 {
@JvmStatic fun main(args: Array<String>) {
if (isWindowsOS())
runLocalMergeTool_noBlock(
"C:\\Program Files (x86)\\WinMerge\\Contributors.txt",
"C:\\Program Files (x86)\\WinMerge\\Files.txt")
else
runLocalMergeTool_noBlock(
"/home/into/pro/febig/fe-private/alraune-private/src-for-alraune/alraune/operations/AlCtl_BackShitUp.kt",
"/home/into/pro/febig/fe-private/alraune-private/src-for-alraune/alraune/operations/AlCtl_BackShitUp_Obsolete.kt")
}
}
object Test2 {
@JvmStatic fun main(args: Array<String>) {
val untidy = File("c:\\tmp\\alraune\\cd84aa22-37c1-4b38-8e5a-20a9d0946677").readText()
val tidy = TextPile.prettyPrintHtml(untidy)
clog(tidy)
}
}
}
| apache-2.0 | 98d56c9d8c6cb2e0cfaf86d183b81936 | 30.733333 | 134 | 0.631513 | 4.006734 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinSmartStepTargetFilterer.kt | 4 | 4131 | // 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.debugger.stepping.smartStepInto
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.trimIfMangledInBytecode
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import java.util.*
class KotlinSmartStepTargetFilterer(
private val targets: List<KotlinMethodSmartStepTarget>,
private val debugProcess: DebugProcessImpl
) {
private val functionCounter = mutableMapOf<String, Int>()
private val targetWasVisited = BooleanArray(targets.size) { false }
fun visitInlineFunction(function: KtNamedFunction) {
val descriptor = function.descriptor ?: return
val label = KotlinMethodSmartStepTarget.calcLabel(descriptor)
val currentCount = functionCounter.increment(label) - 1
val matchedSteppingTargetIndex = targets.indexOfFirst {
it.getDeclaration() === function && it.ordinal == currentCount
}
if (matchedSteppingTargetIndex < 0) return
targetWasVisited[matchedSteppingTargetIndex] = true
}
fun visitOrdinaryFunction(owner: String, name: String, signature: String) {
val currentCount = functionCounter.increment("$owner.$name$signature") - 1
for ((i, target) in targets.withIndex()) {
if (target.shouldBeVisited(owner, name, signature, currentCount)) {
targetWasVisited[i] = true
break
}
}
}
private fun KotlinMethodSmartStepTarget.shouldBeVisited(owner: String, name: String, signature: String, currentCount: Int): Boolean {
val actualName = name.trimIfMangledInBytecode(methodInfo.isNameMangledInBytecode)
if (methodInfo.isInlineClassMember) {
return matches(
owner,
actualName,
// Inline class constructor argument is injected as the first
// argument in inline class' functions. This doesn't correspond
// with the PSI, so we delete the first argument from the signature
signature.getSignatureWithoutFirstArgument(),
currentCount
)
}
return matches(owner, actualName, signature, currentCount)
}
private fun KotlinMethodSmartStepTarget.matches(owner: String, name: String, signature: String, currentCount: Int): Boolean {
if (methodInfo.name == name && ordinal == currentCount) {
val lightClassMethod = getDeclaration()?.getLightClassMethod() ?: return false
return lightClassMethod.matches(owner, name, signature, debugProcess)
}
return false
}
fun getUnvisitedTargets(): List<KotlinMethodSmartStepTarget> =
targets.filterIndexed { i, _ ->
!targetWasVisited[i]
}
fun reset() {
Arrays.fill(targetWasVisited, false)
functionCounter.clear()
}
}
private fun String.getSignatureWithoutFirstArgument() =
removeRange(indexOf('(') + 1..indexOf(';'))
private fun KtDeclaration.getLightClassMethod(): PsiMethod? =
when (this) {
is KtNamedFunction -> LightClassUtil.getLightClassMethod(this)
is KtPropertyAccessor -> LightClassUtil.getLightClassPropertyMethods(property).getter
else -> null
}
private fun PsiMethod.matches(className: String, methodName: String, signature: String, debugProcess: DebugProcessImpl): Boolean =
DebuggerUtilsEx.methodMatches(
this,
className.replace("/", "."),
methodName,
signature,
debugProcess
)
private fun MutableMap<String, Int>.increment(key: String): Int {
val newValue = (get(key) ?: 0) + 1
put(key, newValue)
return newValue
}
| apache-2.0 | 9a00a29325dc9c7673a030fd8195dd6d | 39.90099 | 137 | 0.691842 | 5.056304 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ShowNotificationCommitResultHandler.kt | 5 | 3957 | // 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.vcs.commit
import com.intellij.notification.NotificationType
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.util.text.StringUtil.isEmpty
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_CANCELED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FAILED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED_WITH_WARNINGS
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.vcs.commit.AbstractCommitter.Companion.collectErrors
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
private fun hasOnlyWarnings(exceptions: List<VcsException>) = exceptions.all { it.isWarning }
class ShowNotificationCommitResultHandler(private val committer: AbstractCommitter) : CommitResultHandler {
private val notifier = VcsNotifier.getInstance(committer.project)
override fun onSuccess(commitMessage: String) = reportResult()
override fun onCancel() {
notifier.notifyMinorWarning(COMMIT_CANCELED, "", message("vcs.commit.canceled"))
}
override fun onFailure(errors: List<VcsException>) = reportResult()
private fun reportResult() {
val message = getCommitSummary()
val allExceptions = committer.exceptions
if (allExceptions.isEmpty()) {
notifier.notifySuccess(COMMIT_FINISHED, "", message)
return
}
val errors = collectErrors(allExceptions)
val errorsSize = errors.size
val warningsSize = allExceptions.size - errorsSize
val notificationActions = allExceptions.filterIsInstance<CommitExceptionWithActions>().flatMap { it.actions }
val title: @NlsContexts.NotificationTitle String
val displayId: @NonNls String
val notificationType: NotificationType
if (errorsSize > 0) {
displayId = COMMIT_FAILED
title = message("message.text.commit.failed.with.error", errorsSize)
notificationType = NotificationType.ERROR
}
else {
displayId = COMMIT_FINISHED_WITH_WARNINGS
title = message("message.text.commit.finished.with.warning", warningsSize)
notificationType = NotificationType.WARNING
}
val notification = VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.createNotification(title, message, notificationType)
notification.setDisplayId(displayId)
notificationActions.forEach { notification.addAction(it) }
VcsNotifier.addShowDetailsAction(committer.project, notification)
notification.notify(committer.project)
}
@NlsContexts.NotificationContent
private fun getCommitSummary() = HtmlBuilder().apply {
append(getFileSummaryReport())
val commitMessage = committer.commitMessage
if (!isEmpty(commitMessage)) {
append(": ").append(commitMessage) // NON-NLS
}
val feedback = committer.feedback
if (feedback.isNotEmpty()) {
br()
appendWithSeparators(HtmlChunk.br(), feedback.map(HtmlChunk::text))
}
val exceptions = committer.exceptions
if (!hasOnlyWarnings(exceptions)) {
br()
appendWithSeparators(HtmlChunk.br(), exceptions.map { HtmlChunk.text(it.message) })
}
}.toString()
private fun getFileSummaryReport(): @Nls String {
val failed = committer.failedToCommitChanges.size
val committed = committer.changes.size - failed
if (failed > 0) {
return message("vcs.commit.files.committed.and.files.failed.to.commit", committed, failed)
}
return message("vcs.commit.files.committed", committed)
}
} | apache-2.0 | 32c30eb732e06eaa280e2d06bb6cf5d1 | 40.663158 | 140 | 0.767248 | 4.558756 | false | false | false | false |
chesslave/chesslave | backend/src/main/java/io/chesslave/eyes/MoveRecogniserByPositionDiff.kt | 2 | 1291 | package io.chesslave.eyes
import io.chesslave.app.log
import io.chesslave.model.Move
import io.chesslave.model.Position
import io.chesslave.model.moves
class MoveRecogniserByPositionDiff {
/**
* Detects the move by analyzing the differences between the two positions.
*
* @return the detected move or null if none move was done
* @throws Exception if the detection fails
*/
fun detect(previous: Position, current: Position): Move? {
if (previous == current) {
return null
}
val from = previous.toSet().diff(current.toSet())
val to = current.toSet().diff(previous.toSet())
log.info("changed squares: from=$from, to=$to")
if (to.length() != 1) {
throw UnexpectedMoveException(
String.format("cannot detect move (from: %s, to: %s)", previous, current))
}
val movedPiece = to.get()._2
val fromSquare = from.find { it._2 == movedPiece }.map { it._1 }.get()
val toSquare = to.get()._1
// TODO: validate move outer
return previous.moves(fromSquare)
.filter { it.to == toSquare }
.getOrElseThrow { UnexpectedMoveException("invalid move $fromSquare:$toSquare (from: $previous, to: $current)") }
}
}
| gpl-2.0 | 299a90250a0f1c53a5e4aef6ba169760 | 34.861111 | 125 | 0.618125 | 4.124601 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/pkg/PackageFilter.kt | 1 | 934 | package com.cognifide.gradle.aem.common.instance.service.pkg
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
@JsonIgnoreProperties(ignoreUnknown = true)
class PackageFilter private constructor() {
lateinit var root: String
lateinit var rules: List<PackageFilterRule>
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PackageFilter
return EqualsBuilder()
.append(root, other.root)
.append(rules, other.rules)
.isEquals
}
override fun hashCode() = HashCodeBuilder()
.append(root)
.append(rules)
.toHashCode()
override fun toString() = "PackageFilter(root='$root', rules=$rules)"
}
| apache-2.0 | 33cc36b22fe3d392be62ebf9f7cb2075 | 28.1875 | 73 | 0.669165 | 4.578431 | false | false | false | false |
webianks/BlueChat | app/src/main/java/com/webianks/bluechat/BluetoothChatService.kt | 1 | 16512 | package com.webianks.bluechat
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.util.Log
import android.bluetooth.BluetoothSocket
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothServerSocket
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import android.os.Bundle
import android.os.Handler
import java.util.*
/**
* Created by ramankit on 20/7/17.
*/
class BluetoothChatService(context: Context, handler: Handler){
// Member fields
private var mAdapter: BluetoothAdapter? = null
private var mHandler: Handler? = null
private var mSecureAcceptThread: AcceptThread? = null
private var mInsecureAcceptThread: AcceptThread? = null
private var mConnectThread: ConnectThread? = null
private var mConnectedThread: ConnectedThread? = null
private var mState: Int = 0
private var mNewState: Int = 0
private val TAG: String = javaClass.simpleName
// Unique UUID for this application
private val MY_UUID_SECURE = UUID.fromString("29621b37-e817-485a-a258-52da5261421a")
private val MY_UUID_INSECURE = UUID.fromString("d620cd2b-e0a4-435b-b02e-40324d57195b")
// Name for the SDP record when creating server socket
private val NAME_SECURE = "BluetoothChatSecure"
private val NAME_INSECURE = "BluetoothChatInsecure"
// Constants that indicate the current connection state
companion object {
val STATE_NONE = 0 // we're doing nothing
val STATE_LISTEN = 1 // now listening for incoming connections
val STATE_CONNECTING = 2 // now initiating an outgoing connection
val STATE_CONNECTED = 3 // now connected to a remote device
}
init {
mAdapter = BluetoothAdapter.getDefaultAdapter()
mState = STATE_NONE
mNewState = mState
mHandler = handler
}
/**
* Return the current connection state.
*/
@Synchronized fun getState(): Int {
return mState
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
@Synchronized fun start() {
Log.d(TAG, "start")
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread?.cancel()
mConnectThread = null
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread?.cancel()
mConnectedThread = null
}
// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null) {
mSecureAcceptThread = AcceptThread(true)
mSecureAcceptThread?.start()
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = AcceptThread(false)
mInsecureAcceptThread?.start()
}
// Update UI title
//updateUserInterfaceTitle()
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
* *
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
@Synchronized fun connect(device: BluetoothDevice?, secure: Boolean) {
Log.d(TAG, "connect to: " + device)
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread?.cancel()
mConnectThread = null
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread?.cancel()
mConnectedThread = null
}
// Start the thread to connect with the given device
mConnectThread = ConnectThread(device, secure)
mConnectThread?.start()
// Update UI title
//updateUserInterfaceTitle()
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* *
* @param device The BluetoothDevice that has been connected
*/
@Synchronized fun connected(socket: BluetoothSocket?, device: BluetoothDevice?, socketType: String) {
Log.d(TAG, "connected, Socket Type:" + socketType)
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread?.cancel()
mConnectThread = null
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread?.cancel()
mConnectedThread = null
}
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread?.cancel()
mSecureAcceptThread = null
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread?.cancel()
mInsecureAcceptThread = null
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = ConnectedThread(socket, socketType)
mConnectedThread?.start()
// Send the name of the connected device back to the UI Activity
val msg = mHandler?.obtainMessage(Constants.MESSAGE_DEVICE_NAME)
val bundle = Bundle()
bundle.putString(Constants.DEVICE_NAME, device?.name)
msg?.data = bundle
mHandler?.sendMessage(msg)
// Update UI title
//updateUserInterfaceTitle()
}
/**
* Stop all threads
*/
@Synchronized fun stop() {
Log.d(TAG, "stop")
if (mConnectThread != null) {
mConnectThread?.cancel()
mConnectThread = null
}
if (mConnectedThread != null) {
mConnectedThread?.cancel()
mConnectedThread = null
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread?.cancel()
mSecureAcceptThread = null
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread?.cancel()
mInsecureAcceptThread = null
}
mState = STATE_NONE
// Update UI title
//updateUserInterfaceTitle()
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* *
* @see ConnectedThread.write
*/
fun write(out: ByteArray) {
// Create temporary object
var r: ConnectedThread? = null
// Synchronize a copy of the ConnectedThread
synchronized(this) {
if (mState != STATE_CONNECTED) return
r = mConnectedThread
}
// Perform the write unsynchronized
r?.write(out)
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private fun connectionFailed() {
// Send a failure message back to the Activity
val msg = mHandler?.obtainMessage(Constants.MESSAGE_TOAST)
val bundle = Bundle()
bundle.putString(Constants.TOAST, "Unable to connect device")
msg?.data = bundle
mHandler?.sendMessage(msg)
mState = STATE_NONE
// Update UI title
//updateUserInterfaceTitle()
// Start the service over to restart listening mode
[email protected]()
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private fun connectionLost() {
// Send a failure message back to the Activity
val msg = mHandler?.obtainMessage(Constants.MESSAGE_TOAST)
val bundle = Bundle()
bundle.putString(Constants.TOAST, "Device connection was lost")
msg?.data = bundle
mHandler?.sendMessage(msg)
mState = STATE_NONE
// Update UI title
// updateUserInterfaceTitle()
// Start the service over to restart listening mode
[email protected]()
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private inner class AcceptThread(secure: Boolean) : Thread() {
// The local server socket
private val mmServerSocket: BluetoothServerSocket?
private val mSocketType: String
init {
var tmp: BluetoothServerSocket? = null
mSocketType = if (secure) "Secure" else "Insecure"
// Create a new listening server socket
try {
if (secure) {
tmp = mAdapter?.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE)
} else {
tmp = mAdapter?.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE)
}
} catch (e: IOException) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e)
}
mmServerSocket = tmp
mState = STATE_LISTEN
}
override fun run() {
Log.d(TAG, "Socket Type: " + mSocketType +
"BEGIN mAcceptThread" + this)
name = "AcceptThread" + mSocketType
var socket: BluetoothSocket?
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket?.accept()
} catch (e: IOException) {
Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e)
break
}
// If a connection was accepted
if (socket != null) {
synchronized(this@BluetoothChatService) {
when (mState) {
STATE_LISTEN, STATE_CONNECTING ->
// Situation normal. Start the connected thread.
connected(socket, socket?.remoteDevice,
mSocketType)
STATE_NONE, STATE_CONNECTED ->
// Either not ready or already connected. Terminate new socket.
try {
socket?.close()
} catch (e: IOException) {
Log.e(TAG, "Could not close unwanted socket", e)
}
else -> {
}
}
}
}
}
Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType)
}
fun cancel() {
Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this)
try {
mmServerSocket?.close()
} catch (e: IOException) {
Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e)
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private inner class ConnectThread(private val mmDevice: BluetoothDevice?, secure: Boolean) : Thread() {
private val mmSocket: BluetoothSocket?
private val mSocketType: String
init {
var tmp: BluetoothSocket? = null
mSocketType = if (secure) "Secure" else "Insecure"
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = mmDevice?.createRfcommSocketToServiceRecord(
MY_UUID_SECURE)
} else {
tmp = mmDevice?.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE)
}
} catch (e: IOException) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e)
}
mmSocket = tmp
mState = STATE_CONNECTING
}
override fun run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType)
name = "ConnectThread" + mSocketType
// Always cancel discovery because it will slow down a connection
mAdapter?.cancelDiscovery()
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket?.connect()
} catch (e: IOException) {
// Close the socket
try {
mmSocket?.close()
} catch (e2: IOException) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2)
}
connectionFailed()
return
}
// Reset the ConnectThread because we're done
synchronized(this@BluetoothChatService) {
mConnectThread = null
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType)
}
fun cancel() {
try {
mmSocket?.close()
} catch (e: IOException) {
Log.e(TAG, "close() of connect $mSocketType socket failed", e)
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private inner class ConnectedThread(private val mmSocket: BluetoothSocket?, socketType: String) : Thread() {
private val mmInStream: InputStream?
private val mmOutStream: OutputStream?
init {
Log.d(TAG, "create ConnectedThread: " + socketType)
var tmpIn: InputStream? = null
var tmpOut: OutputStream? = null
// Get the BluetoothSocket input and output streams
try {
tmpIn = mmSocket?.inputStream
tmpOut = mmSocket?.outputStream
} catch (e: IOException) {
Log.e(TAG, "temp sockets not created", e)
}
mmInStream = tmpIn
mmOutStream = tmpOut
mState = STATE_CONNECTED
}
override fun run() {
Log.i(TAG, "BEGIN mConnectedThread")
val buffer = ByteArray(1024)
var bytes: Int
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
try {
// Read from the InputStream
bytes = mmInStream?.read(buffer) ?: 0
// Send the obtained bytes to the UI Activity
mHandler?.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
?.sendToTarget()
} catch (e: IOException) {
Log.e(TAG, "disconnected", e)
connectionLost()
break
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
fun write(buffer: ByteArray) {
try {
mmOutStream?.write(buffer)
// Share the sent message back to the UI Activity
mHandler?.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
?.sendToTarget()
} catch (e: IOException) {
Log.e(TAG, "Exception during write", e)
}
}
fun cancel() {
try {
mmSocket?.close()
} catch (e: IOException) {
Log.e(TAG, "close() of connect socket failed", e)
}
}
}
} | mit | 9d71e5608f531e449e63ef2616cf4f1e | 31.251953 | 112 | 0.552386 | 5.032612 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UMethod.kt | 1 | 3479 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiAnnotationMethod
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A method visitor to be used in [UastVisitor].
*/
interface UMethod : UDeclaration, PsiMethod {
override val psi: PsiMethod
/**
* Returns the body expression (which can be also a [UBlockExpression]).
*/
val uastBody: UExpression?
/**
* Returns the method parameters.
*/
val uastParameters: List<UParameter>
/**
* Returns true, if the method overrides a method of a super class.
*/
val isOverride: Boolean
override fun getName(): String
override fun getReturnType(): PsiType?
override fun isConstructor(): Boolean
@Deprecated("Use uastBody instead.", ReplaceWith("uastBody"))
override fun getBody() = psi.body
override fun accept(visitor: UastVisitor) {
if (visitor.visitMethod(this)) return
annotations.acceptList(visitor)
uastParameters.acceptList(visitor)
uastBody?.accept(visitor)
visitor.afterVisitMethod(this)
}
override fun asRenderString() = buildString {
if (annotations.isNotEmpty()) {
annotations.joinTo(buffer = this, separator = "\n", postfix = "\n", transform = UAnnotation::asRenderString)
}
append(psi.renderModifiers())
append("fun ").append(name)
uastParameters.joinTo(this, prefix = "(", postfix = ")") { parameter ->
val annotationsText = if (parameter.annotations.isNotEmpty())
parameter.annotations.joinToString(separator = " ", postfix = " ") { it.asRenderString() }
else
""
annotationsText + parameter.name + ": " + parameter.type.canonicalText
}
psi.returnType?.let { append(" : " + it.canonicalText) }
val body = uastBody
append(when (body) {
is UBlockExpression -> " " + body.asRenderString()
else -> " = " + ((body ?: UastEmptyExpression(this@UMethod)).asRenderString())
})
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitMethod(this, data)
override fun asLogString() = log("name = $name")
}
interface UAnnotationMethod : UMethod, PsiAnnotationMethod {
override val psi: PsiAnnotationMethod
/**
* Returns the default value of this annotation method.
*/
val uastDefaultValue: UExpression?
override fun getDefaultValue() = psi.defaultValue
override fun accept(visitor: UastVisitor) {
if (visitor.visitMethod(this)) return
annotations.acceptList(visitor)
uastParameters.acceptList(visitor)
uastBody?.accept(visitor)
uastDefaultValue?.accept(visitor)
visitor.afterVisitMethod(this)
}
override fun asLogString() = log("name = $name")
} | apache-2.0 | 2d1f044606207383417e67994d9e2546 | 29.26087 | 114 | 0.703076 | 4.460256 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/NetworkUtil.kt | 1 | 2485 | package ch.rmy.android.http_shortcuts.utils
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED
import android.net.wifi.WifiManager
import android.os.Build
import android.os.PowerManager
import androidx.core.content.getSystemService
import ch.rmy.android.framework.extensions.showToast
import ch.rmy.android.framework.extensions.startActivity
import ch.rmy.android.http_shortcuts.R
import javax.inject.Inject
class NetworkUtil
@Inject
constructor(
private val context: Context,
private val activityProvider: ActivityProvider,
) {
fun isNetworkConnected(): Boolean =
context.getSystemService<ConnectivityManager>()
?.activeNetworkInfo
?.isConnected
?: false
fun isNetworkPerformanceRestricted() =
isDataSaverModeEnabled() || isBatterySaverModeEnabled()
private fun isBatterySaverModeEnabled(): Boolean =
context.getSystemService<PowerManager>()
?.isPowerSaveMode
?: false
private fun isDataSaverModeEnabled(): Boolean =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.getSystemService<ConnectivityManager>()
?.run { isActiveNetworkMetered && restrictBackgroundStatus == RESTRICT_BACKGROUND_STATUS_ENABLED }
?: false
} else {
false
}
fun getCurrentSsid(): String? =
context.applicationContext.getSystemService<WifiManager>()
?.connectionInfo
?.ssid
?.trim('"')
fun getIPV4Address(): String? =
context.applicationContext.getSystemService<WifiManager>()
?.connectionInfo
?.ipAddress
?.takeUnless { it == 0 }
?.let(::formatIPV4Address)
private fun formatIPV4Address(ip: Int): String =
"${ip shr 0 and 0xFF}.${ip shr 8 and 0xFF}.${ip shr 16 and 0xFF}.${ip shr 24 and 0xFF}"
fun showWifiPicker() {
try {
Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
.putExtra("extra_prefs_show_button_bar", true)
.putExtra("wifi_enable_next_on_connect", true)
.startActivity(activityProvider.getActivity())
} catch (e: ActivityNotFoundException) {
context.showToast(R.string.error_not_supported)
}
}
}
| mit | 0b062eb7ade5814a469ba0b47aaf6d03 | 33.041096 | 114 | 0.666801 | 4.97 | false | false | false | false |
timrijckaert/BetterBottomBar | library/src/main/kotlin/be/rijckaert/tim/library/BetterBottomBarDefaultBehavior.kt | 1 | 1797 | package be.rijckaert.tim.library
import android.support.design.widget.BottomNavigationView
import android.support.design.widget.CoordinatorLayout
import android.view.View
class BetterBottomBarDefaultBehavior : CoordinatorLayout.Behavior<BottomNavigationView>() {
private var totalDyConsumed = -1
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout?, child: BottomNavigationView, directTargetChild: View?, target: View?,
nestedScrollAxes: Int): Boolean = true
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: BottomNavigationView, target: View?, dxConsumed: Int, dyConsumed: Int,
dxUnconsumed: Int, dyUnconsumed: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
if (dyConsumed > 0 && totalDyConsumed < 0) {
totalDyConsumed = 0
animateBottomBar(child, coordinatorLayout, ScrollDirection.UP)
} else if (dyConsumed < 0 && totalDyConsumed > 0) {
totalDyConsumed = 0
animateBottomBar(child, coordinatorLayout, ScrollDirection.DOWN)
}
totalDyConsumed += dyConsumed
}
private fun animateBottomBar(view: View, container: View, direction: ScrollDirection) {
val yPos = calculateY(view.height, container.height, direction)
view.animate().y(yPos).start()
}
private fun calculateY(measuredHeightView: Int, measuredHeightContainer: Int, scrollDirection: ScrollDirection): Float =
measuredHeightContainer.plus((measuredHeightView.times(scrollDirection.directionFactor))).toFloat()
private enum class ScrollDirection(val directionFactor: Int = 1) {
UP(), DOWN(-1);
}
} | mit | 7f090dd4d8d605c7a3f9b3fed2cab324 | 45.102564 | 147 | 0.706733 | 5.239067 | false | false | false | false |
iotv/android | app/src/main/kotlin/io/iotv/app/MP4ChunkedUploader.kt | 1 | 1421 | package io.iotv.app
import android.util.Log
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.Okio
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.IOException
class MP4ChunkedUploader(val fileDescriptor: FileDescriptor) {
val inputStream = FileInputStream(fileDescriptor)
val bufferedSource = Okio.buffer(Okio.source(inputStream))
}
class MP4ChunkRequestBody(val buffer: Buffer): RequestBody() {
companion object {
val TAG = "MP4ChunkRequestBody"
// FIXME: Perhaps generate the boundary so it doesn't happen to interfere with a file?
// Since a file containing \n--boundary would split the message if we don't parse this
// properly. It'd probably be smarter to just migrate to protobuf tbh
val MULTIPART_RELATED_TYPE = MediaType.parse("multipart/related; boundary=\"boundary\"")!!
}
override fun contentType(): MediaType {
return MULTIPART_RELATED_TYPE
}
override fun writeTo(sink: BufferedSink?) {
try {
sink!!.writeUtf8("--boundary\nContent-Type: application/json; charset=utf8\n\n{}\n--boundary")
sink.writeAll(buffer)
sink.writeUtf8("\n--boundary--\n")
} catch (e: IOException) {
Log.e(TAG, "IOException in writeTo while writing request body")
throw e
}
}
} | mit | c9cabf9128ba4a400211b05ebcd0af1f | 30.6 | 106 | 0.688951 | 4.319149 | false | false | false | false |
ZoranPandovski/al-go-rithms | dynamic_programing/kotlin/LongestCommonSubsequence.kt | 1 | 1254 | class LongestCommonSubsequence {
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
fun lcs(X: CharArray, Y: CharArray, m: Int, n: Int): Int {
val L = Array(m + 1) { IntArray(n + 1) }
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (i in 0..m) {
for (j in 0..n) {
if (i == 0 || j == 0)
L[i][j] = 0
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1
else
L[i][j] = max(L[i - 1][j], L[i][j - 1])
}
}
return L[m][n]
}
/* Utility function to get max of 2 integers */
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val lcs = LongestCommonSubsequence()
val s1 = "asdpoij"
val s2 = "asdpfwefg"
val X = s1.toCharArray()
val Y = s2.toCharArray()
val m = X.size
val n = Y.size
val result = lcs.lcs(X, Y, m, n)
println(result)
}
}
} | cc0-1.0 | 0347e51561d35e02f762f29e195cf4aa | 27.522727 | 74 | 0.420255 | 3.215385 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/main/ActivityForResult.kt | 1 | 2546 | package com.orgzly.android.ui.main
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.annotation.StringRes
import androidx.core.app.ComponentActivity
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.savedsearch.FileSavedSearchStore
import com.orgzly.android.util.LogUtils
abstract class ActivityForResult(val activity: ComponentActivity) {
fun startSavedSearchesExportFileChooser() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/json"
putExtra(Intent.EXTRA_TITLE, FileSavedSearchStore.FILE_NAME)
}
activity.startActivityForResult(intent, REQUEST_CODE_SAVED_SEARCHES_EXPORT)
}
fun startSavedSearchesImportFileChooser() {
startFileChooser(R.string.import_, REQUEST_CODE_SAVED_SEARCHES_IMPORT)
}
private fun startFileChooser(@StringRes titleResId: Int, code: Int) {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
}
val chooserIntent = Intent.createChooser(intent, activity.getString(titleResId))
activity.startActivityForResult(chooserIntent, code)
}
fun onResult(requestCode: Int, resultCode: Int, intent: Intent?) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, requestCode, resultCode, intent)
if (resultCode != Activity.RESULT_OK) {
Log.w(TAG, "Activity result not OK")
return
}
if (intent == null) {
Log.w(TAG, "Activity result has no intent")
return
}
when (requestCode) {
REQUEST_CODE_SAVED_SEARCHES_EXPORT -> {
intent.data?.let { uri ->
onSearchQueriesExport(uri)
}
}
REQUEST_CODE_SAVED_SEARCHES_IMPORT -> {
intent.data?.let { uri ->
onSearchQueriesImport(uri)
}
}
else -> {
Log.e(TAG, "Unknown request code $requestCode intent $intent")
}
}
}
abstract fun onSearchQueriesExport(uri: Uri)
abstract fun onSearchQueriesImport(uri: Uri)
companion object {
private val TAG = ActivityForResult::class.java.name
const val REQUEST_CODE_SAVED_SEARCHES_EXPORT = 3
const val REQUEST_CODE_SAVED_SEARCHES_IMPORT = 4
}
} | gpl-3.0 | 61df650c0c1fd7b842db7272de9e4a32 | 30.060976 | 88 | 0.634328 | 4.570916 | false | false | false | false |
Litote/kmongo | kmongo-id/src/main/kotlin/org/litote/kmongo/id/IdGenerator.kt | 1 | 1878 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.id
import org.litote.kmongo.Id
import java.util.ServiceLoader
import kotlin.reflect.KClass
import kotlin.reflect.full.valueParameters
/**
* A generator of Ids.
*/
interface IdGenerator {
companion object {
var defaultGenerator: IdGenerator
get() = defaultIdGenerator
set(value) {
defaultIdGenerator = value
}
@Volatile
private var defaultIdGenerator: IdGenerator =
ServiceLoader.load(IdGeneratorProvider::class.java)
.iterator().asSequence().maxByOrNull { it.priority }?.generator
?: UUIDStringIdGenerator
}
/**
* The class of the id.
*/
val idClass: KClass<out Id<*>>
/**
* The class of the wrapped id.
*/
val wrappedIdClass: KClass<out Any>
/**
* Generate a new id.
*/
fun <T> generateNewId(): Id<T>
/**
* Create a new id from its String representation.
*/
fun create(s: String): Id<*> = idClass
.constructors
.firstOrNull { it.valueParameters.size == 1 && it.valueParameters.first().type.classifier == String::class }
?.call(s)
?: error("no constructor with a single string arg found for $idClass}")
} | apache-2.0 | b9b09cf170800235cf0e6486c3495e47 | 26.632353 | 116 | 0.64164 | 4.408451 | false | false | false | false |
RSDT/Japp | app/src/main/java/nl/rsdt/japp/jotial/auth/Authentication.kt | 1 | 3757 | package nl.rsdt.japp.jotial.auth
import android.app.Activity
import android.content.Intent
import com.google.gson.annotations.SerializedName
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.application.activities.LoginActivity
import nl.rsdt.japp.jotial.net.apis.AuthApi
import retrofit2.Call
import retrofit2.Callback
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Description...
*/
class Authentication : Callback<Authentication.KeyObject> {
private var callback: OnAuthenticationCompletedCallback? = null
private var username: String = ""
private var password: String = ""
fun executeAsync() {
val api = Japp.getApi(AuthApi::class.java)
api.login(LoginBody(username, password)).enqueue(this)
}
override fun onResponse(call: Call<KeyObject>, response: retrofit2.Response<KeyObject>) {
if (response.code() == 200) {
val key = response.body()?.key
/**
* Change the key in the release_preferences.
*/
val pEditor = JappPreferences.visiblePreferences.edit()
pEditor.putString(JappPreferences.ACCOUNT_KEY, key)
pEditor.apply()
callback?.onAuthenticationCompleted(AuthenticationResult(key, 200, Japp.getString(R.string.login_succes)))
} else {
val message: String = if (response.code() == 404) {
Japp.getString(R.string.wrong_data)
} else {
Japp.getString(R.string.error_on_login)
}
callback?.onAuthenticationCompleted(AuthenticationResult("", response.code(), message))
}
}
override fun onFailure(call: Call<KeyObject>, t: Throwable) {
callback?.onAuthenticationCompleted(AuthenticationResult("", 0, Japp.getString(R.string.error_on_login)))
}
class AuthenticationResult(val key: String?, val code: Int, val message: String) {
val isSucceeded: Boolean
get() = key != null && !key.isEmpty()
}
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 2-9-2016
* Description...
*/
inner class LoginBody(private val gebruiker: String, private val ww: String)
inner class KeyObject {
@SerializedName("SLEUTEL")
public val key: String = ""
}
inner class ValidateObject {
@SerializedName("exists")
private val exists: Boolean = false
fun exists(): Boolean {
return exists
}
}
class Builder {
internal var buffer = Authentication()
fun setCallback(callback: OnAuthenticationCompletedCallback): Builder {
buffer.callback = callback
return this
}
fun setUsername(username: String): Builder {
buffer.username = username
return this
}
fun setPassword(password: String): Builder {
buffer.password = AeSimpleSHA1.trySHA1(password)
return this
}
fun create(): Authentication {
return buffer
}
}
interface OnAuthenticationCompletedCallback {
fun onAuthenticationCompleted(result: AuthenticationResult)
}
companion object {
val REQUEST_TAG = "Authentication"
/**
* TODO: don't use final here
*/
fun validate(activity: Activity) {
val api = Japp.getApi(AuthApi::class.java)
}
fun startLoginActivity(activity: Activity) {
val intent = Intent(activity, LoginActivity::class.java)
activity.startActivity(intent)
activity.finish()
}
}
}
| apache-2.0 | 3e938093e59e806c9405cd52d7b77867 | 26.224638 | 118 | 0.620176 | 4.626847 | false | false | false | false |
VerifAPS/verifaps-lib | util/src/main/kotlin/edu/kit/iti/formal/util/CodeWriter.kt | 1 | 2355 | package edu.kit.iti.formal.util
import java.io.StringWriter
import java.io.Writer
/**
* CodeWriter class.
*
* @author weigla (15.06.2014)
* @version 2
*/
open class CodeWriter(var stream: Writer = StringWriter())
: Appendable by stream {
var uppercaseKeywords = true
var ident = " "
protected var identDepth = 0
fun write(x: String): CodeWriter {
stream.write(x)
return this
}
fun appendIdent(): CodeWriter {
for (i in 0 until identDepth) {
write(ident)
}
return this
}
fun increaseIndent(): CodeWriter {
identDepth++
return this
}
fun decreaseIndent(): CodeWriter {
identDepth = Math.max(identDepth - 1, 0)
return this
}
open fun keyword(keyword: String): CodeWriter {
return printf(if (uppercaseKeywords) keyword.toUpperCase() else keyword.toLowerCase())
}
fun nl(): CodeWriter {
write("\n")
appendIdent()
return this
}
fun println(arg: String): CodeWriter = print(arg).nl()
fun print(args: String): CodeWriter = write(args)
fun print(vararg args: Any): CodeWriter {
args.forEach { write(it.toString()) }
return this
}
fun printf(fmt: String, vararg args: Any): CodeWriter {
return write(String.format(fmt, *args))
}
fun block(text: String = "", nl: Boolean = false, function: CodeWriter.() -> Unit): CodeWriter {
printf(text)
if (nl) nl()
increaseIndent()
function()
decreaseIndent()
if (nl) nl()
return this
}
fun appendReformat(text: String): CodeWriter {
text.splitToSequence('\n').forEach { nl().printf(it) }
return this
}
fun cblock(head: String, tail: String, function: CodeWriter.() -> Unit): CodeWriter {
printf(head)
increaseIndent()
nl()
function()
decreaseIndent()
nl()
printf(tail)
return this
}
operator fun CharSequence.unaryPlus(): CharSequence {
[email protected](this@unaryPlus)
return this@unaryPlus
}
companion object{
fun with(fn : CodeWriter.() -> Unit) : String {
val cw = CodeWriter()
fn(cw)
return cw.stream.toString()
}
}
}
| gpl-3.0 | bf857a7e73d62d7f48753105793c8c55 | 22.088235 | 100 | 0.572399 | 4.289617 | false | false | false | false |
rharter/windy-city-devcon-android | app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/speakerlist/DividerItemDecoration.kt | 1 | 1610 | package com.gdgchicagowest.windycitydevcon.features.sessions
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.View
internal class DividerItemDecoration(private val context: Context) : RecyclerView.ItemDecoration() {
private val divider: Drawable
init {
val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
divider = a.getDrawable(0)
a.recycle()
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val childCount = parent.childCount
for (i in 0..childCount) {
val view = parent.getChildAt(i)
if (view != null) {
val holder = parent.getChildViewHolder(view)
if (holder.adapterPosition != 0) {
val left = 0
val top = holder.itemView.top
val right = parent.width
val bottom = top + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val holder = parent.getChildViewHolder(view)
if (holder is SessionAdapter.ViewHolder) {
if (holder.adapterPosition != 0) {
outRect.set(0, divider.intrinsicHeight, 0, 0)
}
}
}
} | apache-2.0 | 105a77c6ba4d70b1d4e997b1dd3bdf0b | 34.021739 | 109 | 0.613665 | 4.849398 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/teams/details/TeamDetailsFragment.kt | 1 | 9885 | package ca.josephroque.bowlingcompanion.teams.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.Android
import ca.josephroque.bowlingcompanion.common.fragments.BaseFragment
import ca.josephroque.bowlingcompanion.common.fragments.ListFragment
import ca.josephroque.bowlingcompanion.common.interfaces.IFloatingActionButtonHandler
import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable
import ca.josephroque.bowlingcompanion.database.DatabaseManager
import ca.josephroque.bowlingcompanion.games.GameControllerFragment
import ca.josephroque.bowlingcompanion.games.SeriesProvider
import ca.josephroque.bowlingcompanion.leagues.League
import ca.josephroque.bowlingcompanion.series.Series
import ca.josephroque.bowlingcompanion.statistics.interfaces.IStatisticsContext
import ca.josephroque.bowlingcompanion.statistics.provider.StatisticsProvider
import ca.josephroque.bowlingcompanion.teams.Team
import ca.josephroque.bowlingcompanion.teams.teammember.TeamMember
import ca.josephroque.bowlingcompanion.teams.teammember.TeamMemberDialog
import ca.josephroque.bowlingcompanion.teams.teammember.TeamMembersListFragment
import ca.josephroque.bowlingcompanion.utils.Analytics
import ca.josephroque.bowlingcompanion.utils.BCError
import ca.josephroque.bowlingcompanion.utils.safeLet
import kotlinx.android.synthetic.main.view_screen_header.view.*
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
/**
* Copyright (C) 2018 Joseph Roque
*
* A fragment representing the details of a single team and its members.
*/
class TeamDetailsFragment : BaseFragment(),
IFloatingActionButtonHandler,
ListFragment.ListFragmentDelegate,
TeamMemberDialog.TeamMemberDialogDelegate,
TeamMembersListFragment.TeamMemberListFragmentDelegate,
IStatisticsContext {
companion object {
@Suppress("unused")
private const val TAG = "TeamDetailsFragment"
private const val ARG_TEAM = "${TAG}_team"
fun newInstance(team: Team): TeamDetailsFragment {
val fragment = TeamDetailsFragment()
fragment.arguments = Bundle().apply { putParcelable(ARG_TEAM, team) }
return fragment
}
}
override val statisticsProviders: List<StatisticsProvider> by lazy {
val team = team
return@lazy if (team != null) {
arrayListOf(StatisticsProvider.TeamStatistics(team))
} else {
emptyList<StatisticsProvider>()
}
}
private var team: Team? = null
private var allTeamMembersReady: Boolean = false
set(value) {
if (field != value) {
field = value
launch(Android) {
fabProvider?.invalidateFab()
}
}
}
// MARK: Lifecycle functions
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
team = arguments?.getParcelable(ARG_TEAM)
val view = inflater.inflate(R.layout.fragment_team_details, container, false)
setupHeader(view)
val team = team
if (savedInstanceState == null && team != null) {
val fragment = TeamMembersListFragment.newInstance(team)
childFragmentManager.beginTransaction().apply {
add(R.id.fragment_container, fragment)
commit()
}
}
return view
}
override fun onStart() {
super.onStart()
fabProvider?.invalidateFab()
}
// MARK: BaseFragment
override fun updateToolbarTitle() {
team?.let { navigationActivity?.setToolbarTitle(it.name) }
}
// MARK: IFloatingActionButtonHandler
override fun getFabImage(): Int? = if (allTeamMembersReady) R.drawable.ic_ball else null
override fun onFabClick() {
safeLet(context, team) { context, team ->
val needsNewPracticeSeries = team.members.any { it.league?.isPractice == true && it.series == null }
if (needsNewPracticeSeries) {
League.showPracticeGamesPicker(context, ::launchAttemptToBowl)
} else {
launchAttemptToBowl()
}
}
}
// MARK: ListFragmentDelegate
override fun onItemSelected(item: IIdentifiable, longPress: Boolean) {
if (item is TeamMember) {
val fragment = TeamMemberDialog.newInstance(item)
fragmentNavigation?.pushDialogFragment(fragment)
}
}
override fun onItemDeleted(item: IIdentifiable) {
// Intentionally left blank
}
// MARK: TeamMemberDialogDelegate
override fun onFinishTeamMember(teamMember: TeamMember) {
childFragmentManager.fragments
.filter { it != null && it.isVisible }
.forEach {
val list = it as? TeamMembersListFragment ?: return
list.refreshList(teamMember)
team = team?.replaceTeamMember(teamMember)
}
}
// MARK: TeamMemberListFragmentDelegate
override fun onTeamMembersReadyChanged(ready: Boolean) {
allTeamMembersReady = ready
}
override fun onTeamMembersReordered(order: List<Long>) {
team?.let { team = Team(it.id, it.name, it.members, order) }
Analytics.trackReorderTeamMembers()
}
// MARK: Private functions
private fun setupHeader(rootView: View) {
rootView.tv_header_title.setText(R.string.team_members)
rootView.tv_header_caption.setText(R.string.team_members_select_league)
}
private fun launchAttemptToBowl(practiceNumberOfGames: Int = 1) {
val context = context ?: return
launch(Android) {
val error = attemptToBowl(practiceNumberOfGames).await()
if (error != null) {
error.show(context)
return@launch
}
val team = [email protected]
if (team != null) {
val fragment = GameControllerFragment.newInstance(SeriesProvider.TeamSeries(team))
fragmentNavigation?.pushFragment(fragment)
} else {
BCError().show(context)
}
}
}
private fun attemptToBowl(practiceNumberOfGames: Int): Deferred<BCError?> {
return async(CommonPool) {
val context = [email protected] ?: return@async BCError()
val team = [email protected] ?: return@async BCError()
if (allTeamMembersReady) {
allTeamMembersReady = false
val teamMemberSeries: MutableMap<TeamMember, Series> = HashMap()
// Create series in the database for each team member, if one does not exist,
// or retrieve the existing series if it does.
val database = DatabaseManager.getWritableDatabase(context).await()
try {
team.members.forEach {
val league = it.league!!
when {
league.isEvent -> {
val eventSeries = league.fetchSeries(context).await()
assert(eventSeries.size == 1)
teamMemberSeries[it] = eventSeries.first()
}
it.series == null -> {
if (!database.inTransaction()) {
database.beginTransaction()
}
val (newSeries, seriesError) = league.createNewSeries(
context = context,
openDatabase = database,
numberOfPracticeGamesOverride = practiceNumberOfGames
).await()
if (newSeries != null) {
teamMemberSeries[it] = newSeries
} else if (seriesError != null) {
return@async seriesError
}
}
else -> {
teamMemberSeries[it] = it.series
}
}
}
if (database.inTransaction()) {
database.setTransactionSuccessful()
}
} finally {
if (database.inTransaction()) {
database.endTransaction()
}
}
// Replace immutable [TeamMember] instances with updated series
val membersWithSeries = team.members.map {
return@map TeamMember(
teamId = it.teamId,
bowlerName = it.bowlerName,
bowlerId = it.bowlerId,
league = it.league,
series = teamMemberSeries[it]
)
}
// Replace team with updated members
[email protected] = Team(
id = team.id,
name = team.name,
members = membersWithSeries,
initialOrder = team.order
)
}
return@async null
}
}
}
| mit | 4a62fafbca8a45206ee7ce8dc2b3c75a | 36.301887 | 116 | 0.58432 | 5.410509 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/overall/StrikeMiddleHitsStatistic.kt | 1 | 2429 | package ca.josephroque.bowlingcompanion.statistics.impl.overall
import android.os.Parcel
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.games.lane.isMiddleHit
import ca.josephroque.bowlingcompanion.statistics.PercentageStatistic
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame
/**
* Copyright (C) 2018 Joseph Roque
*
* Percentage of middle hits which were strikes
*/
class StrikeMiddleHitsStatistic(override var numerator: Int = 0, override var denominator: Int = 0) : PercentageStatistic {
companion object {
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::StrikeMiddleHitsStatistic)
const val Id = R.string.statistic_strike_middle_hits
}
override val titleId = Id
override val id = Id.toLong()
override val category = StatisticsCategory.Overall
override val secondaryGraphDataLabelId = R.string.statistic_total_shots_at_middle
override fun isModifiedBy(frame: StatFrame) = true
// MARK: Statistic
override fun modify(frame: StatFrame) {
// This function has a similar construction to `FirstBallStatistic.modify(StatFrame)
// and the two should remain aligned
// Every frame adds 1 possible hit
denominator += if (frame.pinState[0].isMiddleHit) 1 else 0
numerator += if (frame.pinState[0].arePinsCleared) 1 else 0
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
// In the 10th frame, for each time the first or second ball cleared the lane,
// check if the statistic is modified
if (frame.pinState[0].arePinsCleared) {
denominator += if (frame.pinState[1].isMiddleHit) 1 else 0
numerator += if (frame.pinState[1].arePinsCleared) 1 else 0
}
if (frame.pinState[1].arePinsCleared) {
denominator += if (frame.pinState[2].isMiddleHit) 1 else 0
numerator += if (frame.pinState[2].arePinsCleared) 1 else 0
}
}
}
// MARK: Constructors
private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt())
}
| mit | 5b8de6ceab43b92f7ee43de9c845cd83 | 39.483333 | 123 | 0.707287 | 4.609108 | false | false | false | false |
yuzumone/bergamio | app/src/main/kotlin/net/yuzumone/bergamio/activity/AuthActivity.kt | 1 | 2459 | package net.yuzumone.bergamio.activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import net.yuzumone.bergamio.BuildConfig
import net.yuzumone.bergamio.R
import net.yuzumone.bergamio.databinding.ActivityAuthBinding
import net.yuzumone.bergamio.util.PreferenceUtil
import java.util.regex.Pattern
class AuthActivity : AppCompatActivity() {
private lateinit var binding: ActivityAuthBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_auth)
setSupportActionBar(binding.toolbar)
val clientId = BuildConfig.DEVELOPER_ID
val redirect = BuildConfig.REDIRECT_URI
val uri = "https://api.iijmio.jp/mobile/d/v1/authorization/" +
"?response_type=token&state=state&client_id=$clientId&redirect_uri=$redirect"
binding.buttonAuth.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
startActivity(intent)
}
}
override fun onNewIntent(intent: Intent?) {
if (intent == null || intent.data == null) {
return
}
val fragment = intent.data.fragment
val token = getToken(fragment)
val expire = getExpire(fragment)
if (token != "" && expire != 0L) {
storeData(token, expire)
val mainActivityIntent = Intent(this, MainActivity::class.java)
startActivity(mainActivityIntent)
finish()
} else {
Toast.makeText(this, getString(R.string.auth_miss), Toast.LENGTH_LONG).show()
}
}
private fun getToken(string: String): String {
val p = Pattern.compile("(access_token=)(\\w+)")
val m = p.matcher(string)
return if (m.find()) {
m.group(2)
} else {
""
}
}
private fun getExpire(string: String): Long {
val p = Pattern.compile("(expires_in=)(\\d+)")
val m = p.matcher(string)
return if (m.find()) {
m.group(2).toLong()
} else {
0L
}
}
private fun storeData(token: String, expire: Long) {
val pref = PreferenceUtil(this)
pref.token = token
pref.expire = expire
}
} | apache-2.0 | 6e8cdec6eea2cb4be476bb0f46a2073d | 31.8 | 93 | 0.631151 | 4.246978 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/listener/EntityDamageByEntityListener.kt | 1 | 5684 | /*
* Copyright 2021 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.monsters.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.expression.RPKExpressionService
import com.rpkit.core.service.Services
import com.rpkit.monsters.bukkit.RPKMonstersBukkit
import com.rpkit.monsters.bukkit.monsterlevel.RPKMonsterLevelService
import com.rpkit.monsters.bukkit.monsterstat.RPKMonsterStatServiceImpl
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.stats.bukkit.stat.RPKStatService
import com.rpkit.stats.bukkit.stat.RPKStatVariableService
import org.bukkit.entity.Arrow
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.entity.Projectile
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityDamageByEntityEvent
class EntityDamageByEntityListener(private val plugin: RPKMonstersBukkit) : Listener {
@EventHandler
fun onEntityDamageByEntity(event: EntityDamageByEntityEvent) {
if (plugin.config.getBoolean("monsters.${event.entityType}.ignored", plugin.config.getBoolean("monsters.default.ignored"))) {
return
}
var attacker: LivingEntity? = null
var defender: LivingEntity? = null
val damager = event.damager
val attackType = if (damager is Projectile) {
val shooter = damager.shooter
if (shooter is LivingEntity) {
attacker = shooter
}
if (damager is Arrow) {
"bow"
} else {
"projectile"
}
} else {
if (damager is LivingEntity) {
attacker = damager
}
"melee"
}
val entity = event.entity
if (entity is LivingEntity) {
defender = entity
}
val attack = if (attacker != null) {
if (attacker is Player) {
getPlayerStat(attacker, attackType, "attack")
} else {
getEntityStat(attacker, attackType, "attack")
}
} else {
1.0
}
val defence = if (defender != null) {
if (defender is Player) {
getPlayerStat(defender, attackType, "defence")
} else {
getEntityStat(defender, attackType, "defence")
}
} else {
1.0
}
if (attacker != null && defender != null) {
event.damage = getDamage(event.damage, attack, defence)
}
if (defender != null) {
if (defender !is Player) {
val monsterStatService = Services[RPKMonsterStatServiceImpl::class.java] ?: return
monsterStatService.setMonsterNameplate(defender, health = defender.health - event.finalDamage)
}
}
}
private fun getPlayerStat(player: Player, type: String, stat: String): Double {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return 0.0
val characterService = Services[RPKCharacterService::class.java] ?: return 0.0
val statService = Services[RPKStatService::class.java] ?: return 0.0
val statVariableService = Services[RPKStatVariableService::class.java] ?: return 0.0
val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(player) ?: return 0.0
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return 0.0
val expression = expressionService.createExpression(plugin.config.getString("stats.$type.$stat") ?: return 0.0)
val statVariables = statVariableService.statVariables
return expression.parseDouble(statService.stats.associate { it.name.value to it.get(character, statVariables) }) ?: 0.0
}
private fun getEntityStat(entity: LivingEntity, type: String, stat: String): Double {
val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 0.0
val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0
val expression = expressionService.createExpression(plugin.config.getString("monsters.${entity.type}.stats.$type.$stat")
?: plugin.config.getString("monsters.default.stats.$type.$stat") ?: return 0.0)
return expression.parseDouble(mapOf(
"level" to monsterLevelService.getMonsterLevel(entity).toDouble(),
"monsterType" to "\"${entity.type}\""
)) ?: 0.0
}
private fun getDamage(originalDamage: Double, attack: Double, defence: Double): Double {
val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0
val expression = expressionService.createExpression(plugin.config.getString("damage") ?: return 0.0)
return expression.parseDouble(mapOf(
"damage" to originalDamage,
"attack" to attack,
"defence" to defence
)) ?: 0.0
}
} | apache-2.0 | 6afcef3738c4863209b6cee1eb421e40 | 43.069767 | 133 | 0.665904 | 4.647588 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/modules/AutoroleModule.kt | 1 | 1422 | package net.perfectdreams.loritta.morenitta.modules
import net.perfectdreams.loritta.morenitta.utils.extensions.filterOnlyGiveableRoles
import net.dv8tion.jda.api.entities.Member
import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.AutoroleConfig
import java.util.concurrent.TimeUnit
object AutoroleModule {
fun giveRoles(member: Member, autoroleConfig: AutoroleConfig) {
val guild = member.guild
// Transform all role IDs to a role list
val roles = autoroleConfig.roles
.asSequence()
.mapNotNull { guild.getRoleById(it) }
.distinct()
.filterOnlyGiveableRoles()
.toList()
val filteredRoles = roles.filter { !member.roles.contains(it) }
if (filteredRoles.isNotEmpty()) {
if (filteredRoles.size == 1) {
if (autoroleConfig.giveRolesAfter != null)
guild.addRoleToMember(member, filteredRoles[0]).reason("Autorole").queueAfter(autoroleConfig.giveRolesAfter!!, TimeUnit.SECONDS)
else
guild.addRoleToMember(member, filteredRoles[0]).reason("Autorole").queue()
} else {
if (autoroleConfig.giveRolesAfter != null)
guild.modifyMemberRoles(member, member.roles.toMutableList().apply { this.addAll(filteredRoles) }).reason("Autorole").queueAfter(autoroleConfig.giveRolesAfter!!, TimeUnit.SECONDS)
else
guild.modifyMemberRoles(member, member.roles.toMutableList().apply { this.addAll(filteredRoles) }).reason("Autorole").queue()
}
}
}
} | agpl-3.0 | 9b15e44315773701da5956c8038d6b9e | 39.657143 | 184 | 0.754571 | 3.703125 | false | true | false | false |
shyiko/ktlint | ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt | 1 | 1062 | package com.pinterest.ktlint.core.internal
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
import org.ec4j.core.Cache
import org.ec4j.core.EditorConfigLoader
import org.ec4j.core.Resource
import org.ec4j.core.model.EditorConfig
/**
* In-memory [Cache] implementation that could be safely accessed from any [Thread].
*/
internal class ThreadSafeEditorConfigCache : Cache {
private val readWriteLock = ReentrantReadWriteLock()
private val inMemoryMap = HashMap<Resource, EditorConfig>()
override fun get(
editorConfigFile: Resource,
loader: EditorConfigLoader
): EditorConfig {
readWriteLock.read {
return inMemoryMap[editorConfigFile]
?: readWriteLock.write {
val result = loader.load(editorConfigFile)
inMemoryMap[editorConfigFile] = result
result
}
}
}
fun clear() = readWriteLock.write {
inMemoryMap.clear()
}
}
| mit | aaa031301d367bf027a099e94ec62f84 | 29.342857 | 84 | 0.676083 | 4.617391 | false | true | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiSearchPopup.kt | 1 | 3035 | /*
* 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.internal
import android.graphics.Bitmap
import android.graphics.Point
import android.graphics.drawable.BitmapDrawable
import android.view.Gravity
import android.view.View
import android.view.View.MeasureSpec
import android.view.WindowManager
import android.widget.EditText
import android.widget.PopupWindow
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.R
import com.vanniktech.emoji.search.SearchEmojiResult
internal fun interface EmojiSearchDelegate {
fun onEmojiClicked(emoji: Emoji)
}
internal class EmojiSearchPopup(
private val rootView: View,
private val editText: EditText,
private val theming: EmojiTheming,
) {
private var popupWindow: PopupWindow? = null
internal fun show(
emojis: List<SearchEmojiResult>,
delegate: EmojiSearchDelegate?,
) {
if (emojis.isNotEmpty()) {
val context = editText.context
val recyclerView = View.inflate(context, R.layout.emoji_popup_search, null) as MaxHeightSearchRecyclerView
recyclerView.tint(theming)
val adapter = EmojiAdapter(
theming = theming,
emojiSearchDialogDelegate = {
delegate?.onEmojiClicked(it)
dismiss()
},
)
recyclerView.adapter = adapter
val editTextLocation = Utils.locationOnScreen(editText)
adapter.update(emojis, marginStart = editTextLocation.x)
val resources = context.resources
recyclerView.measure(
MeasureSpec.makeMeasureSpec(rootView.width, MeasureSpec.EXACTLY),
0, // Internals will already limit this.
)
val height = recyclerView.measuredHeight
val desiredLocation = Point(
rootView.x.toInt(),
editTextLocation.y - height,
)
popupWindow = PopupWindow(recyclerView, WindowManager.LayoutParams.MATCH_PARENT, height).apply {
isFocusable = false
isOutsideTouchable = true
inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED
setBackgroundDrawable(BitmapDrawable(resources, null as Bitmap?)) // To avoid borders and overdraw.
showAtLocation(rootView, Gravity.NO_GRAVITY, desiredLocation.x, desiredLocation.y)
Utils.fixPopupLocation(this, desiredLocation)
}
} else {
dismiss()
}
}
internal fun dismiss() {
popupWindow?.dismiss()
popupWindow = null
}
}
| apache-2.0 | 9986827ef092ddd9f62ee626032828c0 | 31.265957 | 112 | 0.724365 | 4.533632 | false | false | false | false |
kmizu/kollection | src/main/kotlin/com/github/kmizu/kollection/KOption.kt | 1 | 2119 | package com.github.kmizu.kollection
sealed class KOption<out T>(): Iterable<T>, KFoldable<T>, KLinearSequence<T> {
class Some<T>(val value: T) : KOption<T>() {
override fun equals(other: Any?): Boolean = when(other){
is Some<*> -> value == other.value
else -> false
}
override fun hashCode(): Int = value?.hashCode() ?: 0
}
object None : KOption<Nothing>() {
override fun equals(other: Any?): Boolean = super.equals(other)
}
/**
* Extract the value from this Option.
* Note that this method should not be used as soon as possible since it is dangerous.
*/
fun get(): T = when(this) {
is Some<T> -> this.value
is None -> throw IllegalArgumentException("None")
}
override fun <U> foldLeft(z: U, function: (U, T) -> U): U = when(this) {
is Some<T> -> function(z, this.value)
is None -> z
}
override fun <U> foldRight(z: U, function: (T, U) -> U): U = when(this) {
is Some<T> -> function(this.value, z)
is None -> z
}
override val hd: T
get() = when(this) {
is Some<T> -> this.value
is None -> throw IllegalArgumentException("None")
}
override val tl: KOption<T>
get() = when(this) {
is Some<T> -> None
is None -> throw IllegalArgumentException("None")
}
override val isEmpty: Boolean
get() = when(this) {
is Some<T> -> false
is None -> true
}
fun <U> map(function: (T) -> U): KOption<U> = when(this) {
is Some<T> -> Some(function(this.value))
is None -> None
}
fun <U> flatMap(function: (T) -> KOption<U>): KOption<U> = when(this) {
is Some<T> -> function(this.value)
is None -> None
}
fun filter(function: (T) -> Boolean): KOption<T> = when(this) {
is Some<T> -> if(function(this.value)) this else None
is None -> None
}
override fun toString(): String = when(this){
is Some<*> -> "Some(${value})"
is None -> "None"
}
} | mit | 3695f3edd3bf6dbc98554f9ed7a22f46 | 28.859155 | 90 | 0.530911 | 3.678819 | false | false | false | false |
ScaCap/spring-auto-restdocs | spring-auto-restdocs-dokka-json/src/test/kotlin/capital/scalable/dokka/json/JsonFileGeneratorTest.kt | 1 | 3259 | /*-
* #%L
* Spring Auto REST Docs Dokka JSON
* %%
* Copyright (C) 2015 - 2021 Scalable Capital GmbH
* %%
* 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.
* #L%
*/
package capital.scalable.dokka.json
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.dokka.DocumentationModule
import org.jetbrains.dokka.DokkaConsoleLogger
import org.jetbrains.dokka.Platform
import org.jetbrains.dokka.contentRootFromPath
import org.jetbrains.dokka.tests.ModelConfig
import org.jetbrains.dokka.tests.verifyJavaModel
import org.jetbrains.dokka.tests.verifyModel
import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot
import org.junit.Test
import java.io.File
import kotlin.test.assertTrue
class JsonFileGeneratorTest {
private val analysisPlatform = Platform.common
private val root: File = FileUtil.createTempDirectory("dokka-json", "file-generator-test")
@Test
fun `buildPages should generate JSON files for Kotlin classes and nested classes`() {
val inputFile = "KotlinDataClass.kt"
val expectedFiles = listOf("testdata/KotlinDataClass", "testdata/KotlinDataClass.NestedClass")
verifyOutput(inputFile, verifier(expectedFiles))
}
@Test
fun `buildPages should generate JSON files for Java classes and nested classes`() {
val inputFile = "JavaClass.java"
val expectedFiles = listOf("JavaClass", "JavaClass.NestedJavaClass")
verifyJavaOutput(inputFile, verifier(expectedFiles))
}
private fun verifyOutput(inputFile: String, verifier: (DocumentationModule) -> Unit) {
verifyModel(
ModelConfig(
roots = arrayOf(
KotlinSourceRoot("testdata/$inputFile", false)
),
analysisPlatform = analysisPlatform
),
verifier = verifier
)
}
private fun verifyJavaOutput(inputFile: String, verifier: (DocumentationModule) -> Unit) {
verifyJavaModel(
"testdata/$inputFile",
verifier = verifier
)
}
private fun verifier(expectedFiles: List<String>): (DocumentationModule) -> Unit {
val fileGenerator = initFileGenerator()
val rootPath = File(root.path)
return {
fileGenerator.buildPages(listOf(it))
expectedFiles.forEach { fileName ->
val file = rootPath.resolve("$fileName.json")
assertTrue("Expected file $fileName.json was not generated") { file.exists() }
}
}
}
private fun initFileGenerator(): JsonFileGenerator {
val fileGenerator = JsonFileGenerator(root)
fileGenerator.formatService = JsonFormatService(DokkaConsoleLogger)
return fileGenerator
}
}
| apache-2.0 | 7cf8048612271ceae05b9e925edad1c7 | 34.813187 | 102 | 0.688862 | 4.757664 | false | true | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/Utils.kt | 1 | 5209 | /*
* 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.internal
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Configuration
import android.graphics.Point
import android.graphics.Rect
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.PopupWindow
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.vanniktech.emoji.EmojiAndroidProvider
import com.vanniktech.emoji.EmojiManager
import kotlin.math.roundToInt
private const val DONT_UPDATE_FLAG = -1
internal object Utils {
internal fun dpToPx(context: Context, dp: Float): Int {
return (
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp,
context.resources.displayMetrics,
) + 0.5f
).roundToInt()
}
private fun getOrientation(context: Context): Int {
return context.resources.configuration.orientation
}
internal fun getProperWidth(activity: Activity): Int {
val rect = windowVisibleDisplayFrame(activity)
return if (getOrientation(activity) == Configuration.ORIENTATION_PORTRAIT) rect.right else getScreenWidth(activity)
}
internal fun shouldOverrideRegularCondition(context: Context, editText: EditText): Boolean {
return if (editText.imeOptions and EditorInfo.IME_FLAG_NO_EXTRACT_UI == 0) {
getOrientation(context) == Configuration.ORIENTATION_LANDSCAPE
} else {
false
}
}
internal fun getProperHeight(activity: Activity): Int {
return windowVisibleDisplayFrame(activity).bottom
}
private fun getScreenWidth(context: Activity): Int {
return dpToPx(context, context.resources.configuration.screenWidthDp.toFloat())
}
internal fun locationOnScreen(view: View): Point {
val location = IntArray(2)
view.getLocationOnScreen(location)
return Point(location[0], location[1])
}
private fun windowVisibleDisplayFrame(context: Activity): Rect {
val result = Rect()
context.window.decorView.getWindowVisibleDisplayFrame(result)
return result
}
internal fun asActivity(context: Context): Activity {
var result: Context? = context
while (result is ContextWrapper) {
if (result is Activity) {
return result
}
result = result.baseContext
}
error("The passed Context is not an Activity.")
}
internal fun fixPopupLocation(popupWindow: PopupWindow, desiredLocation: Point) {
popupWindow.contentView.post {
val actualLocation = locationOnScreen(popupWindow.contentView)
if (!(actualLocation.x == desiredLocation.x && actualLocation.y == desiredLocation.y)) {
val differenceX = actualLocation.x - desiredLocation.x
val differenceY = actualLocation.y - desiredLocation.y
val fixedOffsetX = if (actualLocation.x > desiredLocation.x) {
desiredLocation.x - differenceX
} else {
desiredLocation.x + differenceX
}
val fixedOffsetY = if (actualLocation.y > desiredLocation.y) {
desiredLocation.y - differenceY
} else {
desiredLocation.y + differenceY
}
popupWindow.update(fixedOffsetX, fixedOffsetY, DONT_UPDATE_FLAG, DONT_UPDATE_FLAG)
}
}
}
@ColorInt
internal fun resolveColor(context: Context, @AttrRes resource: Int, @ColorRes fallback: Int): Int {
val value = TypedValue()
context.theme.resolveAttribute(resource, value, true)
val resolvedColor = if (value.resourceId != 0) {
ContextCompat.getColor(context, value.resourceId)
} else {
value.data
}
return if (resolvedColor != 0) {
resolvedColor
} else {
ContextCompat.getColor(context, fallback)
}
}
}
internal inline val Context.inputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
internal fun EditText.showKeyboardAndFocus() {
post {
requestFocus()
context.inputMethodManager.showSoftInput(this, 0)
}
}
internal fun EditText.hideKeyboardAndFocus() {
post {
clearFocus()
context.inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
}
internal fun EmojiManager.emojiDrawableProvider(): EmojiAndroidProvider {
val emojiProvider = emojiProvider()
require(emojiProvider is EmojiAndroidProvider) { "Your provider needs to implement EmojiDrawableProvider" }
return emojiProvider
}
| apache-2.0 | 9d36508e2f2598c3f1e0cd8e14be4e51 | 32.378205 | 123 | 0.733436 | 4.484927 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/form/field/GeometryFieldState.kt | 1 | 887 | package mil.nga.giat.mage.form.field
import com.google.android.gms.maps.model.LatLng
import mil.nga.giat.mage.form.FormField
import mil.nga.giat.mage.observation.ObservationLocation
class GeometryFieldState(
definition: FormField<ObservationLocation>,
val defaultMapZoom: Float? = null,
val defaultMapCenter: LatLng? = null
) : FieldState<ObservationLocation, FieldValue.Location>(
definition,
validator = ::isValid,
errorFor = ::errorMessage,
hasValue = ::hasValue
)
private fun errorMessage(definition: FormField<ObservationLocation>, value: FieldValue.Location?): String {
return "Please enter a value"
}
private fun isValid(definition: FormField<ObservationLocation>, value: FieldValue.Location?): Boolean {
return !definition.required || value != null
}
private fun hasValue(value: FieldValue.Location?): Boolean {
return value?.location != null
} | apache-2.0 | 72df0a66467935472621f2e0ab33d5ee | 30.714286 | 107 | 0.765502 | 4.164319 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/util/extensions/Activity.kt | 1 | 1697 | package com.ruuvi.station.util.extensions
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.ruuvi.station.BuildConfig
import com.ruuvi.station.R
fun AppCompatActivity.SendFeedback(){
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf( "[email protected]" ));
intent.putExtra(Intent.EXTRA_SUBJECT, "Ruuvi Station Android Feedback")
val body = """
Device: ${Build.MANUFACTURER} ${Build.MODEL}
Android version: ${Build.VERSION.RELEASE}
App: ${applicationInfo.loadLabel(packageManager)} ${BuildConfig.VERSION_NAME}"""
intent.putExtra(Intent.EXTRA_TEXT, body)
startActivity(Intent.createChooser(intent, getString(R.string.send_email)))
}
fun AppCompatActivity.OpenUrl(url: String){
val webIntent = Intent(Intent.ACTION_VIEW)
webIntent.data = Uri.parse(url)
startActivity(webIntent)
}
fun AppCompatActivity.hideKeyboard() {
val imm: InputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}
fun AppCompatActivity.getMainMenuItems(signed: Boolean) =
arrayOf(
getString(R.string.menu_add_new_sensor),
getString(R.string.menu_app_settings),
getString(R.string.menu_about_help),
getString(R.string.menu_send_feedback),
getString(R.string.menu_get_more_sensors),
if (signed) getString(R.string.sign_out) else getString(R.string.sign_in)
) | mit | 1f744fa481fd6dd67588f35dd44a0a31 | 35.913043 | 108 | 0.743665 | 3.964953 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/chat/ChatPresenter.kt | 1 | 18364 | package org.fossasia.susi.ai.chat
import android.os.Handler
import android.util.Log
import org.fossasia.susi.ai.MainApplication
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.chat.contract.IChatPresenter
import org.fossasia.susi.ai.chat.contract.IChatView
import org.fossasia.susi.ai.data.ChatModel
import org.fossasia.susi.ai.data.UtilModel
import org.fossasia.susi.ai.data.contract.IChatModel
import org.fossasia.susi.ai.data.db.DatabaseRepository
import org.fossasia.susi.ai.data.db.contract.IDatabaseRepository
import org.fossasia.susi.ai.helper.*
import org.fossasia.susi.ai.rest.clients.BaseUrl
import org.fossasia.susi.ai.rest.responses.others.LocationResponse
import org.fossasia.susi.ai.rest.responses.susi.MemoryResponse
import org.fossasia.susi.ai.rest.responses.susi.SusiResponse
import retrofit2.Response
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
/**
* Presentation Layer for Chat View.
*
* The P in MVP
* Created by chiragw15 on 9/7/17.
*/
class ChatPresenter(chatActivity: ChatActivity): IChatPresenter, IChatModel.OnRetrievingMessagesFinishedListener,
IChatModel.OnLocationFromIPReceivedListener, IChatModel.OnMessageFromSusiReceivedListener,
IDatabaseRepository.onDatabaseUpdateListener{
var chatView: IChatView?= null
var chatModel: IChatModel = ChatModel()
var utilModel: UtilModel = UtilModel(chatActivity)
var databaseRepository: IDatabaseRepository = DatabaseRepository()
lateinit var locationHelper: LocationHelper
val nonDeliveredMessages = LinkedList<Pair<String, Long>>()
var newMessageIndex: Long = 0
var micCheck = false
var latitude: Double = 0.0
var longitude: Double = 0.0
var source = Constant.IP
var isDetectionOn = false
var check = false
var atHome = true
var backPressedOnce = false
@Volatile var queueExecuting = AtomicBoolean(false)
override fun onAttach(chatView: IChatView) {
this.chatView = chatView
}
override fun setUp() {
//find total number of messages and find new message index
newMessageIndex = databaseRepository.getMessageCount() + 1
PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex)
micCheck = utilModel.checkMicInput()
chatView?.setupAdapter(databaseRepository.getAllMessages())
getPermissions()
}
override fun checkPreferences() {
micCheck = utilModel.getBooleanPref(Constant.MIC_INPUT, true)
chatView?.checkMicPref(utilModel.getBooleanPref(Constant.MIC_INPUT, true))
chatView?.checkEnterKeyPref(utilModel.getBooleanPref(Constant.ENTER_SEND, false))
}
override fun micCheck(): Boolean {
return micCheck
}
override fun micCheck(boolean: Boolean) {
micCheck = boolean
}
override fun check(boolean: Boolean) {
check = boolean
}
//initiates hotword detection
override fun initiateHotwordDetection() {
if (chatView!!.checkPermission(utilModel.permissionsToGet()[2]) &&
chatView!!.checkPermission(utilModel.permissionsToGet()[1])) {
if ( utilModel.isArmDevice() && utilModel.checkMicInput() ) {
utilModel.copyAssetstoSD()
chatView?.initHotword()
startHotwordDetection()
}
else {
utilModel.putBooleanPref(Constant.HOTWORD_DETECTION, false)
if(utilModel.getBooleanPref(Constant.NOTIFY_USER, true)){
chatView?.showToast(utilModel.getString(R.string.error_hotword))
utilModel.putBooleanPref(Constant.NOTIFY_USER, false)
}
}
}
}
override fun hotwordDetected() {
chatView?.promptSpeechInput()
}
override fun startHotwordDetection() {
if (!isDetectionOn && utilModel.getBooleanPref(Constant.HOTWORD_DETECTION, false)) {
chatView?.startRecording()
isDetectionOn = true
}
}
override fun stopHotwordDetection() {
if (isDetectionOn) {
chatView?.stopRecording()
isDetectionOn = false
}
}
override fun startSpeechInput() {
check = true
chatView?.promptSpeechInput()
}
override fun disableMicInput(boolean: Boolean) {
if(boolean) {
micCheck = false
PrefManager.putBoolean(Constant.MIC_INPUT, false)
} else {
micCheck = utilModel.checkMicInput()
PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput())
chatView?.checkMicPref(micCheck)
}
}
//Retrieves old Messages
override fun retrieveOldMessages(firstRun: Boolean) {
if(firstRun and NetworkUtils.isNetworkConnected()) {
chatView?.showRetrieveOldMessageProgress()
val thread = object : Thread() {
override fun run() {
chatModel.retrieveOldMessages(this@ChatPresenter)
}
}
thread.start()
}
}
override fun onRetrieveSuccess(response: Response<MemoryResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
val allMessages = response.body().cognitionsList
if (allMessages.isEmpty()) {
chatView?.showToast("No messages found")
} else {
var c: Long
for (i in allMessages.size - 1 downTo 0) {
val query = allMessages[i].query
val queryDate = allMessages[i].queryDate
val answerDate = allMessages[i].answerDate
val urlList = ParseSusiResponseHelper.extractUrls(query)
val isHavingLink = !urlList.isEmpty()
newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0)
if (newMessageIndex == 0L) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", "", this)
} else {
val prevDate = DateTimeHelper.getDate(allMessages[i + 1].queryDate)
if (DateTimeHelper.getDate(queryDate) != prevDate) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", "", this)
}
}
c = newMessageIndex
databaseRepository.updateDatabase(newMessageIndex, query, false, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), true, "", null, isHavingLink, null, "", "", this)
if(allMessages[i].answers.isEmpty()) {
databaseRepository.updateDatabase(c, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", "", this)
continue
}
val actionSize = allMessages[i].answers[0].actions.size
for (j in 0..actionSize - 1) {
val psh = ParseSusiResponseHelper()
psh.parseSusiResponse(allMessages[i], j, utilModel.getString(R.string.error_occurred_try_again))
try {
databaseRepository.updateDatabase(c, psh.answer, false, DateTimeHelper.getDate(answerDate),
DateTimeHelper.getTime(answerDate), false, psh.actionType, psh.mapData, psh.isHavingLink,
psh.datumList, psh.webSearch, allMessages[i].answers[0].skills[0], this)
} catch (e: Exception) {
databaseRepository.updateDatabase(c, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", "", this)
}
}
}
}
}
chatView?.hideRetrieveOldMessageProgress()
}
override fun updateMessageCount() {
newMessageIndex++
PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex)
}
override fun onRetrieveFailure() {
chatView?.hideRetrieveOldMessageProgress()
}
//Gets Location of user using his IP Address
override fun getLocationFromIP() {
chatModel.getLocationFromIP(this)
}
override fun onLocationSuccess(response: Response<LocationResponse>) {
if (response.isSuccessful && response.body() != null) {
try {
val loc = response.body().loc
val s = loc.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
latitude = s[0].toDouble()
longitude = s[1].toDouble()
source = Constant.IP
} catch (e: Exception) {
e.printStackTrace()
}
}
}
//Gets Location of user using gps and network
override fun getLocationFromLocationService() {
locationHelper = LocationHelper(MainApplication.getInstance().applicationContext)
getLocation()
}
fun getLocation() {
locationHelper.getLocation()
if (locationHelper.canGetLocation()) {
latitude = locationHelper.latitude
longitude = locationHelper.longitude
source = locationHelper.source
}
}
//get undelivered messages from database
override fun getUndeliveredMessages() {
nonDeliveredMessages.clear()
val nonDelivered = databaseRepository.getUndeliveredMessages()
nonDelivered.mapTo(nonDeliveredMessages) { Pair(it.content, it.id) }
}
//sends message to susi
override fun sendMessage(query: String, actual: String) {
addToNonDeliveredList(query, actual)
computeThread().start()
}
override fun addToNonDeliveredList(query: String, actual: String) {
val urlList = ParseSusiResponseHelper.extractUrls(query)
val isHavingLink = !urlList.isEmpty()
newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0)
if (newMessageIndex == 0L) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date,
DateTimeHelper.currentTime, false, "", null, false, null, "", "", this)
} else {
val s = databaseRepository.getAMessage(newMessageIndex-1).date
if (DateTimeHelper.date != s) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date,
DateTimeHelper.currentTime, false, "", null, false, null, "", "", this)
}
}
nonDeliveredMessages.add(Pair(query, newMessageIndex))
databaseRepository.updateDatabase(newMessageIndex, actual, false, DateTimeHelper.date,
DateTimeHelper.currentTime, true, "", null, isHavingLink, null, "", "", this)
getLocationFromLocationService()
}
override fun startComputingThread() {
computeThread().start()
}
private inner class computeThread : Thread() {
override fun run() {
if(queueExecuting.compareAndSet(false,true)) {
computeOtherMessage()
}
}
}
@Synchronized
fun computeOtherMessage() { Log.v("chirag","chirag run")
if (!nonDeliveredMessages.isEmpty()) {
if (NetworkUtils.isNetworkConnected()) {
chatView?.showWaitingDots()
val tz = TimeZone.getDefault()
val now = Date()
val timezoneOffset = -1 * (tz.getOffset(now.time) / 60000)
val query = nonDeliveredMessages.first.first
val language = if (PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT).equals(Constant.DEFAULT)) Locale.getDefault().language else PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT)
chatModel.getSusiMessage(timezoneOffset, longitude, latitude, source, language, query, this)
} else run {
queueExecuting.set(false)
chatView?.hideWaitingDots()
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
}
}
else {
queueExecuting.set(false)
}
}
override fun onSusiMessageReceivedFailure(t: Throwable) {
chatView?.hideWaitingDots()
if(nonDeliveredMessages.isEmpty())
return
val id = nonDeliveredMessages.first.second
val query = nonDeliveredMessages.first.first
nonDeliveredMessages.pop()
if (!NetworkUtils.isNetworkConnected()) {
nonDeliveredMessages.addFirst(Pair(query, id))
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
} else {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER,
null, false, null, "", "", this)
}
BaseUrl.updateBaseUrl(t)
computeOtherMessage()
}
override fun onSusiMessageReceivedSuccess(response: Response<SusiResponse>?) {
if(nonDeliveredMessages.isEmpty())
return
val id = nonDeliveredMessages.first.second
val query = nonDeliveredMessages.first.first
nonDeliveredMessages.pop()
if (response != null && response.isSuccessful && response.body() != null) {
val susiResponse = response.body()
if(response.body().answers.isEmpty()) {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", "", this)
return
}
val actionSize = response.body().answers[0].actions.size
val date = response.body().answerDate
for (i in 0..actionSize - 1) {
val delay = response.body().answers[0].actions[i].delay
val actionNo = i
val handler = Handler()
handler.postDelayed({
val psh = ParseSusiResponseHelper()
psh.parseSusiResponse(susiResponse, actionNo, utilModel.getString(R.string.error_occurred_try_again))
val setMessage = psh.answer
if (psh.actionType == Constant.ANSWER && (PrefManager.checkSpeechOutputPref() && check || PrefManager.checkSpeechAlwaysPref())){
var speechReply = setMessage
if (psh.isHavingLink) {
speechReply = setMessage.substring(0, setMessage.indexOf("http"))
}
chatView?.voiceReply(speechReply, susiResponse.answers[0].actions[i].language)
}
try {
databaseRepository.updateDatabase(id, setMessage, false, DateTimeHelper.getDate(date),
DateTimeHelper.getTime(date), false, psh.actionType, psh.mapData, psh.isHavingLink,
psh.datumList, psh.webSearch, susiResponse.answers[0].skills[0], this)
} catch (e: Exception) {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", "", this)
}
}, delay)
}
chatView?.hideWaitingDots()
} else {
if (!NetworkUtils.isNetworkConnected()) {
nonDeliveredMessages.addFirst(Pair(query, id))
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
} else {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", "", this)
}
chatView?.hideWaitingDots()
}
computeOtherMessage()
}
override fun onDatabaseUpdateSuccess() {
chatView?.databaseUpdated()
}
//Asks for permissions from user
fun getPermissions() {
val permissionsRequired = utilModel.permissionsToGet()
val permissionsGranted = arrayOfNulls<String>(3)
var c = 0
for(permission in permissionsRequired) {
if(!(chatView?.checkPermission(permission) as Boolean)) {
permissionsGranted[c] = permission
c++
}
}
if(c > 0) {
chatView?.askForPermission(permissionsGranted)
}
if(!(chatView?.checkPermission(permissionsRequired[1]) as Boolean)) {
PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput())
}
}
override fun exitChatActivity() {
if (atHome) {
if (backPressedOnce) {
chatView?.finishActivity()
return
}
backPressedOnce = true
chatView?.showToast(utilModel.getString(R.string.exit))
Handler().postDelayed({ backPressedOnce = false }, 2000)
} else if (!atHome) {
atHome = true
}
}
override fun onDetach() {
locationHelper.removeListener()
databaseRepository.closeDatabase()
chatView = null
}
} | apache-2.0 | 462c1f842d2f1b98a6a636d0c2f64af8 | 39.010893 | 212 | 0.600632 | 5.215564 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | data/src/main/kotlin/de/ph1b/audiobook/data/repo/internals/migrations/Migration28to29.kt | 2 | 1370 | package de.ph1b.audiobook.data.repo.internals.migrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import org.json.JSONObject
import timber.log.Timber
import java.io.File
class Migration28to29 : IncrementalMigration(28) {
override fun migrate(db: SupportSQLiteDatabase) {
db.query("TABLE_BOOK", arrayOf("BOOK_JSON", "BOOK_ID"))
.use { cursor ->
while (cursor.moveToNext()) {
val book = JSONObject(cursor.getString(0))
val chapters = book.getJSONArray("chapters")
for (i in 0 until chapters.length()) {
val chapter = chapters.getJSONObject(i)
val fileName = File(chapter.getString("path")).name
val dotIndex = fileName.lastIndexOf(".")
val chapterName = if (dotIndex > 0) {
fileName.substring(0, dotIndex)
} else {
fileName
}
chapter.put("name", chapterName)
}
val cv = ContentValues()
Timber.d("so saving book=$book")
cv.put("BOOK_JSON", book.toString())
db.update(
"TABLE_BOOK",
SQLiteDatabase.CONFLICT_FAIL,
cv,
"BOOK_ID" + "=?",
arrayOf(cursor.getLong(1).toString())
)
}
}
}
}
| lgpl-3.0 | 05e8af0d34e3244b4b52b1bba9e24d40 | 31.619048 | 63 | 0.587591 | 4.477124 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepEnsureConnectionToCloud.kt | 1 | 1162 | package io.particle.mesh.setup.flow.setupsteps
import io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus
import io.particle.mesh.setup.flow.*
import io.particle.mesh.setup.flow.context.SetupContexts
import kotlinx.coroutines.delay
import mu.KotlinLogging
class StepEnsureConnectionToCloud : MeshSetupStep() {
private val log = KotlinLogging.logger {}
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
// FIXME: these delays should probably live in the flows themselves,
// using a "StepDelay" setup step
delay(1000)
var millis = 0
val limitMillis = 1000 * 45 // 45 seconds
while (millis < limitMillis) {
delay(5000)
millis += 5000
val reply = ctxs.requireTargetXceiver().sendGetConnectionStatus().throwOnErrorOrAbsent()
log.info { "reply=$reply" }
if (reply.status == ConnectionStatus.CONNECTED) {
ctxs.targetDevice.updateDeviceConnectedToCloudLD(true)
return
}
}
throw MeshSetupFlowException(message = "Error ensuring connection to cloud")
}
} | apache-2.0 | f55d888261077abfe1233f14b6966a58 | 32.228571 | 100 | 0.668675 | 4.742857 | false | false | false | false |
chat-sdk/chat-sdk-android | chat-sdk-vendor/src/main/java/smartadapter/viewevent/swipe/AutoRemoveItemSwipeEventBinder.kt | 1 | 1282 | package smartadapter.viewevent.swipe
/*
* Created by Manne Öhlund on 2019-08-17.
* Copyright (c) All rights reserved.
*/
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import smartadapter.SmartRecyclerAdapter
import smartadapter.SmartViewHolderType
import smartadapter.viewevent.model.ViewEvent
import smartadapter.viewholder.SmartAdapterHolder
import smartadapter.viewholder.SmartViewHolder
/**
* Automatically removes an item in [SmartRecyclerAdapter] when swiped.
*
* @see BasicSwipeEventBinder
*
* @see SmartAdapterHolder
*/
class AutoRemoveItemSwipeEventBinder(
override val identifier: Any = AutoRemoveItemSwipeEventBinder::class,
override var swipeFlags: SwipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT,
override var viewHolderTypes: List<SmartViewHolderType> = listOf(SmartViewHolder::class),
override var longPressDragEnabled: Boolean = false,
override var eventListener: (ViewEvent.OnItemSwiped) -> Unit
) : BasicSwipeEventBinder(
eventListener = eventListener
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
super.onSwiped(viewHolder, direction)
smartRecyclerAdapter.removeItem(viewHolder.adapterPosition)
}
}
| apache-2.0 | f0a92395a163a0d982be10a0be7c7273 | 32.710526 | 93 | 0.795472 | 4.641304 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/DockPreferences.kt | 1 | 3822 | /*
* Copyright 2022, Lawnchair
*
* 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 app.lawnchair.ui.preferences
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavGraphBuilder
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.qsb.providers.QsbSearchProvider
import app.lawnchair.ui.preferences.components.DividerColumn
import app.lawnchair.ui.preferences.components.ExpandAndShrink
import app.lawnchair.ui.preferences.components.NavigationActionPreference
import app.lawnchair.ui.preferences.components.PreferenceGroup
import app.lawnchair.ui.preferences.components.PreferenceLayout
import app.lawnchair.ui.preferences.components.SliderPreference
import app.lawnchair.ui.preferences.components.SwitchPreference
import com.android.launcher3.R
object DockRoutes {
const val SEARCH_PROVIDER = "searchProvider"
}
fun NavGraphBuilder.dockGraph(route: String) {
preferenceGraph(route, { DockPreferences() }) { subRoute ->
searchProviderGraph(subRoute(DockRoutes.SEARCH_PROVIDER))
}
}
@Composable
fun DockPreferences() {
val prefs = preferenceManager()
val prefs2 = preferenceManager2()
PreferenceLayout(label = stringResource(id = R.string.dock_label)) {
PreferenceGroup(heading = stringResource(id = R.string.search_bar_label)) {
val hotseatQsbAdapter = prefs2.hotseatQsb.getAdapter()
SwitchPreference(
adapter = hotseatQsbAdapter,
label = stringResource(id = R.string.hotseat_qsb_label),
)
ExpandAndShrink(visible = hotseatQsbAdapter.state.value) {
DividerColumn {
SwitchPreference(
adapter = prefs2.themedHotseatQsb.getAdapter(),
label = stringResource(id = R.string.apply_accent_color_label),
)
SliderPreference(
label = stringResource(id = R.string.corner_radius_label),
adapter = prefs.hotseatQsbCornerRadius.getAdapter(),
step = 0.1F,
valueRange = 0F..1F,
showAsPercentage = true,
)
val hotseatQsbProviderAdapter by preferenceManager2().hotseatQsbProvider.getAdapter()
NavigationActionPreference(
label = stringResource(R.string.search_provider),
destination = subRoute(DockRoutes.SEARCH_PROVIDER),
subtitle = stringResource(
id = QsbSearchProvider.values()
.first { it == hotseatQsbProviderAdapter }
.name,
),
)
}
}
}
PreferenceGroup(heading = stringResource(id = R.string.grid)) {
SliderPreference(
label = stringResource(id = R.string.dock_icons),
adapter = prefs.hotseatColumns.getAdapter(),
step = 1,
valueRange = 3..10,
)
}
}
}
| gpl-3.0 | 1d6d9b4517489e40377d86170266141e | 41 | 105 | 0.637886 | 4.844106 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/reportings/PurityViolationReporting.kt | 1 | 2942 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.reportings
import compiler.ast.Executable
import compiler.ast.type.FunctionModifier
import compiler.binding.BoundAssignmentStatement
import compiler.binding.BoundExecutable
import compiler.binding.BoundFunction
import compiler.binding.expression.BoundIdentifierExpression
import compiler.binding.expression.BoundInvocationExpression
abstract class PurityViolationReporting protected constructor(val violation: BoundExecutable<Executable<*>>, function: BoundFunction, message: String)
: Reporting(Level.ERROR, message, violation.declaration.sourceLocation)
class ReadInPureContextReporting internal constructor(readingExpression: BoundIdentifierExpression, function: BoundFunction) : PurityViolationReporting(
readingExpression,
function,
"pure function ${function.name} cannot read ${readingExpression.identifier} (is not within the pure boundary)"
)
class ImpureInvocationInPureContextReporting internal constructor(invcExpr: BoundInvocationExpression, function: BoundFunction) : PurityViolationReporting(
invcExpr,
function,
"pure function ${function.name} cannot invoke impure function ${invcExpr.dispatchedFunction!!.name}"
)
class ModifyingInvocationInReadonlyContextReporting internal constructor(invcExpr: BoundInvocationExpression, function: BoundFunction) : PurityViolationReporting(
invcExpr,
function,
"readonly function ${function.name} cannot invoke modifying function ${invcExpr.dispatchedFunction!!.name}"
)
class StateModificationOutsideOfPurityBoundaryReporting internal constructor(assignment: BoundAssignmentStatement, function: BoundFunction) : PurityViolationReporting(
assignment,
function,
{
val functionType = if (FunctionModifier.PURE in function.modifiers) FunctionModifier.PURE else FunctionModifier.READONLY
val functionTypeAsString = functionType.name[0].toUpperCase() + functionType.name.substring(1).toLowerCase()
val boundaryType = if (functionType == FunctionModifier.PURE) "purity" else "readonlyness"
"$functionTypeAsString function ${function.name} cannot assign state outside of its $boundaryType boundary"
}()
) | lgpl-3.0 | 8610851493f8eb14f99948b33d51f569 | 48.05 | 167 | 0.797417 | 4.775974 | false | false | false | false |
amith01994/intellij-community | plugins/settings-repository/src/BaseRepositoryManager.kt | 6 | 6583 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.merge.MergeProvider2
import com.intellij.openapi.vcs.merge.MultipleFileMergeDialog
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtilRt
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
public abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManager {
protected val lock: ReentrantReadWriteLock = ReentrantReadWriteLock()
override fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) {
var files: Array<out File>? = null
lock.read {
files = File(dir, path).listFiles({ file, name -> filter(name) })
}
if (files == null || files!!.isEmpty()) {
return
}
for (file in files!!) {
if (file.isDirectory() || file.isHidden()) {
continue;
}
// we ignore empty files as well - delete if corrupted
if (file.length() == 0L) {
if (file.exists()) {
try {
LOG.warn("File $path is empty (length 0), will be removed")
delete(file, path)
}
catch (e: Exception) {
LOG.error(e)
}
}
continue;
}
if (!processor(file.name, file.inputStream())) {
break;
}
}
}
override fun deleteRepository() {
FileUtil.delete(dir)
}
protected open fun isPathIgnored(path: String): Boolean = false
override fun read(path: String): InputStream? {
if (isPathIgnored(path)) {
if (LOG.isDebugEnabled()) {
LOG.debug("$path is ignored")
}
return null
}
var fileToDelete: File? = null
lock.read {
val file = File(dir, path)
// we ignore empty files as well - delete if corrupted
if (file.length() == 0L) {
fileToDelete = file
}
else {
return FileInputStream(file)
}
}
try {
lock.write {
if (fileToDelete!!.exists() && fileToDelete!!.length() == 0L) {
LOG.warn("File $path is empty (length 0), will be removed")
delete(fileToDelete!!, path)
}
}
}
catch (e: Exception) {
LOG.error(e)
}
return null
}
override fun write(path: String, content: ByteArray, size: Int): Boolean {
if (isPathIgnored(path)) {
if (LOG.isDebugEnabled()) {
LOG.debug("$path is ignored")
}
return false
}
if (LOG.isDebugEnabled()) {
LOG.debug("Write $path")
}
try {
lock.write {
val file = File(dir, path)
FileUtil.writeToFile(file, content, 0, size)
addToIndex(file, path, content, size)
}
}
catch (e: Exception) {
LOG.error(e)
return false
}
return true
}
/**
* path relative to repository root
*/
protected abstract fun addToIndex(file: File, path: String, content: ByteArray, size: Int)
override fun delete(path: String) {
if (LOG.isDebugEnabled()) {
LOG.debug("Remove $path")
}
lock.write {
val file = File(dir, path)
// delete could be called for non-existent file
if (file.exists()) {
delete(file, path)
}
}
}
private fun delete(file: File, path: String) {
val isFile = file.isFile()
file.removeWithParentsIfEmpty(dir, isFile)
deleteFromIndex(path, isFile)
}
protected abstract fun deleteFromIndex(path: String, isFile: Boolean)
override fun has(path: String) = lock.read { File(dir, path).exists() }
}
fun File.removeWithParentsIfEmpty(root: File, isFile: Boolean = true) {
FileUtil.delete(this)
if (isFile) {
// remove empty directories
var parent = this.getParentFile()
while (parent != null && parent != root && parent.delete()) {
parent = parent.getParentFile()
}
}
}
var conflictResolver: ((files: List<VirtualFile>, mergeProvider: MergeProvider2) -> Unit)? = null
fun resolveConflicts(files: List<VirtualFile>, mergeProvider: MergeProvider2): List<VirtualFile> {
if (ApplicationManager.getApplication()!!.isUnitTestMode()) {
if (conflictResolver == null) {
throw CannotResolveConflictInTestMode()
}
else {
conflictResolver!!(files, mergeProvider)
}
return files
}
var processedFiles: List<VirtualFile>? = null
invokeAndWaitIfNeed {
val fileMergeDialog = MultipleFileMergeDialog(null, files, mergeProvider, object : MergeDialogCustomizer() {
override fun getMultipleFileDialogTitle() = "Settings Repository: Files Merged with Conflicts"
})
fileMergeDialog.show()
processedFiles = fileMergeDialog.getProcessedFiles()
}
return processedFiles!!
}
class RepositoryVirtualFile(private val path: String) : LightVirtualFile(PathUtilRt.getFileName(path), StdFileTypes.XML, "", CharsetToolkit.UTF8_CHARSET, 1L) {
var content: ByteArray? = null
private set
override fun getPath() = path
override fun setBinaryContent(content: ByteArray, newModificationStamp: Long, newTimeStamp: Long, requestor: Any?) {
$content = content
}
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream {
throw IllegalStateException("You must use setBinaryContent")
}
override fun setContent(requestor: Any?, content: CharSequence, fireEvent: Boolean) {
throw IllegalStateException("You must use setBinaryContent")
}
} | apache-2.0 | 0915a38a2424bb62f3f42c7925671144 | 28.262222 | 159 | 0.670211 | 4.260841 | false | false | false | false |
tinypass/piano-sdk-for-android | composer-c1x/src/main/java/io/piano/android/composer/c1x/C1xInterceptor.kt | 1 | 2514 | package io.piano.android.composer.c1x
import io.piano.android.composer.ExperienceInterceptor
import io.piano.android.composer.model.ExperienceRequest
import io.piano.android.composer.model.ExperienceResponse
import io.piano.android.composer.model.events.ExperienceExecute
import io.piano.android.cxense.CxenseSdk
import io.piano.android.cxense.model.CustomParameter
import io.piano.android.cxense.model.ExternalUserId
import io.piano.android.cxense.model.PageViewEvent
import timber.log.Timber
class C1xInterceptor(
private val siteId: String
) : ExperienceInterceptor {
override fun beforeExecute(
request: ExperienceRequest
) {
check(!request.url.isNullOrEmpty() || !request.contentId.isNullOrEmpty()) {
"URL or Content Id is required for C1X"
}
}
override fun afterExecute(request: ExperienceRequest, response: ExperienceResponse) {
response.apply {
if (cxenseCustomerPrefix == null) {
Timber.w("C1X hasn't configured")
return
}
result.events.firstOrNull {
it.eventData is ExperienceExecute
}?.eventExecutionContext?.also { experienceExecutionContext ->
val userState = when {
response.userId in listOf(null, "", "anon") -> ANON_STATE
experienceExecutionContext.accessList.isNullOrEmpty() -> REGISTERED_STATE
else -> ACTIVE_STATE
}
val externalUserId = response.userId?.let {
ExternalUserId(cxenseCustomerPrefix!!, it)
}
val event = PageViewEvent.Builder(
siteId = siteId,
location = request.url,
contentId = request.contentId,
referrer = request.referer,
customParameters = mutableListOf(CustomParameter(PARAM_USERSTATE, userState)),
).apply {
if (externalUserId != null)
addExternalUserIds(externalUserId)
}.build()
CxenseSdk.getInstance().pushEvents(event)
} ?: Timber.w("C1X can't find ExperienceExecute event")
}
}
companion object {
private const val ACTIVE_STATE = "hasActiveAccess"
private const val ANON_STATE = "anon"
private const val REGISTERED_STATE = "registered"
private const val PARAM_USERSTATE = "userState"
}
}
| apache-2.0 | 7d221341f8f315488ffa975c12c6e425 | 38.904762 | 98 | 0.615752 | 4.891051 | false | false | false | false |
pyamsoft/home-button | app/src/main/java/com/pyamsoft/homebutton/HomeButtonTheme.kt | 1 | 3668 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.homebutton
import android.app.Activity
import androidx.annotation.CheckResult
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Colors
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Shapes
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.google.android.material.R
import com.pyamsoft.pydroid.theme.PYDroidTheme
import com.pyamsoft.pydroid.theme.attributesFromCurrentTheme
import com.pyamsoft.pydroid.ui.theme.ThemeProvider
import com.pyamsoft.pydroid.ui.theme.Theming
@Composable
@CheckResult
private fun themeColors(activity: Activity, isDarkMode: Boolean): Colors {
val colors =
activity.attributesFromCurrentTheme(
R.attr.colorPrimary,
R.attr.colorOnPrimary,
R.attr.colorSecondary,
R.attr.colorOnSecondary,
)
val primary = colorResource(colors[0])
val onPrimary = colorResource(colors[1])
val secondary = colorResource(colors[2])
val onSecondary = colorResource(colors[3])
return if (isDarkMode)
darkColors(
primary = primary,
onPrimary = onPrimary,
secondary = secondary,
onSecondary = onSecondary,
// Must be specified for things like Switch color
primaryVariant = primary,
secondaryVariant = secondary,
)
else
lightColors(
primary = primary,
onPrimary = onPrimary,
secondary = secondary,
onSecondary = onSecondary,
// Must be specified for things like Switch color
primaryVariant = primary,
secondaryVariant = secondary,
)
}
@Composable
@CheckResult
private fun themeShapes(): Shapes {
return Shapes(
medium = RoundedCornerShape(4.dp),
)
}
@Composable
fun Activity.HomeButtonTheme(
themeProvider: ThemeProvider,
content: @Composable () -> Unit,
) {
this.HomeButtonTheme(
theme = if (themeProvider.isDarkTheme()) Theming.Mode.DARK else Theming.Mode.LIGHT,
content = content,
)
}
@Composable
fun Activity.HomeButtonTheme(
theme: Theming.Mode,
content: @Composable () -> Unit,
) {
val isDarkMode =
when (theme) {
Theming.Mode.LIGHT -> false
Theming.Mode.DARK -> true
Theming.Mode.SYSTEM -> isSystemInDarkTheme()
}
PYDroidTheme(
colors = themeColors(this, isDarkMode),
shapes = themeShapes(),
) {
// We update the LocalContentColor to match our onBackground. This allows the default
// content color to be more appropriate to the theme background
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colors.onBackground,
content = content,
)
}
}
| apache-2.0 | bc6297504871c38cd1ef8582e8a2b4cf | 30.084746 | 89 | 0.720284 | 4.619647 | false | false | false | false |
google/ksp | test-utils/src/main/kotlin/com/google/devtools/ksp/processor/CheckOverrideProcessor.kt | 1 | 6932 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.getClassDeclarationByName
import com.google.devtools.ksp.getDeclaredFunctions
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
class CheckOverrideProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
override fun toResult(): List<String> {
return results
}
override fun process(resolver: Resolver): List<KSAnnotated> {
fun checkOverride(overrider: KSDeclaration, overridee: KSDeclaration, containing: KSClassDeclaration? = null) {
results.add(
"${overrider.qualifiedName?.asString()} overrides ${overridee.qualifiedName?.asString()}: " +
"${containing?.let { resolver.overrides(overrider, overridee, containing) }
?: resolver.overrides(overrider, overridee)}"
)
}
val javaList = resolver.getClassDeclarationByName(resolver.getKSNameFromString("JavaList"))
as KSClassDeclaration
val kotlinList = resolver.getClassDeclarationByName(resolver.getKSNameFromString("KotlinList"))
as KSClassDeclaration
val getFunKt = resolver.getSymbolsWithAnnotation("GetAnno").single() as KSFunctionDeclaration
val getFunJava = javaList.getAllFunctions().single { it.simpleName.asString() == "get" }
val fooFunJava = javaList.getDeclaredFunctions().single { it.simpleName.asString() == "foo" }
val fooFunKt = resolver.getSymbolsWithAnnotation("FooAnno").single() as KSFunctionDeclaration
val foooFunKt = resolver.getSymbolsWithAnnotation("BarAnno").single() as KSFunctionDeclaration
val equalFunKt = kotlinList.getDeclaredFunctions().single { it.simpleName.asString() == "equals" }
val equalFunJava = javaList.getAllFunctions().single { it.simpleName.asString() == "equals" }
val bazPropKt = resolver.getSymbolsWithAnnotation("BazAnno").single() as KSPropertyDeclaration
val baz2PropKt = resolver.getSymbolsWithAnnotation("Baz2Anno").single() as KSPropertyDeclaration
val bazzPropKt = resolver.getSymbolsWithAnnotation("BazzAnno")
.filterIsInstance<KSPropertyDeclaration>().single()
val bazz2PropKt = resolver.getSymbolsWithAnnotation("Bazz2Anno").single() as KSPropertyDeclaration
checkOverride(getFunKt, getFunJava)
checkOverride(fooFunKt, fooFunJava)
checkOverride(foooFunKt, fooFunJava)
checkOverride(fooFunKt, fooFunKt)
checkOverride(equalFunKt, equalFunJava)
checkOverride(bazPropKt, baz2PropKt)
checkOverride(bazPropKt, bazz2PropKt)
checkOverride(bazzPropKt, bazz2PropKt)
checkOverride(bazzPropKt, baz2PropKt)
checkOverride(bazPropKt, bazPropKt)
val JavaImpl = resolver.getClassDeclarationByName("JavaImpl")!!
val MyInterface = resolver.getClassDeclarationByName("MyInterface")!!
val MyInterface2 = resolver.getClassDeclarationByName("MyInterface2")!!
val MyInterface2ImplWithoutType = resolver.getClassDeclarationByName("MyInterface2ImplWithoutType")!!
val MyInterface2ImplWithType = resolver.getClassDeclarationByName("MyInterface2ImplWithType")!!
val getX = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getX" }
val getY = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getY" }
val setY = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "setY" }
val setX = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "setX" }
val myInterfaceX = MyInterface.declarations.first { it.simpleName.asString() == "x" }
val myInterfaceY = MyInterface.declarations.first { it.simpleName.asString() == "y" }
val myInterface2receiveList = MyInterface2.declarations.single()
val myInterface2ImplWithoutTypereceiveList = MyInterface2ImplWithoutType.declarations.single()
val myInterface2ImplWithTypereceiveList = MyInterface2ImplWithType.declarations.single()
checkOverride(getY, getX)
checkOverride(getY, myInterfaceX)
checkOverride(getX, myInterfaceX)
checkOverride(setY, myInterfaceY)
checkOverride(setX, myInterfaceX)
checkOverride(getY, getY)
checkOverride(myInterfaceX, getY)
checkOverride(myInterfaceX, getX)
checkOverride(myInterfaceY, setY)
checkOverride(myInterfaceY, myInterfaceY)
checkOverride(myInterface2receiveList, myInterface2ImplWithoutTypereceiveList)
checkOverride(myInterface2ImplWithoutTypereceiveList, myInterface2receiveList)
checkOverride(myInterface2ImplWithTypereceiveList, myInterface2receiveList)
checkOverride(myInterface2ImplWithTypereceiveList, myInterface2ImplWithoutTypereceiveList)
val JavaDifferentReturnTypes =
resolver.getClassDeclarationByName("JavaDifferentReturnType")!!
val diffGetX = JavaDifferentReturnTypes.getDeclaredFunctions()
.first { it.simpleName.asString() == "foo" }
checkOverride(diffGetX, fooFunJava)
val base = resolver.getClassDeclarationByName("Base")!!
val baseF1 = base.declarations.filter { it.simpleName.asString() == "f1" }.single()
val baseProp = base.declarations.filter { it.simpleName.asString() == "prop" }.single()
val myInterface3 = resolver.getClassDeclarationByName("MyInterface3")!!
val myInterfaceF1 = myInterface3.declarations.filter { it.simpleName.asString() == "f1" }.single()
val myInterfaceProp = myInterface3.declarations.filter { it.simpleName.asString() == "prop" }.single()
val baseOverride = resolver.getClassDeclarationByName("BaseOverride")!!
checkOverride(baseF1, myInterfaceF1, baseOverride)
checkOverride(baseProp, myInterfaceProp, baseOverride)
val jbase = resolver.getClassDeclarationByName("JBase")!!
val jBaseOverride = resolver.getClassDeclarationByName("JBaseOverride")!!
val jbaseProp = jbase.declarations.single { it.simpleName.asString() == "getProp" }
checkOverride(jbaseProp, myInterfaceProp, jBaseOverride)
return emptyList()
}
}
| apache-2.0 | ba9117501c0bebfd61c99d197ca35c92 | 59.278261 | 119 | 0.72562 | 4.612109 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/widget/SearchBar.kt | 1 | 2681 | package io.noties.markwon.app.widget
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import io.noties.markwon.app.R
import io.noties.markwon.app.utils.KeyEventUtils
import io.noties.markwon.app.utils.KeyboardUtils
import io.noties.markwon.app.utils.TextWatcherAdapter
import io.noties.markwon.app.utils.hidden
class SearchBar(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
private val focus: View
private val textField: TextField
private val clear: View
private val cancel: View
var onSearchListener: ((String?) -> Unit)? = null
init {
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
View.inflate(context, R.layout.view_search_bar, this)
focus = findViewById(R.id.focus)
textField = findViewById(R.id.text_field)
clear = findViewById(R.id.clear)
cancel = findViewById(R.id.cancel)
// listen for text state
textField.addTextChangedListener(TextWatcherAdapter.afterTextChanged {
textFieldChanged(it)
})
fun looseFocus() {
KeyboardUtils.hide(textField)
focus.requestFocus()
}
// on back pressed - lose focus and hide keyboard
textField.onBackPressedListener = {
// hide keyboard and lose focus
looseFocus()
}
textField.setOnFocusChangeListener { _, hasFocus ->
cancel.hidden = textField.text.isEmpty() && !hasFocus
}
textField.setOnEditorActionListener { _, _, event ->
if (KeyEventUtils.isActionUp(event)) {
looseFocus()
}
return@setOnEditorActionListener true
}
clear.setOnClickListener {
textField.setText("")
// ensure that we have focus when clear is clicked
if (!textField.hasFocus()) {
textField.requestFocus()
// additionally ensure keyboard is showing
KeyboardUtils.show(textField)
}
}
cancel.setOnClickListener {
textField.setText("")
looseFocus()
}
isSaveEnabled = false
textField.isSaveEnabled = false
}
fun search(text: String) {
textField.setText(text)
}
private fun textFieldChanged(text: CharSequence) {
val isEmpty = text.isEmpty()
clear.hidden = isEmpty
cancel.hidden = isEmpty && !textField.hasFocus()
onSearchListener?.invoke(if (text.isEmpty()) null else text.toString())
}
} | apache-2.0 | 8a16684fcd2577df5c04b9ea696380f2 | 28.152174 | 88 | 0.628497 | 4.928309 | false | false | false | false |
polson/MetroTripper | app/src/main/java/com/philsoft/metrotripper/app/ui/view/MapVehicleHelper.kt | 1 | 2331 | package com.philsoft.metrotripper.app.ui.view
import android.app.Activity
import android.view.View
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.philsoft.metrotripper.R
import com.philsoft.metrotripper.app.state.VehicleAction
import com.philsoft.metrotripper.model.Trip
import com.philsoft.metrotripper.utils.createBitmap
import com.philsoft.metrotripper.utils.map.fadeIn
import com.philsoft.metrotripper.utils.map.fadeOutAndRemove
import kotlinx.android.synthetic.main.vehicle.view.*
class MapVehicleHelper(private val activity: Activity, private val map: GoogleMap) {
private val vehicleMarkers = HashSet<Marker>()
companion object {
private const val FADE_DURATION = 1000
}
fun render(action: VehicleAction) {
when (action) {
is VehicleAction.ShowVehicles -> displayVehicleMarkers(action.trips)
}
}
private fun displayVehicleMarkers(trips: List<Trip>) {
// Fade out existing vehicles
for (vehicleMarker in vehicleMarkers) {
vehicleMarker.fadeOutAndRemove(FADE_DURATION)
}
vehicleMarkers.clear()
// Fade in new vehicles
for (trip in trips) {
val vehicleMarker = createVehicleMarker(trip)
vehicleMarkers.add(vehicleMarker)
vehicleMarker.fadeIn(FADE_DURATION)
}
}
private fun createVehicleMarker(trip: Trip): Marker {
val vehicleView = buildVehicleView(trip)
return map.addMarker(
MarkerOptions().anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.title(activity.getString(R.string.vehicle) + " " + trip.route + trip.terminal)
.position(LatLng(trip.vehicleLatitude.toDouble(), trip.vehicleLongitude.toDouble()))
.icon(BitmapDescriptorFactory.fromBitmap(vehicleView.createBitmap())))
}
private fun buildVehicleView(trip: Trip): View {
val view = activity.layoutInflater.inflate(R.layout.vehicle, null)
view.vehicleNumber.text = "${trip.route}${trip.terminal}"
return view
}
}
| apache-2.0 | f991fbeca647ab573eb0ad546c78f174 | 37.85 | 108 | 0.699271 | 4.332714 | false | false | false | false |
lskycity/AndroidTools | app/src/main/java/com/lskycity/androidtools/ui/FeedbackActivity.kt | 1 | 4175 | package com.lskycity.androidtools.ui
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.*
import android.text.style.UnderlineSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.lskycity.androidtools.AppConstants
import com.lskycity.androidtools.R
import com.lskycity.androidtools.app.BaseActivity
import com.lskycity.androidtools.app.ToolApplication
import com.lskycity.androidtools.apputils.Feedback
/**
* collect feedback from user
*
* @author zhaofliu
* @since 1/6/17
*/
class FeedbackActivity : BaseActivity(), TextWatcher, View.OnClickListener {
private lateinit var feedback: EditText
private lateinit var textCount: TextView
private var clickTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feedback)
feedback = findViewById<View>(R.id.feedback_content) as EditText
feedback.addTextChangedListener(this)
textCount = findViewById<View>(R.id.text_count) as TextView
val checkNewVersion = findViewById<View>(R.id.check_new_version) as TextView
//link the check user guide activity.
val checkNewVersionString = getString(R.string.check_new_version)
val checkNewVersionSpannable = SpannableString(checkNewVersionString)
checkNewVersionSpannable.setSpan(UnderlineSpan(), 0, checkNewVersionString.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
checkNewVersion.text = checkNewVersionSpannable
checkNewVersion.setOnClickListener(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_feedback, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_send) {
sendFeedback(feedback.text.toString())
return true
}
return false
}
private fun sendFeedback(content: String) {
val currentTime = System.currentTimeMillis()
if (currentTime - clickTime < 2000) {
return
}
clickTime = currentTime
if (TextUtils.isEmpty(content.trim { it <= ' ' })) {
Toast.makeText(this@FeedbackActivity, R.string.send_feedback_empty, Toast.LENGTH_LONG).show()
return
}
val request = JsonObjectRequest(Request.Method.POST, AppConstants.FEEDBACK_URL, Feedback.obtain(this, content).toJSONObject(), Response.Listener {
Toast.makeText(this@FeedbackActivity, R.string.send_feedback_success, Toast.LENGTH_LONG).show()
supportFinishAfterTransition()
},
Response.ErrorListener { volleyError -> Toast.makeText(this@FeedbackActivity, getString(R.string.send_feedback_fail) + ", " + volleyError.message, Toast.LENGTH_LONG).show() })
ToolApplication.get().requestQueue.add(request)
Toast.makeText(this@FeedbackActivity, R.string.sending_feedback, Toast.LENGTH_SHORT).show()
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
@SuppressLint("SetTextI18n")
override fun afterTextChanged(s: Editable) {
textCount.text = s.length.toString() + "/125"
if (s.length == MAX_TEXT_COUNT) {
textCount.setTextColor(Color.RED)
} else {
textCount.setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, theme))
}
}
override fun onClick(v: View) {
if (v.id == R.id.check_new_version) {
AppConstants.startUrlWithCustomTab(this, AppConstants.MAIN_PAGE_URL)
}
}
companion object {
private val MAX_TEXT_COUNT = 125
}
}
| apache-2.0 | 15d937965834aaa9dc902fa5902bf8b9 | 32.669355 | 191 | 0.702275 | 4.326425 | false | false | false | false |
rumboalla/apkupdater | app/src/main/java/com/apkupdater/model/ui/AppSearch.kt | 1 | 458 | package com.apkupdater.model.ui
import com.apkupdater.util.adapter.Id
import com.apkupdater.util.crc.crc16
data class AppSearch(
val name: String,
val url: String = "",
val iconurl: String = "",
val developer: String = "",
val source: Int = 0,
val packageName: String = "",
val versionCode: Int = 0,
override val id: Int = crc16("$name$url$iconurl$developer$source$packageName$versionCode"),
var loading: Boolean = false
): Id { companion object } | gpl-3.0 | 26e5245e337a3ab58ac119e53d3c0be2 | 27.6875 | 92 | 0.718341 | 3.248227 | false | false | false | false |
googlecodelabs/fido2-codelab | android/app/src/main/java/com/example/android/fido2/ui/home/CredentialAdapter.kt | 2 | 2261 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* 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.example.android.fido2.ui.home
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.fido2.api.Credential
import com.example.android.fido2.databinding.CredentialItemBinding
class CredentialAdapter(
private val onDeleteClicked: (String) -> Unit
) : ListAdapter<Credential, CredentialViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CredentialViewHolder {
return CredentialViewHolder(
CredentialItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
onDeleteClicked
)
}
override fun onBindViewHolder(holder: CredentialViewHolder, position: Int) {
holder.binding.credential = getItem(position)
}
}
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Credential>() {
override fun areItemsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem == newItem
}
}
class CredentialViewHolder(
val binding: CredentialItemBinding,
onDeleteClicked: (String) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.delete.setOnClickListener {
binding.credential?.let { c ->
onDeleteClicked(c.id)
}
}
}
}
| apache-2.0 | 81daba7bb0ebb28dbb07c61eed97a41e | 32.25 | 93 | 0.707651 | 4.710417 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/PhysicsRoot.kt | 1 | 5267 | package com.binarymonks.jj.core.physics
import box2dLight.Light
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.Joint
import com.badlogic.gdx.physics.box2d.Transform
import com.badlogic.gdx.utils.Array
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.async.OneTimeTask
import com.binarymonks.jj.core.pools.Poolable
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.scenes.Scene
import com.binarymonks.jj.core.utils.NamedArray
private val COLLISION_MASK_CACHE = "collision_mask_cache"
private val COLLISION_CAT_CACHE = "collision_cat_cache"
private val jointsToDestroy = Array<Joint>()
private val physicsPoolLocation = Vector2(10000f, 10000f)
private val NONE: Short = 0x0000
open class PhysicsRoot(val b2DBody: Body) {
var parent: Scene? = null
set(value) {
field = value
b2DBody.userData = value
collisionResolver.me = value
nodes.forEach { it.collisionResolver.me = value }
}
var nodes: NamedArray<PhysicsNode> = NamedArray()
var collisionResolver: CollisionResolver = CollisionResolver()
var lights: NamedArray<Light> = NamedArray()
fun position(): Vector2 {
return b2DBody.position
}
fun rotationR(): Float {
return b2DBody.angle
}
fun setPosition(x: Float, y: Float) {
b2DBody.setTransform(x, y, b2DBody.angle)
}
fun setPosition(position: Vector2) {
b2DBody.setTransform(position.x, position.y, b2DBody.angle)
}
fun setRotationR(rotation: Float) {
val position = b2DBody.position
b2DBody.setTransform(position.x, position.y, rotation)
}
val transform: Transform
get() = b2DBody.transform
fun hasProperty(propertyKey: String): Boolean {
if (parent != null) return parent!!.hasProp(propertyKey)
return false
}
fun getProperty(propertyKey: String): Any? {
if (parent != null) return parent!!.getProp(propertyKey)
return null
}
internal fun destroy(pooled: Boolean) {
collisionResolver.collisions.onRemoveFromWorld()
if (!pooled) {
JJ.B.physicsWorld.b2dworld.destroyBody(b2DBody)
} else {
neutralise()
}
}
internal fun neutralise() {
if (!JJ.B.physicsWorld.isUpdating) {
for (node in nodes) {
node.unStashFilter()
}
for (fixture in b2DBody.fixtureList) {
val sceneNode = fixture.userData as PhysicsNode
sceneNode.properties.put(COLLISION_CAT_CACHE, fixture.filterData.categoryBits)
sceneNode.properties.put(COLLISION_MASK_CACHE, fixture.filterData.maskBits)
val filterData = fixture.filterData
filterData.categoryBits = NONE
filterData.maskBits = NONE
fixture.filterData = filterData
}
jointsToDestroy.clear()
for (joint in b2DBody.jointList) {
jointsToDestroy.add(joint.joint)
}
for (joint in jointsToDestroy) {
JJ.B.physicsWorld.b2dworld.destroyJoint(joint)
}
jointsToDestroy.clear()
b2DBody.setTransform(physicsPoolLocation, 0f)
b2DBody.setLinearVelocity(Vector2.Zero)
b2DBody.setAngularVelocity(0f)
b2DBody.setActive(false)
b2DBody.setAwake(false)
for (light in lights) {
light.isActive = false
}
} else {
JJ.tasks.addPostPhysicsTask(
new(NeutralisePhysics::class)
.setRoot(this)
)
}
}
fun reset(x: Float, y: Float, rotationD: Float) {
for (fixture in b2DBody.fixtureList) {
val fixtureGameData = fixture.userData as PhysicsNode
val filterData = fixture.filterData
filterData.categoryBits = fixtureGameData.properties.get(COLLISION_CAT_CACHE) as Short
filterData.maskBits = fixtureGameData.properties.get(COLLISION_MASK_CACHE) as Short
fixture.filterData = filterData
}
b2DBody.setTransform(x, y, rotationD * MathUtils.degreesToRadians)
b2DBody.isActive = true
b2DBody.isAwake = true
for (light in lights) {
light.isActive = true
}
}
fun addNode(physicsNode: PhysicsNode) {
if(physicsNode.name != null){
nodes.add(physicsNode.name!!,physicsNode)
}else{
nodes.add(physicsNode)
}
}
fun getNode(name:String): PhysicsNode? {
return nodes.get(name)
}
fun onAddToWorld() {
collisionResolver.collisions.onAddToWorld()
}
}
class NeutralisePhysics : OneTimeTask(), Poolable {
internal var physicsRoot: PhysicsRoot? = null
fun setRoot(physicsRoot: PhysicsRoot): NeutralisePhysics {
this.physicsRoot = physicsRoot
return this
}
override fun reset() {
physicsRoot = null
}
override fun doOnce() {
checkNotNull(physicsRoot).neutralise()
}
}
| apache-2.0 | 51cd5583c3810ed75a78ccb4e77439ed | 30.16568 | 98 | 0.628062 | 4.073473 | false | false | false | false |
b95505017/android-architecture-components | PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inMemory/byItem/InMemoryByItemRepository.kt | 1 | 2949 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.paging.pagingwithnetwork.reddit.repository.inMemory.byItem
import android.arch.lifecycle.Transformations
import android.arch.paging.LivePagedListBuilder
import android.arch.paging.PagedList
import android.support.annotation.MainThread
import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi
import com.android.example.paging.pagingwithnetwork.reddit.repository.Listing
import com.android.example.paging.pagingwithnetwork.reddit.repository.RedditPostRepository
import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost
import java.util.concurrent.Executor
/**
* Repository implementation that returns a Listing that loads data directly from the network
* and uses the Item's name as the key to discover prev/next pages.
*/
class InMemoryByItemRepository(
private val redditApi: RedditApi,
private val networkExecutor: Executor) : RedditPostRepository {
@MainThread
override fun postsOfSubreddit(subredditName: String, pageSize: Int): Listing<RedditPost> {
val sourceFactory = SubRedditDataSourceFactory(redditApi, subredditName, networkExecutor)
val pagedListConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(pageSize * 2)
.setPageSize(pageSize)
.build()
val pagedList = LivePagedListBuilder(sourceFactory, pagedListConfig)
// provide custom executor for network requests, otherwise it will default to
// Arch Components' IO pool which is also used for disk access
.setBackgroundThreadExecutor(networkExecutor)
.build()
val refreshState = Transformations.switchMap(sourceFactory.sourceLiveData) {
it.initialLoad
}
return Listing(
pagedList = pagedList,
networkState = Transformations.switchMap(sourceFactory.sourceLiveData, {
it.networkState
}),
retry = {
sourceFactory.sourceLiveData.value?.retryAllFailed()
},
refresh = {
sourceFactory.sourceLiveData.value?.invalidate()
},
refreshState = refreshState
)
}
}
| apache-2.0 | d02cda215279ec309df8b06c9d04a56a | 42.367647 | 97 | 0.695829 | 5.102076 | false | false | false | false |
opengl-8080/kotlin-lifegame | src/main/kotlin/gl8080/lifegame/logic/definition/GameDefinition.kt | 1 | 2525 | package gl8080.lifegame.logic.definition
import gl8080.lifegame.logic.AbstractEntity
import gl8080.lifegame.logic.LifeGame
import gl8080.lifegame.logic.LifeGameCell
import gl8080.lifegame.logic.Position
import gl8080.lifegame.logic.exception.IllegalParameterException
import gl8080.lifegame.util.NestedLoop
import java.util.*
import javax.persistence.*
/**
* ゲーム定義を表すクラス。
*/
@Entity
@Table(name="GAME_DEFINITION")
class GameDefinition(
private val size: Int
): AbstractEntity(), LifeGame {
companion object {
/**ゲームのサイズに指定できる最大値*/
val MAX_SIZE = 50
}
@Version
private var version: Long? = null
@OneToMany(cascade = arrayOf(CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE))
@JoinColumn(name="GAME_DEFINITION_ID")
private val cells: Map<Position, CellDefinition>
init {
if (this.size < 1) {
throw IllegalParameterException("サイズに0以外の値は指定できません size = ${this.size}")
} else if (MAX_SIZE < this.size) {
throw IllegalParameterException("サイズに $MAX_SIZE 以上の値は指定できません size = ${this.size}")
}
this.cells = NestedLoop.collectMap(this.size, {i: Int, j: Int -> Position(i, j)}, { -> CellDefinition()})
}
/**
* 指定した位置のセル定義の状態を変更します。
*
* @param position 位置
* @param status 生存に変更する場合は {@code true}
* @throws IllegalArgumentException 位置が {@code null} の場合
* @throws IllegalParameterException 位置に指定した場所にセル定義が存在しない場合
*/
fun setStatus(position: Position, status: Boolean) {
val cell = this.cells[position]
?: throw IllegalParameterException("位置が範囲外です (size = ${this.size}, position = $position)")
cell.setStatus(status)
}
override fun getCells(): Map<Position, LifeGameCell> = HashMap(this.cells)
override fun getVersion() = this.version
fun setVersion(version: Long?) {
this.version = version
}
override fun getSize() = this.size
override fun toString(): String{
return "GameDefinition(id=${this.getId()}, size=$size, version=$version, cells=$cells)"
}
@Deprecated(message="JPA 用", level = DeprecationLevel.ERROR)
constructor() : this(1)
}
| mit | 663185f3d90dd51f1288f8767e103e33 | 29 | 113 | 0.650906 | 3.558176 | false | false | false | false |
CarrotCodes/Pellet | server/src/main/kotlin/dev/pellet/server/codec/http/HTTPHeaderConstants.kt | 1 | 356 | package dev.pellet.server.codec.http
object HTTPHeaderConstants {
const val contentLength = "Content-Length"
const val contentType = "Content-Type"
const val transferEncoding = "Transfer-Encoding"
const val chunked = "chunked"
const val connection = "Connection"
const val keepAlive = "keep-alive"
const val close = "close"
}
| apache-2.0 | f58be9024c10a6e895f14817a1dca5d0 | 28.666667 | 52 | 0.713483 | 4.188235 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/light/SkyLightSystem.kt | 1 | 4982 | package com.fracturedskies.light
import com.fracturedskies.api.*
import com.fracturedskies.api.block.Block
import com.fracturedskies.api.block.data.SkyLight
import com.fracturedskies.engine.api.Cause
import com.fracturedskies.engine.collections.*
import com.fracturedskies.engine.math.Vector3i
import java.lang.Integer.max
import java.util.*
import javax.enterprise.event.Observes
import javax.inject.*
import kotlin.collections.HashSet
@Singleton
class SkyLightSystem {
@Inject
lateinit var world: World
private var initialized = false
private lateinit var light: IntMutableSpace
private lateinit var opaque: BooleanMutableSpace
fun onWorldGenerated(@Observes message: WorldGenerated) {
message.blocks.forEach(this::updateLocalCache)
val sky = mutableListOf<Vector3i>()
(0 until world.width).forEach { x ->
(0 until world.depth).forEach { z ->
sky.add(Vector3i(x, world.height - 1, z))
}
}
refresh(sky)
}
fun onBlocksUpdated(@Observes message: BlocksUpdated) {
message.blocks.forEach { update -> updateLocalCache(update.position, update.target) }
refresh(message.blocks
.filter { it.original.type.opaque != it.target.type.opaque || it.original[SkyLight::class] != it.target[SkyLight::class] }
.map(BlockUpdate::position))
}
private fun updateLocalCache(position: Vector3i, target: Block) {
if (!initialized) {
light = IntMutableSpace(world.dimension, {0})
opaque = BooleanMutableSpace(world.dimension, {false})
initialized = true
}
light[position] = target[SkyLight::class]!!.value
opaque[position] = target.type.opaque
}
private fun refresh(positions: Collection<Vector3i>) {
if (positions.isEmpty()) return
val lightSources = mutableListOf<Vector3i>()
// If not opaque, propagate the light!
positions
.filter { !opaque[it] }
.toCollection(lightSources)
// If opaque, any blocks that may have been lighted by this one are updated to zero...
// Then any adjacent lights that may have lighted them are added to the list of light propagators
val darkenedCells = darken(positions.filter { opaque[it] })
darkenedCells.asSequence()
.flatMap(light::neighbors)
.toCollection(lightSources)
darkenedCells
.filter { it.y == light.height - 1 }
.toCollection(lightSources)
// Any position that is acting as a light source should propagate the light!
val lightenedCells = lighten(lightSources.filter { !opaque[it] })
// Update the world
val blocks = (darkenedCells + lightenedCells)
.filter { light[it] != world.blocks[it][SkyLight::class]!!.value }
.distinct()
.map { it to world.blocks[it].with(SkyLight(light[it])) }
.toMap()
if (blocks.isNotEmpty()) {
world.updateBlocks(blocks, Cause.of(this))
}
}
private fun darken(initialPositions: List<Vector3i>): Collection<Vector3i> {
val darkenedCells = HashSet<Vector3i>()
val unvisitedCells = LinkedList<Vector3i>()
initialPositions.asSequence().flatMap(light::neighbors)
.toCollection(unvisitedCells)
while (unvisitedCells.isNotEmpty()) {
val pos = unvisitedCells.remove()
if (light[pos] == 0) continue
light.neighbors(pos)
.filter { !darkenedCells.contains(it) }
.filter {
if (pos.y > it.y) light[pos] >= light[it]
else light[pos] > light[it]
}
.toCollection(unvisitedCells)
darkenedCells.add(pos)
light[pos] = 0
}
return darkenedCells
}
private fun targetLight(pos: Vector3i): Int {
val topPos = light.top(pos)
return when {
topPos == null -> MAX_LIGHT_LEVEL
light[topPos] == MAX_LIGHT_LEVEL -> MAX_LIGHT_LEVEL
else -> max(0, (light.neighbors(pos).map {light[it]}.max() ?: 0) - 1)
}
}
data class Lighten(val position: Vector3i, val targetLight: Int)
private fun lighten(initialPositions: List<Vector3i>): Collection<Vector3i> {
val lightenedCells = HashSet<Vector3i>()
val unvisitedCells = PriorityQueue<Lighten>({ a, b -> -a.targetLight.compareTo(b.targetLight)})
initialPositions
.asSequence()
.map { Lighten(it, targetLight(it)) }
.toCollection(unvisitedCells)
while (unvisitedCells.isNotEmpty()) {
val (pos, targetLight) = unvisitedCells.poll()
if (light[pos] >= targetLight) continue
light[pos] = targetLight
lightenedCells.add(pos)
world.neighbors(pos)
.filter { !opaque[it] }
.map {
val propagateLight = when {
targetLight == MAX_LIGHT_LEVEL && pos.y > it.y -> MAX_LIGHT_LEVEL
else -> targetLight - 1
}
Lighten(it, propagateLight)
}
.filter { light[it.position] < it.targetLight }
.filter { it.targetLight > 0 }
.toCollection(unvisitedCells)
}
return lightenedCells
}
} | unlicense | 384f2983af55001172589a768b4b6c6c | 31.357143 | 130 | 0.658169 | 3.932123 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/engine/math/Color4.kt | 1 | 1013 | package com.fracturedskies.engine.math
import org.lwjgl.BufferUtils
data class Color4(val red: Int, val green: Int, val blue: Int, val alpha: Int) {
companion object {
val WHITE = Color4(255, 255, 255, 255)
val GREEN = Color4(142, 204, 149, 255)
val DARK_GREEN = Color4(76, 118, 81, 255)
val BROWN = Color4(178, 161, 130, 255)
val GRAY = Color4(172, 175, 174, 255)
val DARK_BROWN = Color4(114, 110, 105, 255)
val BLACK = Color4(0, 0, 0, 255)
val WATER = Color4(138, 172, 206, 200)
}
fun toFloat(): Float {
val colorBuffer = BufferUtils.createByteBuffer(4)
colorBuffer.put(red.toByte())
colorBuffer.put(green.toByte())
colorBuffer.put(blue.toByte())
colorBuffer.put(alpha.toByte())
colorBuffer.flip()
return colorBuffer.asFloatBuffer().get(0)
}
operator fun div(value: Int) = Color4(red / value, green / value, blue / value, alpha / value)
operator fun times(value: Int) = Color4(red * value, green * value, blue * value, alpha * value)
} | unlicense | eab28af86a7c4c82a0d83ab619d79ad2 | 33.965517 | 98 | 0.663376 | 3.236422 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/datax/CsvReader.kt | 1 | 3633 | package me.shkschneider.skeleton.datax
import me.shkschneider.skeleton.helperx.Logger
import java.io.BufferedReader
import java.io.IOException
// <http://opencsv.sourceforge.net>
open class CsvReader(
private val bufferedReader: BufferedReader,
private val separator: Char = ',',
private val quote: Char = '"',
skip: Int = 0
) {
private var hasNext = false
@Throws(IOException::class)
private fun getNextLine(): String {
val nextLine = bufferedReader.readLine()
nextLine ?: run {
hasNext = false
throw IOException("EOF")
}
return nextLine
}
fun hasNext(): Boolean {
return hasNext
}
fun readNext(): List<String>? {
try {
val nextLine = getNextLine()
return parseLine(nextLine)
} catch (e: IOException) {
return null
}
}
@Throws(IOException::class)
private fun parseLine(nextLine: String): List<String>? {
var line: String = nextLine
val tokensOnThisLine = ArrayList<String>()
var stringBuffer = StringBuffer()
var inQuotes = false
do {
if (inQuotes) {
// continuing a quoted section, re-append newline
stringBuffer.append("\n")
line = getNextLine()
}
var i = 0
while (i < line.length) {
val c = line[i]
if (c == quote) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if (inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& line.length > i + 1 // there is indeed another character to check.
&& line[i + 1] == quote) { // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
stringBuffer.append(line[i + 1])
i++
} else {
inQuotes = !inQuotes
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if (i > 2 // not on the beginning of the line
&& line[i - 1] != separator // not at the beginning of an escape sequence
&& line.length > i + 1
&& line[i + 1] != separator) { // not at the end of an escape sequence
stringBuffer.append(c)
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(stringBuffer.toString())
stringBuffer = StringBuffer() // start work on next token
} else {
stringBuffer.append(c)
}
i++
}
} while (inQuotes)
tokensOnThisLine.add(stringBuffer.toString())
return tokensOnThisLine
}
@Throws(IOException::class)
fun close() {
bufferedReader.close()
}
init {
hasNext = true
if (skip > 0) {
try {
for (i in 0 until skip) {
bufferedReader.readLine()
}
} catch (e: IOException) {
Logger.warning(e.toString())
}
}
}
}
| apache-2.0 | 00b868579382260617665e675b1883c6 | 33.273585 | 105 | 0.48142 | 5.017956 | false | false | false | false |
android/topeka | categories/src/main/java/com/google/samples/apps/topeka/activity/CategorySelectionActivity.kt | 1 | 4904 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.transition.TransitionInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.google.samples.apps.topeka.R as baseR
import com.google.samples.apps.topeka.categories.R
import com.google.samples.apps.topeka.fragment.CategorySelectionFragment
import com.google.samples.apps.topeka.helper.ActivityLaunchHelper
import com.google.samples.apps.topeka.helper.ApiLevelHelper
import com.google.samples.apps.topeka.helper.REQUEST_LOGIN
import com.google.samples.apps.topeka.helper.REQUEST_SAVE
import com.google.samples.apps.topeka.helper.database
import com.google.samples.apps.topeka.helper.findFragmentById
import com.google.samples.apps.topeka.helper.logout
import com.google.samples.apps.topeka.helper.onSmartLockResult
import com.google.samples.apps.topeka.helper.replaceFragment
import com.google.samples.apps.topeka.helper.requestLogin
import com.google.samples.apps.topeka.model.Player
import com.google.samples.apps.topeka.widget.AvatarView
class CategorySelectionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_selection)
initializePlayer()
setUpToolbar()
if (savedInstanceState == null) {
attachCategoryGridFragment()
} else {
setProgressBarVisibility(View.GONE)
}
supportPostponeEnterTransition()
}
private fun updatePlayerViews(player: Player) {
findViewById<TextView>(R.id.title).text = player.toString()
player.avatar?.run { findViewById<AvatarView>(R.id.avatar).setAvatar(this) }
}
private fun initializePlayer() = requestLogin { updatePlayerViews(it) }
private fun setUpToolbar() {
setSupportActionBar(findViewById(R.id.toolbar_player))
supportActionBar?.setDisplayShowTitleEnabled(false)
}
private fun attachCategoryGridFragment() {
replaceFragment(R.id.category_container,
findFragmentById(R.id.category_container) ?: CategorySelectionFragment())
setProgressBarVisibility(View.GONE)
}
private fun setProgressBarVisibility(visibility: Int) {
findViewById<View>(R.id.progress).visibility = visibility
}
override fun onResume() {
super.onResume()
(findViewById<TextView>(R.id.score)).text =
getString(com.google.samples.apps.topeka.base.R.string.x_points,
database().getScore())
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(baseR.menu.menu_category, menu)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CategorySelectionFragment.REQUEST_CATEGORY) {
data?.let {
findFragmentById(R.id.category_container)?.run {
onActivityResult(requestCode, resultCode, data)
}
}
} else if (requestCode == REQUEST_LOGIN || requestCode == REQUEST_SAVE) {
onSmartLockResult(
requestCode,
resultCode,
data,
success = { },
failure = { requestLogin { updatePlayerViews(it) } })
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == baseR.id.sign_out) {
handleSignOut()
true
} else super.onOptionsItemSelected(item)
}
@SuppressLint("NewApi")
private fun handleSignOut() {
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
window.exitTransition = TransitionInflater.from(this)
.inflateTransition(R.transition.category_enter)
}
logout()
ActivityLaunchHelper.launchSignIn(this, true)
supportFinishAfterTransition()
}
}
| apache-2.0 | 336341ee1db1919dd5a00dfcf32b4177 | 36.435115 | 89 | 0.694331 | 4.613358 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/ext/ParticleEffectExt.kt | 1 | 2871 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("FunctionName", "NOTHING_TO_INLINE")
package org.lanternpowered.server.ext
import org.lanternpowered.api.util.optional.orNull
import org.spongepowered.api.block.BlockState
import org.spongepowered.api.block.BlockType
import org.spongepowered.api.data.type.NotePitch
import org.spongepowered.api.effect.particle.ParticleEffect
import org.spongepowered.api.effect.particle.ParticleOption
import org.spongepowered.api.effect.particle.ParticleOptions
import org.spongepowered.api.effect.particle.ParticleType
import org.spongepowered.api.item.ItemType
import org.spongepowered.api.item.inventory.ItemStack
import org.spongepowered.api.item.inventory.ItemStackSnapshot
import org.spongepowered.api.util.Color
import org.spongepowered.api.util.Direction
inline fun <V> ParticleEffect.option(option: ParticleOption<V>): V? = getOption(option).orNull()
inline fun <V> ParticleEffect.optionOrDefault(option: ParticleOption<V>): V? = getOptionOrDefault(option).orNull()
inline fun ParticleEffect(type: ParticleType, fn: ParticleEffect.Builder.() -> Unit = {}): ParticleEffect =
ParticleEffect.builder().type(type).apply(fn).build()
inline fun ParticleEffect.Builder.block(block: BlockState): ParticleEffect.Builder = option(ParticleOptions.BLOCK_STATE, block)
inline fun ParticleEffect.Builder.block(block: BlockType): ParticleEffect.Builder = option(ParticleOptions.BLOCK_STATE, block.defaultState)
inline fun ParticleEffect.Builder.item(item: ItemStackSnapshot): ParticleEffect.Builder = option(ParticleOptions.ITEM_STACK_SNAPSHOT, item)
inline fun ParticleEffect.Builder.item(item: ItemStack): ParticleEffect.Builder = option(ParticleOptions.ITEM_STACK_SNAPSHOT, item.createSnapshot())
inline fun ParticleEffect.Builder.item(item: ItemType): ParticleEffect.Builder =
option(ParticleOptions.ITEM_STACK_SNAPSHOT, ItemStack.of(item, 1).createSnapshot())
inline fun ParticleEffect.Builder.color(color: Color): ParticleEffect.Builder = option(ParticleOptions.COLOR, color)
inline fun ParticleEffect.Builder.direction(direction: Direction): ParticleEffect.Builder = option(ParticleOptions.DIRECTION, direction)
inline fun ParticleEffect.Builder.note(notePitch: NotePitch): ParticleEffect.Builder = option(ParticleOptions.NOTE, notePitch)
inline fun ParticleEffect.Builder.scale(scale: Double): ParticleEffect.Builder = option(ParticleOptions.SCALE, scale)
inline fun ParticleEffect.Builder.slowHorizontalVelocity(slow: Boolean = true): ParticleEffect.Builder =
option(ParticleOptions.SLOW_HORIZONTAL_VELOCITY, slow)
| mit | 33fceb3cb6d4413527b7a6c3c77c60be | 61.413043 | 148 | 0.810171 | 4.240768 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/TerranVMReferenceBIOS.kt | 1 | 6674 | package net.torvald.terranvm.runtime
import net.torvald.terranvm.assets.Loader
import net.torvald.terranvm.toBytesBin
import net.torvald.terranvm.toReadableBin
import net.torvald.terrarum.virtualcomputer.terranvmadapter.PeriMDA
import java.io.IOException
/**
* Created by minjaesong on 2018-04-14.
*/
class TerranVMReferenceBIOS(val vm: TerranVM) : VMPeripheralHardware {
override fun inquireBootstrapper(): ByteArray? {
TODO("Boot from ROM BASIC")
}
/**
* Puts `prg` into the memory and moves program counter to its starting position.
*/
private fun eatShitAndPoop(prg: ByteArray) {
val ptr = vm.malloc(prg.size)
System.arraycopy(prg, 0, vm.memory, ptr.memAddr, prg.size)
vm.pc = ptr.memAddr
}
private fun Int.KB() = this shl 10
override fun call(arg: Int) {
val upper8Bits = arg.ushr(24)
val midHigh8Bits = arg.and(0xFF0000).ushr(16)
val midLow8Bits = arg.and(0xFF00).ushr(8)
val lower8Bits = arg.and(0xFF)
//println("BIOS called with arg: ${arg.toBytesBin()}")
when (upper8Bits) {
// various
0 -> when (midLow8Bits) {
// boot from device
0 -> {
when (lower8Bits) {
// load BIOS Setup Utility
TerranVM.IRQ_BIOS -> eatShitAndPoop(vm.parametreRAM.sliceArray(4.KB()..6.KB()))
TerranVM.IRQ_KEYBOARD -> {
val asm = Assembler(vm)
val prg = asm(Loader.invoke())
eatShitAndPoop(prg.bytes)
}
0 -> {
val bootOrder = vm.parametreRAM.sliceArray(0..3)
// try to boot using Boot Order
for (ord in 0..3) {
try {
if (bootOrder[ord] == 0.toByte()) throw IllegalArgumentException()
call(bootOrder[ord].toUint())
}
catch (e: IllegalArgumentException) {
}
catch (e: Exception) {
e.printStackTrace()
return
}
}
// boot ROM BASIC
try {
eatShitAndPoop(vm.parametreRAM.sliceArray(6.KB()..8.KB()))
}
catch (e: Exception) {
e.printStackTrace()
throw IOException("No bootable medium")
}
}
else -> {
val dev = vm.peripherals[lower8Bits]
if (dev == null) throw IllegalArgumentException("No such device: $lower8Bits")
else {
val prg = dev.inquireBootstrapper()
if (prg == null) throw IllegalArgumentException("Medium not bootable: $lower8Bits")
else eatShitAndPoop(prg)
}
}
}
}
// getchar from keyboard
1 -> {
(vm.peripherals[1] as VMPeripheralWrapper).call(lower8Bits and 0b111)
}
// printchar immediate
2 -> {
(vm.peripherals[3] as VMPeripheralWrapper).call(0x0800 or lower8Bits)
}
// printchar from register
3 -> {
val data = vm.readregInt(arg.and(0b111))
(vm.peripherals[3] as VMPeripheralWrapper).call(0x0800 or data)
}
// DMA Copy
in 0b010_0000_0..0b010_1111_1 -> {
val rParams = midLow8Bits.ushr(1).and(15)
val rFromAddr = lower8Bits.ushr(4).and(15)
val rToAddr = lower8Bits.and(15)
val params = vm.readregInt(rParams)
val src = params.and(0xFF)
val dest = params.ushr(8).and(0xFF)
var len = params.ushr(16).and(0xFFFF)
if (len == 0) len = 65536
val srcMem = if (src == 0) vm.memory else vm.peripherals[src]!!.memory
val destMem = if (dest == 0) vm.memory else vm.peripherals[dest]!!.memory
val fromAddr = vm.readregInt(rFromAddr)
val toAddr = vm.readregInt(rToAddr)
System.arraycopy(srcMem, fromAddr, destMem, toAddr, len)
}
}
// file operations
1 -> {
val fileOp = midHigh8Bits.ushr(3)
val targetRegister = midHigh8Bits.and(0b111)
val argument = midLow8Bits
val device = lower8Bits
when (fileOp) {
}
}
// print string
2 -> {
val dbAddr = arg.shl(2).and(0xFFFFFF)
var strLen = 0 // length INCLUSIVE to the null terminator
var _readByte: Byte
do {
_readByte = vm.memory[dbAddr + strLen]
strLen++
} while (_readByte != 0.toByte())
val mda = vm.peripherals[3]!! as PeriMDA
//if (strLen > 1) {
mda.printStream.write(vm.memSliceBySize(dbAddr, strLen - 1))
//}
}
// get file by name
4, 5 -> {
val rDest = arg.ushr(22).and(0b111)
val dbAddr = arg.shl(2).and(0xFFFFFF)
}
// compatible BIOS private use area -- ReferenceBIOS will ignore it
in 128..255 -> {
}
else -> {
throw UnsupportedOperationException("Unsupported op: ${arg.toReadableBin().replace('_', 0.toChar())}")
}
}
}
}
/* LOADER commands
CASE INSENSITIVE
0..9, A..F: hex literal
K: peek what byte is in the current address (example output: "0003DC : 3F")
P: put a byte to memory and increment program counter
R: run
T: move program counter
SYNTAX
000100L09P3EP45P00P
As soon as you hit a key, the command is entered, no RETURN key required.
*/ | mit | 1c5aef8bc85cfaace7dbfb30fea4d3f6 | 33.056122 | 118 | 0.453551 | 4.568104 | false | false | false | false |
asamm/locus-api | locus-api-core/src/main/java/locus/api/objects/styles/GeoDataStyle.kt | 1 | 8210 | /*
* Copyright 2012, Asamm Software, s. r. o.
*
* This file is part of LocusAPI.
*
* LocusAPI is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* LocusAPI 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with LocusAPI. If not, see
* <http://www.gnu.org/licenses/lgpl.html/>.
*/
package locus.api.objects.styles
import locus.api.objects.Storable
import locus.api.objects.extra.KmlVec2
import locus.api.objects.styles.deprecated.LineStyleOld
import locus.api.objects.styles.deprecated.OldStyleHelper
import locus.api.objects.styles.deprecated.PolyStyleOld
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import locus.api.utils.Logger
import java.io.IOException
/**
* Create new instance of style container.
*/
class GeoDataStyle() : Storable() {
/**
* ID in style tag.
*/
var id: String = ""
/**
* name of the style.
*/
var name: String = ""
/**
* Style for popup balloons.
*/
var balloonStyle: BalloonStyle? = null
/**
* Style for icons.
*/
var iconStyle: IconStyle? = null
/**
* Style of label.
*/
var labelStyle: LabelStyle? = null
/**
* Style of lists.
*/
var listStyle: ListStyle? = null
/**
* Style for line and polygons.
*/
var lineStyle: LineStyle? = null
//*************************************************
// SETTERS & GETTERS
//*************************************************
/**
* Get style Url for an icon.
*
* @return style Url/href parameter
*/
val iconStyleIconUrl: String?
get() = if (iconStyle == null) {
null
} else iconStyle!!.iconHref
/**
* Create new instance of style container with defined name.
*
* @param name name of style container
*/
constructor(name: String?) : this() {
// set name
if (name != null) {
this.name = name
}
}
fun setIconStyle(iconUrl: String, scale: Float) {
setIconStyle(iconUrl, COLOR_DEFAULT, 0.0f, scale)
}
fun setIconStyle(iconUrl: String, color: Int, heading: Float, scale: Float) {
// set style
iconStyle = IconStyle().apply {
this.iconHref = iconUrl
this.color = color
this.heading = heading
this.scale = scale
}
// set hot spot
setIconStyleHotSpot(HOTSPOT_BOTTOM_CENTER)
}
fun setIconStyleHotSpot(hotspot: Int) {
setIconStyleHotSpot(when (hotspot) {
HOTSPOT_TOP_LEFT -> {
KmlVec2(0.0, KmlVec2.Units.FRACTION, 1.0, KmlVec2.Units.FRACTION)
}
HOTSPOT_CENTER_CENTER -> {
KmlVec2(0.5, KmlVec2.Units.FRACTION, 0.5, KmlVec2.Units.FRACTION)
}
else -> {
// HOTSPOT_BOTTOM_CENTER
generateDefaultHotSpot()
}
})
}
fun setIconStyleHotSpot(vec2: KmlVec2) {
if (iconStyle == null) {
Logger.logW(TAG, "setIconStyleHotSpot($vec2), " +
"initialize IconStyle before settings hotSpot or hotSpot is null!")
return
}
// set hotSpot
iconStyle!!.hotSpot = vec2
}
/**
* Set parameters for style that draw a lines.
*
* @param color color of lines
* @param width width of lines in pixels
*/
fun setLineStyle(color: Int, width: Float) {
// check if style exists
if (lineStyle == null) {
lineStyle = LineStyle()
}
// set parameters
lineStyle!!.colorBase = color
lineStyle!!.width = width
}
/**
* Set line style for drawing a polygons.
*
* @param color color of inner area
*/
fun setPolyStyle(color: Int) {
if (lineStyle == null) {
lineStyle = LineStyle().apply {
this.drawBase = false
}
}
lineStyle?.drawFill = true
lineStyle?.colorFill = color
}
//*************************************************
// STORABLE
//*************************************************
override fun getVersion(): Int {
return 2
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
// read core
id = dr.readString()
name = dr.readString()
// ignore old version, not compatible anymore
if (version == 0) {
return
}
// read styles
var lineStyleOld: LineStyleOld? = null
var polyStyleOld: PolyStyleOld? = null
try {
if (dr.readBoolean()) {
balloonStyle = read(BalloonStyle::class.java, dr)
}
if (dr.readBoolean()) {
iconStyle = read(IconStyle::class.java, dr)
}
if (dr.readBoolean()) {
labelStyle = read(LabelStyle::class.java, dr)
}
if (dr.readBoolean()) {
lineStyleOld = read(LineStyleOld::class.java, dr)
}
if (dr.readBoolean()) {
listStyle = read(ListStyle::class.java, dr)
}
if (dr.readBoolean()) {
polyStyleOld = read(PolyStyleOld::class.java, dr)
}
} catch (e: Exception) {
e.printStackTrace()
}
// convert old style to new system
lineStyle = OldStyleHelper.convertToNewLineStyle(lineStyleOld, polyStyleOld)
// V2
if (version >= 2) {
if (dr.readBoolean()) {
lineStyle = LineStyle()
lineStyle!!.read(dr)
}
}
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
// write core
dw.writeString(id)
dw.writeString(name)
// balloon style
if (balloonStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
balloonStyle!!.write(dw)
}
// icon style
if (iconStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
iconStyle!!.write(dw)
}
// label style
if (labelStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
labelStyle!!.write(dw)
}
// line style (removed)
dw.writeBoolean(false)
// list style
if (listStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
listStyle!!.write(dw)
}
// poly style (removed)
dw.writeBoolean(false)
// V2
if (lineStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
lineStyle!!.write(dw)
}
}
companion object {
// tag for logger
private const val TAG = "GeoDataStyle"
// definition of hotSpot of icon to bottom center
const val HOTSPOT_BOTTOM_CENTER = 0
const val HOTSPOT_TOP_LEFT = 1
const val HOTSPOT_CENTER_CENTER = 2
fun generateDefaultHotSpot(): KmlVec2 {
// HOTSPOT_BOTTOM_CENTER
return KmlVec2(
0.5, KmlVec2.Units.FRACTION,
0.0, KmlVec2.Units.FRACTION)
}
// STYLES
// shortcut to simple black color
const val BLACK = -0x1000000
// shortcut to simple white color
const val WHITE = -0x1
// default basic color
const val COLOR_DEFAULT = WHITE
}
}
| mit | bd6ed7a278793bb621cfca5440183215 | 25.655844 | 87 | 0.533496 | 4.343915 | false | false | false | false |
jamieadkins95/Roach | data/src/main/java/com/jamieadkins/gwent/data/update/repository/NotificationsRepository.kt | 1 | 4055 | package com.jamieadkins.gwent.data.update.repository
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.res.Resources
import android.os.Build
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.google.firebase.messaging.FirebaseMessaging
import com.jamieadkins.gwent.data.BuildConfig
import com.jamieadkins.gwent.data.R
import com.jamieadkins.gwent.domain.update.repository.UpdateRepository
import io.reactivex.Completable
import io.reactivex.Observable
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class NotificationsRepository @Inject constructor(
private val preferences: RxSharedPreferences,
private val resources: Resources,
private val notificationManager: NotificationManager
) : UpdateRepository {
override fun isUpdateAvailable(): Observable<Boolean> {
// No work to do.
return Observable.just(false)
}
override fun performUpdate(): Completable {
// No work to do.
return Completable.complete()
}
override fun hasDoneFirstTimeSetup(): Observable<Boolean> {
return preferences.getBoolean(KEY_NEWS_NOTIFCATIONS_SETUP).asObservable()
}
override fun performFirstTimeSetup(): Completable {
return hasDoneFirstTimeSetup()
.first(false)
.flatMapCompletable { doneSetup ->
if (!doneSetup) {
Completable.fromCallable {
setupNotificationChannel()
setupNewsNotifications()
setupPatchNotifications()
}
} else {
Completable.complete()
}
}
}
private fun setupNewsNotifications() {
val language = Locale.getDefault().language
val newsLanguage = resources.getStringArray(R.array.locales_news).firstOrNull { it.contains(language) } ?: "en"
preferences.getString(resources.getString(R.string.pref_news_notifications_key)).set(newsLanguage)
preferences.getBoolean(KEY_NEWS_NOTIFCATIONS_SETUP).set(true)
unsubscribeFromAllNews(resources)
val topic = "news-$newsLanguage"
Timber.i("Subscribing to $topic")
FirebaseMessaging.getInstance().subscribeToTopic(topic)
.addOnCompleteListener { Timber.i("Subscribed to $topic") }
if (BuildConfig.DEBUG) {
Timber.i("Subscribing to $DEBUG_NEWS_TOPIC")
FirebaseMessaging.getInstance().subscribeToTopic(DEBUG_NEWS_TOPIC)
.addOnCompleteListener { Timber.i("Subscribed to $DEBUG_NEWS_TOPIC") }
}
}
private fun unsubscribeFromAllNews(resources: Resources) {
for (key in resources.getStringArray(R.array.locales_news)) {
FirebaseMessaging.getInstance().unsubscribeFromTopic("news-$key")
}
if (BuildConfig.DEBUG) {
Timber.i("Unsubscribing from $DEBUG_NEWS_TOPIC")
FirebaseMessaging.getInstance().unsubscribeFromTopic(DEBUG_NEWS_TOPIC)
}
}
private fun setupNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
val channelId = resources.getString(R.string.notification_channel_id)
val channelName = resources.getString(R.string.notification_channel_name)
notificationManager.createNotificationChannel(NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW))
}
}
private fun setupPatchNotifications() {
val topic = "patch-" + BuildConfig.CARD_DATA_VERSION
FirebaseMessaging.getInstance().subscribeToTopic(topic)
val key = resources.getString(R.string.pref_patch_notifications_topic_key)
preferences.getString(key).set(topic)
}
private companion object {
const val KEY_NEWS_NOTIFCATIONS_SETUP = "com.jamieadkins.gwent.news.locale.setup"
const val DEBUG_NEWS_TOPIC = "news-debug"
}
} | apache-2.0 | d15fe3f13399766f84187b8b03fa072d | 38.378641 | 138 | 0.679408 | 4.909201 | false | false | false | false |
thm-projects/arsnova-backend | gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/AnnouncementService.kt | 1 | 3122 | package de.thm.arsnova.service.httpgateway.service
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import de.thm.arsnova.service.httpgateway.exception.ForbiddenException
import de.thm.arsnova.service.httpgateway.model.Announcement
import de.thm.arsnova.service.httpgateway.model.AnnouncementState
import de.thm.arsnova.service.httpgateway.model.Room
import de.thm.arsnova.service.httpgateway.model.User
import de.thm.arsnova.service.httpgateway.security.AuthProcessor
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.Optional
@Service
class AnnouncementService(
private val webClient: WebClient,
private val httpGatewayProperties: HttpGatewayProperties,
private val authProcessor: AuthProcessor,
private val roomAccessService: RoomAccessService,
private val roomService: RoomService
) {
private val logger = LoggerFactory.getLogger(javaClass)
fun getByUserId(userId: String): Flux<Announcement> {
return authProcessor.getAuthentication()
.filter { authentication ->
authentication.principal == userId
}
.switchIfEmpty(Mono.error(ForbiddenException()))
.flatMapMany { auth ->
val jwt: String = auth.credentials.toString()
roomAccessService.getRoomAccessByUser(userId).map {
it.roomId
}.collectList().flatMapMany { roomIds ->
val roomIdsStr = roomIds.joinToString(",")
val url = "${httpGatewayProperties.httpClient.core}/room/-/announcement/?roomIds=$roomIdsStr"
logger.trace("Querying core for announcements with url: {}", url)
webClient.get()
.uri(url)
.header("Authorization", jwt)
.retrieve().bodyToFlux(Announcement::class.java).cache()
.checkpoint("Request failed in ${this::class.simpleName}::${::getByUserId.name}.")
}
}
.sort { a, b ->
(b.updateTimestamp ?: b.creationTimestamp).compareTo(a.updateTimestamp ?: a.creationTimestamp)
}
}
fun getByUserIdWithRoomName(userId: String): Flux<Announcement> {
return getByUserId(userId).collectList().flatMapMany { announcements ->
roomService.get(announcements.map { it.roomId }.distinct())
.filter(Optional<Room>::isPresent)
.map(Optional<Room>::get)
.collectMap { it.id }
.flatMapIterable { rooms ->
announcements.map {
it.copy(roomName = rooms[it.roomId]?.name)
}
}
}
}
fun getStateByUser(user: User): Mono<AnnouncementState> {
return getByUserId(user.id).collectList().map { announcements ->
AnnouncementState(
announcements.count(),
announcements
.filter { it.creatorId != user.id }
.count { a ->
user.announcementReadTimestamp == null ||
(a.updateTimestamp ?: a.creationTimestamp) > user.announcementReadTimestamp
},
user.announcementReadTimestamp
)
}
}
}
| gpl-3.0 | db8af3e5240da4409c1a6a63929a42b4 | 37.54321 | 103 | 0.694427 | 4.544396 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/views/LeagueTableActivityView.kt | 1 | 2979 | package com.bravelocation.yeltzlandnew.views
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.navigation.NavController
import com.bravelocation.yeltzlandnew.models.LeagueTable
import com.bravelocation.yeltzlandnew.models.LoadingState
import com.bravelocation.yeltzlandnew.ui.YeltzlandTheme
import com.bravelocation.yeltzlandnew.viewmodels.LeagueTableViewModel
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
@Composable
fun LeagueTableActivityView(
model: LeagueTableViewModel,
navController: NavController
) {
val table: LeagueTable? by model.table.collectAsState()
val loadingState: LoadingState by model.loadingState.observeAsState(LoadingState.LOADING)
val swipeRefreshState = rememberSwipeRefreshState(false)
YeltzlandTheme {
Scaffold(topBar = {
TopAppBar(
title = {
Text(text = "League Table", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
navigationIcon = {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(Icons.Filled.ArrowBack,"Back", tint = colors.onPrimary)
}
},
actions = {
IconButton(onClick = {
model.load()
}) {
Icon(Icons.Outlined.Refresh,"Reload", tint = colors.onPrimary)
}
},
backgroundColor = colors.primary,
contentColor = colors.onPrimary
)
}) { padding ->
SwipeRefresh(
state = swipeRefreshState,
onRefresh = { model.load() }
) {
Box(modifier = Modifier
.fillMaxSize()
.background(colors.background)
.padding(padding)
) {
table?.let { it1 -> LeagueTableView(it1) }
LoadingOverlay(loadingState == LoadingState.LOADING)
ErrorMessageOverlay(isDisplayed = loadingState == LoadingState.ERROR)
}
}
}
}
} | mit | 64a26be73ba995efcabe7a95d252fecc | 38.210526 | 95 | 0.636455 | 5.446069 | false | false | false | false |