repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lunabox/leetcode | kotlin/problems/src/data/structure/LRUCache.kt | 1 | 776 | package data.structure
class LRUCache(capacity: Int) {
private val dataCapacity = capacity
private val data = HashMap<Int, Int>()
private val frequent = mutableListOf<Int>()
fun get(key: Int): Int {
if (key !in data) {
return -1
}
val value = data[key]!!
activeKey(key)
return value
}
fun put(key: Int, value: Int) {
if (dataCapacity == 0) {
return
}
if (key !in data && data.size >= dataCapacity) {
val m = frequent.first()
data.remove(m)
frequent.remove(m)
}
data[key] = value
activeKey(key)
}
private fun activeKey(key: Int) {
frequent.remove(key)
frequent.add(key)
}
} | apache-2.0 | e436378b16c552de4f30932cb1390e82 | 21.852941 | 56 | 0.516753 | 3.88 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/minecraft/McSkinCommand.kt | 1 | 2205 | package net.perfectdreams.loritta.morenitta.commands.vanilla.minecraft
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.LorittaUtils
import net.perfectdreams.loritta.morenitta.utils.minecraft.MCUtils
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.LorittaBot
class McSkinCommand(loritta: LorittaBot) : AbstractCommand(loritta, "mcskin", listOf("skinsteal", "skinstealer"), net.perfectdreams.loritta.common.commands.CommandCategory.MINECRAFT) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.mcskin.description")
override fun getExamplesKey() = LocaleKeyData("commands.category.minecraft.skinPlayerNameExamples")
// TODO: Fix Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "minecraft player skin")
if (context.args.isNotEmpty()) {
val nickname = context.args[0]
val profile = MCUtils.getUserProfileFromName(nickname)
if (profile == null) {
context.reply(
LorittaReply(
locale["commands.category.minecraft.unknownPlayer", context.args.getOrNull(0)],
Constants.ERROR
)
)
return
}
if (!profile.textures.containsKey("SKIN")) {
context.reply(
LorittaReply(
"Player não possui skin!",
Constants.ERROR
)
)
return
}
val bufferedImage = LorittaUtils.downloadImage(loritta, profile.textures["SKIN"]!!.url)
context.sendFile(bufferedImage!!, "${nickname}.png", context.getAsMention(true))
} else {
context.explain()
}
}
} | agpl-3.0 | 123d93c57625e5d5edf4d5de6e90949c | 36.372881 | 184 | 0.719601 | 4.54433 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/ContentAwareScaleCommand.kt | 1 | 2154 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.utils.LorittaImage
import net.perfectdreams.loritta.morenitta.utils.SeamCarver
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.morenitta.api.commands.Command
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.LorittaBot
class ContentAwareScaleCommand(loritta: LorittaBot) : AbstractCommand(loritta, "contentawarescale", listOf("cas", "contentaware", "seamcarver"), category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.contentawarescale.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
override fun getUsage() = arguments {
argument(ArgumentType.IMAGE) {}
}
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
var contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val loriImage = LorittaImage(contextImage)
loriImage.resize(256, 256, true)
contextImage = loriImage.bufferedImage
var newImage = contextImage
for (i in 0 until 256) {
// determine scale
var scaleTo = if (i % 2 == 0) SeamCarver.CarveDirection.HORIZONTAL else SeamCarver.CarveDirection.VERTICAL
if (32 > newImage.height) { // se ficar menos que 32 irá ficar bem ruim a imagem
break
}
if (32 > newImage.width) { // se ficar menos que 32 irá ficar bem ruim a imagem
break
}
// Get the new image w/o one seam.
newImage = SeamCarver.carveSeam(newImage, scaleTo)
}
context.sendFile(newImage, "content_aware_scale.png", context.getAsMention(true))
}
} | agpl-3.0 | 5000f7cf62ab6f92c0a6b63e263b43e3 | 39.622642 | 223 | 0.789033 | 3.80885 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/platform/discord/legacy/commands/DiscordCommandContext.kt | 1 | 17716 | package net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands
import com.github.kevinsawicki.http.HttpRequest
import net.perfectdreams.loritta.morenitta.dao.ServerConfig
import net.perfectdreams.loritta.morenitta.utils.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.*
import net.dv8tion.jda.api.entities.channel.ChannelType
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel
import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji
import net.dv8tion.jda.api.exceptions.PermissionException
import net.dv8tion.jda.api.utils.FileUpload
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder
import net.dv8tion.jda.api.utils.messages.MessageCreateData
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.morenitta.api.commands.Command
import net.perfectdreams.loritta.morenitta.messages.LorittaMessage
import net.perfectdreams.loritta.common.utils.image.Image
import net.perfectdreams.loritta.common.utils.image.JVMImage
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.locale.LocaleStringData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.DiscordMessage
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda.JDAUser
import net.perfectdreams.loritta.morenitta.utils.DiscordUtils
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.api.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.ImageFormat
import net.perfectdreams.loritta.morenitta.utils.extensions.*
import org.jsoup.Jsoup
import java.io.File
import java.io.InputStream
import java.time.Instant
class DiscordCommandContext(
loritta: LorittaBot,
command: Command<CommandContext>,
args: List<String>,
val discordMessage: Message,
locale: BaseLocale,
i18nContext: I18nContext,
val serverConfig: ServerConfig,
val lorittaUser: LorittaUser,
val executedCommandLabel: String
) : CommandContext(loritta, command, args, DiscordMessage(discordMessage), locale, i18nContext) {
val isPrivateChannel = discordMessage.channelType == ChannelType.PRIVATE
val guild: Guild
get() = discordMessage.guild
val user = discordMessage.author
val member = discordMessage.member
suspend fun sendMessage(message: String, embed: MessageEmbed): Message {
return sendMessage(MessageCreateBuilder()
.denyMentions(
Message.MentionType.EVERYONE,
Message.MentionType.HERE
)
.setEmbeds(embed)
.addContent(if (message.isEmpty()) " " else message)
.build()
)
}
suspend fun sendMessageEmbeds(embed: MessageEmbed): Message {
return sendMessage(MessageCreateBuilder()
.denyMentions(
Message.MentionType.EVERYONE,
Message.MentionType.HERE
)
.addContent(getUserMention(true))
.setEmbeds(embed)
.build()
)
}
suspend fun sendMessage(message: MessageCreateData): Message {
if (isPrivateChannel || discordMessage.textChannel.canTalk()) {
return discordMessage.channel.sendMessage(message)
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
} else {
throw RuntimeException("Sem permissão para enviar uma mensagem!")
}
}
override suspend fun sendImage(image: Image, fileName: String, content: String): net.perfectdreams.loritta.morenitta.api.entities.Message {
return DiscordMessage(
discordMessage.channel.sendMessage(LorittaMessage(content).content)
.addFiles(FileUpload.fromData(image.toByteArray(), fileName))
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
)
}
override suspend fun sendFile(byteArray: ByteArray, fileName: String, content: String): net.perfectdreams.loritta.morenitta.api.entities.Message {
return DiscordMessage(
discordMessage.channel.sendMessage(LorittaMessage(content).content)
.addFiles(FileUpload.fromData(byteArray, fileName))
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
)
}
suspend fun sendFile(file: File, fileName: String, content: String = this.getUserMention(true), embed: MessageEmbed? = null): DiscordMessage {
return DiscordMessage(
discordMessage.channel.sendMessage(
MessageCreateBuilder()
.denyMentions(
Message.MentionType.EVERYONE,
Message.MentionType.HERE
)
.addContent(content)
.setEmbeds(embed)
.build()
)
.addFiles(FileUpload.fromData(file, fileName))
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
)
}
suspend fun sendFile(inputStream: InputStream, fileName: String, content: String = this.getUserMention(true), embed: MessageEmbed? = null): DiscordMessage {
return DiscordMessage(discordMessage.channel.sendMessage(
MessageCreateBuilder()
.denyMentions(
Message.MentionType.EVERYONE,
Message.MentionType.HERE
)
.addContent(content)
.setEmbeds(embed)
.build()
)
.addFiles(FileUpload.fromData(inputStream, fileName))
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
)
}
override suspend fun user(argument: Int) = this.args.getOrNull(argument)
?.let {
DiscordUtils.extractUserFromString(
loritta,
it,
discordMessage.mentions.users,
if (isPrivateChannel) null else discordMessage.guild
)?.let { JDAUser(it) }
}
override suspend fun imageUrl(argument: Int, searchPreviousMessages: Int): String? {
if (this.args.size > argument) { // Primeiro iremos verificar se existe uma imagem no argumento especificado
val link = this.args[argument] // Ok, será que isto é uma URL?
if (LorittaUtils.isValidUrl(link) && loritta.connectionManager.isTrusted(link)) {
// Workaround for direct prnt.sc image links (Lightshot is trash but a lot of people use it)
if (link.contains("prnt.sc")) {
val document = withContext(Dispatchers.IO) { Jsoup.connect(link).get() }
val elements = document.getElementsByAttributeValue("property", "og:image")
if (!elements.isEmpty()) {
return elements.attr("content")
}
}
return link // Se é um link, vamos enviar para o usuário agora
}
// Vamos verificar por usuários no argumento especificado
val user = user(argument)
if (user != null)
return user.getEffectiveAvatarUrl(ImageFormat.PNG, 256)
// Ainda não?!? Vamos verificar se é um emoji.
// Um emoji custom do Discord é + ou - assim: <:loritta:324931508542504973>
for (emote in this.discordMessage.mentions.customEmojis) {
if (link.equals(emote.asMention, ignoreCase = true)) {
return emote.imageUrl
}
}
for (embed in discordMessage.embeds) {
if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!))
return embed.image!!.url
}
for (attachment in discordMessage.attachments) {
if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url))
return attachment.url
}
// Se não é nada... então talvez seja um emoji padrão do Discordão!
// Na verdade é um emoji padrão...
try {
var unicodeEmoji = LorittaUtils.toUnicode(this.args[argument].codePointAt(0)) // Vamos usar codepoints porque emojis
unicodeEmoji = unicodeEmoji.substring(2) // Remover coisas desnecessárias
val toBeDownloaded = "https://twemoji.maxcdn.com/2/72x72/$unicodeEmoji.png"
if (HttpRequest.get(toBeDownloaded).code() == 200) {
return toBeDownloaded
}
} catch (e: Exception) {
}
}
// Nothing found? Try retrieving the replied message content
if (!this.isPrivateChannel && this.guild.selfMember.hasPermission(this.discordMessage.textChannel, Permission.MESSAGE_HISTORY)) {
val referencedMessage = discordMessage.referencedMessage
if (referencedMessage != null) {
for (embed in referencedMessage.embeds) {
if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!))
return embed.image!!.url
}
for (attachment in referencedMessage.attachments) {
if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url))
return attachment.url
}
}
}
// Still nothing valid? You know what? I give up! Let's search old messages from this server & embeds to find attachments...
if (searchPreviousMessages > 0 && !this.isPrivateChannel && guild.selfMember.hasPermission(discordMessage.channel.asGuildMessageChannel(), Permission.MESSAGE_HISTORY)) {
val messageChannel = discordMessage.channel.asGuildMessageChannel()
try {
val message = messageChannel.history.retrievePast(searchPreviousMessages).await()
attach@ for (msg in message) {
for (embed in msg.embeds) {
if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!))
return embed.image!!.url
}
for (attachment in msg.attachments) {
if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url))
return attachment.url
}
}
} catch (e: PermissionException) {
}
}
return null
}
override suspend fun image(argument: Int, searchPreviousMessages: Int, createTextAsImageIfNotFound: Boolean): Image? {
var toBeDownloaded = imageUrl(argument, 0)
if (toBeDownloaded == null) {
if (args.isNotEmpty() && createTextAsImageIfNotFound) {
val theTextThatWillBeWritten = args.drop(argument).joinToString(" ")
if (theTextThatWillBeWritten.isNotEmpty())
return JVMImage(ImageUtils.createTextAsImage(loritta, 256, 256, theTextThatWillBeWritten))
}
if (searchPreviousMessages != 0) {
toBeDownloaded = imageUrl(argument, searchPreviousMessages)
}
}
if (toBeDownloaded == null)
return null
// let's download the image!
try {
val image = LorittaUtils.downloadImage(loritta, toBeDownloaded) ?: return null
return JVMImage(image)
} catch (e: Exception) {
return null
}
}
fun textChannel(argument: Int): TextChannel? {
val channelId = args.getOrNull(argument)
?.replace("<#", "")
?.replace(">", "")
return if (channelId?.isValidSnowflake()!!) {
guild.getTextChannelById(channelId)
} else {
null
} ?: if (guild.getTextChannelsByName(args[0], true).isNotEmpty()) {
guild.getTextChannelsByName(args[0], true).first()
} else {
null
} ?: if (guild.textChannels.filter { it.name == args[0] }.isNotEmpty()) {
guild.textChannels.filter { it.name == args[0] }.first()
} else {
null
}
}
fun voiceChannel(argument: Int): VoiceChannel? {
val channelId = args.getOrNull(argument)
?.replace("<#", "")
?.replace(">", "")
return if (channelId?.isValidSnowflake()!!) {
guild.getVoiceChannelById(channelId)
} else {
null
} ?: if (guild.getVoiceChannelsByName(args[0], true).isNotEmpty()) {
guild.getVoiceChannelsByName(args[0], true).first()
} else {
null
} ?: if (guild.voiceChannels.filter { it.name == args[0] }.isNotEmpty()) {
guild.voiceChannels.filter { it.name == args[0] }.first()
} else {
null
}
}
fun role(argument: Int): Role? {
val roleId = args.getOrNull(argument)
?.replace("<@&", "")
?.replace(">", "")
return if (roleId?.isValidSnowflake()!!) {
guild.getRoleById(roleId)
} else {
null
} ?: if (guild.getRolesByName(args[0], true).isNotEmpty()) {
guild.getRolesByName(args[0], true).first()
} else {
null
} ?: if (guild.roles.filter { it.name == args[0] }.isNotEmpty()) {
guild.roles.filter { it.name == args[0] }.first()
} else {
null
}
}
fun emote(argument: Int): RichCustomEmoji? {
val regexEmote = Regex("(<)|[a-z]|(_)|(:)|(>)")
val emoteId = args.getOrNull(argument)?.let { regexEmote.replace(it, "") }
return if (emoteId?.isValidSnowflake()!!) {
guild.getEmojiById(emoteId)
} else {
null
} ?: if (guild.getEmojisByName(args[0], true).isNotEmpty()) {
guild.getEmojisByName(args[0], true).first()
} else {
null
} ?: if (guild.emojis.filter { it.name == args[0] }.isNotEmpty()) {
guild.emojis.filter { it.name == args[0] }.first()
} else {
null
}
}
/**
* Sends an embed explaining what the command does
*
* @param context the context of the command
*/
override suspend fun explain() {
val commandDescription = command.description.invoke(locale)
val commandLabel = command.labels.first()
val commandLabelWithPrefix = "${serverConfig.commandPrefix}$commandLabel"
val embed = EmbedBuilder()
.setColor(Constants.LORITTA_AQUA)
.setAuthor(locale["commands.explain.clickHereToSeeAllMyCommands"], "${loritta.config.loritta.website.url}commands", discordMessage.jda.selfUser.effectiveAvatarUrl)
.setTitle("${Emotes.LORI_HM} `${serverConfig.commandPrefix}${executedCommandLabel}`")
.setFooter("${user.name + "#" + user.discriminator} • ${command.category.getLocalizedName(locale)}", user.effectiveAvatarUrl)
.setTimestamp(Instant.now())
val description = buildString {
// Builds the "How to Use" string
this.append(commandDescription)
this.append('\n')
this.append('\n')
this.append("${Emotes.LORI_SMILE} **${locale["commands.explain.howToUse"]}**")
this.append(" `")
this.append(commandLabelWithPrefix)
this.append('`')
// Only add the arguments if the list is not empty (to avoid adding a empty "` `")
if (command.usage.arguments.isNotEmpty()) {
this.append("**")
this.append('`')
this.append(' ')
for ((index, argument) in command.usage.arguments.withIndex()) {
argument.build(this, locale)
if (index != command.usage.arguments.size - 1)
this.append(' ')
}
this.append('`')
this.append("**")
// If we have arguments with explanations, let's show them!
val argumentsWithExplanations = command.usage.arguments.filter { it.explanation != null }
if (argumentsWithExplanations.isNotEmpty()) {
this.append('\n')
// Same thing again, but with a *twist*!
for ((index, argument) in argumentsWithExplanations.withIndex()) {
this.append("**")
this.append('`')
argument.build(this, locale)
this.append('`')
this.append("**")
this.append(' ')
when (val explanation = argument.explanation) {
is LocaleKeyData -> {
this.append(locale.get(explanation))
}
is LocaleStringData -> {
this.append(explanation.text)
}
else -> throw IllegalArgumentException("I don't know how to process a $argument!")
}
this.append('\n')
}
}
}
}
embed.setDescription(description)
// Create example list
val examplesKey = command.examplesKey
val examples = ArrayList<String>()
if (examplesKey != null) {
val examplesAsString = locale.getList(examplesKey)
for (example in examplesAsString) {
val split = example.split("|-|")
.map { it.trim() }
if (split.size == 2) {
// If the command has a extended description
// "12 |-| Gira um dado de 12 lados"
// A extended description can also contain "nothing", but contains a extended description
// "|-| Gira um dado de 6 lados"
val (commandExample, explanation) = split
examples.add("\uD83D\uDD39 **$explanation**")
examples.add("`" + commandLabelWithPrefix + "`" + (if (commandExample.isEmpty()) "" else "**` $commandExample`**"))
} else {
val commandExample = split[0]
examples.add("`" + commandLabelWithPrefix + "`" + if (commandExample.isEmpty()) "" else "**` $commandExample`**")
}
}
}
if (examples.isNotEmpty()) {
embed.addField(
"\uD83D\uDCD6 ${locale["commands.explain.examples"]}",
examples.joinToString("\n", transform = { it }),
false
)
}
val command = command
if (command is DiscordCommand) {
if (command.botRequiredPermissions.isNotEmpty() || command.userRequiredPermissions.isNotEmpty()) {
var field = ""
if (command.userRequiredPermissions.isNotEmpty()) {
field += "\uD83D\uDC81 ${locale["commands.explain.youNeedToHavePermission", command.userRequiredPermissions.joinToString(", ", transform = { "`${it.localized(locale)}`" })]}\n"
}
if (command.botRequiredPermissions.isNotEmpty()) {
field += "<:loritta:331179879582269451> ${locale["commands.explain.loriNeedToHavePermission", command.botRequiredPermissions.joinToString(", ", transform = { "`${it.localized(locale)}`" })]}\n"
}
embed.addField(
"\uD83D\uDCDB ${locale["commands.explain.permissions"]}",
field,
false
)
}
}
val otherAlternatives = command.labels.filter { it != executedCommandLabel }
if (otherAlternatives.isNotEmpty()) {
embed.addField(
"\uD83D\uDD00 ${locale["commands.explain.aliases"]}",
otherAlternatives.joinToString(transform = { "`${serverConfig.commandPrefix}$it`" }),
false
)
}
val similarCommands = loritta.commandMap.commands.filter {
it.commandName != command.commandName && it.commandName in command.similarCommands
}
if (similarCommands.isNotEmpty()) {
embed.addField(
"${Emotes.LORI_WOW} ${locale["commands.explain.relatedCommands"]}",
similarCommands.joinToString(transform = { "`${serverConfig.commandPrefix}${it.labels.first()}`" }),
false
)
}
val messageBuilder = MessageCreateBuilder()
.denyMentions(
Message.MentionType.EVERYONE,
Message.MentionType.HERE
)
.addContent(getUserMention(true))
.setEmbeds(embed.build())
discordMessage.channel.sendMessage(messageBuilder.build())
.referenceIfPossible(discordMessage, serverConfig, true)
.await()
}
} | agpl-3.0 | c335e1e088b6121472ec32078569634b | 33.634051 | 198 | 0.707973 | 3.648866 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/data/classes/ASBSession.kt | 1 | 4165 | package com.ghstudios.android.data.classes
import android.util.Log
import com.ghstudios.android.ITintedIcon
import com.ghstudios.android.mhgendatabase.R
/**
* Contains all of the juicy stuff regarding ASB sets, like the armor inside and the skills it provides.
*/
class ASBSession(id: Long, name: String, rank: Rank, hunterType: Int) :
ASBSet(id, name, rank, hunterType), ArmorSet {
private val pieceData = sortedMapOf<Int, ArmorSetPiece>()
var numWeaponSlots: Int
/** Retrieves the number of weapon slots */
get() = getEquipment(ArmorSet.WEAPON)?.numSlots ?: 0
/**
* Sets the number of weapon slots. This also clears all decorations.
*/
set(value) {
setEquipment(ArmorSet.WEAPON, DummyWeapon(value))
}
init {
setEquipment(ArmorSet.WEAPON, DummyWeapon(3))
}
/**
* Returns a list of all set pieces, including weapons and talismans.
*/
override val pieces: List<ArmorSetPiece> get() = pieceData.values.toList()
override fun getPiece(pieceIndex: Int) = pieceData[pieceIndex]
/**
* @return The set's talisman.
*/
val talisman: ASBTalisman?
get() = pieceData[ArmorSet.TALISMAN]?.equipment as ASBTalisman?
fun getDecorations(pieceIndex: Int): List<Decoration> {
return getPiece(pieceIndex)?.decorations ?: emptyList()
}
fun getAvailableSlots(pieceIndex: Int): Int {
val equipment = getEquipment(pieceIndex) ?: return 0
val usedSlots = getDecorations(pieceIndex).sumBy { it.numSlots }
return equipment.numSlots - usedSlots
}
/**
* Attempts to add a decoration to the specified armor piece.
* @param pieceIndex The index of a piece in the set to fetch, according to [ASBSession].
* @param decoration The decoration to add.
* @return The 0-based index of the slot that the decoration was added to, or -1 if it failed
*/
fun addDecoration(pieceIndex: Int, decoration: Decoration): Int {
val piece = getPiece(pieceIndex) ?: return -1
Log.v("ASB", "Adding decoration at piece index $pieceIndex")
if (getAvailableSlots(pieceIndex) >= decoration.numSlots) {
piece.decorations.add(decoration)
return piece.decorations.size - 1
} else {
Log.e("ASB", "Cannot add that decoration!")
return -1
}
}
/**
* Removes the decoration at the specified location from the specified armor piece.
* Will fail if the decoration in question is non-existent or a dummy.
*/
fun removeDecoration(pieceIndex: Int, decorationIndex: Int) {
val list = getPiece(pieceIndex)?.decorations ?: return
if (list.getOrNull(decorationIndex) == null) {
return
}
list.removeAt(decorationIndex)
}
/**
* @return A piece of the armor set based on the provided piece index.
* Returns null if there is no equipment in that slot.
*/
fun getEquipment(pieceIndex: Int): Equipment? {
return getPiece(pieceIndex)?.equipment
}
/**
* Changes the equipment at the specified location.
*/
fun setEquipment(pieceIndex: Int, equip: Equipment) {
pieceData[pieceIndex] = ArmorSetPiece(pieceIndex, equip)
}
/**
* Removes the equipment at the specified location.
* If a weapon, clears the decorations.
*/
fun removeEquipment(pieceIndex: Int) {
if (pieceIndex == ArmorSet.WEAPON) {
getPiece(pieceIndex)?.decorations?.clear()
} else {
pieceData.remove(pieceIndex)
}
}
/**
* Internal fake weapon. Shows the slots and whether its a gunner or blademaster set.
*/
inner class DummyWeapon(val slots: Int) : Equipment(), ITintedIcon {
override fun getNumSlots() = slots
override fun getIconResourceString() = when (hunterType) {
Armor.ARMOR_TYPE_GUNNER -> "icon_heavy_bowgun"
else -> "icon_great_sword"
}
override fun getColorArrayId() = R.array.rare_colors
override fun getIconColorIndex() = 0
}
}
| mit | eee2ec5781528adac1cc86ced64a3873 | 32.32 | 104 | 0.637935 | 4.245668 | false | false | false | false |
vsch/SmartData | src/com/vladsch/smart/SmartCharSequenceBase.kt | 1 | 18839 | /*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>
*
* 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.vladsch.smart
import java.util.*
abstract class SmartCharSequenceBase<T : SmartCharSequence> : SmartCharSequence {
protected var myCachedProxy: SmartCharSequence? = null
/*
* cached proxy should return original sequence for editing purposes
*/
override fun getOriginal(): SmartCharSequenceBase<T> = this
override fun getContents(): SmartCharSequenceBase<T> = this
override fun getContents(startIndex: Int, endIndex: Int): SmartCharSequence = subSequence(startIndex, endIndex)
/*
* raw access, never via proxy or in proxy via original
*/
internal abstract fun properSubSequence(startIndex: Int, endIndex: Int): T
internal abstract fun charAtImpl(index: Int): Char
internal abstract fun getCharsImpl(dst: CharArray, dstOffset: Int)
// internal fun getCharsImpl(dst: CharArray, dstOffset: Int) {
// val iMax = length
// for (i in 0..iMax-1) {
// dst[dstOffset+i] = charAtImpl(i)
// }
// }
internal open fun getCharsImpl(): CharArray {
val iMax = length
val chars = CharArray(iMax)
getCharsImpl(chars, 0)
return chars
}
/*
* use proxy if fresh otherwise raw access
*/
open val freshProxyOrNull: SmartCharSequence?
get() {
val cachedProxy = myCachedProxy
if (cachedProxy == null || cachedProxy.version.isStale) return null
return cachedProxy
}
override fun get(index: Int): Char {
return freshProxyOrNull?.get(index) ?: charAtImpl(index)
}
override fun subSequence(startIndex: Int, endIndex: Int): T {
checkBounds(startIndex, endIndex)
@Suppress("UNCHECKED_CAST")
if (startIndex == 0 && endIndex == length) return original.contents as T
val subSequence = original.properSubSequence(startIndex, endIndex)
// val cachedProxy = freshProxyOrNull
// if (subSequence is SmartCharSequenceBase<*> && cachedProxy is SmartCharSequenceBase<*>) {
// // grab a copy of the cached proxy if it is not stale
// subSequence.myCachedProxy = cachedProxy.properSubSequence(startIndex, endIndex)
// }
assert(subSequence === subSequence.contents)
return subSequence
}
override fun getChars(): CharArray {
return freshProxyOrNull?.chars ?: getCharsImpl()
}
override fun getChars(dst: CharArray, dstOffset: Int) {
freshProxyOrNull?.getChars(dst, dstOffset) ?: getCharsImpl(dst, dstOffset)
}
override fun getSourceLocations(sources: ArrayList<Any>, locations: ArrayList<Range>, sourceLocations: ArrayList<Range>) {
throw UnsupportedOperationException()
}
override fun equivalent(other: CharSequence): Boolean {
if (this === other) return true
if (length != other.length) return false
val ourProxy: CharSequence = freshProxyOrNull ?: this
val otherProxy: CharSequence = if (other is SmartCharSequenceBase<*>) other.freshProxyOrNull ?: other else other
val iMax = length
for (i in 0..iMax - 1) {
if (ourProxy[i] != otherProxy[i]) return false
}
return true
}
/*
* full sequence scanning, proxy refreshing functions
*/
override fun getCachedProxy(): SmartCharSequence {
var cachedProxy = freshProxyOrNull
if (cachedProxy == null) {
cachedProxy = SmartCharArraySequence(this, getCharsImpl())
myCachedProxy = cachedProxy
}
return cachedProxy
}
override fun extractGroupsSegmented(regex: String): SmartSegmentedCharSequence? {
val segments = extractGroups(regex) ?: return null
return SmartSegmentedCharSequence(segments)
}
override fun extractGroups(regex: String): List<SmartCharSequence>? {
// var matchResult = regex.toRegex().matchEntire(cachedProxy)
var matchResult = regex.toRegex().matchEntire(this)
if (matchResult != null) {
val segments = ArrayList<SmartCharSequence>(matchResult.groups.size)
var group = 0
for (matchGroup in matchResult.groups) {
if (matchGroup != null && matchGroup.range.start <= matchGroup.range.endInclusive) {
segments.add(original.subSequence(matchGroup.range.start, matchGroup.range.endInclusive + 1))
} else {
segments.add(NULL_SEQUENCE)
}
group++
}
return segments
}
return null
}
override fun splitParts(delimiter: Char, includeDelimiter: Boolean): List<SmartCharSequence> {
// return (cachedProxy as CharSequence).splitParts(delimiter, includeDelimiter) as List<SmartCharSequence>
@Suppress("UNCHECKED_CAST")
return (this as CharSequence).splitParts(delimiter, includeDelimiter) as List<SmartCharSequence>
}
override fun splitPartsSegmented(delimiter: Char, includeDelimiter: Boolean): SmartSegmentedCharSequence {
return segmentedFlat(splitParts(delimiter, includeDelimiter))
}
override fun wrapParts(delimiter: Char, includeDelimiter: Boolean, prefix: CharSequence, suffix: CharSequence): SmartCharSequence {
// return SmartSegmentedCharSequence(cachedProxy.wrapParts(delimiter, includeDelimiter, prefix, suffix))
return SmartSegmentedCharSequence((this as CharSequence).wrapParts(delimiter, includeDelimiter, prefix, suffix))
}
override fun expandTabs(tabSize: Int): SmartCharSequence {
var lastPos = 0
val parts = ArrayList<SmartCharSequence>()
val length = length
var col = 0
val tabExpansion = RepeatedCharSequence(' ', tabSize)
// val proxy = cachedProxy.chars
val proxy = this
for (i in 0..length - 1) {
val c = proxy[i]
if (c == '\t') {
parts.add(subSequence(lastPos, i))
parts.add(SmartReplacedCharSequence(subSequence(i, i + 1), tabExpansion.subSequence(0, tabSize - col % tabSize)))
lastPos = i + 1
} else if (c == '\n') {
col = 0
} else {
col++
}
}
if (lastPos < length) parts.add(this.subSequence(lastPos, length))
return SmartSegmentedCharSequence(parts)
}
// NOTE: if overriding getCachedProxy or freshProxyOrNull to return `this` then need to override this method otherwise will get infinite recursion
override fun toString(): String {
return cachedProxy.toString()
}
/*
* convenience type change functions
*/
override fun mapped(mapper: CharSequenceMapper): SmartMappedCharSequence {
val base = original
return if (base is SmartMappedCharSequence && base.myMapper === mapper) base else SmartMappedCharSequence(base, mapper)
}
override fun lowercase(): SmartCharSequence {
return mapped(LowerCaseMapper)
}
override fun uppercase(): SmartCharSequence {
return mapped(UpperCaseMapper)
}
override fun reversed(): SmartCharSequence {
val base = original
return if (base is SmartReversedCharSequence) base else SmartReversedCharSequence(base)
}
override fun asEditable(): EditableCharSequence {
return EditableCharSequence(this)
}
override fun segmented(): SmartSegmentedCharSequence {
val base = original
return if (base is SmartSegmentedCharSequence) base else SmartSegmentedCharSequence(base)
}
override fun variable(): SmartVariableCharSequence {
val base = original
return if (base is SmartVariableCharSequence) base else SmartVariableCharSequence(base)
}
/*
* convenience implementation functions
*/
override fun insert(charSequence: CharSequence, startIndex: Int): SmartCharSequence {
return replace(charSequence, startIndex, startIndex)
}
override fun delete(startIndex: Int, endIndex: Int): SmartCharSequence {
return replace(EMPTY_SEQUENCE, startIndex, endIndex)
}
override fun append(vararg others: CharSequence): SmartCharSequence {
val segments = ArrayList<SmartCharSequence>(others.size + 1)
if (this is SmartSegmentedCharSequence) segments.addAll(this.segments)
else flattened(segments)
for (charSequence in others) {
segments.add(smart(charSequence))
}
return SmartSegmentedCharSequence(segments)
}
override fun appendOptimized(vararg others: CharSequence): SmartCharSequence {
val segments = ArrayList<SmartCharSequence>(others.size + 1)
flattened(segments)
for (charSequence in others) {
if (!charSequence.isEmpty() || charSequence is SmartCharSequence && charSequence.version.isMutable) {
segments.add(smart(charSequence))
}
}
return SmartSegmentedCharSequence(spliceSequences(segments))
}
override fun replace(charSequence: CharSequence, startIndex: Int, endIndex: Int): SmartCharSequence {
if (startIndex < 0 || startIndex > length) {
throw IndexOutOfBoundsException()
}
val canEliminate = charSequence.length == 0 && (charSequence !is SmartCharSequence || !charSequence.version.isMutable)
if (startIndex == endIndex) {
// pure insert
if (canEliminate) {
return original.contents
}
if (startIndex == 0) {
return SmartSegmentedCharSequence(charSequence, original.contents)
} else if (startIndex == length) {
return segmentedFlat(original.contents, smart(charSequence))
} else {
return segmentedFlat(subSequence(0, startIndex), smart(charSequence), subSequence(startIndex, length))
}
} else if (canEliminate) {
// pure delete
if (startIndex == 0) {
if (endIndex >= length) {
return EMPTY_SEQUENCE
} else {
return subSequence(endIndex, length)
}
} else if (endIndex >= length) {
return subSequence(0, startIndex)
} else {
return segmentedFlat(subSequence(0, startIndex), subSequence(endIndex, length))
}
} else {
// a mix of delete and insert
if (startIndex == 0) {
if (endIndex >= length) {
return smart(charSequence)
} else {
return segmentedFlat(smart(charSequence), subSequence(endIndex, length))
}
} else if (startIndex >= length) {
return segmentedFlat(this, smart(charSequence))
} else {
return segmentedFlat(subSequence(0, startIndex), smart(charSequence), subSequence(endIndex, length))
}
}
}
protected fun checkBounds(start: Int, end: Int) {
if (start < 0 || start > end || end > length) {
throw IndexOutOfBoundsException("subSequence($start, $end) is not within range [0, $length)")
}
}
protected fun checkIndex(index: Int) {
if (index < 0 || index >= length) {
throw IndexOutOfBoundsException("index $index is not within range [0, $length)")
}
}
override fun flattened(sequences: ArrayList<SmartCharSequence>) {
sequences.add(original.contents)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CharSequence) return false
if (other !is SmartCharSequenceBase<*>) {
return equivalent(other)
}
// if (!cachedProxy.equivalent(other.cachedProxy)) return false
if (!equivalent(other)) return false
return true
}
override fun hashCode(): Int {
return myCachedProxy?.hashCode() ?: 0
}
companion object {
@JvmStatic
fun segmentedFlat(vararg others: SmartCharSequence): SmartSegmentedCharSequence {
if (others.size == 0)
return EMPTY_SEGMENTED_SEQUENCE
else {
val segments = ArrayList<SmartCharSequence>(others.size)
for (other in others) {
other.flattened(segments)
}
return SmartSegmentedCharSequence(segments)
}
}
@JvmStatic
fun segmentedFlat(others: Iterable<SmartCharSequence>): SmartSegmentedCharSequence {
val segments = ArrayList<SmartCharSequence>()
for (other in others) {
other.flattened(segments)
}
return if (segments.isEmpty()) EMPTY_SEGMENTED_SEQUENCE else SmartSegmentedCharSequence(segments)
}
@JvmStatic
fun smart(other: CharSequence): SmartCharSequence {
return if (other is SmartCharSequenceContainer) other.contents else SmartCharSequenceWrapper(other, 0, other.length)
}
@JvmStatic
fun smartList(others: Collection<CharSequence>): List<SmartCharSequence> {
val smartCharSequences = ArrayList<SmartCharSequence>(others.size)
for (other in others) {
smartCharSequences.add(smart(other))
}
return smartCharSequences
}
@JvmStatic
fun smart(vararg others: SmartCharSequence): SmartCharSequence {
val list = spliceSequences(*others)
return if (list.size == 1) list[0] else SmartSegmentedCharSequence(list)
}
@JvmStatic
fun smart(vararg others: CharSequence): SmartCharSequence {
val list = spliceSequences(others.asList())
return if (list.size == 1) list[0] else SmartSegmentedCharSequence(list)
}
@JvmStatic
fun smart(others: List<CharSequence>): SmartCharSequence {
return if (others.size == 1) others[0].asSmart() else SmartSegmentedCharSequence(others)
}
@Suppress("NAME_SHADOWING")
@JvmStatic
fun trackingSequences(charSequences: List<SmartCharSequence>, startIndex: Int, startOffset: Int, endIndex: Int, endOffset: Int): List<SmartCharSequence> {
var endIndex = endIndex
var endOffset = endOffset
// adjust parameters if endIndex is one past all sequences
if (endIndex == charSequences.size) {
endIndex = charSequences.size - 1
endOffset = charSequences[endIndex].length
}
if (startIndex == endIndex) {
// just one
return listOf(charSequences[startIndex].subSequence(startOffset, endOffset))
} else {
// partial of first and last and in between
val smartCharSequences = ArrayList<SmartCharSequence>(endIndex - startIndex + 1)
smartCharSequences.add(charSequences[startIndex].subSequence(startOffset, charSequences[startIndex].length))
if (endIndex - startIndex > 1) smartCharSequences.addAll(charSequences.subList(startIndex + 1, endIndex))
smartCharSequences.add(charSequences[endIndex].subSequence(0, endOffset))
return smartCharSequences
}
}
@JvmStatic
fun spliceSequences(vararg charSequences: SmartCharSequence): ArrayList<SmartCharSequence> {
if (charSequences.size == 0) {
return ArrayList()
}
val smartCharSequences = ArrayList<SmartCharSequence>()
var charSequence = charSequences[0].contents
val iMax = charSequences.size
for (i in 1..iMax - 1) {
val other = charSequences[i]
val merged = charSequence.splicedWith(other.contents)
if (merged == null) {
smartCharSequences.add(charSequence)
charSequence = other.contents
} else {
charSequence = merged
}
}
smartCharSequences.add(charSequence)
return smartCharSequences
}
@JvmStatic
fun spliceSequences(charSequences: Collection<CharSequence>): ArrayList<SmartCharSequence> {
if (charSequences.size == 0) {
return ArrayList()
}
val smartCharSequences = ArrayList<SmartCharSequence>()
var charSequence: SmartCharSequence? = null
for (other in charSequences) {
if (other.isEmpty() && !(other is SmartCharSequence && other.version.isMutable)) continue
if (charSequence == null) {
charSequence = smartContents(other)
} else {
val merged = charSequence.splicedWith(smartContents(other))
if (merged == null) {
smartCharSequences.add(charSequence)
charSequence = smartContents(other)
} else {
charSequence = merged
}
}
}
if (charSequence != null) smartCharSequences.add(charSequence)
return smartCharSequences
}
@JvmStatic
fun smartContents(charSequence: CharSequence): SmartCharSequence {
if (charSequence !is SmartCharSequenceContainer) return SmartCharSequenceWrapper(charSequence)
return charSequence.contents
}
@JvmStatic
fun editableCharSequence(charSequence: CharSequence): EditableCharSequence {
return if (charSequence is EditableCharSequence) charSequence else EditableCharSequence(charSequence)
}
}
}
| apache-2.0 | 03a3a452a8e937e62760c1c7b0cf57b9 | 36.981855 | 162 | 0.62015 | 5.23015 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/adapter/AlertAdapter.kt | 1 | 2843 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import fr.cph.chicago.R
import fr.cph.chicago.core.model.dto.AlertType
import fr.cph.chicago.core.model.dto.RoutesAlertsDTO
/**
* Adapter that handle alert lists
*
* @author Carl-Philipp Harmant
* @version 1
*/
class AlertAdapter(private var routesAlertsDTOS: List<RoutesAlertsDTO> = listOf()) : BaseAdapter() {
override fun getCount(): Int {
return routesAlertsDTOS.size
}
override fun getItem(position: Int): RoutesAlertsDTO {
return routesAlertsDTOS[position]
}
override fun getItemId(position: Int): Long {
return 0L
}
@SuppressLint("ViewHolder")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val vi = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = vi.inflate(R.layout.list_alerts, parent, false)
val item = getItem(position)
val color = view.findViewById<LinearLayout>(R.id.station_color_value)
color.setBackgroundColor(
if (item.alertType == AlertType.TRAIN)
Color.parseColor(item.routeBackgroundColor)
else
Color.GRAY
)
val stationName = view.findViewById<TextView>(R.id.station_name_value)
stationName.text =
if (item.alertType === AlertType.TRAIN)
item.routeName
else
item.id + " - " + item.routeName
val status = view.findViewById<TextView>(R.id.status)
status.text = item.routeStatus
if ("Normal Service" != item.routeStatus) {
val imageView = view.findViewById<ImageView>(R.id.alert_warning)
imageView.visibility = View.VISIBLE
}
return view
}
fun setAlerts(routesAlertsDTOS: List<RoutesAlertsDTO>) {
this.routesAlertsDTOS = routesAlertsDTOS
}
}
| apache-2.0 | bf9c8c1d37af675ce0da6a3926b8e57b | 30.588889 | 100 | 0.690468 | 4.23696 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/refactoring/RsConvertToNamedFieldsAction.kt | 2 | 2897 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.refactoring
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.actions.BaseRefactoringAction
import org.rust.lang.RsLanguage
import org.rust.lang.core.psi.RsEnumVariant
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RsTupleFields
import org.rust.lang.core.psi.ext.ancestorOrSelf
class RsConvertToNamedFieldsAction : BaseRefactoringAction() {
override fun isAvailableInEditorOnly(): Boolean = true
override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = false
override fun isAvailableOnElementInEditorAndFile(element: PsiElement, editor: Editor, file: PsiFile, context: DataContext): Boolean {
return findTupleStructBody(element) != null
}
override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler
override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RsLanguage)
private object Handler : RefactoringActionHandler {
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
val offset = editor.caretModel.offset
val element = file.findElementAt(offset) ?: return
invoke(project, arrayOf(element), dataContext)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
WriteCommandAction.runWriteCommandAction(project) {
doRefactoring(findTupleStructBody(elements.single())!!)
}
}
}
}
private fun findTupleStructBody(element: PsiElement): RsTupleFields? {
val parent = element.ancestorOrSelf<RsTupleFields>()
if (parent != null) return parent
val struct = element.ancestorOrSelf<RsStructItem>()
if (struct != null) return struct.tupleFields
val enumVariant = element.ancestorOrSelf<RsEnumVariant>()
if (enumVariant != null) return enumVariant.tupleFields
return null
}
private fun doRefactoring(tupleFields: RsTupleFields) {
val fields = tupleFields.tupleFieldDeclList.mapIndexed { idx, field ->
RsPsiFactory.BlockField(field.isPublic, "_$idx", field.typeReference)
}
val blockFields = RsPsiFactory(tupleFields.project).createBlockFields(fields)
val parent = tupleFields.parent
if (parent is RsStructItem) {
parent.semicolon?.delete()
}
tupleFields.replace(blockFields)
}
| mit | ce9152fd8d5396b541a9e908842a67e0 | 36.623377 | 137 | 0.750431 | 4.687702 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/komga/Komga.kt | 1 | 3430 | package eu.kanade.tachiyomi.data.track.komga
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.EnhancedTrackService
import eu.kanade.tachiyomi.data.track.NoLoginTrackService
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import okhttp3.Dns
import okhttp3.OkHttpClient
class Komga(private val context: Context, id: Int) : TrackService(id), EnhancedTrackService, NoLoginTrackService {
companion object {
const val UNREAD = 1
const val READING = 2
const val COMPLETED = 3
}
override val client: OkHttpClient =
networkService.client.newBuilder()
.dns(Dns.SYSTEM) // don't use DNS over HTTPS as it breaks IP addressing
.build()
val api by lazy { KomgaApi(client) }
@StringRes
override fun nameRes() = R.string.tracker_komga
override fun getLogo() = R.drawable.ic_tracker_komga
override fun getLogoColor() = Color.rgb(51, 37, 50)
override fun getStatusList() = listOf(UNREAD, READING, COMPLETED)
override fun getStatus(status: Int): String = with(context) {
when (status) {
UNREAD -> getString(R.string.unread)
READING -> getString(R.string.currently_reading)
COMPLETED -> getString(R.string.completed)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = -1
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> = emptyList()
override fun displayScore(track: Track): String = ""
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
} else {
track.status = READING
}
}
}
return api.updateProgress(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
return track
}
override suspend fun search(query: String): List<TrackSearch> {
TODO("Not yet implemented: search")
}
override suspend fun refresh(track: Track): Track {
val remoteTrack = api.getTrackSearch(track.tracking_url)
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
return track
}
override suspend fun login(username: String, password: String) {
saveCredentials("user", "pass")
}
// TrackService.isLogged works by checking that credentials are saved.
// By saving dummy, unused credentials, we can activate the tracker simply by login/logout
override fun loginNoop() {
saveCredentials("user", "pass")
}
override fun getAcceptedSources() = listOf("eu.kanade.tachiyomi.extension.all.komga.Komga")
override suspend fun match(manga: Manga): TrackSearch? =
try {
api.getTrackSearch(manga.url)
} catch (e: Exception) {
null
}
}
| apache-2.0 | 4b08149a25f25ec9f7272e14265ce3ee | 31.358491 | 114 | 0.661224 | 4.443005 | false | false | false | false |
google/horologist | auth-data/src/main/java/com/google/android/horologist/auth/data/oauth/common/impl/google/api/DeviceCodeResponse.kt | 1 | 1060 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.auth.data.oauth.common.impl.google.api
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
public data class DeviceCodeResponse(
@Json(name = "verification_url") val verificationUri: String,
@Json(name = "user_code") val userCode: String,
@Json(name = "device_code") val deviceCode: String,
@Json(name = "interval") val interval: Int
)
| apache-2.0 | 4e8d57eeb03294ce635fb5d16ed77606 | 36.857143 | 76 | 0.742453 | 3.955224 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCProductCategoryModel.kt | 2 | 1006 | package org.wordpress.android.fluxc.model
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.RawConstraints
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.persistence.WellSqlConfig
@Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE)
@RawConstraints(
"FOREIGN KEY(LOCAL_SITE_ID) REFERENCES SiteModel(_id) ON DELETE CASCADE",
"UNIQUE (REMOTE_CATEGORY_ID, LOCAL_SITE_ID) ON CONFLICT REPLACE"
)
data class WCProductCategoryModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
@Column var localSiteId = 0
@Column var remoteCategoryId = 0L // The unique identifier for this category on the server
@Column var name = ""
@Column var slug = ""
@Column var parent = 0L
override fun getId() = id
override fun setId(id: Int) {
this.id = id
}
}
| gpl-2.0 | 98572478f9150df7cd99317d04962232 | 36.259259 | 95 | 0.750497 | 4.139918 | false | true | false | false |
canou/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/views/Breadcrumbs.kt | 1 | 5651 | package com.simplemobiletools.commons.views
import android.content.Context
import android.graphics.Point
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getBasePath
import com.simplemobiletools.commons.extensions.humanizePath
import com.simplemobiletools.commons.models.FileDirItem
import kotlinx.android.synthetic.main.breadcrumb_item.view.*
class Breadcrumbs(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs), View.OnClickListener {
private var mDeviceWidth: Int = 0
private var mInflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
private var mListener: BreadcrumbsListener? = null
private var mTextColor = 0
init {
mDeviceWidth = getDeviceWidth()
mTextColor = context.baseConfig.textColor
}
fun setListener(listener: BreadcrumbsListener) {
mListener = listener
}
fun setTextColor(color: Int) {
mTextColor = color
}
fun getDeviceWidth(): Int {
val display = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
val deviceDisplay = Point()
display.getSize(deviceDisplay)
return deviceDisplay.x
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val childRight = measuredWidth - paddingRight
val childBottom = measuredHeight - paddingBottom
val childHeight = childBottom - paddingTop
val usableWidth = mDeviceWidth - paddingLeft - paddingRight
var maxHeight = 0
var curWidth: Int
var curHeight: Int
var curLeft = paddingLeft
var curTop = paddingTop
val cnt = childCount
for (i in 0..cnt - 1) {
val child = getChildAt(i)
child.measure(MeasureSpec.makeMeasureSpec(usableWidth, MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST))
curWidth = child.measuredWidth
curHeight = child.measuredHeight
if (curLeft + curWidth >= childRight) {
curLeft = paddingLeft
curTop += maxHeight
maxHeight = 0
}
child.layout(curLeft, curTop, curLeft + curWidth, curTop + curHeight)
if (maxHeight < curHeight)
maxHeight = curHeight
curLeft += curWidth
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val usableWidth = mDeviceWidth - paddingLeft - paddingRight
var width = 0
var rowHeight = 0
var lines = 1
val cnt = childCount
for (i in 0..cnt - 1) {
val child = getChildAt(i)
measureChild(child, widthMeasureSpec, heightMeasureSpec)
width += child.measuredWidth
rowHeight = child.measuredHeight
if (width / usableWidth > 0) {
lines++
width = child.measuredWidth
}
}
val parentWidth = MeasureSpec.getSize(widthMeasureSpec)
val calculatedHeight = paddingTop + paddingBottom + rowHeight * lines
setMeasuredDimension(parentWidth, calculatedHeight)
}
fun setBreadcrumb(fullPath: String) {
val basePath = fullPath.getBasePath(context)
var currPath = basePath
val tempPath = context.humanizePath(fullPath)
removeAllViewsInLayout()
val dirs = tempPath.split("/".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
for (i in dirs.indices) {
val dir = dirs[i]
if (i > 0) {
currPath += dir + "/"
}
if (dir.isEmpty())
continue
if (!currPath.endsWith('/'))
currPath += "/"
val item = FileDirItem(currPath, dir, true, 0, 0)
addBreadcrumb(item, i > 0)
}
}
private fun addBreadcrumb(item: FileDirItem, addPrefix: Boolean) {
mInflater.inflate(R.layout.breadcrumb_item, null, false).apply {
var textToAdd = item.name
if (addPrefix)
textToAdd = "/ $textToAdd"
if (childCount == 0) {
resources.apply {
background = getDrawable(R.drawable.breadcrumb_gradient)
background.colorFilter = PorterDuffColorFilter(mTextColor, PorterDuff.Mode.SRC_IN)
val medium = getDimension(R.dimen.medium_margin).toInt()
setPadding(medium, medium, medium, medium)
}
}
breadcrumb_text.text = textToAdd
breadcrumb_text.setTextColor(mTextColor)
addView(this)
setOnClickListener(this@Breadcrumbs)
tag = item
}
}
fun removeBreadcrumb() {
removeView(getChildAt(childCount - 1))
}
val lastItem: FileDirItem get() = getChildAt(childCount - 1).tag as FileDirItem
override fun onClick(v: View) {
val cnt = childCount
for (i in 0..cnt - 1) {
if (getChildAt(i) != null && getChildAt(i) == v) {
mListener?.breadcrumbClicked(i)
}
}
}
interface BreadcrumbsListener {
fun breadcrumbClicked(id: Int)
}
}
| apache-2.0 | 59089083e9cc554ab558e97fb9251cd9 | 32.046784 | 119 | 0.620598 | 5.045536 | false | false | false | false |
lgou2w/MoonLakeLauncher | src/main/kotlin/com/minecraft/moonlake/launcher/animation/MuiCachedAnimation.kt | 1 | 1863 | /*
* Copyright (C) 2017 The MoonLake Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.launcher.animation
import javafx.animation.Animation
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.Node
open class MuiCachedAnimation(animation: Animation, vararg muiCachedNodes: Node) {
protected var animation: ObjectProperty<Animation> = SimpleObjectProperty()
private var moments: Array<MuiCachedMoment>? = null
init {
if(muiCachedNodes.isNotEmpty())
moments = Array(muiCachedNodes.size, { i -> MuiCachedMoment(muiCachedNodes[i]) })
this.animation.set(animation)
this.animation.get().statusProperty().addListener { _, _, newValue -> run {
when(newValue) {
Animation.Status.RUNNING -> starting()
else -> stopping()
}
}}
}
protected fun starting() {
if(moments != null)
moments!!.forEach { moment -> moment.cached() }
}
protected fun stopping() {
if(moments != null)
moments!!.forEach { moment -> moment.restore() }
}
fun getAnimation(): Animation
= animation.get()
}
| gpl-3.0 | e224e8fa7af39d9ae4f4d40af01de40d | 33.5 | 93 | 0.676329 | 4.383529 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdOrderedListItemImpl.kt | 1 | 3375 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.vladsch.md.nav.actions.handlers.util.PsiEditContext
import com.vladsch.md.nav.psi.api.MdBlockPrefixProvider
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.plugin.util.ifElse
class MdOrderedListItemImpl(node: ASTNode) : MdListItemImpl(node), MdOrderedListItem {
companion object {
@JvmStatic
fun adjustOrderedItemPrefix(listItemOffset: Int, ordinal: Int, listItems: Int, actualItemPrefix: CharSequence, actualTextPrefix: CharSequence, LIST_RENUMBER_ITEMS: Boolean?, LIST_ALIGN_NUMERIC: Int?, editContext: PsiEditContext): CharSequence {
return MdBlockPrefixProvider.getAdjustedOrderedItemPrefix(listItemOffset, ordinal, listItems, actualItemPrefix, actualTextPrefix, LIST_RENUMBER_ITEMS, LIST_ALIGN_NUMERIC, editContext)
}
}
override fun getListItemMarker(): ASTNode? {
return node.findChildByType(MdTypes.ORDERED_LIST_ITEM_MARKER)
}
override fun getTaskItemPriority(editContext: PsiEditContext): Int {
return isTaskItem.ifElse(isEmptyItem.ifElse(MdListItem.LOW_PRIORITY, MdBlockPrefixProvider.getOrderedTaskItemPriority(editContext)), -1)
}
private fun itemPrefixOffset(editContext: PsiEditContext): Int {
return (parent as? MdOrderedList)?.itemOrdinalOffset(false, editContext) ?: 0
}
override fun itemPrefix(editContext: PsiEditContext): CharSequence {
val ordinal = MdPsiImplUtil.childElementOrdinal(this)
val offset = itemPrefixOffset(editContext) + 1
return itemPrefix(offset, ordinal, parent.children.size, editContext)
}
override fun itemPrefixForPrefixes(editContext: PsiEditContext): CharSequence {
val actualTextPrefix = actualTextPrefix(this, editContext, true)
val itemPrefix = itemPrefix(editContext)
val prefix = actualTextPrefix.replaceFirst("\\s*\\d+[.)]\\s*".toRegex(), itemPrefix.toString())
return MdBlockPrefixProvider.getAdjustedTaskItemPrefix(prefix, editContext)
}
fun itemPrefix(listItemOffset: Int, ordinal: Int, listItems: Int, editContext: PsiEditContext): CharSequence {
return adjustOrderedItemPrefix(listItemOffset, ordinal, listItems, actualItemPrefix(editContext), actualTextPrefix(editContext, true), null, null, editContext)
}
override fun itemTextPrefix(editContext: PsiEditContext): CharSequence {
val actualTextPrefix = actualTextPrefix(editContext, true)
val actualItemPrefix = actualItemPrefix(editContext)
val itemPrefix = itemPrefix(editContext)
val rightPad = actualTextPrefix.length - actualItemPrefix.length
return if (rightPad > 0) itemPrefix.toString() + " ".repeat(rightPad) else itemPrefix
}
override fun getStructureViewPresentation(): ItemPresentation {
return super.getStructureViewPresentation()
}
override fun getLocationString(): String? {
return super.getLocationString()
}
override fun getPresentableText(): String? {
return super.getPresentableText()
}
}
| apache-2.0 | 74c3b839c3538ed57562e04b3dd078c7 | 47.214286 | 252 | 0.751111 | 4.62963 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/fragments/MeetingFragment.kt | 1 | 2706 | package nl.ecci.hamers.ui.fragments
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_hamers_list.*
import nl.ecci.hamers.R
import nl.ecci.hamers.data.GetCallback
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.models.Meeting
import nl.ecci.hamers.ui.activities.MainActivity
import nl.ecci.hamers.ui.activities.NewMeetingActivity
import nl.ecci.hamers.ui.adapters.MeetingAdapter
import java.util.*
class MeetingFragment : HamersListFragment() {
private val dataSet = ArrayList<Meeting>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_hamers_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hamers_list.adapter = MeetingAdapter(dataSet, activity!!)
hamers_fab.setOnClickListener { startActivityForResult(Intent(activity, NewMeetingActivity::class.java), 1) }
}
override fun onRefresh() {
setRefreshing(true)
Loader.getData(requireContext(), Loader.MEETINGURL, -1, object : GetCallback {
override fun onSuccess(response: String) {
populateList().execute(response)
}
}, null)
}
override fun onResume() {
super.onResume()
onRefresh()
activity?.title = resources.getString(R.string.navigation_item_meetings)
}
private inner class populateList : AsyncTask<String, Void, ArrayList<Meeting>>() {
override fun doInBackground(vararg params: String): ArrayList<Meeting> {
val result: ArrayList<Meeting>
val type = object : TypeToken<ArrayList<Meeting>>() {
}.type
val gsonBuilder = GsonBuilder().setDateFormat(MainActivity.dbDF.toPattern())
val gson = gsonBuilder.create()
result = if (params.isNotEmpty()) {
gson.fromJson<ArrayList<Meeting>>(params[0], type)
} else {
gson.fromJson<ArrayList<Meeting>>(prefs?.getString(Loader.MEETINGURL, null), type)
}
return result
}
override fun onPostExecute(result: ArrayList<Meeting>) {
if (result.isNotEmpty()) {
dataSet.clear()
dataSet.addAll(result)
notifyAdapter()
}
setRefreshing(false)
}
}
}
| gpl-3.0 | 99fb58b7040e6ce378a26f5362445b33 | 34.605263 | 117 | 0.669993 | 4.633562 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt | 1 | 15136 | package eu.kanade.tachiyomi.data.download
import android.content.Context
import android.net.Uri
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.download.model.DownloadQueue
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.source.SourceManager
import eu.kanade.tachiyomi.data.source.base.Source
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.event.DownloadChaptersEvent
import eu.kanade.tachiyomi.util.*
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import timber.log.Timber
import java.io.File
import java.io.FileReader
import java.util.*
class DownloadManager(private val context: Context, private val sourceManager: SourceManager, private val preferences: PreferencesHelper) {
private val gson = Gson()
private val downloadsQueueSubject = PublishSubject.create<List<Download>>()
val runningSubject = BehaviorSubject.create<Boolean>()
private var downloadsSubscription: Subscription? = null
private val threadsSubject = BehaviorSubject.create<Int>()
private var threadsSubscription: Subscription? = null
val queue = DownloadQueue()
val imageFilenameRegex = "[^\\sa-zA-Z0-9.-]".toRegex()
val PAGE_LIST_FILE = "index.json"
@Volatile private var isRunning: Boolean = false
private fun initializeSubscriptions() {
downloadsSubscription?.unsubscribe()
threadsSubscription = preferences.downloadThreads().asObservable()
.subscribe { threadsSubject.onNext(it) }
downloadsSubscription = downloadsQueueSubject.flatMap { Observable.from(it) }
.lift(DynamicConcurrentMergeOperator<Download, Download>({ downloadChapter(it) }, threadsSubject))
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread())
.map { download -> areAllDownloadsFinished() }
.subscribe({ finished ->
if (finished!!) {
DownloadService.stop(context)
}
}, { e ->
DownloadService.stop(context)
Timber.e(e, e.message)
context.toast(e.message)
})
if (!isRunning) {
isRunning = true
runningSubject.onNext(true)
}
}
fun destroySubscriptions() {
if (isRunning) {
isRunning = false
runningSubject.onNext(false)
}
if (downloadsSubscription != null) {
downloadsSubscription?.unsubscribe()
downloadsSubscription = null
}
if (threadsSubscription != null) {
threadsSubscription?.unsubscribe()
}
}
// Create a download object for every chapter in the event and add them to the downloads queue
fun onDownloadChaptersEvent(event: DownloadChaptersEvent) {
val manga = event.manga
val source = sourceManager.get(manga.source)
// Used to avoid downloading chapters with the same name
val addedChapters = ArrayList<String>()
val pending = ArrayList<Download>()
for (chapter in event.chapters) {
if (addedChapters.contains(chapter.name))
continue
addedChapters.add(chapter.name)
val download = Download(source, manga, chapter)
if (!prepareDownload(download)) {
queue.add(download)
pending.add(download)
}
}
if (isRunning) downloadsQueueSubject.onNext(pending)
}
// Public method to check if a chapter is downloaded
fun isChapterDownloaded(source: Source, manga: Manga, chapter: Chapter): Boolean {
val directory = getAbsoluteChapterDirectory(source, manga, chapter)
if (!directory.exists())
return false
val pages = getSavedPageList(source, manga, chapter)
return isChapterDownloaded(directory, pages)
}
// Prepare the download. Returns true if the chapter is already downloaded
private fun prepareDownload(download: Download): Boolean {
// If the chapter is already queued, don't add it again
for (queuedDownload in queue) {
if (download.chapter.id == queuedDownload.chapter.id)
return true
}
// Add the directory to the download object for future access
download.directory = getAbsoluteChapterDirectory(download)
// If the directory doesn't exist, the chapter isn't downloaded.
if (!download.directory.exists()) {
return false
}
// If the page list doesn't exist, the chapter isn't downloaded
val savedPages = getSavedPageList(download) ?: return false
// Add the page list to the download object for future access
download.pages = savedPages
// If the number of files matches the number of pages, the chapter is downloaded.
// We have the index file, so we check one file more
return isChapterDownloaded(download.directory, download.pages)
}
// Check that all the images are downloaded
private fun isChapterDownloaded(directory: File, pages: List<Page>?): Boolean {
return pages != null && !pages.isEmpty() && pages.size + 1 == directory.listFiles().size
}
// Download the entire chapter
private fun downloadChapter(download: Download): Observable<Download> {
DiskUtils.createDirectory(download.directory)
val pageListObservable = if (download.pages == null)
// Pull page list from network and add them to download object
download.source.pullPageListFromNetwork(download.chapter.url)
.doOnNext { pages ->
download.pages = pages
savePageList(download)
}
else
// Or if the page list already exists, start from the file
Observable.just(download.pages)
return Observable.defer { pageListObservable
.doOnNext { pages ->
download.downloadedImages = 0
download.status = Download.DOWNLOADING
}
// Get all the URLs to the source images, fetch pages if necessary
.flatMap { download.source.getAllImageUrlsFromPageList(it) }
// Start downloading images, consider we can have downloaded images already
.concatMap { page -> getOrDownloadImage(page, download) }
// Do after download completes
.doOnCompleted { onDownloadCompleted(download) }
.toList()
.map { pages -> download }
// If the page list threw, it will resume here
.onErrorResumeNext { error ->
download.status = Download.ERROR
Observable.just(download)
}
}.subscribeOn(Schedulers.io())
}
// Get the image from the filesystem if it exists or download from network
private fun getOrDownloadImage(page: Page, download: Download): Observable<Page> {
// If the image URL is empty, do nothing
if (page.imageUrl == null)
return Observable.just(page)
val filename = getImageFilename(page)
val imagePath = File(download.directory, filename)
// If the image is already downloaded, do nothing. Otherwise download from network
val pageObservable = if (isImageDownloaded(imagePath))
Observable.just(page)
else
downloadImage(page, download.source, download.directory, filename)
return pageObservable
// When the image is ready, set image path, progress (just in case) and status
.doOnNext {
page.imagePath = imagePath.absolutePath
page.progress = 100
download.downloadedImages++
page.status = Page.READY
}
// Mark this page as error and allow to download the remaining
.onErrorResumeNext {
page.progress = 0
page.status = Page.ERROR
Observable.just(page)
}
}
// Save image on disk
private fun downloadImage(page: Page, source: Source, directory: File, filename: String): Observable<Page> {
page.status = Page.DOWNLOAD_IMAGE
return source.getImageProgressResponse(page)
.flatMap {
it.body().source().saveTo(File(directory, filename))
Observable.just(page)
}
.retry(2)
}
// Public method to get the image from the filesystem. It does NOT provide any way to download the image
fun getDownloadedImage(page: Page, chapterDir: File): Observable<Page> {
if (page.imageUrl == null) {
page.status = Page.ERROR
return Observable.just(page)
}
val imagePath = File(chapterDir, getImageFilename(page))
// When the image is ready, set image path, progress (just in case) and status
if (isImageDownloaded(imagePath)) {
page.imagePath = imagePath.absolutePath
page.progress = 100
page.status = Page.READY
} else {
page.status = Page.ERROR
}
return Observable.just(page)
}
// Get the filename for an image given the page
private fun getImageFilename(page: Page): String {
val url = page.imageUrl
val number = String.format("%03d", page.pageNumber + 1)
// Try to preserve file extension
return when {
UrlUtil.isJpg(url) -> "$number.jpg"
UrlUtil.isPng(url) -> "$number.png"
UrlUtil.isGif(url) -> "$number.gif"
else -> Uri.parse(url).lastPathSegment.replace(imageFilenameRegex, "_")
}
}
private fun isImageDownloaded(imagePath: File): Boolean {
return imagePath.exists()
}
// Called when a download finishes. This doesn't mean the download was successful, so we check it
private fun onDownloadCompleted(download: Download) {
checkDownloadIsSuccessful(download)
savePageList(download)
}
private fun checkDownloadIsSuccessful(download: Download) {
var actualProgress = 0
var status = Download.DOWNLOADED
// If any page has an error, the download result will be error
for (page in download.pages) {
actualProgress += page.progress
if (page.status != Page.READY) status = Download.ERROR
}
// Ensure that the chapter folder has all the images
if (!isChapterDownloaded(download.directory, download.pages)) {
status = Download.ERROR
}
download.totalProgress = actualProgress
download.status = status
// Delete successful downloads from queue after notifying
if (status == Download.DOWNLOADED) {
queue.del(download)
}
}
// Return the page list from the chapter's directory if it exists, null otherwise
fun getSavedPageList(source: Source, manga: Manga, chapter: Chapter): List<Page>? {
val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter)
val pagesFile = File(chapterDir, PAGE_LIST_FILE)
return try {
JsonReader(FileReader(pagesFile)).use {
val collectionType = object : TypeToken<List<Page>>() {}.type
gson.fromJson(it, collectionType)
}
} catch (e: Exception) {
null
}
}
// Shortcut for the method above
private fun getSavedPageList(download: Download): List<Page>? {
return getSavedPageList(download.source, download.manga, download.chapter)
}
// Save the page list to the chapter's directory
fun savePageList(source: Source, manga: Manga, chapter: Chapter, pages: List<Page>) {
val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter)
val pagesFile = File(chapterDir, PAGE_LIST_FILE)
pagesFile.outputStream().use {
try {
it.write(gson.toJson(pages).toByteArray())
it.flush()
} catch (e: Exception) {
Timber.e(e, e.message)
}
}
}
// Shortcut for the method above
private fun savePageList(download: Download) {
savePageList(download.source, download.manga, download.chapter, download.pages)
}
fun getAbsoluteMangaDirectory(source: Source, manga: Manga): File {
val mangaRelativePath = source.visibleName +
File.separator +
manga.title.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_")
return File(preferences.downloadsDirectory().getOrDefault(), mangaRelativePath)
}
// Get the absolute path to the chapter directory
fun getAbsoluteChapterDirectory(source: Source, manga: Manga, chapter: Chapter): File {
val chapterRelativePath = chapter.name.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_")
return File(getAbsoluteMangaDirectory(source, manga), chapterRelativePath)
}
// Shortcut for the method above
private fun getAbsoluteChapterDirectory(download: Download): File {
return getAbsoluteChapterDirectory(download.source, download.manga, download.chapter)
}
fun deleteChapter(source: Source, manga: Manga, chapter: Chapter) {
val path = getAbsoluteChapterDirectory(source, manga, chapter)
DiskUtils.deleteFiles(path)
}
fun areAllDownloadsFinished(): Boolean {
for (download in queue) {
if (download.status <= Download.DOWNLOADING)
return false
}
return true
}
fun startDownloads(): Boolean {
if (queue.isEmpty())
return false
if (downloadsSubscription == null || downloadsSubscription!!.isUnsubscribed)
initializeSubscriptions()
val pending = ArrayList<Download>()
for (download in queue) {
if (download.status != Download.DOWNLOADED) {
if (download.status != Download.QUEUE) download.status = Download.QUEUE
pending.add(download)
}
}
downloadsQueueSubject.onNext(pending)
return !pending.isEmpty()
}
fun stopDownloads() {
destroySubscriptions()
for (download in queue) {
if (download.status == Download.DOWNLOADING) {
download.status = Download.ERROR
}
}
}
}
| apache-2.0 | 76bb08787df1fea94cff1e376886f650 | 36.651741 | 139 | 0.624471 | 5.006947 | false | false | false | false |
KieranP/Game-Of-Life-Implementations | kotlin/world.kt | 1 | 4550 | public class World(
private val width: Int,
private val height: Int
) {
private class LocationOccupied(): Exception()
public var tick = 0
private val cells = HashMap<String, Cell>()
private val cached_directions = arrayOf(
intArrayOf(-1, 1), intArrayOf(0, 1), intArrayOf(1, 1), // above
intArrayOf(-1, 0), intArrayOf(1, 0), // sides
intArrayOf(-1, -1), intArrayOf(0, -1), intArrayOf(1, -1) // below
)
init {
populate_cells()
prepopulate_neighbours()
}
public fun _tick() {
// First determine the action for all cells
for ((_, cell) in cells) {
val alive_neighbours = alive_neighbours_around(cell)
if (!cell.alive && alive_neighbours == 3) {
cell.next_state = true
} else if (alive_neighbours < 2 || alive_neighbours > 3) {
cell.next_state = false
} else {
cell.next_state = cell.alive
}
}
// Then execute the determined action for all cells
for ((_, cell) in cells) {
cell.alive = cell.next_state!!
}
tick++
}
// Implement first using string concatenation. Then implement any
// special string builders, and use whatever runs the fastest
public fun render(): String {
// The following works but is slower
// var rendering = ""
// for (y in 0 until height) {
// for (x in 0 until width) {
// val cell = cell_at(x, y)!!
// rendering += cell.to_char()
// }
// rendering += "\n"
// }
// return rendering
// The following works but is slower
// val rendering = ArrayList<String>();
// for (y in 0 until height) {
// for (x in 0 until width) {
// val cell = cell_at(x, y)!!
// rendering.add(cell.to_char().toString())
// }
// rendering.add("\n")
// }
// return rendering.joinToString(separator = "");
// The following was the fastest method
val rendering = StringBuilder()
for (y in 0 until height) {
for (x in 0 until width) {
// !! tells the compiler we expect a value to be there
val cell = cell_at(x, y)!!
rendering.append(cell.to_char())
}
rendering.append("\n")
}
return rendering.toString()
}
private fun populate_cells() {
for (y in 0 until height) {
for (x in 0 until width) {
val alive = (Math.random() <= 0.2)
add_cell(x, y, alive)
}
}
}
private fun prepopulate_neighbours() {
for ((_, cell) in cells) {
neighbours_around(cell)
}
}
private fun add_cell(x: Int, y: Int, alive: Boolean = false): Cell {
if (cell_at(x, y) != null) { // Must return a boolean
throw LocationOccupied()
}
val cell = Cell(x, y, alive)
cells.put("$x-$y", cell)
// !! tells the compiler we expect a value to be there
return cell_at(x, y)!!
}
private fun cell_at(x: Int, y: Int): Cell? {
return cells["$x-$y"]
}
private fun neighbours_around(cell: Cell): ArrayList<Cell> {
if (cell.neighbours == null) { // Must return a boolean
cell.neighbours = ArrayList<Cell>()
for ((rel_x, rel_y) in cached_directions) {
val neighbour = cell_at(
(cell.x + rel_x),
(cell.y + rel_y)
)
if (neighbour != null) {
// !! tells the compiler we expect a value to be there
cell.neighbours!!.add(neighbour)
}
}
}
// !! tells the compiler we expect a value to be there
return cell.neighbours!!
}
private fun alive_neighbours_around(cell: Cell): Int {
// The following works but is slower
// val neighbours = neighbours_around(cell)
// return neighbours.filter { it.alive }.size
// The following works but is slower
// var alive_neighbours = 0
// val neighbours = neighbours_around(cell)
// for (neighbour in neighbours) {
// if (neighbour.alive) {
// alive_neighbours += 1
// }
// }
// return alive_neighbours
// The following was the fastest method
var alive_neighbours = 0
val neighbours = neighbours_around(cell)
for (i in 0 until neighbours.size) {
val neighbour = neighbours.get(i)
if (neighbour.alive) {
alive_neighbours++
}
}
return alive_neighbours
}
}
public class Cell(
public val x: Int,
public val y: Int,
public var alive: Boolean = false
) {
public var next_state: Boolean? = null
public var neighbours: ArrayList<Cell>? = null
fun to_char(): Char {
return if (this.alive) 'o' else ' '
}
}
| mit | 65f21a1f332dffc34b8d218769f0950a | 25.608187 | 70 | 0.576923 | 3.754125 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/LeaveNoteInsteadFragment.kt | 1 | 3557 | package de.westnordost.streetcomplete.quests
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.quest.QuestKey
import de.westnordost.streetcomplete.databinding.FormLeaveNoteBinding
import de.westnordost.streetcomplete.databinding.FragmentQuestAnswerBinding
import de.westnordost.streetcomplete.ktx.viewBinding
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/** Bottom sheet fragment with which the user can leave a note instead of solving the quest */
class LeaveNoteInsteadFragment : AbstractCreateNoteFragment(), IsShowingQuestDetails {
private var _binding: FragmentQuestAnswerBinding? = null
private val binding: FragmentQuestAnswerBinding get() = _binding!!
override val bottomSheetContainer get() = binding.bottomSheetContainer
override val bottomSheet get() = binding.bottomSheet
override val scrollViewChild get() = binding.scrollViewChild
override val bottomSheetTitle get() = binding.speechBubbleTitleContainer
override val bottomSheetContent get() = binding.speechbubbleContentContainer
override val floatingBottomView get() = binding.okButton
override val backButton get() = binding.closeButton
override val okButton get() = binding.okButton
private val contentBinding by viewBinding(FormLeaveNoteBinding::bind, R.id.content)
override val noteInput get() = contentBinding.noteInput
interface Listener {
fun onCreatedNoteInstead(questKey: QuestKey, questTitle: String, note: String, imagePaths: List<String>)
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
private lateinit var questTitle: String
override lateinit var questKey: QuestKey
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
val args = requireArguments()
questTitle = args.getString(ARG_QUEST_TITLE)!!
questKey = Json.decodeFromString(args.getString(ARG_QUEST_KEY)!!)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentQuestAnswerBinding.inflate(inflater, container, false)
inflater.inflate(R.layout.form_leave_note, binding.content)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonPanel.isGone = true
contentBinding.descriptionLabel.isGone = true
binding.titleLabel.text = getString(R.string.map_btn_create_note)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onComposedNote(text: String, imagePaths: List<String>) {
listener?.onCreatedNoteInstead(questKey, questTitle, text, imagePaths)
}
companion object {
private const val ARG_QUEST_TITLE = "questTitle"
private const val ARG_QUEST_KEY = "questKey"
fun create(questKey: QuestKey, questTitle: String): LeaveNoteInsteadFragment {
val f = LeaveNoteInsteadFragment()
f.arguments = bundleOf(
ARG_QUEST_KEY to Json.encodeToString(questKey),
ARG_QUEST_TITLE to questTitle
)
return f
}
}
}
| gpl-3.0 | 9afe3a84aae7f0176a6d1cbc9dd5941d | 39.420455 | 116 | 0.739387 | 4.774497 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/speakers/Speaker.kt | 1 | 1608 | package org.fossasia.openevent.general.speakers
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
import com.github.jasminb.jsonapi.LongIdHandler
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.Type
import org.fossasia.openevent.general.auth.UserId
import org.fossasia.openevent.general.event.EventId
@Type("speaker")
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
@Entity
data class Speaker(
@Id(LongIdHandler::class)
@PrimaryKey
val id: Long,
val name: String? = null,
val email: String? = null,
val photoUrl: String? = null,
val shortBiography: String? = null,
val longBiography: String? = null,
val speakingExperience: String? = null,
val position: String? = null,
val mobile: String? = null,
val location: String? = null,
val country: String? = null,
val city: String? = null,
val organisation: String? = null,
val gender: String? = null,
val website: String? = null,
val twitter: String? = null,
val facebook: String? = null,
val linkedin: String? = null,
val github: String? = null,
val heardFrom: String? = null,
val isFeatured: Boolean = false,
@ColumnInfo(index = true)
@Relationship("event")
val event: EventId? = null,
@ColumnInfo(index = true)
@Relationship("user")
val user: UserId? = null
)
| apache-2.0 | 4527666a44cdbc6813206692106f0ee1 | 31.816327 | 60 | 0.722015 | 3.819477 | false | false | false | false |
naosim/rtmjava | src/main/java/com/naosim/someapp/infra/api/task/list/TaskListApi.kt | 1 | 933 | package com.naosim.someapp.infra.api.task.list
import com.naosim.rtm.domain.model.auth.Token
import com.naosim.someapp.domain.タスクEntity
import com.naosim.someapp.infra.MapConverter
import com.naosim.someapp.infra.RepositoryFactory
import com.naosim.someapp.infra.api.lib.Api
class TaskListApi(val repositoryFactory: RepositoryFactory): Api<TaskListRequest> {
val mapConvertor = MapConverter()
override val description = "タスク取得"
override val path = "/task/list"
override val requestParams = TaskListRequest()
override val ok: (TaskListRequest) -> Any = {
val タスクEntityList: List<タスクEntity> = getTaskList(it.token.get())
mapConvertor.apiOkResult(タスクEntityList.map { mapConvertor.toMap(it) })
}
fun getTaskList(token: Token): List<タスクEntity> {
return repositoryFactory.createタスクRepository(token).すべてのタスク取得()
}
} | mit | fc1f284ce44ef58d861f5c4bfa382962 | 36.826087 | 83 | 0.750288 | 3.862222 | false | false | false | false |
jonninja/node.kt | src/main/kotlin/node/inject/inject.kt | 1 | 7945 | package node.inject
import java.util.HashMap
import kotlin.properties.ReadWriteProperty
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import javax.naming.OperationNotSupportedException
import node.NotFoundException
import node.util._with
import node.configuration.Configuration
import node.inject.Registry.BindingReceiver
import node.util.konstructor
enum class CacheScope {
GLOBAL,
OPERATION,
SESSION
}
interface IFactory {
fun instanceOf<T:Any?>(clazz: Class<T>, name: String? = null): T
fun install<T>(instance: T, clazz: Class<T>, name: String? = null)
}
/**
* Creates and manages instances of bound classes. Instances are cached based on the CacheScope that
* is bound to the instance. For example, if a class is bound with an OPERATION scope, a Factory with that
* scope will cache the instance.
*/
@suppress("UNCHECKED_CAST")
open class Factory(val registry: Registry, val scope: CacheScope, val parent: Factory? = null) {
val cache = HashMap<String, Any?>()
open fun instanceOf<T:Any>(clazz: Class<T>): T? {
return instanceOf(clazz, null)
}
/**
* Get an instance of the given class, optionally bound to the given name.
*/
open fun instanceOf<T:Any>(clazz: Class<T>, name: String?): T? {
if (clazz == javaClass<Factory>()) {
return this as T;
}
if (clazz == javaClass<Registry>()) {
return registry as T;
}
val binding = registry.getBinding(clazz, name)
if (binding == null) {
try {
return ConstructorBinding(clazz).instance(this, name)
} catch(e: Exception) {
throw NotFoundException("No binding found for ${bindingKey(clazz, name)}")
}
}
return if (binding.scope == null) {
if (cache.containsKey(bindingKey(clazz, binding.name))) {
return cache.get(bindingKey(clazz, binding.name)) as T
}
binding.binding.instance(this, name)
} else if (binding.scope == this.scope) {
if (cache.containsKey(bindingKey(clazz, binding.name))) {
cache.get(bindingKey(clazz, binding.name)) as T
} else {
synchronized(binding) {
_with (binding.binding.instance(this, binding.name)) {
cache.put(bindingKey(clazz, binding.name), it)
}
}
}
} else if (parent != null) {
parent.instanceOf(clazz, name)
} else {
// if the type is bound to a scope, but it is not this one, we have a problem
throw IllegalStateException("Unable to create ${clazz.getCanonicalName()} in the scope that it was bound to. Make sure you are using a factory with the correct cache scope.")
}
}
/**
* Install an instance into the Factory. Useful if you have objects that can't be instantiated
* with the standard bindings that you need to make available to bound instances.
*/
fun install<T:Any>(instance: T?, clazz: Class<T>, name: String? = null) {
cache.put(bindingKey(clazz, name), instance)
if (registry.getBinding(clazz, name) == null) {
registry.bind(clazz, name)
}
}
/**
* Install a string value
*/
fun installString(name: String, value: String?) {
install(value, javaClass<String>(), name)
}
/**
* Get a string value from the facotry
*/
fun getString(name: String): String? {
val result = instanceOf(javaClass<String>(), name)
if (result != null && result.length() == 0) {
return null
} else {
return result
}
}
}
fun bindingKey<T>(src: Class<T>, name: String? = null): String {
return "${src.getCanonicalName()}${if (name != null) name else ""}"
}
/**
* A registry of class bindings to be used by the factory.
*/
@suppress("UNCHECKED_CAST")
open class Registry(val parentRegistry: Registry? = null) {
val bindings = hashMapOf<String, BindingReceiver<*>>()
val globalFactory = Factory(this, CacheScope.GLOBAL, null)
/**
* Bind a class to the registry. The binding is not complete until one of the methods
* of the BindingReciever is called: ie. bind(String.class).to("foo")
*/
fun <T> bind(src: Class<T>, name: String? = null): BindingReceiver<T> {
return _with(BindingReceiver<T>(src, name)) {
bindings.put("${src.getCanonicalName()}${if (name != null) name else ""}", it)
}
}
/**
* Short hand for binding strings
*/
fun bindString(name: String, value: String) {
this.bind(javaClass<String>(), name).toInstance(value)
}
fun get(key: Any): Binding<*>? {
return bindings[key]?.binding
}
@suppress("BASE_WITH_NULLABLE_UPPER_BOUND")
public class BindingReceiver<T>(val src: Class<T>, val name: String? = null) {
var binding: Binding<T> = ConstructorBinding(src)
var scope: CacheScope? = null
var cached: T? = null
/**
* Bind a class to a key. The class's constructor will be called to create the instance when the key
* is requested.
*/
fun <I:T> toImplementation(target: Class<I>): BindingReceiver<T> {
binding = ConstructorBinding(target)
return this;
}
/**
* Bind an instance to a key.
*/
fun <I:T> toInstance(target: I): BindingReceiver<T> {
binding = InstanceBinding(target)
return this
}
@suppress("UNUSED_PARAMETER")
fun to(ignored: Any?) {
throw IllegalArgumentException("This is probably not what you want! Use toInstance to map to an instance")
}
/**
* Bind a callback to a key.
*/
fun toFactory(target: (factory: Factory, name: String?)->T): BindingReceiver<T> {
binding = LiteralBinding(target)
return this
}
fun withScope(scope: CacheScope): BindingReceiver<T> {
this.scope = scope
return this
}
}
open fun getBinding<T>(clazz: Class<T>, name: String? = null): BindingReceiver<T>? {
val key = bindingKey(clazz, name)
var result = bindings[key] as? BindingReceiver<T> ?: parentRegistry?.getBinding(clazz, name)
if (result == null && name != null) {
result = getBinding(clazz) // get a binding without a name
}
return result
}
/**
* Get a factory for this registry, bound to the given cache scope.
*/
public fun factory(scope: CacheScope? = null): Factory {
if (scope == null || scope == CacheScope.GLOBAL) {
return globalFactory
} else {
return Factory(this, scope, globalFactory)
}
}
}
/**
* A registry that reads instances from Configuration
*/
@suppress("UNCHECKED_CAST")
class ConfigurationRegistry(parentRegistry: Registry? = null): Registry(parentRegistry) {
override fun <T> getBinding(clazz: Class<T>, name: String?): Registry.BindingReceiver<T>? {
if (name != null) {
val configValue = Configuration.get(name)
if (configValue != null) {
return BindingReceiver(clazz, name).toInstance(configValue as T)
}
}
return super<Registry>.getBinding(clazz, name)
}
}
private interface Binding<T> {
fun instance(factory: Factory, name: String?): T
}
private class ConstructorBinding<T,I:T>(val clazz: Class<I>): Binding<T> {
override fun instance(factory: Factory, name: String?): T {
return clazz.konstructor().newInstance({ p ->
val pname = p.getAnnotation(javaClass<named>())?.key ?: p.name
@suppress("UNCHECKED_CAST")
factory.instanceOf(p.jType as Class<T>, pname)
})
}
}
private class InstanceBinding<T>(val instance: T): Binding<T> {
override fun instance(factory: Factory, name: String?): T {
return instance
}
}
private class LiteralBinding<T>(val factory: (factory: Factory, name: String?)->T): Binding<T> {
override fun instance(factory: Factory, name: String?): T {
return factory(factory, name)
}
}
/**
* Key annotation. Allows for annotating a parameter such that the injected instance will
* relate to that key. Useful for when you want to have available different versions of the
* same type.
*/
Retention(RetentionPolicy.RUNTIME)
annotation class named(val key: String) | mit | 6194dca848df53b233089e5f760987b4 | 30.039063 | 180 | 0.660164 | 3.8927 | false | false | false | false |
McGars/percents | feature/details/src/main/java/com/gars/percents/details/presentation/adapter/CalculateTableAdapter.kt | 1 | 3633 | package com.gars.percents.details.presentation.adapter
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.cleveroad.adaptivetablelayout.LinkedAdaptiveTableAdapter
import com.cleveroad.adaptivetablelayout.ViewHolder
import com.cleveroad.adaptivetablelayout.ViewHolderImpl
import com.gars.percents.details.R
import com.gars.percents.details.databinding.ItemCellBinding
import com.gars.percents.details.databinding.ItemCornerCellBinding
import com.gars.percents.details.databinding.ItemHeaderColumnCellBinding
import com.gars.percents.details.databinding.ItemHeaderRowCellBinding
import com.gars.percents.common.dp
import com.gars.percents.common.inflate
class CalculateTableAdapter(
private val source: TableDataSource
) : LinkedAdaptiveTableAdapter() {
private companion object {
const val TOTAL_COLUMNS = 5
}
override fun getRowCount(): Int = source.size
override fun getColumnCount(): Int = TOTAL_COLUMNS
override fun onCreateItemViewHolder(parent: ViewGroup): ViewHolderImpl =
CellViewHolder(parent.inflate(R.layout.item_cell))
override fun onCreateColumnHeaderViewHolder(parent: ViewGroup): ViewHolderImpl =
ColumnHeaderViewHolder(parent.inflate(R.layout.item_header_column_cell))
override fun onCreateRowHeaderViewHolder(parent: ViewGroup): ViewHolderImpl =
RowHeaderViewHolder(parent.inflate(R.layout.item_header_row_cell))
override fun onCreateLeftTopHeaderViewHolder(parent: ViewGroup): ViewHolderImpl =
CornerViewHolder(parent.inflate(R.layout.item_corner_cell))
override fun onBindViewHolder(viewHolder: ViewHolder, row: Int, column: Int) {
val vh = viewHolder as CellViewHolder
val item = source.getCellData(column, row)
vh.viewBinding.tvTitle.text = item.text
vh.viewBinding.tvTitle.setTextColor(item.textColor)
vh.viewBinding.tvSubtitle.isVisible = item.subtext.isNullOrBlank().not()
vh.viewBinding.tvSubtitle.text = item.subtext
}
override fun onBindHeaderColumnViewHolder(viewHolder: ViewHolder, column: Int) {
val vh = viewHolder as ColumnHeaderViewHolder
val headerData = source.getHeaderData(column)
vh.viewBinding.tvTitle.text = concatenateWithNewLineSeparator(headerData.text, headerData.subtext)
}
override fun onBindHeaderRowViewHolder(viewHolder: ViewHolder, row: Int) {
val vh = viewHolder as RowHeaderViewHolder
vh.viewBinding.tvTitle.text = row.toString()
}
override fun onBindLeftTopHeaderViewHolder(viewHolder: ViewHolder) {
}
override fun getColumnWidth(column: Int): Int = 90.dp
override fun getRowHeight(row: Int): Int = 50.dp
override fun getHeaderColumnHeight(): Int = 50.dp
override fun getHeaderRowWidth(): Int = 30.dp
private class CellViewHolder(itemView: View) : ViewHolderImpl(itemView) {
val viewBinding = ItemCellBinding.bind(itemView)
}
private class ColumnHeaderViewHolder(itemView: View) : ViewHolderImpl(itemView) {
val viewBinding = ItemHeaderColumnCellBinding.bind(itemView)
}
private class RowHeaderViewHolder(itemView: View) : ViewHolderImpl(itemView) {
val viewBinding = ItemHeaderRowCellBinding.bind(itemView)
}
private class CornerViewHolder(itemView: View) : ViewHolderImpl(itemView) {
val viewBinding = ItemCornerCellBinding.bind(itemView)
}
private fun concatenateWithNewLineSeparator(vararg texts: String?): String {
return texts
.mapNotNull { it }
.joinToString(separator = " /\n")
}
} | apache-2.0 | 23b733421f9fac88f481b091a14a8d14 | 36.854167 | 106 | 0.752271 | 4.54125 | false | false | false | false |
pokk/mvp-magazine | app/src/main/kotlin/taiwan/no1/app/ui/customize/AdjustHeightImageView.kt | 1 | 1643 | package taiwan.no1.app.ui.customize
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import taiwan.no1.app.R
/**
* An [ImageView] layout that maintains a consistent width to height aspect ratio.
*
* @author Jieyi
* @since 2/10/17
*/
class AdjustHeightImageView: ImageView {
//region Member Variables
var heightRatio: Float = 0f
set(value) {
if (value != field) {
field = value
this.requestLayout()
}
}
get() = field
//endregion
//region Constructors
constructor(context: Context): this(context, null, 0)
constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int): super(context, attrs, defStyle) {
attrs?.let {
context.obtainStyledAttributes(it, R.styleable.AdjustHeightImageView).apply {
[email protected] = this.getFloat(R.styleable.AdjustHeightImageView_heightRatio,
1f)
}.recycle()
}
}
//endregion
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (this.heightRatio > 0) {
// Set the image views size.
val width: Int = View.MeasureSpec.getSize(widthMeasureSpec)
val height: Int = (width * this.heightRatio).toInt()
this.setMeasuredDimension(width, height)
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
}
| apache-2.0 | d2faee60c72fed0af5d7e3c0afeb50f2 | 28.872727 | 117 | 0.626293 | 4.489071 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/data/model/Tweet.kt | 1 | 2409 | package com.andreapivetta.blu.data.model
import twitter4j.MediaEntity
import twitter4j.Status
import twitter4j.User
import java.io.Serializable
/**
* Created by andrea on 20/07/16.
*/
data class Tweet(val status: Status) : Serializable {
val text: String = status.text
val id: Long = status.id
val timeStamp: Long = status.createdAt.time
val user: User = status.user
val quotedStatus: Boolean = status.quotedStatus != null
val retweet: Boolean = status.isRetweet
val mediaEntities: Array<MediaEntity> = status.mediaEntities
var retweeted: Boolean = status.isRetweeted
var retweetCount: Int = status.retweetCount
var favorited: Boolean = status.isFavorited
var favoriteCount: Int = status.favoriteCount
var links: List<String> = status.urlEntities.map { it.expandedURL }
var metaData: MetaData? = null
fun getRetweetedTweet(): Tweet {
if (retweet)
return Tweet(status.retweetedStatus)
throw RuntimeException("This Tweet is not a Retweet")
}
fun getQuotedTweet(): Tweet {
if (quotedStatus)
return Tweet(status.quotedStatus)
throw RuntimeException("This Tweet does not contain a quoted Tweet")
}
fun hasSingleImage() = mediaEntities.size == 1 && "photo" == mediaEntities[0].type
fun hasSingleVideo() = mediaEntities.size == 1 && "photo" != mediaEntities[0].type
fun hasMultipleMedia() = mediaEntities.size > 1
fun hasLinks() = links.isNotEmpty()
fun getImageUrl(): String {
if (hasSingleImage() || hasMultipleMedia())
return mediaEntities[0].mediaURL
throw RuntimeException("This Tweet does not have a photo")
}
fun getVideoCoverUrl(): String {
if (hasSingleVideo() || hasMultipleMedia())
return mediaEntities[0].mediaURL
throw RuntimeException("This Tweet does not have a video")
}
fun getVideoUrlType(): Pair<String, String> {
if (hasSingleVideo() || hasMultipleMedia())
return Pair(mediaEntities[0].videoVariants[0].url, mediaEntities[0].type)
throw RuntimeException("This Tweet does not have a video")
}
fun getTextWithoutMediaURLs(): String {
var noUrlText = text
for (i in mediaEntities.indices)
noUrlText = text.replace(mediaEntities[i].url, "")
return noUrlText
}
fun getLink() = links[0]
} | apache-2.0 | c026b9a948d0e474f4709e9af6cc4d54 | 31.133333 | 86 | 0.669988 | 4.301786 | false | false | false | false |
jasonwyatt/AsyncListUtil-Example | app/src/main/java/co/jasonwyatt/asynclistutil_example/MainActivity.kt | 1 | 1090 | package co.jasonwyatt.asynclistutil_example
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: AsyncAdapter
private lateinit var itemSource: SQLiteItemSource
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recycler)
itemSource = SQLiteItemSource(getDatabase(this, "database.sqlite"))
adapter = AsyncAdapter(itemSource, recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = adapter
}
override fun onStart() {
super.onStart()
adapter.onStart(recyclerView)
}
override fun onStop() {
super.onStop()
adapter.onStop(recyclerView)
}
}
| unlicense | 9bd6a17a069d70cb8997b849cfd5275e | 29.277778 | 99 | 0.733028 | 4.866071 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/UsernameAutoCompleteAdapter.kt | 1 | 1789 | package com.pr0gramm.app.ui
import android.content.Context
import android.widget.ArrayAdapter
import android.widget.Filter
import com.pr0gramm.app.services.UserSuggestionService
import com.pr0gramm.app.util.matches
import java.util.regex.Pattern
/**
*/
class UsernameAutoCompleteAdapter(
private val suggestionService: UserSuggestionService,
context: Context, resource: Int, val prefix: String = "@") : ArrayAdapter<String>(context, resource) {
private val filter = UsernameFilter()
private val validConstraint = Pattern.compile(Pattern.quote(this.prefix) + "[a-zA-Z0-9]{2,}")
override fun getFilter(): Filter {
return filter
}
private inner class UsernameFilter : Filter() {
override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
if (!constraint.matches(validConstraint))
return toFilterResults(emptyList())
val term = constraint.toString().substring(prefix.length)
return toFilterResults(suggestionService.suggestUsers(term).map { prefix + it })
}
private fun toFilterResults(names: List<String>): Filter.FilterResults {
val results = Filter.FilterResults()
results.values = names
results.count = names.size
return results
}
@Suppress("UNCHECKED_CAST")
override fun publishResults(constraint: CharSequence?, results: Filter.FilterResults) {
setNotifyOnChange(false)
clear()
addAll(results.values as List<String>)
setNotifyOnChange(true)
if (results.count > 0) {
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}
}
}
| mit | 7ae330b8611e13a8550347f9ae584d02 | 31.527273 | 110 | 0.64673 | 4.874659 | false | false | false | false |
oubowu/AndroidExerciseProgram | ExerciseProgram/app/src/main/java/com/oubowu/exerciseprogram/kotlin/KotlinActivity.kt | 1 | 82488 | package com.oubowu.exerciseprogram.kotlin
import com.oubowu.exerciseprogram.BaseActivity
import com.oubowu.exerciseprogram.R
import com.socks.library.KLog
import java.io.File
import java.util.*
import kotlin.properties.Delegates
/**
* ClassName:
* Author:oubowu
* Fuction:
* CreateDate:2015/11/30 22:38
* UpdateUser:
* UpdateDate:
*/
@SuppressWarnings("unchecked")
public open class KotlinActivity : BaseActivity() {
// 声明public,随处可见
public var publicVariable: Int = 5
private set
// 不指定任何可见性修饰符,那么默认情况下使用internal修饰,这意味着你们将声明在同一个模块(就是这一个Module)中可见;
internal val internalVariable = 6
// 声明private,只会是这个包及其子包内可见的,并且只在相同的模块;
private val privateVariable = 10
// (只适用于类/接口成员)和"private"一样,但也在子类可见;
protected val protectedVariable = 10
// Kotlin语言的特性:在语句的行尾可以不用加分号(加上也不会错),声明一个方法需要加上fun关键字,
// 如果函数是重载父类的方法,还必须要加上override关键字,方法的参数是先写形参名后跟冒号再写形参类型。
override fun provideLayoutId(): Int {
return R.layout.activity_mvp;
}
override fun initView() {
toast("LoginActivity那里拓展了Activity,这里也可以用到,十分方便")
}
// fun show(list: ArrayList<String>) {
// for (v in list) {
// KLog.e("Show:$v")
// }
// }
//
// fun show1(list: List<String>) {
// for (v in list) {
// KLog.e("Show:$v")
// }
// }
//
//
// /*********************************第一章 1.基础语法*********************************************/
//
// /*2.定义函数方法*/
// // 方法包含两个Int参数并返回Int类型值
// fun sum(a: Int, b: Int): Int {
// return a + b
// }
//
// // 方法体只有一条语句,并且自动推测返回类型
// fun sum1(a: Int, b: Int) = a + b
//
// // 如果方法是一个public的,则必须明确写出返回类型(经测试不用也可以)
// public fun sum2(a: Int, b: Int): Int = a + b
//
// // 返回一个没有意义的值(Unit类似Java中的void,可省略)
// fun printSum(a: Int, b: Int): Unit {
// // print(a + b)
// KLog.e(a + b)
// }
//
// // 如果是返回Unit类型,则可以省略(对于public方法也是这样):
// public fun printSum1(a: Int, b: Int) {
// // print(a + b)
// KLog.e(a + b)
// }
//
// /*3.定义变量*/
// //只能赋值一次的变量(类似Java中final修饰的变量)
// val a: Int = 1
// val b = 1 // 系统自动推断变量类型为Int
//
// fun evaluate() {
// val c: Int // 如果不在声明时初始化则必须提供变量类型
// c = 1 // 明确赋值
//
// // val相当于final修饰变量,var相当于普通变量定义
//
// // 可以多次赋值的变量
// var x = 5 // 系统自动推断变量类型为Int
// x += 1
//
// }
//
// /*4.使用泛型Array*/
// fun main(args: Array<String>) {
// if (args.size == 0) return
// print("First argument: ${args[0]}")
// }
//
// /*5.条件语句*/
// fun max(a: Int, b: Int): Int {
// if (a > b)
// return a
// else
// return b
// }
//
// //或者也可以把if语句作为省略方法体的方法
// fun max1(a: Int, b: Int) = if (a > b) a else b
//
// /*6.使用nullable值以及空值检测*/
// //引用或函数返回值如果可能为null值,则必须显式标记nullable。
// // (译者注 :在类型后面跟一个问号表示这个对象可能为空,跟两个感叹号表示这个类型一定不为空)
// fun nullTest(args: Array<String>) {
// if (args.size < 2) {
// print("Two integers expected")
// return
// }
// val x = parseInt(args[0])
// val y = parseInt(args[1])
// //必须做判断,因为x或y有可能为空
// if (x != null && y != null) {
// // x 和 y 在已经检测不为null时,系统会自动将其转换为非空类型
// /*check*/ KLog.e("x * y = ${x * y}")
// } else {
// KLog.e("其中一个为null")
// }
// }
//
// /**
// * 如果str不能转为Int类型,则返回null
// */
// fun parseInt(str: String): Int? {
// // 类型后面带?说明可以为null
// var i: Int? = 0
// try {
// i = Integer.parseInt(str)
// } catch(e: Exception) {
// i = null
// }
// return i
// }
//
// /*7.类型检测并自动转换*/
// // is关键字的用法(类似于Java中的instanceof关键字)
// fun getStringLength(obj: Any): Int? {
// if (obj is String) {
// // 做过类型判断以后,obj会被系统自动转换为String类型
// return obj.length
// }
// // 这里的obj仍然是Any类型的引用
// return null
// }
//
// fun getStringLength1(obj: Any): Int? {
// // 在左侧obj已经被判断为String类型,所以在&&的右侧可以直接将obj当成String类型来使用
// if (obj is String && obj.length > 0) {
// return obj.length
// }
// return null
// }
//
// /*8.循环的使用*/
// fun loop(array: Array<String>) {
// for (item in array)
// KLog.e(item)
// //或者也可以
// for (i in array.indices)
// KLog.e(array[i])
// }
//
// fun loop1(array: Array<String>) {
// var i = 0
// while (i < array.size) {
// KLog.e(array[i++])
// }
// }
//
// /*9.when表达式*/
// // 类似于Java中的switch
// fun cases(obj: Any) {
// when (obj) {
// 1 -> KLog.e("数字1")
// "hello" -> KLog.e("字符串Hello")
// is Long -> KLog.e("Long类型数")
// !is String -> KLog.e("不是字符串")
// else -> KLog.e("else类似java中的default")
// }
// }
//
// /*10.in关键字的使用*/
// // 如果一个数字是在某一个区间内,可以使用in关键字
// fun inUseCase() {
// val x = 5
// val y = 10
// if (x in 1..y - 1) {
// KLog.e("OK")
// }
//
// //如果x不存在于array中,则输出Out(明显不对,这里是索引)
// val array = arrayOf(4, 5, 1, 2, 3, 7)
// if (x !in 0..array.lastIndex)/*0..array.lastIndex应该换为array*/
// KLog.e("Out")
//
// //打印1到5
// for (x in 1..5)
// KLog.e(x)
//
// //遍历集合(类似于Java中的for(String name : names))
// val names = arrayOf("ou", "bo", "mu")
// for (name in names)
// KLog.e(name)
//
// val text = "ou"
// if (text in names)
// KLog.e("集合中确实存在$text")
//
// }
//
// /*********************************第一章 2.常用语法*********************************************/
//
// // 创建DTO(POJO’s/POCO’s)
// data class Customer(val name: String, val email: String)
// //默认提供了以下功能的Customer类: — getters (and setters in case of var’s) for all properties — equals() — hashCode() — toString() — copy() — component1() , component2() , ..., for all properties
//
// // 为函数参数设置默认值(a默认为0,b默认为空字符串)
// fun foo(a: Int = 0, b: String = "") {
// // 声明一个常量
// val a = foo()
// }
//
// // 列表过滤器
// fun filter(list: Array<Int>) {
// val positives = list.filter { x -> x > 0 }
// KLog.e("positives = $positives")
// //或者(it是一个iterator迭代器,内置的,只能是it,不能是其它的名字)
// val positives1 = list.filter { it > 0 }
// KLog.e("positives1 = $positives1")
// // 返回的是List<Int>
// for (k in positives) {
// KLog.e(k)
// }
// }
//
// // 字符串插入
// //译者注:name是一个String变量 println("他的名字是:$name)
//
// // 对象检测
// /*when (x) {
// is Foo -> ...
// is Bar -> ...
// else -> ...
// }*/
//
// // 遍历一个map或list
// fun traverse(map: Map<String, String>) {
// for ((k, v) in map) {
// KLog.e("key:$k value:$v")
// }
// }
//
// // 使用区间(using ranges)
// // for (i in 1..100) { ... }
// // for (x in 2..10) { ... }
//
// // 只读的map或list
// val list = listOf("a", "b", "c")
// val map = mapOf("a" to 1, "b" to 2, "c" to 3)
//
// // 扩展函数
// //译者注:为String类添加spaceToCamelCase()方法,String所有子类都可以调用这个方法
// fun String.spaceToCamelCase() {
// KLog.e("拓展了String的函数")
// }
//
// // 创建一个单元素类(singleton)
// object Resource {
// val name = "Name"
// }
//
// // 空指针安全操作
// fun nullPointerSaftyOperation() {
// //如果files不为空,则打印files.size,否则什么都不做
// val files = File("Test").listFiles();
// // ?会使其做非空判断
// KLog.e(files?.size)
//
// //如果files为空了,则打印empty,否则打印files.size
// val files1 = File("Test").listFiles()
// // 后面?:代表为空的操作
// println(files?.size ?: "empty")
//
// //如果data["email"]为空才执行'?:'后面的语句
// // val data = ...
// // val email = data["email"] ?: throw IllegalStateException("Email is missing!")
//
// //如果不为空才执行某些操作
// // val data = ...
// // data?.let {
// // ... //做某些操作
// // }
//
// }
//
// // 使用when声明返回
// fun transform(color: String): Int {
// return when (color) {
// "Red" -> 0
// "Green" -> 1
// "Blue" -> 2
// else -> throw IllegalArgumentException("Invalid color param value")
// }
// }
//
// //使用try...catch...块返回
// fun test() {
// val result = try {
// //count()
// } catch (e: ArithmeticException) {
// throw IllegalStateException(e)
// }
// // Working with result
// }
//
// // 使用if返回值
// fun foo(param: Int): String {
// val result = if (param == 1) {
// "one"
// } else if (param == 2) {
// "two"
// } else {
// "three"
// }
// return result
// }
//
// // 单表达式函数(单语句函数)(Single-expression functions)
// fun theAnswer() = 42
//
// //上面的单表达式函数等价于下面的函数
// fun theAnswer1(): Int {
// return 42
// }
//
// //同样的,可以结合其他常用语法,例如:
// fun transform1(color: String): Int = when (color) {
// "Red" -> 0
// "Green" -> 1
// "Blue" -> 2
// else -> throw IllegalArgumentException("Invalid color param value")
// }
//
// /*********************************第一章 3.编码风格*********************************************/
// /*编码风格(Coding Conventions)
//
// 本页介绍当前kotlin语言编码风格。
//
// 命名风格
//
// 如果有争议,则默认以Java编码风格为准,例如:
//
// 使用驼峰法命名(避免使用下划线命名)
// 类型(包括Java中的基本数据类型)使用大写开头
// 方法和成员变量(属性)以小写字母开头
// 使用4个空格缩进
// 公有方法(public functions)应该有文档注释 kotlin语言不具有主键概念(primary concept),应该避免给成员变量(属性)使用前缀,例如""或"m"或其他类型的标记,
// 如果你需要保持一个field备份,使用$前缀,例如:$foo,千万不要创建一个私有变量还给命名为_foo冒号
//
// 对于冒号之前的空格,在分隔子父类或接口的时候,或在分隔实例和类型的时候应该有一个空格,其他地方不应该有空格。
//
// interface Foo<out T : Any> : Bar {
// fun foo(a: Int): T
// }
// 代码单元(Unit)
//
// 如果函数返回值是一个代码单元,则应该忽略返回类型,例如
//
// fun foo() { // 这里的": Unit"是应该被省略掉的
// }*/
//
//
// /*********************************第二章 1.基础数据类型*********************************************/
// // 基本类型
// // 在Kotlin中,所有东西都是对象,所以我们可以调用成员函数和属性的任何变量对象。有些类型是内置的,他们的实现被优化过,
// // 但是用户看起来他们就像普通的类. 本节我们会描述这些类型: numbers, characters, booleans 和 arrays.
//
// /***********Numbers*************/
// /* Kotlin处理numbers和Java很接近,但是并不完全相同. 例如, 对于numbers没有隐式扩大转换(如java中int可以隐式变为long),在一些情况下文字的使用有所不同.
//
// 对于numbers Kotlin提供了如下的内置类型 (与Java很相近):
//
// Type Bitwidth
// Double 64
// Float 32
// Long 64
// Int 32
// Short 16
// Byte 8
// 注意在kotlin中 characters 不是 numbers
//
// 字面量
//
// 下面是一些常量的写法:
//
// 十进制: 123
// Longs类型用大写 L 标记: 123L
// 十六进制: 0x0F
// 二进制: 0b00001011
// 注意: 不支持8进制
//
// Kotlin 同样支持浮点数的常规表示方法:
//
// Doubles 123.5, 123.5e10
// Floats用 f 或者 F 标记: 123.5f*/
//
// /*存储方式
//
// 在Java平台数字是物理存储为JVM的原始类型,除非我们需要一个可空的引用(例如int?)或泛型. 后者情况下数字被装箱(指的是赋值的时候把实例复制了一下,不是相同实例)。
//
// 装箱数字不会保存它的实例:
//
// val a: Int = 10000
// print(a identityEquals a) // Prints 'true'
// val boxedA: Int? = a
// val anotherBoxedA: Int? = a
// print(boxedA identityEquals anotherBoxedA) // !!!Prints 'false'!!!
// 另一方面它们值相等:
//
// val a: Int = 10000
// print(a == a) // Prints 'true'
// val boxedA: Int? = a
// val anotherBoxedA: Int? = a
// print(boxedA == anotherBoxedA) // Prints 'true'*/
//
// /*显示转换
//
// 由于不同的存储方式小的类型并不是大类型的子类型。 如果它们是的话,就会出现下述问题(下面的代码不能通过编译):
//
// // Hypothetical code, does not actually compile:
// val a: Int? = 1 // A boxed Int (java.lang.Integer)
// val b: Long? = a // implicit conversion yields a boxed Long (java.lang.Long)
// print(a == b) // Surprise! This prints "false" as Long's equals() check for other part to be Long as well
// 假设这样是可以的,这里我们就悄无声息的丢掉了一些数据.
//
// 因此较小的类型不能隐式转换为较大的类型。 因此我们不能声明一个 Byte 类型给一个 Int 变量,在不进行显示转换的情况下。
//
// val b: Byte = 1 // OK, literals are checked statically
// val i: Int = b // ERROR
// 我们可以显示转换的去扩大类型
//
// val i: Int = b.toInt() // OK: explicitly widened
// 每个number类型支持如下的转换:
//
// toByte(): Byte
// toShort(): Short
// toInt(): Int
// toLong(): Long
// toFloat(): Float
// toDouble(): Double
// toChar(): Char
// 失去隐式类型转换,其实并没有带来多少困扰,因为使用字面量的时候是没有代价的,因为字面量的类型是推导出来的; 另一方面,算数运算操作都针对不同类型的参数做好了重载,比如:
//
// val l = 1.toLong() + 3 // Long + Int => Long*/
//
// /*运算符
//
// Kotlin支持标准的算数操作符,并在相应的类上定义为成员函数(但编译器会针对运算进行优化,将函数调用优化成直接的算数操作)。 查看 Operator overloading.
//
// 对于按位操作(bitwise operation),没有特别的符号来表示,而是直接使用命名函数:
//
// val x = (1 shl 2) and 0x000FF000
// 这是完整的位运算操作 (只能对 Int 或者 Long 使用):
//
// shl(bits) – signed shift left (Java's <<)
// shr(bits) – signed shift right (Java's >>)
// ushr(bits) – unsigned shift right (Java's >>>)
// and(bits) – bitwise and
// or(bits) – bitwise or
// xor(bits) – bitwise xor
// inv() – bitwise inversion*/
//
// /********Characters**************/
// /*Characters 用 Char来表示. 像对待numbers那样就行
//
// fun check(c: Char) {
// if (c == 1) { // ERROR: incompatible types
// // ...
// }
// }
// 用单引号表示一个Character,例如: '1', '\n', '\uFF00'. 我们可以调用显示转换把Character转换为Int*/
//
// fun decimalDigitValue(c: Char): Int {
// if (c !in '0'..'9')
// throw IllegalArgumentException("Out of range")
// return c.toInt() - '0'.toInt() // Explicit conversions to numbers
// }
// /*像numbers, characters是被装箱当使用一个可空的引用.这样实例不会被保存。*/
//
// /********Booleans**********/
// /*类型Boolean有两个值: true{: .keyword } 和 false{: .keyword }.
//
// Booleans使用nullable时候Boolean也会被装箱.
//
// 内置对Booelan的操作
//
// || – 短路或
// && – 短路与*/
//
// /*********数组************/
// /*数组在Kotlin中使用 Array类来表示, Array类定义了set和get函数(使用时可以用[],通过符号重载的约定转换), 和size等等一些有用的成员函数:
//
// class Array<T> private () {
// fun size(): Int
// fun get(index: Int): T
// fun set(index: Int, value: T): Unit
//
// fun iterator(): Iterator<T>
// // ...
// }
// 我们可以使用库函数array()来创建一个包含数值的数组, array(1, 2, 3) 创建了 array [1, 2, 3]. 或者, arrayOfNulls()可以创建一个指定大小,元素都为空的数组。
// 或者使用函数来创建一个数组:
//
// // Creates an Array<String> with values ["0", "1", "4", "9", "16"]
// val asc = Array(5, {i -> (i * i).toString()})
// 综上, []操作符代表了成员函数get()和set().
//
// 注意: 与Java不同的是, Kotlin中数组不可变. 这意味着我们不能声明 Array<String>到Array<Any>, 否则可能会产生一个运行时错误(但是你可以使用 Array<out Any>, 查看 Type Projections).
//
// Kotlin有专门的类来表示原始类型的数组,避免了装箱开销: ByteArray, ShortArray, IntArray 等等. 这些类和Array并没有继承关系,但是它们有同样的方法属性集. 它们也都有相应的工厂方法:
//
// val x: IntArray = intArray(1, 2, 3)
// x[0] = x[1] + x[2]*/
//
// /*****字符串*****/
// /*字符串用String表示。字符串是不可变的。
// 字符串的原始字符可以使用操作符访问: s[i]. 字符串可以使用for{: .keyword }循环遍历:
//
// for (c in str) {
// println(c)
// }*/
//
// /*******字符串字面量********/
// /*Kotlin有两种类型的字符串: 转义字符串可能由转义字符、原生字符串、换行和任意文本.转义字符串很像java的String:
//
// val s = "Hello, world!\n"
// 转义方式采用传统的反斜杠.
//
// 原生字符串使用三个引号(""")包括,内部没有转义,可以包含换行和任何其他文本:
//
// val text = """
// for (c in "foo")
// print(c)
// """*/
//
// /***********模板***********/
// /*字符串可以包含模板表达式,即一些小段代码,会求值并把结果合并到字符串中。模板表达式以$符号开始,包含一个简单的名称:
//
// val i = 10
// val s = "i = $i" // evaluates to "i = 10"
// 或者用花括号扩起来,内部可以是任意表达式:
//
// val s = "abc"
// val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"*/
//
// /*********************************第二章 1.包*********************************************/
// /*包
// 源文件通常以包声明开头:
//
// package foo.bar
//
// fun baz() {}
//
// class Goo {}
//
// // ...
// 源文件所有的(无论是类或者函数)被包声明覆盖. 所以baz()的全名是foo.bar.baz, Goo的全名是foo.bar.Goo.
//
// 如果没有明确声明文件属于"default"且包没有名称.
//
// 导入
//
// 除了模块定义的默认导入之外,每个源文件也可以声明自己的导入。 导入语句的语法定义描述在grammar.
//
// 可以导入一个单独的名称,如.
//
// import foo.Bar // Bar is now accessible without qualification
// 也可以导入一个作用域下的所有内容(包、类、对象等):
//
// import foo.* // everything in 'foo' becomes accessible
// 如果出现名称冲突,可以使用 as{: .keyword } as关键字来重命名导入的名称:
//
// import foo.Bar // Bar is accessible
// import bar.Bar as bBar // bBar stands for 'bar.Bar'
// 可见性和包嵌套
//
// 如果顶层声明是private{: .keyword }, 它将是私有的(查看 Visibility Modifiers). 尽管Kotlin中可以包嵌套, 如 包foo.bar 是foo的一个成员,但是一些private{: .keyword } 仅仅可以被它的子包所见.
//
// 注意外部包成员不是默认引入的,例如,在foo.bar包的文件中我们不能在不引入的情况下访问foo.*/
//
// /*********************************第二章 2.控制流*********************************************/
// /********If表达式********/
// // 在Kotlin中, if{: .keyword }是一个表达式,它会返回一个值. 因此就不需要三元运算符 (如 ? 三元表达式), 因为使用 if{: .keyword } 就可以了。
// /*
// // Traditional usage
// var max = a
// if (a < b)
// max = b
//
// // With else
// var max: Int
// if (a > b)
// max = a
// else
// max = b
//
// // As expression
// val max = if (a > b) a else b
//
// if{: .keyword }的分支可以是代码段, 最后一行的表达式作为段的返回值:
//
// val max = if (a > b) {
// print("Choose a")
// a
// }
// else {
// print("Choose b")
// b
// }
// 当if{: .keyword }仅仅有一个分支, 或者其中一个分支的返回结果Unit, 它的类型Unit.*/
//
// /*********When表达式*************/
// /*when{: .keyword } 替代了c语言风格的switch操作符. 最简单的形式如下:
//
// when (x) {
// 1 -> print("x == 1")
// 2 -> print("x == 2")
// else -> { // Note the block
// print("x is neither 1 nor 2")
// }
// }
// when{: .keyword } 将它的参数和所有的分支条件进行比较,直到某个分支满足条件。 when{: .keyword }既可以被当做表达式使用也可以被当做语句使用。
// 如果它被当做表达式, 符合条件的分支的值就是整个表达式的值,如果当做语句使用,则忽略单个分支的值。
// (就像if{: .keyword },每一个分支可以是一个代码块,它的值是最后的表达式的值.)
//
// else{: .keyword } 分支将被执行如果其他分支都不满足条件。 如果 when{: .keyword } 作为一个表达式被使用,
// else{: .keyword } 分支是必须的,除非编译器能够检测出所有的可能情况都已经覆盖了。
//
// 如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起, 用,逗号分隔:
//
// when (x) {
// 0, 1 -> print("x == 0 or x == 1")
// else -> print("otherwise")
// }
// 我们可以在判断分支条件的地方使用任何表达式,而不仅仅是常量(和switch不同):
//
// when (x) {
// parseInt(s) -> print("s encodes x")
// else -> print("s does not encode x")
// }
// 我们也可以检查一个值 in{: .keyword } 或者 !in{: .keyword } 一个 范围 或者集合:
//
// when (x) {
// in 1..10 -> print("x is in the range")
// in validNumbers -> print("x is valid")
// !in 10..20 -> print("x is outside the range")
// else -> print("none of the above")
// }
// 另一种用法是可以检查一个值is{: .keyword }或者!is{: .keyword }某种特定类型.注意,由于smart casts, 你可以访问该类型的方法和属性而不用额外的检查。
//
// val hasPrefix = when(x) {
// is String -> x.startsWith("prefix")
// else -> false
// }
// when{: .keyword } 也可以用来替代if{: .keyword }-else{: .keyword } if{: .keyword }链. 如果不提供参数,所有的分支条件都是简单的布尔值,
// 而当一个分支的条件返回true时,则调用该分支:
//
// when {
// x.isOdd() -> print("x is odd")
// x.isEven() -> print("x is even")
// else -> print("x is funny")
// }*/
//
// /*******For循环***********/
//
// /*for{: .keyword } 循环可以对任何提供迭代器(iterator)的集合进行遍历,语法如下:
//
// for (item in collection)
// print(item)
// 循环体可以是一个代码块.
//
// for (item: Int in ints) {
// // ...
// }
// 像上面提到的一样, for{: .keyword }可以循环遍历任何提供了迭代器的集合。例如:
//
// 有一个成员函数或者扩展函数iterator(),它返回一个类型
// 有一个成员函数或者扩展函数next(),并且
// 有一个成员函数或者扩展函数hasNext()返回 Boolean.
// 如果你想要遍历一个数组或者一个list,你可以这么做:
//
// for (i in array.indices)
// print(array[i])
// 注意这种“遍历一个范围”的函数会被编译器优化,不会产生额外的对象。*/
//
// /********While循环************/
// /*while{: .keyword } 和 do{: .keyword }..while{: .keyword } 的使用方法和其他语言一致
//
// while (x > 0) {
// x--
// }
//
// do {
// val y = retrieveData()
// } while (y != null) // y is visible here!*/
//
// /************Break和continue在循环中的使用********/
// // 在循环中Kotlin支持传统的break{: .keyword }和continue{: .keyword }操作符.
//
// /*********************************第二章 3.返回与跳转*********************************************/
// /*返回和跳转
// Kotlin 有三种跳出结构
//
// return{: .keyword }.默认情况下,从最近的一个封闭的方法或者 方法表达式跳出.
//
// break{: .keyword }.终止最近的封闭循环
//
// continue{: .keyword }.直接进入循环体的下次循环
//
// 中断和继续标签
//
// 在Kotlin中任何表达式都可以用label{: .keyword } (标签)来标记。
// label的格式是被'@'标识符标记,例如:abc@, fooBar@都是有效的label(参见语法)
//
// 你可以在一个方法前面放一个label。
//
// loop@ for (i in 1..100) {
// // ...
// }
// 现在,我们可以将label与 break{: .keyword } 或者continue{: .keyword }一起使用:
//
// loop@ for (i in 1..100) {
// for (j in 1..100) {
// if (...)
// break@loop
// }
// }
// break执行后将跳转到标记处。
//
// continue{: .keyword }将进入循环体的下次循环
//
// 返回标签
//
// 在Kotlin里,函数字面量、局部函数和对象表达式等函数都可以被嵌套在一起 适当的返回方式允许我们从外部方法返回值
//
// 带标签的return,最重要的一个用途,就是让我们可以从函数字面量中返回。
//
// fun foo() {
// ints.forEach {
// if (it == 0) return
// print(it)
// }
// }
// 这个 return{: .keyword }表达式从最近的封闭的方法中返回,例如‘foo’。
//
// (注意,非全局的返回只支持内部方法,参见内联方法.) 如果我们只是需要跳出内部方法,我们必须标记它并且返回这个标签
//
// fun foo() {
// ints.forEach lit@ {
// if (it == 0) return@lit
// print(it)
// }
// }
// 现在只是从内部方法返回。有时候用匿名的标签将会更加方便 像这样和方法同名的标签是可以的
//
// fun foo() {
// ints.forEach {
// if (it == 0) return@forEach
// print(it)
// }
// }
// 通常,我们用一个方法表达式替代内部匿名方法。在方法内部声明一个return{: .keyword }将从其内部返回
//
// fun foo() {
// ints.forEach(fun(value: Int) {
// if (value == 0) return
// print(value)
// })
// }
// 当要返回一个值得时候,推荐使用描述性的返回,例如:
//
// return@a 1
// 意思是“返回被标记为‘@a’值是‘1’的标签,而不是像‘(@a 1)’的一个标签表达式”
//
// 被命名的方法自动被定义成为标签
//
// fun outer() {
// fun inner() {
// return@outer // the label @outer was defined automatically
// }
// }*/
//
// fun looper(i: Int = 10) {
// loop@ for (i in 1..100) {
// for (j in 1..100) {
// if (j == 10)
// // break执行后将跳转到标记处
// break@loop
// }
// }
// }
//
// fun foo(ints: Array<Int>) {
// ints.forEach {
// if (it == 0) return@forEach
// KLog.e(it)
// }
// }
//
// /*********************************第三章 1.类与继承*********************************************/
// /*********类*******/
//
// /*类声明Kotlin使用关键字*class *{:.keyword}
//
// class Invoice {
// }
// 这个类声明被花括号包围,包括类名、类头(指定其类型参数,主构造函数等)和这个类的主干。类头和主干都是可选的; 如果这个类没有主干,花括号可以被省略。
//
// class Empty*/
//
// /*******构造******/
//
// /*在Kotlin中的类可以有主构造函数和一个或多个二级构造函数。主构造函数是类头的一部分:它跟在这个类名后面(和可选的类型参数)
//
// class Person constructor(firstName: String) {
// }
// 如果这个主构造函数没有任何注解或者可见的修饰符,这个constructor{: .keyword }关键字可以被省略
//
// class Person(firstName: String) {
// }
// 这个主构造函数不能包含任何的代码。初始化的代码可以被放置在initializer blocks(初始的模块),以init为前缀作为关键字{:.keyword}
//
// class Customer(name: String) {
// init {
// logger.info("Customer initialized with value ${name}")
// }
// }
// 请注意,主构造的参数可以在初始化模块中使用。它们也可以在类体内声明初始化的属性:
//
// class Customer(name: String) {
// val customerKey = name.toUpperCase()
// }
// 事实上,声明属性和初始化主构造函数,Kotlin有简洁的语法:
//
// class Person(val firstName: String, val lastName: String, var age: Int) {
// // ...
// }
// 与普通属性一样,主构造函数中声明的属性可以是可变的或者是只读的
//
// If the constructor has annotations or visibility modifiers, the constructor{: .keyword } keyword is required, and the modifiers go before it: 如果构造函数有注解或可见性修饰符,这个constructor{: .keyword }需要被关键字修饰。
//
// class Customer public inject constructor(name: String) { ... }
// 更多请查看Visibility Modifiers*/
//
// /*********扩展构造函数******/
//
// /*类也可以拥有被称为"二级构造函数"(为了实现Kotlin向Java一样拥有多个构造函数),通常被加上前缀"constructor"
//
// class Person {
// constructor(parent: Person) {
// parent.children.add(this)
// }
// }
// 如果类有一个主构造函数,每个二级构造函数需要委托给主构造函数,直接或间接地通过另一个二级函数。 委托到另一个使用同一个类的构造函数用this{: .keyword }关键字
//
// class Person(val name: String) {
// constructor(name: String, parent: Person) : this(name) {
// parent.children.add(this)
// }
// }
// 如果一个非抽象类没有声明任何构造函数(原发性或继发性),这将有一个生成的主构造函数不带参数。构造函数的可见性是public。如果你不希望你的类有一个公共构造函数,你需要声明与非缺省可见一个空的主构造函数:
//
// class DontCreateMe private constructor () {
// }
// 注意在JVM上,如果所有的主构造函数的参数有默认值,编译器会产生一个额外的参数的构造函数,将使用默认值。 这使得更易于使用kotlin与通过参数构造函数创建类的实例,如使用Jackson或JPA库的时候。
//
// class Customer(val customerName: String = "")
// {:.info}*/
//
// class Person constructor(val firstName: String = "Kobe") {
// constructor(firstName: String, email: String) : this(firstName) {
//
// }
//
// fun getName(): String {
// return firstName
// }
//
// fun getName1() = firstName
// }
//
// /*********创建类的实例**********/
// /*要创建一个类的实例,我们调用构造函数,就好像它是普通的函数:
//
// val invoice = Invoice()
//
// val customer = Customer("Joe Smith")
// 注意Kotlin不能有“new”关键字
//
// 类成员
//
// 类可以包括
//
// 构造和初始化模块
// 函数
// 属性
// 匿名和内部类
// 对象声明
// 继承
//
// 在Kotlin所有的类中都有一个共同的父类Any,这是一个默认的父类且没有父类型声明:
//
// class Example // Implicitly inherits from Any
// Any不属于java.lang.Object;特别是,它并没有任何其他任何成员,甚至连equals(),hashCode()和toString()都没有。
//
// 请参阅Java的互操作性更多的细节部分。
//
// 要声明一个明确的父类,我们把类型放到类头冒号之后:
//
// open class Base(p: Int)
//
// class Derived(p: Int) : Base(p)
// 如上所见,父类可以(并且必须)在声明继承的地方,用原始构造函数初始化。
//
// 如果类没有主构造,那么每个次级构造函数初始化基本类型 使用super{:.keyword}关键字,或委托给另一个构造函数做到这一点。
// 注意,在这种情况下,不同的二级构造函数可以调用基类型的不同的构造:
//
// class MyView : View {
// constructor(ctx: Context) : super(ctx) {
// }
//
// constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {
// }
// }
// 父类上的open{:.keyword}标注可以理解为Java中final{:.keyword}的反面,它允许其他他类 从这个类中继承。默认情况下,在Kotlin所有的类都是final,
// 对应于 Effective Java 书中的17条:设计并显示标注继承,否则就禁止它。*/
//
// // 显示标注继承open,否则就禁止它
// open class Pop {
// // 方法也是要显示的标明才能给子类重写
// open fun play() {
// }
// }
//
// class KPop : Pop() {
// override fun play() {
// }
// }
//
// /********覆盖成员***********/
// /*我们之前提到过,Kotlin力求清晰显式。不像Java中,Kotlin需要明确的 标注覆盖的成员(我们称之为open)和重写的函数。
// (继承父类并覆盖父类函数时,Kotlin要求父类必须有open标注,被覆盖的函数必须有open标注,并且子类的函数必须加override标注。):
//
// open class Base {
// open fun v() {}
// fun nv() {}
// }
// class Derived() : Base() {
// override fun v() {}
// }
// Derived.v()函数上必须加上override标注。如果没写,编译器将会报错。 如果父类的这个函数没有标注open,则子类中不允许定义同名函数,
// 不论加不加override。 在一个final类中(即没有声明open的类),函数上也不允许加open标注。
//
// 成员标记为override{:.keyword}的本身是开放的,也就是说,它可以在子类中重写。如果你想禁止重写的,使用final{:.keyword}关键字:
//
// open class AnotherDerived() : Base() {
// final override fun v() {}
// }
// 等等!!这样我怎么hack我的库?
//
// 我们这样设计继承和覆盖的方式(类和成员默认final),会让人很难继承第三方的类,因此很难进行hack。
//
// 我们认为这不是一个劣势,原因如下:
//
// 最佳实践已经表明不应该使用这些hacks
// 其他的有类似机制的语言(C++, C#)已经证明是成功的
// 如果人们实在想hack,仍然有办法:比如某些情况下可以使用Java进行hack,再用Kotlin调用;或者使用面向切面的框架(Aspect)。(请参阅Java的互操作)*/
//
// /********重写的规则*******/
//
// // 在Kotlin中,实现继承的调用通过以下规则: 如果一个类继承父类成员的多种实现方法,可以直接在子类中引用,
// // 它必须重写这个成员,并提供其自己的实现(当然也可以使用父类的)。 为了表示从中继承的实现而采取的父类型,
// // 我们使用super{:.keyword}在尖括号,如规范的父名super<Base>:
//
// open class A {
// open fun f() {
// KLog.e("A")
// }
//
// fun a() {
// KLog.e("a")
// }
// }
//
// // 接口函数默认为open
// interface B {
// fun f() {
// KLog.e("B")
// } // interface members are 'open' by default
//
// fun b() {
// KLog.e("b")
// }
// }
//
// class C() : A(), B {
// // The compiler requires f() to be overridden:
// override fun f() {
// super<A>.f() // call to A.f()
// super<B>.f() // call to B.f()
// }
// }
// // 类C同时继承A和B是可以的,而且我们在调用a()和b()函数时没有任何问题,因为他们在C的基类中只有一个实现。
// // 但是f()函数则在A,B中都有实现,所以我们必须在C中覆盖f(),并且提供我们的实现以消除歧义。
//
// /*******抽象类********/
// // 类和其中的某些实现可以声明为abstract{:.keyword}。 抽象成员在本类中可以不用实现。。 因此,当一些子类继承一个抽象的成员,它并不算是一个实现:
// /*abstract class A1 {
// abstract fun f()
// }
//
// interface B1 {
// open fun f() {
// print("B")
// }
// }
//
// class C1() : A1(), B1 {
// // We are not required to override f()
// }*/
// // 需要注意的是,我们并不需要标注一个抽象类或者函数为open - 因为这不言而喻。我们可以重写一个open非抽象成员使之为抽象的。
// open class Base {
// open fun f() {
// }
// }
//
// abstract class Derived : Base() {
// override abstract fun f()
// }
//
// /*同伴对象*/
// // 在Kotlin中,不像Java或C#,类没有静态方法。在大多数情况下,它建议简单地使用包级函数。
// // 如果你需要写一个可以调用的函数,而不依赖一个类的实例,但需要访问的内部一个类(例如,一个工厂方法),
// // 你可以写为[对象声明](object_declarations.html)中的一员里面的那个类。
// // 更具体地讲,如果你声明一个同伴对象在你的的类中, 你就可以在Java/ C#中调用与它的成员方法相同的语法的静态方法,只使用类名作为一个修饰语。
//
// /*********************************第三章 2.属性和字段*********************************************/
// /********声明属性*******/
// /*Kotlin的属性. 这些声明是可变的,用关键字var{: .keyword }或者使用只读关键字val{: .keyword }.
//
// public class Address {
// public var name: String = ...
// public var street: String = ...
// public var city: String = ...
// public var state: String? = ...
// public var zip: String = ...
// }
// 要使用一个属性,只需要使用名称引用即可,就相当于Java中的公共字段:
//
// fun copyAddress(address: Address): Address {
// val result = Address() // there's no 'new' keyword in Kotlin
// result.name = address.name // accessors are called
// result.street = address.street
// // ...
// return result
// }*/
//
// /*********getters和setters*******/
// /* 声明一个属性的完整语法
//
// var <propertyName>: <PropertyType> [= <property_initializer>]
// <getter>
// <setter>
// 上面的定义中,初始器(initializer)、getter和setter都是可选的。 属性类型(PropertyType)如果可以从初始器或者父类中推导出来,也可以省略。
//
// 例如:
//
// var allByDefault: Int? // error: explicit initializer required, default getter and setter implied
// var initialized = 1 // has type Int, default getter and setter
// 注意公有的API(即public和protected)的属性,类型是不做推导的。 这么设计是为了防止改变初始化器时不小心改变了公有API。比如:
//
// public val example = 1 // error: a public property must have a type specified explicitly
// 一个只读属性的语法和一个可变的语法有两方面的不同:1·只读属性的用val开始代替var 2·只读属性不许setter
//
// val simple: Int? // has type Int, default getter, must be initialized in constructor
// val inferredType = 1 // has type Int and a default getter
// 我们可以编写自定义的访问器,非常像普通函数,对内部属性声明。这里有一个定义的getter的例子:
//
// val isEmpty: Boolean
// get() = this.size == 0
// 一个定义setter的例子:
//
// var stringRepresentation: String
// get() = this.toString()
// set(value) {
// setDataFromString(value) // parses the string and assigns values to other properties
// }
// 按照惯例,setter参数的名称是“value”,但是如果你喜欢你可以选择一个不同的名称。
//
// 如果你需要改变一个访问器或注释的可见性,但是不需要改变默认的实现, 您可以定义访问器而不定义它的实例:
//
// var setterVisibility: String = "abc" // Initializer required, not a nullable type
// private set // the setter is private and has the default implementation
//
// var setterWithAnnotation: Any?
// @Inject set // annotate the setter with Inject*/
//
// // var和val在定义的时候必须初始化
// // 类型为Int,默认getter和setter
// var initialized = 1
// // 公有的API(即public和protected)的属性,类型是不做推导的(将测试没问题啊)
// public val example = 1
// // 类型为Int,默认getter,因为val是只读的
// val inferredType = 1
// // 自定义getter
// val isBelongBaseActivity: Boolean get() = this is BaseActivity
// // 自定义getter和setter
// var stringRepresentation: String
// get() = this.toString()
// set(value) {
// // 在对其赋值的时候可以把该值传递给其他地方
// setDataFromString(value)
// }
//
// private fun setDataFromString(value: String) {
// KLog.e(value)
// }
//
// /********实际字段********/
// /*在Kotlin不能有字段。然而,有时有必要有使用一个字段在使用定制的访问器的时候。对于这些目的,Kotlin提供 自动支持,在属性名后面使用* $ *符号。
//
// (经测试压根编译不过去)
// var counter = 0 // the initializer value is written directly to the backing field
// set(value) {
// if (value >= 0)
// $counter = value
// }
// 上面的$counter字段就可以在counter属性的访问器实现里读和写。并且只能在构造函数里赋值。在其他地方,都不能使用或访问$counter
//
// 编译器会查看访问器的内部, 如果他们使用了实际字段(或者访问器使用默认实现),那么将会生成一个实际字段,否则不会生成。
//
// 例如,下面的情况下, 就没有实际字段:
//
// val isEmpty: Boolean
// get() = this.size == 0*/
//
// /********支持属性********/
// /*如果你的需求不符合这套“隐式的实际字段“方案,那么总可以使用“后背支持属性”(backing property)的方法:*/
// private var _table: Map<String, Int>? = null //?标示可以为null
// public val table: Map<String, Int>
// get() {
// if (_table == null)
// _table = HashMap() // Type parameters are inferred
// return _table ?: throw AssertionError("Set to null by another thread")
// }
// /*从各种角度看,这和在Java中定义Bean属性的方式一样。因为访问私有的属性的getter和setter函数,会被编译器优化成直接反问其实际字段。*/
//
// /***********重写属性***********/
// //查看 Overriding Members
//
// /********委托属性********/
// // 从支持域最常见类型的属性只读(写入)。 另一方面,使用自定义getter和setter属性可以实现任何方法行为。 介于两者之间,有一些常见的模式属性是如何工作的。
// // 一个例子:lazy values,从映射读取关键字,访问一个数据库,访问通知侦听器,等等。
// // 像常见的行为可以从函数库调用像delegated properties。 更多信息在delegated-properties.html。
//
// /*********************************第三章 3.接口*********************************************/
// /*Kotlin 的接口很像 java 8。它们都可以包含抽象方法,以及方法的实现。和抽象类不同的是,接口不能保存状态。可以有属性但必须是抽象的。
//
// 接口是通过关键字 interface 来定义的:
//
// // 接口中的成员变量和函数(有函数体的,没有函数体的方法是抽象的)默认是open的,因此可以重写
// interface MyInterface {
// fun bar()
// fun foo() {
// //函数体是可选的
// }
// }
// 接口的实现
//
// 一个类或对象可以实现一个或多个接口
//
// class Child : MyInterface {
// fun bar () {
// //函数体
// }
// }
// 接口中的属性
//
// 因为接口没有状态,所以中只允许有无状态的属性。
//
// interface MyInterface {
// val property: Int //抽象属性
// fun foo() {
// print(property)
// }
// }
//
// class Child : MyInterface {
// override val property: Int = 29
// }
// 解决重写冲突
//
// 当我们在父类中声明了许多类型,有可能出现一个方法的多种实现。比如:
//
// interface A {
// fun foo() { print("A") }
// fun bar()
// }
//
// interface B {
// fun foo() { print("B") }
// fun bar() { print("bar") }
// }
//
// //
// class C : A {
// override fun bar() { print("bar") }
// }
//
// class D : A, B {
// override fun foo() {
// super<A>.foo()
// super<B>.foo()
// }
// // 这里不重写bar()会报错,因为bar接口在A中没有实现方法故它是抽象的,不知道这里为什么不重写
// }
// A B 接口都有声明了 foo() bar() 函数。它们都实现了 foo() 方法,但只有 B 实现了 bar() ,bar() 在 A 中并没有声明它是抽象的,
// 这是因为在接口中如果函数没有函数体,那么默认是抽像的。现在,如果我们从 A 中派生一个 C 实体类,显然我们需要重写 bar() ,并实现它。
// 而我们从 A 和 B 派生一个 D ,我们不用重写 bar() 方法,因为我们的一个继承中有一个已经实现了它。
// (这句话不对啊!!!!!!!!!!!!!!! 经测试明明只要其中一个没有实现bar方法都要重写)
// 但我们继承了俩个 foo() 的实现,因此编译器不知道应该选哪个,并强制我们重写 foo() 并且明确指出我们想怎么实现。*/
//
// /*********************************第三章 4.范围修饰符(例如public)*********************************************/
// /*类,对象,接口,构造方法,和它们的setter方法都可以用visibility modifiers来做修饰。(getter一直与属性有着相同的可见性.)
//
// 在Kotlin中有以下四个可见性修饰符:
//
// private --- 只有在声明的范围及其方法可见(在同一模块);
//
// protected --- (只适用于类/接口成员)和"private"一样,但也在子类可见;
//
// internal --- (在默认情况下使用)在同一个模块中可见(如果声明范围的所有者是可见的);
//
// public --- 随处可见(如果声明范围的所有者是可见的).
//
// 注意: 函数 with expression bodies 所有的属性声明public必须始终显式指定返回类型。 这是必需的,这样我们就不会随意改变一个类型,仅通过改变实现公共API的一部分。
//
// public val foo: Int = 5 // explicit return type required
// public fun bar(): Int = 5 // explicit return type required
// public fun bar() {} // block body: return type is Unit and can't be changed accidentally, so not required
// 下面将解释不同类型的声明范围。
//
// 包名
//
// 函数,属性和类,对象和接口可以在顶层声明,即直接在包内:
//
// // file name: example.kt
// package foo
//
// fun baz() {}
// class Bar {}
// 如果你不指定任何可见性修饰符,那么默认情况下使用internal修饰,这意味着你们将声明在同一个模块中可见;
//
// 如果你声明private,只会是这个包及其子包内可见的,并且只在相同的模块;
//
// 如果你声明public,随处可见。
//
// protected不适用于顶层声明。
//
// 例子:
//
// // file name: example.kt
// package foo
//
// private fun foo() {} // visible inside this package and subpackaged
//
// public var bar: Int = 5 // property is visible everywhere
// private set // setter is visible only in this package and subpackages
//
// internal val baz = 6 // visible inside the same module, the modifier can be omitted
// 类和接口
//
// 当一个类中声明:
//
// private 意味着这个类只在内部可见(包含所有成员).
//
// protected--- 和private一样+在子类可见。
//
// internal --- 任何客户端 inside this module 谁看到声明类,其internal成员在里面;
//
// public --- 任何客户端看到声明类看到其public成员。
//
// 注意 对于Java用户:外部类不能访问Kotlin内部类的private成员。
//
// 例子:
//
// open class Outer {
// private val a = 1
// protected val b = 2
// val c = 3 // internal by default
// public val d: Int = 4 // return type required
//
// protected class Nested {
// public val e: Int = 5
// }
// }
//
// class Subclass : Outer() {
// // a is not visible
// // b, c and d are visible
// // Nested and e are visible
// }
//
// class Unrelated(o: Outer) {
// // o.a, o.b are not visible
// // o.c and o.d are visible (same module)
// // Outer.Nested is not visible, and Nested::e is not visible either
// }
// 构造函数
//
// 指定一个类的可见性的主构造函数,使用以下语法(注意你需要添加一个显示构造函数{:.keyword} keyword):
//
// class C private constructor(a: Int) { ... }
// 这里的构造函数是私有的。不像其他的声明,在默认情况下,所有构造函数是public,这实际上等于他们是随处可见,其中的类是可见(即内部类的构造函数是唯一可见在同一模块内).
//
// 局部声明
//
// 局部变量,函数和类不能有可见性修饰符。*/
//
// /*********************************第三章 5.拓展*********************************************/
// /*Kotlin 与 C# Gosu 类似,提供了不用从父类继承,或者使用像装饰模式这样的设计模式来给某个类进行扩展。
// 这是通过叫扩展的特殊声明来达到的。现在, Kotlin 支持扩展函数和属性。*/
//
// /***********扩展函数***********/
// /*声明一个扩展函数,我们需要添加一个接收者类型的的前缀。下面是给MutableList<Int>添加一个 swap 函数的例子:
//
// (MutableList是Kotlin中已有的接口)
// fun MutableList<Int>.swap(x: Int, y: Int) {
// val temp = this[x] // this 对应 list
// this[x] = this[y]
// this[y] = tmp
// }
// 在扩展函数中的 this 关键字对应接收者对象。现在我们可以在任何 MutableList<Int> 中使用这个函数了:
//
// fun <T> MutableList<T>.swap(x: Int, y: Int) {
// val tmp = this[x] // 'this' corresponds to the list
// this[x] = this[y]
// this[y] = tmp
// }*/
//
// /**************可空的接受者***********/
// /* 值得注意的是扩展可以定义一个可空的接受者。这样的扩展可以算作对象的变量,即使它是空的,你可以在函数体内检查 this == null 。
// 这样你就可以在 Kotlin 中不进行空检查就可以调用 toString() 方法:这样的检查是在扩展函数中做的。
//
// fun Any?.toString(): String {
// if (this == null) return "null"
// return toString()
// }*/
//
// /***************扩展属性*************/
// /*和函数类似, Kotlin 也支持属性扩展:
//
// val <T> List<T>.lastIndex: Int
// get() = size-1
// 注意,扩展并不是真正给类添加了成员,没有比给扩展添加备用字段更有效的办法了/这就是为什么初始化函数是不允许扩展属性。
// 它们只能通过明确提供 getter setter 来作用。
//
// 例子:
//
// val Foo.bar = 1 //error: initializers are not allowed for extension properties*/
//
// /************伴随对象扩展**************/
// /*如果一个对象定义了伴随对象,你也可以给伴随对象添加扩展函数或扩展属性:
//
// class MyClass {
// companion object {}
// }
//
// fun Myclass.Companion,foo() {
//
// }
// 和普通伴随对象的成员一样,它们可以只用类的名字就调用:
//
// MyClass.foo()*/
//
// /*************扩展的范围**************/
// /*大多数时候我们在 top level 定义扩展,就在包下面直接定义:
//
// package foo.bar
// fun Baz.goo() { ... }
// 在声明的包外面使用这样的扩展,我们需要在 import 时导入:
//
// package com.example,usage
//
// import foo.bar.goo//导入所有名字叫 "goo" 的扩展
//
// import foo.bar.*
//
// fun usage(baz: Baz) {
// baz.goo()
// }*/
//
// /**************动机(Motivation)***************/
// /*在 java 中,我经常给类命名为 "*Utils": FileUtils,StringUtils等等。很有名的 java.util.Collections 也是这样的,
// 这些 Utils 类不方便的地方就是我们用起来总是像下面这样:
//
// //java
// Collections.swap(list, Collections.binarySearch(list, Collections.max(otherList)), Collections.max(list))
// 这些类名总是通过一样的方式得到的。我我们可以使用静态导入并这样使用:
//
// swap(list, binarySearch(list, max(otherList)), max(list))
// 这样就好很多了,但这样我们就只能从 IDE 自动完成代码那里获得很少或得不到帮助。如果我们可以像下面这样那门就好多了
//
// list.swap(list.binarySearch(otherList.max()), list.max())
// 但我们又不想在 List 类中实现所有可能的方法。这就是扩展带来的好处。*/
//
// /*********************************第三章 6.数据类(javabean)************************************/
// /***********数据类(javabean)************/
// /*我们经常创建一些只是处理数据的类。在这些类里的功能经常是衍生自他们所持有的数据。在Kotlin中,这样的类可以被称为data:
// data class User(val name: String, val age: Int)
// 这被叫做一个 数据类。编译器自动从在主构造函数定义的全部特性中得到以下成员:
// equals()/hashCode(),
// toString() 格式是 "User(name=John, age=42)",
// componentN() functions 对应按声明顺序出现的所有属性,
// copy() 方法 .
// 如果有某个函数被明确地定义在类里或者被继承,编译器就不会生成这个函数。
// NOTE如果一个构造参数没有val或者var在前面,它将不会被包括进这些成员里;也不会在类里声明成属性或者继承自父类
// 在JVM中,如果生成的类需要含有一个无参的构造函数,则所有的属性必须有默认值。
// data class User(val name: String = "", val age: Int = 0)*/
//
// /**********复制************/
// /*在很多情况下,我们我们需要对一些属性做修改而其他的不变。这就是copy()这个方法的来源。对于上文的User类,应该是这么实现这个方法的
// fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
// 也可以这么写
// val jack = User(name = "Jack", age = 1)
// val olderJack = jack.copy(age = 2)*/
//
// data class User(val name: String, val age: Int)
//
// // 报错
// // fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
// val jack = User(name = "Jack", age = 1)
// // 使用copy可以bean的修改某些属性
// val olderJack = jack.copy(age = 2)
//
// /**********数据类和多重声明**********/
// /*成员方法用于使数据类可以多声明:
// val jane = User("Jane", 35)
// val (name, age) = jane
// println("$name, $age years of age") // prints "Jane, 35 years of age"*/
//
// /********标准数据类*********/
// /*在标准库提供了Pair和Triple。在很多情况下,即使命名数据类是一个更好的设计选择,因为这能让代码可读性更强。*/
//
// /*********************************第三章 7.泛型************************************/
// /*像 java 一样,Kotlin 中可以所有类型参数:
//
// class Box<T>(t: T){
// var value = t
// }
// 通常来说,创建一个这样类的实例,我们需要提供类型参数:
//
// val box: Box<Int> = Box<Int>(1)
// 但如果类型有可能是推断的,比如来自构造函数的参数或者通过其它的一些方式,一个可以忽略类型的参数:
//
// val box = Box(1)//1是 Int 型,因此编译器会推导出我们调用的是 Box*/
// class Box<T>(t: T) {
// var value = t
// }
//
// val box = Box(1)
//
// /*******变动*********/
// /*java 类型系统最狡猾的一部分就是通配符类型。但 kotlin 没有,代替它的是俩中其它的东西:
// 声明变化和类型预测(declaration-site variance and type projections)。
//
// 首先,我们想想为什么 java 需要这些神秘的通配符。这个问题在Effective Java,条目18中是这样解释的:使用界限通配符增加 API 的灵活性。
// 首先 java 中的泛型是不变的,这就意味着 List 不是 List 的子类型。为什么呢,如果 List 不是不变的,就会引发下面的问题:
//
// // Java
// List<String> strs = new ArrayList<String>();
// List<Object> objs = strs; // !!! The cause of the upcoming problem sits here. Java prohibits this!
// objs.add(1); // Here we put an Integer into a list of Strings
// String s = strs.get(0); // !!! ClassCastException: Cannot cast Integer to String
// 因此 java 禁止了这样的事情来保证运行时安全。但这有些其它影响。比如,Collection 接口的 addAll() 方法。这个方法的签名在哪呢?直观来讲是这样的:
//
// //java
// interface Collection<E> ... {
// void addAdd(Collection<E> items);
// }
// 但接下来我们就不能做下面这些简单事情了:
//
// //java
// void copyAll(Collection<Object> to, Collection<String> from){
// to.addAll(from);
// }
// 这就是为什么 addAll() 的签名是下面这样的:
//
// //java
// interface Collection<E> ... {
// void addAll(Colletion<? extend E> items);
// }
// 这个通配符参数? extents T意味着这个方法接受一些 T 类型的子类而非 T 类型本身。这就是说我们可以安全的读
// T's(这里表示 T 子类元素的集合),但不能写,因为我们不知道 T 的子类究竟是什么样的,针对这样的限制,
// 我们很想要这样的行为:Collection 是 Collection<? extens Object>的子类。在“智能关键字(不知道这样翻译对不对,原词clever words)”,
// 用通配符的扩展绑定(上限),使该类型的协变。
// 关键要理解这种方式的工作原理:如果你只能从集合取对象,然后用字符串的集合读取对象是最好的。相反,如果你只能把对象放入集合
// ,那么put一个String对这个集合中:在Java中,我们有目录<?super String>的集合的超类型。 .....
// 太复杂了原谅我偷懒 原文地址:http://kotlinlang.org/docs/reference/generics.html*/
//
// /*********************************第三章 8.内部类************************************/
// /*在类的内部可以嵌套其他的类
//
// class Outer {
// private val bar: Int = 1
// class Nested {
// fun foo() = 2
// }
// }
//
// val demo = Outer.Nested().foo() // == 2
// 内部类
//
// 为了能被外部类访问一个类可以被标记为内部类(“inner” 关键词)。 内部类会带有一个来自外部类的对象的引用:
//
// class Outer {
// private val bar: Int = 1
// inner class Inner {
// fun foo() = bar
// }
// }
//
// val demo = Outer().Inner().foo() // == 1
// 参阅this-expressions.html中“this”关键词用法来学习在内部类中如何消除“this”关键词的歧义。*/
//
// class Outer {
// private val bar: Int = 1
//
// class Nested {
// fun foo() = 2
// }
// }
//
// val kk = Outer.Nested().foo()
//
// /*********************************第三章 9.枚举************************************/
// // 不推荐在Android中使用枚举,这章就不写了
//
// /*********************************第三章 10.对象表达式和声明************************************/
// /*有时候我们需要创建一个对当前类做轻微修改的对象,而不用重新声明一个子类。java 用匿名内部类来解决这个问题。
// Kotlin 更希望推广用对象表达式和声明来解决这个问题。*/
//
// /***********对象表达式*************/
// /*我们通过下面这样的方式创建继承自某种(或某些)匿名类的对象:
//
// window.addMouseListener(object: MouseAdapter () {
// override fun mouseClicked(e: MouseEvent) {
// //...
// }
// })
// 如果父类有构造函数,则必须传递相应的构造函数。多个父类可以用逗号隔开,跟在冒号后面:
//
// open class A(x: Int) {
// public open val y: Int = x
// }
//
// interface B { ... }
//
// val ab = object : A(1), B {
// override val y = 14
// }
// 有时候我们只是需要一个没有父类的对象,我们可以这样写:
//
// val adHoc = object {
// var x: Int = 0
// var y: Int = 0
// }
//
// print(adHoc.x + adHoc.y)
// 像 java 的匿名内部类一样,对象表达式可以访问闭合范围内的变量 (和 java 不一样的是,这些不用声明为 final)
//
// fun countClicks(windows: JComponent) {
// var clickCount = 0
// var enterCount = 0
// window.addMouseListener(object : MouseAdapter() {
// override fun mouseClicked(e: MouseEvent) {
// clickCount++
// }
// override fun mouseEntered(e: MouseEvent){
// enterCount++
// }
// })
// }*/
//
// open class A1(x: Int) {
// public open val y: Int = x
// }
//
// // ab类型为对象,并且重写了父类的成员变量,故为对象表达式
// val ab = object : A1(1) {
// override val y = 14
// }
//
// val adHoc = object {
// var x: Int = 0
// var y: Int = 0
// }
//
// /************对象声明************/
// /*单例模式是一种很有用的模式,Kotln 中声明它很方便:
//
// object DataProviderManager {
// fun registerDataProvider(provider: Dataprovider) {
// //...
// }
// val allDataProviders : Collection<DataProvider>
// get() = //...
// }
// 这叫做对象声明。如果在 object 关键字后面有个名字,我们不能把它当做表达式了。虽然不能把它赋值给变量,,但可以通过名字赋值。这样的对象可以有父类:
//
// object DefaultListener : MouseAdapter() {
// override fun mouseClicked(e: MouseEvent) {
// // ...
// }
// override fun mouseEntered(e: MouseEvent) {
// // ...
// }
// }
// 注意:对象声明不可以是局部的(比如不可以直接在函数内部声明),但可以在其它对象的声明或非内部类中使用*/
//
// class MouseEvent {
// }
//
// open class MouseAdapter {
// open fun mouseClicked(e: MouseEvent) {
// }
//
// open fun mouseEntered(e: MouseEvent) {
// }
// }
//
// // DefaultListener是一个单例对象,然后父类为MouseAdapter
// object DefaultListener : MouseAdapter() {
// override fun mouseClicked(e: MouseEvent) {
// }
//
// override fun mouseEntered(e: MouseEvent) {
// }
// }
//
// /************伴随对象*********/
// /*在类声明内部可以用 companion 关键字标记对象声明:
//
// class MyClass {
// companion object Factory {
// fun create(): MyClass = MyClass()
// }
// }
// 伴随对象的成员可以通过类名做限定词直接使用:
//
// val instance = MyClass.create()
// 在使用了 companion 关键字时,伴随对象的名字可以省略:
//
// class MyClass {
// companion object {
//
// }
// }
// 注意,尽管伴随对象的成员很像其它语言中的静态成员,但在运行时它们任然是真正对象的成员实例,比如可以实现接口:
//
// interface Factory<T> {
// fun create(): T
// }
//
// class MyClass {
// companion object : Factory<MyClass> {
// override fun create(): MyClass = MyClass()
// }
// }*/
//
// class MyClass {
// companion object Factory {
// // 单例工厂create方法返回一个MyClass的对象
// fun create(): MyClass = MyClass()
// }
// }
//
// // 伴随对象Factory的成员函数create可以通过类名做限定词直接使用
// // 在使用了 companion 关键字时,伴随对象的名字可以省略,Factory都可以去掉
// val instance = MyClass.create()
//
// interface Factory1<T> {
// fun create(): T
// }
//
// class MyClass1 {
// companion object : Factory1<MyClass1> {
// override fun create(): MyClass1 = MyClass1()
// }
// }
//
// /************对象表达式和声明的区别***********/
// /*他俩之间只有一个特别重要的区别:
// 对象声明是 lazily 初始化的,我们只能访问一次 对象表达式在我们使用的地方立即初始化并执行的*/
//
// /*********************************第三章 11.代理************************************/
// /*类代理
//
// 代理模式 给实现继承提供了很好的代替方式, Kotlin 原生支持它,所以并不需要什么样板代码。Derived 类可以继承 Base 接口并且代理了它全部的公共方法:
//
// interface Base {
// fun print()
// }
//
// class BaseImpl(val x: Int) : Base {
// override fun print() { printz(x) }
// }
//
// class Derived(b: Base) : Base by b
//
// fun main() {
// val b = BaseImpl(10)
// Derived(b).print()
// }
// 在 Derived 的父类列表中的条款意味这 b 将会存储在 Derived 对象中并且编译器会生成 Base 的所有方法并转给 b。*/
//
// interface Base1 {
// fun print()
// }
//
// class BaseImpl(val x: Int) : Base1 {
// override fun print() {
// KLog.e(x)
// }
// }
//
// // Derived1代理b实例 ( Derived1 通过 by 关键字 代理后面的变量 b)
// class Derived1(b: Base1) : Base1 by b
//
// fun derivedPrint() {
// val b = BaseImpl(10)
// // b 将会存储在 Derived 对象中并且编译器会生成 Base 的所有方法并转给 b
// Derived1(b).print()
// }
//
// /*********************************第三章 12.属性代理************************************/
// /*很多常用属性,虽然我们可以在需要的时候手动实现它们,但更好的办法是一次实现多次使用,并放到库。比如:
//
// 延迟属性:只在第一次访问是计算它的值 观察属性:监听者从这获取这个属性更新的通知 在 map 中存储的属性,而不是单独存在分开的字段
// 为了满足这些情形,Kotllin 支持代理属性:
//
// class Example {
// var p: String by Delegate()
// }
// 语法结构是: val/var <property name>: <Type> by <expression> 在 by 后面的属性就是代理,这样这个属性的 get() 和 set() 方法就代理给了它。
//
// 属性代理不需要任何接口的实现,但必须要提供 get() 方法(如果是变量还需要 set() 方法)。像这样:
//
// class Delegate {
// fun get(thisRef: Any?, prop: PropertyMetadata): String {
// return "$thisRef, thank you for delegating '${prop.name}' to me !"
// }
//
// fun set(thisRef: Any?, prop: PropertyMatada, value: String) {
// println("$value has been assigned to '${prop.name} in $thisRef.'")
// }
// }
// 当我们从 p 也就是 Delegate 的代理,中读东西时,会调用 Delegate 的 get() 函数,因此第一个参数是我们从 p 中读取的,第二个参数是 p 自己的一个描述。比如:
//
// val e = Example()
// pintln(e.p)
// 打印结果:
//
// Example@33a17727, thank you for delegating ‘p’ to me! 同样当我们分配 p 时 set() 函数就会调动。前俩个参数所以一样的,第三个持有分配的值:
//
// e.p = "NEW"
// 打印结果: NEW has been assigned to ‘p’ in Example@33a17727.
// 代理属性的要求
//
// 这里总结一些代理对象的要求。
//
// 只读属性 (val),代理必须提供一个名字叫 get 的方法并接受如下参数:
//
// 接收者--必须是相同的,或者是属性拥有者的子类型 元数据--必须是 PropertyMetadata 或这它的子类型
// 这个函数必须返回同样的类型作为属性。
//
// 可变属性 (var),代理必须添加一个叫 set 的函数并接受如下参数: 接受者--与 get() 一样 元数据--与 get() 一样 新值--必须和属性类型一致或是它的字类型
//
// 标准代理
//
// kotlin.properties.Delegates 对象是标准库提供的一个工厂方法并提供了很多有用的代理
//
// 延迟
//
// Delegate.lazy() 是一个接受 lamdba 并返回一个实现延迟属性的代理:第一次调用 get() 执行 lamdba 并传递 lazy() 并记下结果,随后调用 get() 并简单返回之前记下的值。
//
// import kotlin.properties.Delegates
//
// val lazy: String by Delegates.lazy {
// println("computed!")
// "Hello"
// }
//
// fun main(args: Array<String>) {
// println(lazy)
// println(lazy)
// }
// 如果你想要线程安全,使用 blockingLazy(): 它还是按照同样的方式工作,但保证了它的值只会在一个线程中计算,并且所有的线程都获取的同一个值。
//
// 观察者
//
// Delegates.observable() 需要俩个参数:一个初始值和一个修改者的 handler 。每次我们分配属性时都会调用handler (在分配前执行)。它有三个参数:一个分配的属性,旧值,新值:
//
// class User {
// var name: String by Delegates.observable("<no name>") {
// d.old,new -> println("$old -> $new")
// }
// }
//
// fun main(args: Array<String>) {
// val user = User()
// user.name = "first"
// user.name = "second"
// }
// 打印结果
//
// -> first first -> second 如果你想能够截取它的分配并取消它,用 vetoable()代替 observable()
// 非空
//
// 有时我们有一个非空的 var ,但我们在构造函数中没有一个合适的值,比如它必须稍后再分配。问题是你不能持有一个未初始化并且是非抽象的属性:
//
// class Foo {
// var bar: Bat //错误必须初始化
// }
// 我们可以用 null 初始化它,但我们不用每次访问时都检查它。
//
// Delegates.notNull()可以解决这个问题
//
// class Foo {
// var bar: Bar by Delegates.notNull()
// }
// 如果这个属性在第一次写之前读,它就会抛出一个异常,只有分配之后才会正常。
//
// 在 Map 中存储属性
//
// Delegates.mapVal() 拥有一个 map 实例并返回一个可以从 map 中读其中属性的代理。在应用中有很多这样的例子,比如解析 JSON 或者做其它的一些 "动态"的事情:
//
// class User(val map: Map<String, Any?>) {
// val name: String by Delegates.mapVal(map)
// val age: Int by Delegates.mapVal(map)
// }
// 在这个例子中,构造函数持有一个 map :
//
// val user = User(mapOf (
// "name" to "John Doe",
// "age" to 25
// ))
// 代理从这个 map 中取指(通过属性的名字):
//
// println(user.name) // Prints "John Doe"
// println(user.age) // Prints 25
// var 可以用 mapVar*/
//
//// class Example {
//// // p代理了Delegate,当使用KLog.e(e.p)会调用Delegate的get方法,使用e.p = "google"会调用Delegate的set方法
//// var p: String by Delegate()
//// }
//
// /*class Delegate {
// fun get(thisRef: Any?, prop: PropertyMetadata): String {
// return "${thisRef}, thank you for delegating '${prop.name}' to me !"
// }
//
// fun set(thisRef: Any?, prop: PropertyMetadata, value: String) {
// KLog.e("$value has been assigned to '${prop.name} in $thisRef.'")
// }
// }*/
//
// class Player {
// // Delegates.observable() 需要俩个参数:一个初始值和一个修改者的 handler
// // 每次我们分配属性时都会调用handler (在分配前执行)。它有三个参数:一个分配的属性,旧值,新值:
// // <no name>为初始值
// var name: String by Delegates.observable("<no name>") {
// d, old, new ->
// KLog.e("$old -> $new")
// }
// }
//
// fun setPlayer() {
// val player = Player()
// player.name = "first"
// player.name = "second"
// // 打印 <no name> -> first;然后是 first -> second
// }
//
// // 有一个非空的 var ,但我们在构造函数中没有一个合适的值,比如它必须稍后再分配。
// // 问题是你不能持有一个未初始化并且是非抽象的属性
// // 我们可以用 null 初始化它,但我们不用每次访问时都检查它。
// // Delegates.notNull()可以解决这个问题
// // 如果这个属性在第一次写之前读,它就会抛出一个异常,只有分配之后才会正常。
// class Foo {
// var bar: Any by Delegates.notNull<Any>()
// }
//
// class User1(val map: Map<String, Any?>) {
// // Delegates.mapVal() 拥有一个 map 实例并返回一个可以从 map 中读其中属性的代理
//// val name: String by Delegates.mapVal(map)
//// val age: Int by Delegates.mapVal(map)
// }
//
// val user = User1(mapOf(
// "name" to "John Doe",
// "age" to 25
// ))
override fun initData() {
// for ((a, b) in user.map) {
// KLog.e("$a--$b")
// }
// val foo = Foo()
// foo.bar = 1
// foo.bar
// setPlayer()
// val e = Example()
// KLog.e(e.p)
// e.p = "google"
// derivedPrint()
// KLog.e(MyClass1.create())
// KLog.e(ab.y)
// KLog.e("Outer.Nested().foo() = $kk")
// KLog.e(box.value)
// KLog.e(olderJack)
// val jane = User("Jane", 35)
// 将jane的属性值赋给(name,age)
// val (name, age) = jane
// KLog.e("$name, $age years of age")
// _table = mapOf(Pair("1", 1))
// KLog.e("_table的大小为:${_table?.size}")
// stringRepresentation = "你好吗"
// KLog.e("isBelongBaseActivity=$isBelongBaseActivity")
// KLog.e("example=$example")
// val c = C();
// c.f()
// val p = Person()
// KLog.e(p.getName() + " " + p.getName1())
// foo(arrayOf(1, 2, 3, 4, 0))
// var k = 10
// while (k > 0) {
// k--
// KLog.e(k)
// // 跳出循环
// if (k == 4)
// break
// }
// var y = 10
// do {
// y--
// KLog.e(y)
// } while (y > 0)
// val ints = arrayOf(1, 2, 3, 4, 5)
// // 三种遍历集合方式
// for (item: Int in ints) {
// KLog.e(item)
// }
// for (item in ints) {
// KLog.e(item)
// }
// for (item in ints.indices) {
// KLog.e(item)
// }
// val x=11
// val s="11"
// when (x) {
// parseInt(s) -> KLog.e("s encodes x")
// else -> KLog.e("s does not encode x")
// }
// val text = """ \n """
// KLog.e(text)
// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
// val asc = Array(5, {i -> (i * i).toString()})
// KLog.e(decimalDigitValue('9'))
/*// 测试结果>>与>>>值一毛一样,不解
var i = 0b11010011
// >> 将一个数的各二进制位右移两位,移到右端的低位被舍弃,最高位则移入原来高位的值.
// >>> 将一个数的各二进制位无符号右移若干位,与运算符>>相同,移出的低位被舍弃,但不同的是最高位补0
// i>>2位, 11010011 有符号右移 => 11110100
KLog.e(i shr 2)
var j = 0b11010011
// i>>>2位, 11010011 无符号右移 => 00110100
KLog.e(j ushr 2)*/
// 我们可以显示转换的去扩大类型
// val b: Byte = 1 // OK, literals are checked statically
// val i: Int = b.toInt() // OK: explicitly widened
// KLog.e("Green=${transform("Green")}")
// KLog.e("foo=${foo(2)}")
// "Convert this to camelcase".spaceToCamelCase()
// show1(list)
// traverse(mapOf(Pair("Mexi", "Basa"), Pair("C罗", "RM")))
// KLog.e(Customer("oubowu", "[email protected]").toString())
// filter(arrayOf(-1, -2, 1, 2, 3))
/*val list = arrayListOf<String>()
list.add("Kobe")
list.add("Pole")
list.add("Curry")
show(list)
KLog.e("sum2= " + sum2(1, 8))
printSum(3, 4)*/
// nullTest(arrayOf("k", "2"))
// val s = "ni hao ma"
// KLog.e("\"$s\" length is ${getStringLength(s)}")
// val s1 = -1
// KLog.e("\"$s1\" length is ${getStringLength(s1)}")
// loop(arrayOf("cao", "ni", "ma"))
// loop1(arrayOf("qu", "ni", "mei"))
// cases(1)
// cases("hello")
// cases(1L)
// cases(2.00f)
// inUseCase();
}
}
| apache-2.0 | 6ee79433089d2049844167c1be259302 | 27.311239 | 200 | 0.520002 | 2.565571 | false | false | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/screens/album/detail/AlbumDetailFragment.kt | 1 | 22413 | package com.simplecity.amp_library.ui.screens.album.detail
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.v4.app.SharedElementCallback
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.Toolbar
import android.transition.Transition
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.Toast
import com.afollestad.aesthetic.Aesthetic
import com.afollestad.aesthetic.Rx.distinctToMainThread
import com.bumptech.glide.Priority
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.gms.cast.framework.CastButtonFactory
import com.simplecity.amp_library.R
import com.simplecity.amp_library.cast.CastManager
import com.simplecity.amp_library.glide.utils.AlwaysCrossFade
import com.simplecity.amp_library.model.Album
import com.simplecity.amp_library.model.ArtworkProvider
import com.simplecity.amp_library.model.Playlist
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.ui.common.BaseFragment
import com.simplecity.amp_library.ui.common.TransitionListenerAdapter
import com.simplecity.amp_library.ui.dialog.AlbumBiographyDialog
import com.simplecity.amp_library.ui.dialog.DeleteDialog
import com.simplecity.amp_library.ui.dialog.SongInfoDialog
import com.simplecity.amp_library.ui.modelviews.DiscNumberView
import com.simplecity.amp_library.ui.modelviews.EmptyView
import com.simplecity.amp_library.ui.modelviews.SelectableViewModel
import com.simplecity.amp_library.ui.modelviews.SongView
import com.simplecity.amp_library.ui.modelviews.SubheaderView
import com.simplecity.amp_library.ui.screens.drawer.DrawerLockManager
import com.simplecity.amp_library.ui.screens.playlist.dialog.CreatePlaylistDialog
import com.simplecity.amp_library.ui.screens.tagger.TaggerDialog
import com.simplecity.amp_library.ui.views.ContextualToolbar
import com.simplecity.amp_library.ui.views.ContextualToolbarHost
import com.simplecity.amp_library.utils.ActionBarUtils
import com.simplecity.amp_library.utils.ArtworkDialog
import com.simplecity.amp_library.utils.ContextualToolbarHelper
import com.simplecity.amp_library.utils.Operators
import com.simplecity.amp_library.utils.PlaceholderProvider
import com.simplecity.amp_library.utils.ResourceUtils
import com.simplecity.amp_library.utils.RingtoneManager
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.ShuttleUtils
import com.simplecity.amp_library.utils.StringUtils
import com.simplecity.amp_library.utils.TypefaceManager
import com.simplecity.amp_library.utils.extensions.share
import com.simplecity.amp_library.utils.menu.album.AlbumMenuUtils
import com.simplecity.amp_library.utils.menu.song.SongMenuUtils
import com.simplecity.amp_library.utils.playlists.PlaylistMenuHelper
import com.simplecity.amp_library.utils.sorting.SongSortHelper
import com.simplecity.amp_library.utils.sorting.SortManager
import com.simplecityapps.recycler_adapter.adapter.CompletionListUpdateCallbackAdapter
import com.simplecityapps.recycler_adapter.adapter.ViewModelAdapter
import com.simplecityapps.recycler_adapter.model.ViewModel
import com.simplecityapps.recycler_adapter.recyclerview.RecyclerListener
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_detail.background
import kotlinx.android.synthetic.main.fragment_detail.fab
import kotlinx.android.synthetic.main.fragment_detail.recyclerView
import kotlinx.android.synthetic.main.fragment_detail.textProtectionScrim
import kotlinx.android.synthetic.main.fragment_detail.textProtectionScrim2
import kotlinx.android.synthetic.main.fragment_detail.toolbar
import kotlinx.android.synthetic.main.fragment_detail.toolbar_layout
import java.util.ArrayList
import javax.inject.Inject
import kotlinx.android.synthetic.main.fragment_detail.contextualToolbar as ctxToolbar
@SuppressLint("RestrictedApi")
class AlbumDetailFragment :
BaseFragment(),
AlbumDetailView,
Toolbar.OnMenuItemClickListener,
DrawerLockManager.DrawerLock,
ContextualToolbarHost {
private lateinit var album: Album
private lateinit var adapter: ViewModelAdapter
private lateinit var presenter: AlbumDetailPresenter
@Inject lateinit var requestManager: RequestManager
@Inject lateinit var presenterFactory: AlbumDetailPresenter.Factory
@Inject lateinit var sortManager: SortManager
@Inject lateinit var settingsManager: SettingsManager
@Inject lateinit var playlistMenuHelper: PlaylistMenuHelper
private val disposables = CompositeDisposable()
private var collapsingToolbarTextColor: ColorStateList? = null
private var collapsingToolbarSubTextColor: ColorStateList? = null
private val emptyView = EmptyView(R.string.empty_songlist)
private var setItemsDisposable: Disposable? = null
private var contextualToolbarHelper: ContextualToolbarHelper<Single<List<Song>>>? = null
private var isFirstLoad = true
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
album = arguments!!.getSerializable(ARG_ALBUM) as Album
}
override fun onCreate(icicle: Bundle?) {
super.onCreate(icicle)
presenter = presenterFactory.create(album)
adapter = ViewModelAdapter()
setHasOptionsMenu(true)
setEnterSharedElementCallback(enterSharedElementCallback)
isFirstLoad = true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar.setNavigationOnClickListener { navigationController.popViewController() }
if (ShuttleUtils.canDrawBehindStatusBar()) {
toolbar.layoutParams.height = (ActionBarUtils.getActionBarHeight(context!!) + ActionBarUtils.getStatusBarHeight(context!!)).toInt()
toolbar.setPadding(toolbar!!.paddingLeft, (toolbar.paddingTop + ActionBarUtils.getStatusBarHeight(context!!)).toInt(), toolbar.paddingRight, toolbar.paddingBottom)
}
setupToolbarMenu(toolbar)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setRecyclerListener(RecyclerListener())
recyclerView.adapter = adapter
if (isFirstLoad) {
recyclerView!!.layoutAnimation = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_from_bottom)
}
toolbar_layout.title = album.name
toolbar_layout.setSubtitle(album.albumArtistName)
toolbar_layout.setExpandedTitleTypeface(TypefaceManager.getInstance().getTypeface(context, TypefaceManager.SANS_SERIF_LIGHT))
toolbar_layout.setCollapsedTitleTypeface(TypefaceManager.getInstance().getTypeface(context, TypefaceManager.SANS_SERIF))
setupContextualToolbar()
val transitionName = arguments!!.getString(ARG_TRANSITION_NAME)
ViewCompat.setTransitionName(background!!, transitionName)
if (isFirstLoad) {
fab.visibility = View.GONE
}
fab.setOnClickListener { presenter.shuffleAll() }
if (transitionName == null) {
fadeInUi()
}
loadBackgroundImage()
disposables.add(Aesthetic.get(context)
.colorPrimary()
.compose(distinctToMainThread())
.subscribe { primaryColor ->
toolbar_layout.setContentScrimColor(primaryColor!!)
toolbar_layout.setBackgroundColor(primaryColor)
})
presenter.bindView(this)
}
override fun onResume() {
super.onResume()
presenter.loadData()
DrawerLockManager.getInstance().addDrawerLock(this)
}
override fun onPause() {
DrawerLockManager.getInstance().removeDrawerLock(this)
super.onPause()
}
override fun onDestroyView() {
setItemsDisposable?.dispose()
disposables.clear()
presenter.unbindView(this)
isFirstLoad = false
super.onDestroyView()
}
private fun setupToolbarMenu(toolbar: Toolbar) {
toolbar.inflateMenu(R.menu.menu_detail_sort)
if (CastManager.isCastAvailable(context!!, settingsManager)) {
val menuItem = CastButtonFactory.setUpMediaRouteButton(context, toolbar.menu, R.id.media_route_menu_item)
menuItem.isVisible = true
}
toolbar.setOnMenuItemClickListener(this)
// Create playlist menu
val sub = toolbar.menu.findItem(R.id.addToPlaylist).subMenu
disposables.add(playlistMenuHelper.createUpdatingPlaylistMenu(sub).subscribe())
// Inflate sorting menus
val item = toolbar.menu.findItem(R.id.sorting)
activity!!.menuInflater.inflate(R.menu.menu_detail_sort_albums, item.subMenu)
activity!!.menuInflater.inflate(R.menu.menu_detail_sort_songs, item.subMenu)
toolbar.menu.findItem(R.id.editTags).isVisible = true
toolbar.menu.findItem(R.id.info).isVisible = true
toolbar.menu.findItem(R.id.artwork).isVisible = true
SongSortHelper.updateSongSortMenuItems(toolbar.menu, sortManager.albumDetailSongsSortOrder, sortManager.albumDetailSongsAscending)
}
override fun onMenuItemClick(item: MenuItem): Boolean {
if (!AlbumMenuUtils.getAlbumMenuClickListener(album, presenter).onMenuItemClick(item)) {
val songSortOder = SongSortHelper.handleSongMenuSortOrderClicks(item)
if (songSortOder != null) {
sortManager.albumDetailSongsSortOrder = songSortOder
presenter.loadData()
}
val songsAsc = SongSortHelper.handleSongDetailMenuSortOrderAscClicks(item)
if (songsAsc != null) {
sortManager.albumDetailSongsAscending = songsAsc
presenter.loadData()
}
SongSortHelper.updateSongSortMenuItems(toolbar!!.menu, sortManager.albumDetailSongsSortOrder, sortManager.albumDetailSongsAscending)
}
return super.onOptionsItemSelected(item)
}
private fun loadBackgroundImage() {
val width = ResourceUtils.getScreenSize().width + ResourceUtils.toPixels(60f)
val height = resources.getDimensionPixelSize(R.dimen.header_view_height)
requestManager.load<ArtworkProvider>(album as ArtworkProvider?)
// Need to override the height/width, as the shared element transition tricks Glide into thinking this ImageView has
// the same dimensions as the ImageView that the transition starts with.
// So we'll set it to screen width (plus a little extra, which might fix an issue on some devices..)
.override(width, height)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.priority(Priority.HIGH)
.placeholder(PlaceholderProvider.getInstance(context).getPlaceHolderDrawable(album.name, true, settingsManager))
.centerCrop()
.animate(AlwaysCrossFade(false))
.into(background!!)
}
override fun setSharedElementEnterTransition(transition: Any?) {
super.setSharedElementEnterTransition(transition)
(transition as Transition).addListener(sharedElementEnterTransitionListenerAdapter)
}
internal fun fadeInUi() {
if (textProtectionScrim == null || textProtectionScrim2 == null || fab == null) {
return
}
//Fade in the text protection scrim
textProtectionScrim!!.alpha = 0f
textProtectionScrim!!.visibility = View.VISIBLE
var fadeAnimator = ObjectAnimator.ofFloat(textProtectionScrim, View.ALPHA, 0f, 1f)
fadeAnimator.duration = 600
fadeAnimator.start()
textProtectionScrim2!!.alpha = 0f
textProtectionScrim2!!.visibility = View.VISIBLE
fadeAnimator = ObjectAnimator.ofFloat(textProtectionScrim2, View.ALPHA, 0f, 1f)
fadeAnimator.duration = 600
fadeAnimator.start()
//Fade & grow the FAB
fab!!.alpha = 0f
fab!!.visibility = View.VISIBLE
fadeAnimator = ObjectAnimator.ofFloat(fab, View.ALPHA, 0.5f, 1f)
val scaleXAnimator = ObjectAnimator.ofFloat(fab, View.SCALE_X, 0f, 1f)
val scaleYAnimator = ObjectAnimator.ofFloat(fab, View.SCALE_Y, 0f, 1f)
val animatorSet = AnimatorSet()
animatorSet.playTogether(fadeAnimator, scaleXAnimator, scaleYAnimator)
animatorSet.duration = 250
animatorSet.start()
}
override fun getContextualToolbar(): ContextualToolbar? {
return ctxToolbar as ContextualToolbar
}
private fun setupContextualToolbar() {
val contextualToolbar = ContextualToolbar.findContextualToolbar(this)
if (contextualToolbar != null) {
contextualToolbar.setTransparentBackground(true)
contextualToolbar.menu.clear()
contextualToolbar.inflateMenu(R.menu.context_menu_general)
val subMenu = contextualToolbar.menu.findItem(R.id.addToPlaylist).subMenu
disposables.add(playlistMenuHelper.createUpdatingPlaylistMenu(subMenu).subscribe())
contextualToolbar.setOnMenuItemClickListener(
SongMenuUtils.getSongMenuClickListener(Single.defer { Operators.reduceSongSingles(contextualToolbarHelper!!.items) }, presenter)
)
contextualToolbarHelper = object : ContextualToolbarHelper<Single<List<Song>>>(context!!, contextualToolbar, object : ContextualToolbarHelper.Callback {
override fun notifyItemChanged(viewModel: SelectableViewModel) {
val index = adapter.items.indexOf(viewModel as ViewModel<*>)
if (index >= 0) {
adapter.notifyItemChanged(index, 0)
}
}
override fun notifyDatasetChanged() {
adapter.notifyItemRangeChanged(0, adapter.items.size, 0)
}
}) {
override fun start() {
super.start()
// Need to hide the collapsed text, as it overlaps the contextual toolbar
collapsingToolbarTextColor = toolbar_layout.collapsedTitleTextColor
collapsingToolbarSubTextColor = toolbar_layout.collapsedSubTextColor
toolbar_layout.setCollapsedTitleTextColor(0x01FFFFFF)
toolbar_layout.setCollapsedSubTextColor(0x01FFFFFF)
toolbar!!.visibility = View.GONE
}
override fun finish() {
if (toolbar_layout != null && collapsingToolbarTextColor != null && collapsingToolbarSubTextColor != null) {
toolbar_layout.collapsedTitleTextColor = collapsingToolbarTextColor!!
toolbar_layout.collapsedSubTextColor = collapsingToolbarSubTextColor!!
}
toolbar?.visibility = View.VISIBLE
super.finish()
}
}
}
}
private val sharedElementEnterTransitionListenerAdapter: TransitionListenerAdapter
get() = object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
transition.removeListener(this)
fadeInUi()
}
}
private val enterSharedElementCallback = object : SharedElementCallback() {
override fun onSharedElementStart(sharedElementNames: List<String>?, sharedElements: List<View>?, sharedElementSnapshots: List<View>?) {
super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots)
fab?.visibility = View.GONE
}
}
private var songClickListener: SongView.ClickListener = object : SongView.ClickListener {
override fun onSongClick(position: Int, songView: SongView) {
if (!contextualToolbarHelper!!.handleClick(songView, Single.just(listOf(songView.song)))) {
presenter.play(songView.song)
}
}
override fun onSongLongClick(position: Int, songView: SongView): Boolean {
return contextualToolbarHelper!!.handleLongClick(songView, Single.just(listOf(songView.song)))
}
override fun onSongOverflowClick(position: Int, v: View, song: Song) {
val popupMenu = PopupMenu(v.context, v)
SongMenuUtils.setupSongMenu(popupMenu, false, false, playlistMenuHelper)
popupMenu.setOnMenuItemClickListener(SongMenuUtils.getSongMenuClickListener(song, presenter))
popupMenu.show()
}
override fun onStartDrag(holder: SongView.ViewHolder) {
}
}
// AlbumDetailView implementation
override fun setData(data: MutableList<Song>) {
val viewModels = ArrayList<ViewModel<*>>()
val songsSortOrder = sortManager.albumDetailSongsSortOrder
if (!data.isEmpty()) {
viewModels.add(SubheaderView(StringUtils.makeSongsAndTimeLabel(context!!, data.size, data.map { song -> song.duration / 1000 }.sum())))
viewModels.addAll(
ArrayList<ViewModel<*>>(
data
.map { song ->
val songView = SongView(song, requestManager, sortManager, settingsManager)
songView.showArtistName(false)
songView.showAlbumName(false)
songView.setShowTrackNumber(songsSortOrder == SortManager.SongSort.TRACK_NUMBER || songsSortOrder == SortManager.SongSort.DETAIL_DEFAULT)
songView.setClickListener(songClickListener)
songView
}.toList()
)
)
if (album.numDiscs > 1 && (songsSortOrder == SortManager.SongSort.DETAIL_DEFAULT || songsSortOrder == SortManager.SongSort.TRACK_NUMBER)) {
var discNumber = 0
val length = viewModels.size
for (i in 0 until length) {
val viewModel = viewModels[i]
if (viewModel is SongView) {
if (discNumber != viewModel.song.discNumber) {
discNumber = viewModel.song.discNumber
viewModels.add(i, DiscNumberView(discNumber))
}
}
}
}
} else {
viewModels.add(emptyView)
}
setItemsDisposable = adapter.setItems(viewModels, object : CompletionListUpdateCallbackAdapter() {
override fun onComplete() {
recyclerView?.scheduleLayoutAnimation()
}
})
}
override fun closeContextualToolbar() {
contextualToolbarHelper?.finish()
}
// AlbumMenuContract.View Implementation
override fun presentTagEditorDialog(album: Album) {
TaggerDialog.newInstance(album).show(childFragmentManager)
}
override fun presentDeleteAlbumsDialog(albums: List<Album>) {
DeleteDialog.newInstance(DeleteDialog.ListAlbumsRef { albums }).show(childFragmentManager)
}
override fun presentAlbumInfoDialog(album: Album) {
AlbumBiographyDialog.newInstance(album).show(childFragmentManager)
}
override fun presentArtworkEditorDialog(album: Album) {
ArtworkDialog.build(context, album).show()
}
override fun onPlaybackFailed() {
// Todo: Improve error message
Toast.makeText(context, R.string.empty_playlist, Toast.LENGTH_SHORT).show()
}
// SongMenuContract.View Implementation
override fun presentCreatePlaylistDialog(songs: List<Song>) {
CreatePlaylistDialog.newInstance(songs).show(childFragmentManager, "CreatePlaylistDialog")
}
override fun presentSongInfoDialog(song: Song) {
SongInfoDialog.newInstance(song).show(childFragmentManager)
}
override fun onSongsAddedToPlaylist(playlist: Playlist, numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoplaylist, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun onSongsAddedToQueue(numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoqueue, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun presentTagEditorDialog(song: Song) {
TaggerDialog.newInstance(song).show(childFragmentManager)
}
override fun presentDeleteDialog(songs: List<Song>) {
DeleteDialog.newInstance(DeleteDialog.ListSongsRef { songs }).show(childFragmentManager)
}
override fun shareSong(song: Song) {
song.share(context!!)
}
override fun presentRingtonePermissionDialog() {
RingtoneManager.getDialog(context!!).show()
}
override fun showRingtoneSetMessage() {
Toast.makeText(context, R.string.ringtone_set_new, Toast.LENGTH_SHORT).show()
}
// BaseFragment Implementation
public override fun screenName(): String {
return "AlbumDetailFragment"
}
companion object {
private const val ARG_TRANSITION_NAME = "transition_name"
private const val ARG_ALBUM = "album"
fun newInstance(album: Album, transitionName: String?): AlbumDetailFragment {
val args = Bundle()
val fragment = AlbumDetailFragment()
args.putSerializable(ARG_ALBUM, album)
args.putString(ARG_TRANSITION_NAME, transitionName)
fragment.arguments = args
return fragment
}
}
}
| gpl-3.0 | 42c12ed792d48774e2000d1a18149a30 | 39.094812 | 175 | 0.700263 | 4.912977 | false | false | false | false |
gumil/basamto | app/src/main/kotlin/io/github/gumil/basamto/widget/html/HtmlParser.kt | 1 | 10450 | /*
* The MIT License (MIT)
*
* Copyright 2018 Miguel Panelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.gumil.basamto.widget.html
import android.os.Build
import android.text.Html
import org.apache.commons.text.StringEscapeUtils
import java.util.*
import java.util.regex.Pattern
/**
* Utility methods to transform html received from Reddit into a more parsable
* format.
*
* The output will unescape all html, except for table tags and some special delimiter
* token such as for code blocks.
*/
private val SPOILER_PATTERN = Pattern.compile("<a[^>]*title=\"([^\"]*)\"[^>]*>([^<]*)</a>")
private val TABLE_START_TAG = "<table>"
private val HR_TAG = "<hr/>"
private val TABLE_END_TAG = "</table>"
/**
* Parses html and returns a list corresponding to blocks of text to be
* formatted.
*
* Each block is one of:
* - Vanilla text
* - Code block
* - Table
*
* Note that this method will unescape html entities, so this is best called
* with the raw html received from reddit.
*
* @param html html to be formatted. Can be raw from the api
* @return list of text blocks
*/
fun String.getBlocks(): List<String> {
var html = this
html = StringEscapeUtils.unescapeHtml4(html)
.replace("<p>", "<div>")
.replace("</p>", "</div>")
.replace("<li>\\s*<div>", "<li>")
.replace("</div>\\s*</li>", "</li>")
.replace("<li><div>", "<li>")
.replace("</div></li>", "</li>")
.replace("<del>", "[[d[")
.replace("<sup>", "<sup><small>")
.replace("</sup>", "</small></sup>")
.replace("</del>", "]d]]")
if (html.contains("\n")) {
html = html.substring(0, html.lastIndexOf("\n"))
}
if (html.contains("<!-- SC_ON -->")) {
html = html.substring(15, html.lastIndexOf("<!-- SC_ON -->"))
}
html = parseSpoilerTags(html)
if (html.contains("<ol") || html.contains("<ul")) {
html = parseLists(html)
}
var codeBlockSeperated = parseCodeTags(html)
if (html.contains(HR_TAG)) {
codeBlockSeperated = parseHR(codeBlockSeperated)
}
return if (html.contains("<table")) {
parseTableTags(codeBlockSeperated)
} else {
codeBlockSeperated
}.toMutableList().apply {
remove("<div class=\"md\">")
}
}
private fun parseLists(html: String): String {
var html = html
val firstIndex: Int
var isNumbered: Boolean
val firstOl = html.indexOf("<ol")
val firstUl = html.indexOf("<ul")
if (firstUl != -1 && firstOl > firstUl || firstOl == -1) {
firstIndex = firstUl
isNumbered = false
} else {
firstIndex = firstOl
isNumbered = true
}
val listNumbers = ArrayList<Int>()
var indent = -1
var i = firstIndex
while (i < html.length - 4 && i != -1) {
if (html.substring(i, i + 3) == "<ol" || html.substring(i, i + 3) == "<ul") {
if (html.substring(i, i + 3) == "<ol") {
isNumbered = true
indent++
listNumbers.add(indent, 1)
} else {
isNumbered = false
}
i = html.indexOf("<li", i)
} else if (html.substring(i, i + 3) == "<li") {
val tagEnd = html.indexOf(">", i)
val itemClose = html.indexOf("</li", tagEnd)
val ulClose = html.indexOf("<ul", tagEnd)
val olClose = html.indexOf("<ol", tagEnd)
val closeTag: Int
// Find what is closest: </li>, <ul>, or <ol>
if ((ulClose == -1 && itemClose != -1 || itemClose != -1 && ulClose != -1 && itemClose < ulClose) && (olClose == -1 && itemClose != -1 || itemClose != -1 && olClose != -1 && itemClose < olClose)) {
closeTag = itemClose
} else if ((ulClose == -1 && olClose != -1 || olClose != -1 && ulClose != -1 && olClose < ulClose) && (olClose == -1 && itemClose != -1 || olClose != -1 && itemClose != -1 && olClose < itemClose)) {
closeTag = olClose
} else {
closeTag = ulClose
}
val text = html.substring(tagEnd + 1, closeTag)
var indentSpacing = ""
for (j in 0 until indent) {
indentSpacing += " "
}
if (isNumbered) {
html = (html.substring(0, tagEnd + 1)
+ indentSpacing +
listNumbers[indent] + ". " +
text + "<br/>" +
html.substring(closeTag))
listNumbers[indent] = listNumbers[indent] + 1
i = closeTag + 3
} else {
html = html.substring(0, tagEnd + 1) + indentSpacing + "• " + text + "<br/>" + html.substring(closeTag)
i = closeTag + 2
}
} else {
i = html.indexOf("<", i + 1)
if (i != -1 && html.substring(i, i + 4) == "</ol") {
indent--
if (indent == -1) {
isNumbered = false
}
}
}
}
html = html.replace("<ol>", "").replace("<ul>", "").replace("<li>", "").replace("</li>", "").replace("</ol>", "").replace("</ul>", "") //Remove the tags, which actually work in Android 7.0 on
return html
}
@Suppress("deprecation")
internal fun String.fromHtml() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this)
}
private fun parseHR(blocks: List<String>): List<String> {
val newBlocks = ArrayList<String>()
for (block in blocks) {
if (block.contains(HR_TAG)) {
for (s in block.split(HR_TAG.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
newBlocks.add(s)
newBlocks.add(HR_TAG)
}
newBlocks.removeAt(newBlocks.size - 1)
} else {
newBlocks.add(block)
}
}
return newBlocks
}
/**
* For code within `<pre>` tags, line breaks are converted to
* `<br />` tags, and spaces to &nbsp;. This allows for Html.fromHtml
* to preserve indents of these blocks.
*
*
* In addition, `[[<[` and `]>]]` are inserted to denote the
* beginning and end of code segments, for styling later.
*
* @param html the unparsed HTML
* @return the code parsed HTML with additional markers, split but code blocks
*/
private fun parseCodeTags(html: String): List<String> {
val startTag = "<pre><code>"
val endTag = "</code></pre>"
val startSeperated = html.split(startTag.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val preSeperated = ArrayList<String>()
var text: String
var code: String
var split: Array<String>
preSeperated.add(startSeperated[0].replace("<code>", "<code>[[<[").replace("</code>", "]>]]</code>"))
for (i in 1 until startSeperated.size) {
text = startSeperated[i]
split = text.split(endTag.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
code = split[0]
code = code.replace("\n", "<br/>")
code = code.replace(" ", " ")
preSeperated.add("$startTag[[<[$code]>]]$endTag")
if (split.size > 1) {
preSeperated.add(split[1].replace("<code>", "<code>[[<[").replace("</code>", "]>]]</code>"))
}
}
return preSeperated
}
/**
* Move the spoil text inside of the "title" attribute to inside the link
* tag. Then surround the spoil text with `[[s[` and `]s]]`.
*
*
* If there is no text inside of the link tag, insert "spoil".
*
* @param html
* @return
*/
private fun parseSpoilerTags(html: String): String {
var html = html
var spoilerText: String
var tag: String
var spoilerTeaser: String
val matcher = SPOILER_PATTERN.matcher(html)
while (matcher.find()) {
tag = matcher.group(0)
spoilerText = matcher.group(1)
spoilerTeaser = matcher.group(2)
// Remove the last </a> tag, but keep the < for parsing.
if (!tag.contains("<a href=\"http")) {
html = html.replace(tag, tag.substring(0, tag.length - 4) + (if (spoilerTeaser.isEmpty()) "spoiler" else "") + "< [[s[ " + spoilerText + "]s]]</a>")
}
}
return html
}
/**
* Parse a given list of html strings, splitting by table blocks.
*
* All table tags are html escaped.
*
* @param blocks list of html with or individual table blocks
* @return list of html with tables split into it's entry
*/
private fun parseTableTags(blocks: List<String>): List<String> {
val newBlocks = ArrayList<String>()
for (block in blocks) {
if (block.contains(TABLE_START_TAG)) {
val startSeperated = block.split(TABLE_START_TAG.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
newBlocks.add(startSeperated[0].trim { it <= ' ' })
for (i in 1 until startSeperated.size) {
val split = startSeperated[i].split(TABLE_END_TAG.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
newBlocks.add("<table>" + split[0] + "</table>")
if (split.size > 1) {
newBlocks.add(split[1])
}
}
} else {
newBlocks.add(block)
}
}
return newBlocks
}
| mit | 99fb89a993c6226fc22663248025de90 | 33.710963 | 210 | 0.568913 | 3.84825 | false | false | false | false |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/alert/handler/AlertHandler.kt | 1 | 11847 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.alert.handler
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.location.Location
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Vibrator
import android.util.Log
import org.blitzortung.android.alert.AlertParameters
import org.blitzortung.android.alert.AlertResult
import org.blitzortung.android.alert.data.AlertSignal
import org.blitzortung.android.alert.event.AlertCancelEvent
import org.blitzortung.android.alert.event.AlertEvent
import org.blitzortung.android.alert.event.AlertResultEvent
import org.blitzortung.android.app.BOApplication
import org.blitzortung.android.app.Main
import org.blitzortung.android.app.R
import org.blitzortung.android.app.controller.NotificationHandler
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.get
import org.blitzortung.android.data.beans.Strike
import org.blitzortung.android.data.provider.result.ClearDataEvent
import org.blitzortung.android.data.provider.result.ResultEvent
import org.blitzortung.android.location.LocationEvent
import org.blitzortung.android.location.LocationHandler
import org.blitzortung.android.protocol.ConsumerContainer
import org.blitzortung.android.protocol.Event
import org.blitzortung.android.util.MeasurementSystem
import org.blitzortung.android.util.isAtLeast
class AlertHandler(
private val locationHandler: LocationHandler,
private val preferences: SharedPreferences,
private val context: Context,
private val vibrator: Vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator,
private val notificationHandler: NotificationHandler = NotificationHandler(context),
private val alertDataHandler: AlertDataHandler = AlertDataHandler()
) : OnSharedPreferenceChangeListener {
var alertParameters: AlertParameters
var alertEvent: AlertEvent = ALERT_CANCEL_EVENT
private set
val alertConsumerContainer: ConsumerContainer<AlertEvent> = object : ConsumerContainer<AlertEvent>() {
override fun addedFirstConsumer() {
Log.d(Main.LOG_TAG, "added first alert consumer")
refresh()
}
override fun removedLastConsumer() {
Log.d(Main.LOG_TAG, "removed last alert consumer")
refresh()
}
}
private val dataHandler = BOApplication.dataHandler
private var lastStrikes: Collection<Strike>? = null
private var alertSignal: AlertSignal = AlertSignal()
var currentLocation: Location? = null
private set
var isAlertEnabled: Boolean = false
private set
private var notificationDistanceLimit: Float = 0.0f
private var notificationLastTimestamp: Long = 0
private var signalingDistanceLimit: Float = 0.0f
private var signalingThresholdTime: Long = 0
private var signalingLastTimestamp: Long = 0
val locationEventConsumer: (LocationEvent) -> Unit = { event ->
Log.v(Main.LOG_TAG, "AlertHandler received location " + currentLocation + " vs " + event.location)
currentLocation = event.location
checkStrikes(lastStrikes)
}
val dataEventConsumer: (Event) -> Unit = { event ->
if (event is ResultEvent) {
if (!event.failed && event.containsRealtimeData()) {
checkStrikes(if (event.incrementalData) event.totalStrikes else event.strikes)
} else {
broadcastResult(null)
}
} else if (event is ClearDataEvent) {
broadcastResult(null)
}
}
init {
val rangeSteps = arrayOf(10f, 25f, 50f, 100f, 250f, 500f)
val alarmInterval = 10 * 60 * 1000L
val sectorLabels = context.resources.getStringArray(R.array.direction_names)
alertParameters = AlertParameters(alarmInterval, rangeSteps, sectorLabels, MeasurementSystem.METRIC)
preferences.registerOnSharedPreferenceChangeListener(this)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_ENABLED)
onSharedPreferenceChanged(preferences, PreferenceKey.MEASUREMENT_UNIT)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_NOTIFICATION_DISTANCE_LIMIT)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_SIGNALING_DISTANCE_LIMIT)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_SIGNALING_THRESHOLD_TIME)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_VIBRATION_SIGNAL)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_SOUND_SIGNAL)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, keyString: String) {
onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString))
}
private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) {
when (key) {
PreferenceKey.ALERT_ENABLED -> isAlertEnabled = sharedPreferences.get(key, false)
PreferenceKey.MEASUREMENT_UNIT -> {
val measurementSystemName = sharedPreferences.get(key, MeasurementSystem.METRIC.toString())
alertParameters = alertParameters.copy(measurementSystem = MeasurementSystem.valueOf(measurementSystemName))
}
PreferenceKey.ALERT_NOTIFICATION_DISTANCE_LIMIT -> notificationDistanceLimit = sharedPreferences.get(key, "50").toFloat()
PreferenceKey.ALERT_SIGNALING_DISTANCE_LIMIT -> signalingDistanceLimit = sharedPreferences.get(key, "25").toFloat()
PreferenceKey.ALERT_SIGNALING_THRESHOLD_TIME -> signalingThresholdTime = sharedPreferences.get(key, "25").toLong() * 1000 * 60
PreferenceKey.ALERT_VIBRATION_SIGNAL -> alertSignal = alertSignal.copy(vibrationDuration = sharedPreferences.get(key, 3) * 10)
PreferenceKey.ALERT_SOUND_SIGNAL -> {
val signalUri = sharedPreferences.get(key, "")
alertSignal = alertSignal.copy(soundSignal = if (!signalUri.isEmpty()) Uri.parse(signalUri) else null)
}
}
}
private fun refresh() {
if (isAlertEnabled) {
locationHandler.requestUpdates(locationEventConsumer)
dataHandler.requestUpdates(dataEventConsumer)
} else {
locationHandler.removeUpdates(locationEventConsumer)
dataHandler.removeUpdates(dataEventConsumer)
currentLocation = null
broadcastResult(null)
}
}
fun checkStrikes(strikes: Collection<Strike>?) {
val alertResult = checkStrikes(strikes, currentLocation)
processResult(alertResult)
}
fun checkStrikes(strikes: Collection<Strike>?, location: Location?): AlertResult? {
lastStrikes = strikes
return if (isAlertEnabled && location != null && strikes != null) {
alertDataHandler.checkStrikes(strikes, location, alertParameters)
} else {
null
}
}
fun unsetAlertListener() {
refresh()
}
val maxDistance: Float
get() = alertParameters.rangeSteps.last()
private fun broadcastResult(alertResult: AlertResult?) {
alertEvent = if (alertResult != null) AlertResultEvent(alertResult) else ALERT_CANCEL_EVENT
broadcastEvent()
}
private fun broadcastEvent() {
Log.v(Main.LOG_TAG, "AlertHandler.broadcastResult() $alertEvent")
alertConsumerContainer.storeAndBroadcast(alertEvent)
}
private fun processResult(alertResult: AlertResult?) {
if (alertResult != null) {
handleAlert(alertResult)
} else {
Log.v(Main.LOG_TAG, "AlertHandler.processResult() no result")
notificationHandler.clearNotification()
broadcastResult(null)
}
}
private fun handleAlert(alertResult: AlertResult) {
if (alertResult.closestStrikeDistance <= signalingDistanceLimit) {
handleAlertSignal(alertResult)
}
if (alertResult.closestStrikeDistance <= notificationDistanceLimit) {
handleAlertNotification(alertResult)
} else {
notificationHandler.clearNotification()
}
Log.v(Main.LOG_TAG, "AlertHandler.processResult() broadcast result %s".format(alertResult))
broadcastResult(alertResult)
}
private fun handleAlertSignal(alertResult: AlertResult) {
val signalingLatestTimestamp = alertDataHandler.getLatestTimstampWithin(signalingDistanceLimit, alertResult)
if (signalingLatestTimestamp > signalingLastTimestamp + signalingThresholdTime) {
Log.d(Main.LOG_TAG, "AlertHandler.handleAlertSignal() signal ${signalingLatestTimestamp / 1000}")
vibrateIfEnabled()
playSoundIfEnabled()
signalingLastTimestamp = signalingLatestTimestamp
} else {
Log.d(Main.LOG_TAG, "AlertHandler.handleAlertSignal() skipped - ${(signalingLatestTimestamp - signalingLastTimestamp) / 1000}, threshold: ${signalingThresholdTime / 1000}")
}
}
private fun handleAlertNotification(alertResult: AlertResult) {
val notificationLatestTimestamp = alertDataHandler.getLatestTimstampWithin(notificationDistanceLimit, alertResult)
if (notificationLatestTimestamp > notificationLastTimestamp) {
Log.d(Main.LOG_TAG, "AlertHandler.handleAlertNotification() notification ${notificationLatestTimestamp / 1000}")
notificationHandler.sendNotification(context.resources.getString(R.string.activity) + ": " + alertDataHandler.getTextMessage(alertResult, notificationDistanceLimit))
notificationLastTimestamp = notificationLatestTimestamp
} else {
Log.d(Main.LOG_TAG, "AlertHandler.handleAlertNotification() skipped - ${notificationLatestTimestamp - notificationLastTimestamp}")
}
}
private fun vibrateIfEnabled() {
vibrator.vibrate(alertSignal.vibrationDuration.toLong())
}
private fun playSoundIfEnabled() {
alertSignal.soundSignal?.let { signal ->
RingtoneManager.getRingtone(context, signal)?.let { ringtone ->
if (!ringtone.isPlaying) {
if (isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
ringtone.audioAttributes = AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_NOTIFICATION).build()
} else {
ringtone.streamType = AudioManager.STREAM_NOTIFICATION
}
ringtone.play()
}
Log.v(Main.LOG_TAG, "playing " + ringtone.getTitle(context))
}
}
}
fun requestUpdates(alertEventConsumer: (AlertEvent) -> Unit) {
alertConsumerContainer.addConsumer(alertEventConsumer)
}
fun removeUpdates(alertEventConsumer: (AlertEvent) -> Unit) {
alertConsumerContainer.removeConsumer(alertEventConsumer)
}
companion object {
val ALERT_CANCEL_EVENT = AlertCancelEvent()
}
}
| apache-2.0 | 20acae41866a80f688040a1f4ddc6a35 | 39.430034 | 184 | 0.706905 | 4.921479 | false | false | false | false |
henrikfroehling/timekeeper | storage/src/main/kotlin/de/froehling/henrik/timekeeper/storage/local/LocalCustomersRepository.kt | 1 | 3080 | package de.froehling.henrik.timekeeper.storage.local
import de.froehling.henrik.timekeeper.domain.repository.ICustomersRepository
import de.froehling.henrik.timekeeper.models.Customer
import de.froehling.henrik.timekeeper.models.Project
import de.froehling.henrik.timekeeper.models.Task
import io.realm.Realm
import io.realm.RealmAsyncTask
import io.realm.Sort
import rx.Observable
class LocalCustomersRepository(private val realm: Realm) : ICustomersRepository {
override fun getCustomersFilteredByLastName(ascending: Boolean): Observable<List<Customer>> {
val customers = realm.where(Customer::class.java)
.findAllSortedAsync("lastName", if (ascending) Sort.ASCENDING else Sort.DESCENDING)
return customers.asObservable().filter { it.isLoaded }.map { it.toList() }
}
override fun getCustomersFilteredByFirstName(ascending: Boolean): Observable<List<Customer>> {
val customers = realm.where(Customer::class.java)
.findAllSortedAsync("firstName", if (ascending) Sort.ASCENDING else Sort.DESCENDING)
return customers.asObservable().filter { it.isLoaded }.map { it.toList() }
}
override fun getCustomersFilteredByCompany(ascending: Boolean): Observable<List<Customer>> {
val customers = realm.where(Customer::class.java)
.findAllSortedAsync("company", if (ascending) Sort.ASCENDING else Sort.DESCENDING)
return customers.asObservable().filter { it.isLoaded }.map { it.toList() }
}
override fun getCustomerDetails(customerID: String): Observable<Customer> {
return realm.where(Customer::class.java).equalTo("uuid", customerID)
.findFirstAsync().asObservable()
}
override fun getCustomerProjects(customerID: String): Observable<List<Project>> {
val projects = realm.where(Customer::class.java).equalTo("uuid", customerID)
.findFirstAsync().projects.orEmpty()
return Observable.just(projects).map { it.toList() }
}
override fun getCustomerTasks(customerID: String): Observable<List<Task>> {
val tasks = realm.where(Customer::class.java).equalTo("uuid", customerID)
.findFirstAsync().tasks.orEmpty()
return Observable.just(tasks).map { it.toList() }
}
override fun getAll(): Observable<List<Customer>> = getCustomersFilteredByLastName(true)
override fun create(obj: Customer): Observable<RealmAsyncTask> {
return Observable.just(
realm.executeTransaction({ realm ->
realm.copyToRealmOrUpdate(obj)
}, null)
)
}
override fun update(obj: Customer): Observable<RealmAsyncTask> {
return create(obj)
}
override fun delete(uuid: String): Observable<RealmAsyncTask> {
return Observable.just(
realm.executeTransaction({ realm ->
val customer = realm.where(Customer::class.java).equalTo("uuid", uuid).findFirst()
customer.removeFromRealm()
}, null)
)
}
}
| gpl-3.0 | aea49cef5b0caf052ca72cd78c76fe41 | 39.526316 | 102 | 0.680195 | 4.483261 | false | false | false | false |
pavelaizen/SoundZones | app/src/main/java/com/gm/soundzones/activity/PreAssessmentActivity.kt | 1 | 7283 | package com.gm.soundzones.activity
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.gm.soundzones.*
import com.gm.soundzones.excel.DataProvider
import com.gm.soundzones.fragment.InformationFragment
import com.gm.soundzones.fragment.preassessment.SoundSelectFragment
import com.gm.soundzones.listener.OnClickNextListener
import com.gm.soundzones.manager.UserDataManager
import com.gm.soundzones.model.SoundRun
import com.gm.soundzones.model.SoundSet
import com.gm.soundzones.model.SoundTrack
import com.gm.soundzones.model.User
import kotlinx.android.synthetic.main.activity_toolbar_container.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn
class PreAssessmentActivity : BaseActivity(), OnClickNextListener {
private var continuation: Continuation<Boolean>? = null
private var stepIndex = 0
private val lastStep = 12
private var prevSelectedVolume = 0
private val soundCheckUser: User by lazy {
val mi = SoundSet("MI_Pre_0", SoundTrack("40-MI"), SoundTrack("39-MI"))
val miNoise = SoundSet("MI_Pre_40", SoundTrack("40-MI"), SoundTrack("39-MI"))
val ml = SoundSet("ML_Pre_0", SoundTrack("40-ML"), SoundTrack("39-ML"))
val mlNoise = SoundSet("ML_Pre_40", SoundTrack("40-ML"), SoundTrack("39-ML"))
val tr = SoundSet("TR_Pre_0", SoundTrack("40-TR"), SoundTrack("39-TR"))
val trNoise = SoundSet("TR_Pre_40", SoundTrack("40-TR"), SoundTrack("39-TR"))
val run1 = SoundRun("1", arrayOf(mi))
val run2 = SoundRun("2", arrayOf(miNoise))
val run3 = SoundRun("3", arrayOf(ml))
val run4 = SoundRun("4", arrayOf(mlNoise))
val run5 = SoundRun("5", arrayOf(tr))
val run6 = SoundRun("6", arrayOf(trNoise))
User(0, arrayOf(run1, run2, run3, run4, run5, run6))
}
fun getTrack(): SoundTrack {
val track = stepIndex % 2
val soundRun = soundCheckUser.soundRuns[stepIndex / 2]
val (_, primaryTrack, secondaryTrack) = soundRun.soundSets[0]
return if (track == 0) {
primaryTrack
} else {
secondaryTrack;
}
}
private fun saveAndPlayNext(args: Bundle) {
val volumeLevel = args.getInt(EXTRA_VOLUME_LEVEL)
val currentSoundSet = getCurrentSoundSet
val dirName = currentSoundSet.secondaryTrack.dirName
if (stepIndex % 2 == 0) {
prevSelectedVolume = volumeLevel
} else {
val savedVolume = Math.round((prevSelectedVolume + volumeLevel) / 2.0).toInt()
log("PreAssessment volume $savedVolume for $dirName userID ${UserDataManager.userID} average between $prevSelectedVolume and $volumeLevel and noise = " + currentSoundSet.hasNoise)
DataProvider.setDefaultVolume(dirName, currentSoundSet.hasNoise, savedVolume)
prevSelectedVolume = 0
}
if (stepIndex < lastStep) {
stepIndex++
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_toolbar_container)
setSupportActionBar(toolbar)
toolbar.visibility = View.VISIBLE
if (savedInstanceState == null) {
val welcomeFragment = InformationFragment.newInstance(
getString(R.string.welcome_text_title),
desc3 = getString(R.string.press_next_when_ready),
desc4 = UserDataManager.userID.toString(),
btnVisibility = View.INVISIBLE)
loadFragment { replace(R.id.container, welcomeFragment) }
launch(UI) {
do {
val isGranted = suspendCoroutineOrReturn<Boolean> {
continuation = it
requestWritePermission()
COROUTINE_SUSPENDED
}
} while (!isGranted)
hasWritePermission = true
welcomeFragment.update(Bundle().also {
it.putInt(InformationFragment.EXTRA_BTN_VISIBILITY, View.VISIBLE)
})
}
}
}
override fun onResumeFragments() {
super.onResumeFragments()
val frag = supportFragmentManager.findFragmentById(R.id.container)
if (frag is InformationFragment) {
frag.update(Bundle().apply {
putString(InformationFragment.EXTRA_DESC4, UserDataManager.userID.toString())
})
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
toolbar.inflateMenu(R.menu.main_menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?) = when (item?.itemId) {
R.id.settings_menu -> {
startActivity(Intent(this, SettingsActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
val getCurrentSoundSet: SoundSet
get() {
val runNumber = stepIndex / 2
return soundCheckUser.soundRuns[runNumber].soundSets[0]
}
override fun onClickNext(fragment: Fragment, args: Bundle) {
if (fragment is InformationFragment) {
supportActionBar?.hide()
}
if (fragment is SoundSelectFragment) {
saveAndPlayNext(args)
}
if (stepIndex < lastStep) {
val soundSelectFragment = SoundSelectFragment()
loadFragment { replace(R.id.container, soundSelectFragment) }
} else {
startActivity(Intent(this, PreparationActivity::class.java))
finish()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_WRITE_PERMISSION -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
continuation?.resume(true)
} else {
continuation?.resume(false)
}
continuation = null
}
}
}
private fun requestWritePermission(): Boolean {
val writePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && writePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_PERMISSION)
} else {
continuation?.resume(true)
continuation = null
}
return false;
}
companion object {
val REQUEST_WRITE_PERMISSION = 1
}
}
| apache-2.0 | fed41bf51dd54d890ac16b27bafbcd31 | 38.797814 | 191 | 0.642318 | 4.609494 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/MyTab.kt | 1 | 3886 | /*
ParaTask Copyright (C) 2017 Nick Robinson>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.gui
import javafx.beans.property.StringProperty
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.TabPane
import javafx.scene.input.MouseEvent
import javafx.scene.layout.BorderPane
/**
* A part of MyTabPane.
* Unlike the standard JavaFX Tab, MyTab is a Node
*/
open class MyTab(text: String = "", content: Node = Label("Empty"), graphic: Node? = null, canClose: Boolean = true) : BorderPane() {
open var tabPane: MyTabPane<*>? = null
var label = Label(text)
var text: String
get() = textProperty().get()
set(v) {
textProperty().set(v)
}
var graphic: Node?
set(v) {
label.graphic = v
}
get() = label.graphic
val closeButton = Button("✕")
/**
* Can this tab be close by the user?
*/
var canClose: Boolean = canClose
set(v) {
field = v
if (isSelected && v && tabPane?.tabClosingPolicy != TabPane.TabClosingPolicy.UNAVAILABLE) {
right = closeButton
} else {
right = null
}
}
var content: Node = content
set(v) {
tabPane?.let {
it.contents.children.remove(field)
it.contents.children.add(v)
if (isSelected) {
// Ensure that the new content is displayed
it.untypedSelectedTab = this
}
}
field = v
}
init {
this.graphic = graphic
styleClass.add("tab")
label.styleClass.add("tab-label")
closeButton.styleClass.add("tab-close-button")
graphic?.let { children.add(it) }
center = label
addEventHandler(MouseEvent.MOUSE_PRESSED) { tabPane?.let { it.untypedSelectedTab = this } }
closeButton.addEventHandler(MouseEvent.MOUSE_CLICKED) { close() }
closeButton.isVisible = canClose
addEventHandler(MouseEvent.MOUSE_DRAGGED) { tabPane?.onDraggedTab(it, this) }
addEventHandler(MouseEvent.MOUSE_RELEASED) { onReleased(it) }
}
fun textProperty() : StringProperty = label.textProperty()
open fun close() {
tabPane?.remove(this)
}
var isSelected: Boolean
get() {
tabPane?.let {
return it.selectedTab === this
}
return false
}
set(v) {
tabPane?.let {
@Suppress("UNCHECKED_CAST")
(it as MyTabPane<MyTab>).selectedTab = this
}
}
override fun computeMinWidth(height: Double): Double {
return computePrefWidth(height)
}
override fun computeMinHeight(width: Double): Double {
return computePrefHeight(width)
}
open fun removed() {}
fun onReleased(event: MouseEvent) {
val scene = this.scene
val sceneX = event.sceneX
val sceneY = event.sceneY
if (sceneX < 0 || sceneY < 0 || sceneX > scene.width || sceneY > scene.height) {
tearOffTab(event)
}
}
open fun tearOffTab(event: MouseEvent) {}
}
| gpl-3.0 | 8a4aeb5dd1e02247103a7f8a2c315070 | 27.985075 | 133 | 0.603759 | 4.329989 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/HasPlatformTypeSpec.kt | 1 | 2662 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object HasPlatformTypeSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { HasPlatformType(Config.empty) }
describe("Deprecation detection") {
it("reports when public function returns expression of platform type") {
val code = """
class Person {
fun apiCall() = System.getProperty("propertyName")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when private") {
val code = """
class Person {
private fun apiCall() = System.getProperty("propertyName")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when public function returns expression of platform type and type explicitly declared") {
val code = """
class Person {
fun apiCall(): String = System.getProperty("propertyName")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("reports when property initiated with platform type") {
val code = """
class Person {
val name = System.getProperty("name")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when private") {
val code = """
class Person {
private val name = System.getProperty("name")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when property initiated with platform type and type explicitly declared") {
val code = """
class Person {
val name: String = System.getProperty("name")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
})
| apache-2.0 | c34c7a09f8127799fb10880f5918fef3 | 35.465753 | 117 | 0.577761 | 5.592437 | false | false | false | false |
chibatching/Kotpref | livedata-support/src/main/kotlin/com/chibatching/kotpref/livedata/KotprefLiveDataExtensions.kt | 1 | 1290 | package com.chibatching.kotpref.livedata
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import com.chibatching.kotpref.KotprefModel
import kotlin.reflect.KProperty0
public fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> {
return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
private val key: String = [email protected](property)
?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref")
override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String?) {
// propertyName will be null when preferences are cleared on Android R
val isCleared = propertyName == null
if (isCleared || propertyName == key) {
postValue(property.get())
}
}
override fun onActive() {
this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this)
if (value != property.get()) {
value = property.get()
}
}
override fun onInactive() {
this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this)
}
}
}
| apache-2.0 | 3d7ec11a2f59d4fef5db10e1063f8f9e | 39.3125 | 134 | 0.675969 | 5.536481 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/config/MixinConfigFileType.kt | 1 | 1319 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.config
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.json.JsonLanguage
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile
import com.intellij.openapi.vfs.VirtualFile
object MixinConfigFileType : LanguageFileType(JsonLanguage.INSTANCE), FileTypeIdentifiableByVirtualFile {
private val filenameRegex = "(^|\\.)mixins?(\\.[^.]+)*\\.json\$".toRegex()
// Dynamic file type detection is sadly needed as we're overriding the built-in json file type.
// Simply using an extension pattern is not sufficient as there is no way to bump the version to tell
// the cache that the pattern has changed, as it now has, without changing the file type name.
// See https://www.plugin-dev.com/intellij/custom-language/file-type-detection/#guidelines
override fun isMyFileType(file: VirtualFile) = file.name.contains(filenameRegex)
override fun getName() = "Mixin Configuration"
override fun getDescription() = "Mixin Configuration"
override fun getDefaultExtension() = ""
override fun getIcon() = PlatformAssets.MIXIN_ICON
}
| mit | 4573ef764f9b4f979f5dc3e87c1e21b2 | 38.969697 | 105 | 0.75815 | 4.32459 | false | true | false | false |
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/ui/nav/BottomNavDrawerFragment.kt | 1 | 14520 | /*
* Copyright 2019 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.materialstudies.reply.ui.nav
import android.animation.ValueAnimator
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.observe
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HALF_EXPANDED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN
import com.google.android.material.bottomsheet.BottomSheetBehavior.from
import com.google.android.material.shape.MaterialShapeDrawable
import com.materialstudies.reply.R
import com.materialstudies.reply.data.Account
import com.materialstudies.reply.data.AccountStore
import com.materialstudies.reply.databinding.FragmentBottomNavDrawerBinding
import com.materialstudies.reply.util.lerp
import com.materialstudies.reply.util.themeColor
import com.materialstudies.reply.util.themeInterpolator
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.math.abs
/**
* A [Fragment] which acts as a bottom navigation drawer.
*/
class BottomNavDrawerFragment :
Fragment(),
NavigationAdapter.NavigationAdapterListener,
AccountAdapter.AccountAdapterListener {
/**
* Enumeration of states in which the account picker can be in.
*/
enum class SandwichState {
/**
* The account picker is not visible. The navigation drawer is in its default state.
*/
CLOSED,
/**
* the account picker is visible and open.
*/
OPEN,
/**
* The account picker sandwiching animation is running. The account picker is neither open
* nor closed.
*/
SETTLING
}
private lateinit var binding: FragmentBottomNavDrawerBinding
private val behavior: BottomSheetBehavior<FrameLayout> by lazy(NONE) {
from(binding.backgroundContainer)
}
private val bottomSheetCallback = BottomNavigationDrawerCallback()
private val sandwichSlideActions = mutableListOf<OnSandwichSlideAction>()
private val navigationListeners: MutableList<NavigationAdapter.NavigationAdapterListener> =
mutableListOf()
private val backgroundShapeDrawable: MaterialShapeDrawable by lazy(NONE) {
val backgroundContext = binding.backgroundContainer.context
MaterialShapeDrawable(
backgroundContext,
null,
R.attr.bottomSheetStyle,
0
).apply {
fillColor = ColorStateList.valueOf(
backgroundContext.themeColor(R.attr.colorPrimarySurfaceVariant)
)
elevation = resources.getDimension(R.dimen.plane_08)
initializeElevationOverlay(requireContext())
}
}
private val foregroundShapeDrawable: MaterialShapeDrawable by lazy(NONE) {
val foregroundContext = binding.foregroundContainer.context
MaterialShapeDrawable(
foregroundContext,
null,
R.attr.bottomSheetStyle,
0
).apply {
fillColor = ColorStateList.valueOf(
foregroundContext.themeColor(R.attr.colorPrimarySurface)
)
elevation = resources.getDimension(R.dimen.plane_16)
shadowCompatibilityMode = MaterialShapeDrawable.SHADOW_COMPAT_MODE_NEVER
initializeElevationOverlay(requireContext())
shapeAppearanceModel = shapeAppearanceModel.toBuilder()
.setTopEdge(
SemiCircleEdgeCutoutTreatment(
resources.getDimension(R.dimen.grid_1),
resources.getDimension(R.dimen.grid_3),
0F,
resources.getDimension(R.dimen.navigation_drawer_profile_image_size_padded)
)
)
.build()
}
}
private var sandwichState: SandwichState = SandwichState.CLOSED
private var sandwichAnim: ValueAnimator? = null
private val sandwichInterp by lazy(NONE) {
requireContext().themeInterpolator(R.attr.motionInterpolatorPersistent)
}
// Progress value which drives the animation of the sandwiching account picker. Responsible
// for both calling progress updates and state updates.
private var sandwichProgress: Float = 0F
set(value) {
if (field != value) {
onSandwichProgressChanged(value)
val newState = when(value) {
0F -> SandwichState.CLOSED
1F -> SandwichState.OPEN
else -> SandwichState.SETTLING
}
if (sandwichState != newState) onSandwichStateChanged(newState)
sandwichState = newState
field = value
}
}
private val closeDrawerOnBackPressed = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
close()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(this, closeDrawerOnBackPressed)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentBottomNavDrawerBinding.inflate(inflater, container, false)
binding.foregroundContainer.setOnApplyWindowInsetsListener { view, windowInsets ->
// Record the window's top inset so it can be applied when the bottom sheet is slide up
// to meet the top edge of the screen.
view.setTag(
R.id.tag_system_window_inset_top,
windowInsets.systemWindowInsetTop
)
windowInsets
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.run {
backgroundContainer.background = backgroundShapeDrawable
foregroundContainer.background = foregroundShapeDrawable
scrimView.setOnClickListener { close() }
bottomSheetCallback.apply {
// Scrim view transforms
addOnSlideAction(AlphaSlideAction(scrimView))
addOnStateChangedAction(VisibilityStateAction(scrimView))
// Foreground transforms
addOnSlideAction(ForegroundSheetTransformSlideAction(
binding.foregroundContainer,
foregroundShapeDrawable,
binding.profileImageView
))
// Recycler transforms
addOnStateChangedAction(ScrollToTopStateAction(navRecyclerView))
// Close the sandwiching account picker if open
addOnStateChangedAction(object : OnStateChangedAction {
override fun onStateChanged(sheet: View, newState: Int) {
sandwichAnim?.cancel()
sandwichProgress = 0F
}
})
// If the drawer is open, pressing the system back button should close the drawer.
addOnStateChangedAction(object : OnStateChangedAction {
override fun onStateChanged(sheet: View, newState: Int) {
closeDrawerOnBackPressed.isEnabled = newState != STATE_HIDDEN
}
})
}
profileImageView.setOnClickListener { toggleSandwich() }
behavior.addBottomSheetCallback(bottomSheetCallback)
behavior.state = STATE_HIDDEN
val adapter = NavigationAdapter(this@BottomNavDrawerFragment)
navRecyclerView.adapter = adapter
NavigationModel.navigationList.observe(viewLifecycleOwner) {
adapter.submitList(it)
}
NavigationModel.setNavigationMenuItemChecked(0)
val accountAdapter = AccountAdapter(this@BottomNavDrawerFragment)
accountRecyclerView.adapter = accountAdapter
AccountStore.userAccounts.observe(viewLifecycleOwner) {
accountAdapter.submitList(it)
currentUserAccount = it.first { acc -> acc.isCurrentAccount }
}
}
}
fun toggle() {
when {
sandwichState == SandwichState.OPEN -> toggleSandwich()
behavior.state == STATE_HIDDEN -> open()
behavior.state == STATE_HIDDEN
|| behavior.state == STATE_HALF_EXPANDED
|| behavior.state == STATE_EXPANDED
|| behavior.state == STATE_COLLAPSED -> close()
}
}
fun open() {
behavior.state = STATE_HALF_EXPANDED
}
fun close() {
behavior.state = STATE_HIDDEN
}
fun addOnSlideAction(action: OnSlideAction) {
bottomSheetCallback.addOnSlideAction(action)
}
fun addOnStateChangedAction(action: OnStateChangedAction) {
bottomSheetCallback.addOnStateChangedAction(action)
}
fun addNavigationListener(listener: NavigationAdapter.NavigationAdapterListener) {
navigationListeners.add(listener)
}
/**
* Add actions to be run when the slide offset (animation progress) or the sandwiching account
* picker has changed.
*/
fun addOnSandwichSlideAction(action: OnSandwichSlideAction) {
sandwichSlideActions.add(action)
}
override fun onNavMenuItemClicked(item: NavigationModelItem.NavMenuItem) {
NavigationModel.setNavigationMenuItemChecked(item.id)
close()
navigationListeners.forEach { it.onNavMenuItemClicked(item) }
}
override fun onNavEmailFolderClicked(folder: NavigationModelItem.NavEmailFolder) {
navigationListeners.forEach { it.onNavEmailFolderClicked(folder) }
}
override fun onAccountClicked(account: Account) {
AccountStore.setCurrentUserAccount(account.id)
toggleSandwich()
}
/**
* Open or close the account picker "sandwich".
*/
private fun toggleSandwich() {
val initialProgress = sandwichProgress
val newProgress = when (sandwichState) {
SandwichState.CLOSED -> {
// Store the original top location of the background container so we can animate
// the delta between its original top position and the top position needed to just
// show the account picker RecyclerView, and back again.
binding.backgroundContainer.setTag(
R.id.tag_view_top_snapshot,
binding.backgroundContainer.top
)
1F
}
SandwichState.OPEN -> 0F
SandwichState.SETTLING -> return
}
sandwichAnim?.cancel()
sandwichAnim = ValueAnimator.ofFloat(initialProgress, newProgress).apply {
addUpdateListener { sandwichProgress = animatedValue as Float }
interpolator = sandwichInterp
duration = (abs(newProgress - initialProgress) *
resources.getInteger(R.integer.reply_motion_duration_medium)).toLong()
}
sandwichAnim?.start()
}
/**
* Called each time the value of [sandwichProgress] changes. [progress] is the state of the
* sandwiching, with 0F being the default [SandwichState.CLOSED] state and 1F being the
* [SandwichState.OPEN] state.
*/
private fun onSandwichProgressChanged(progress: Float) {
binding.run {
val navProgress = lerp(0F, 1F, 0F, 0.5F, progress)
val accProgress = lerp(0F, 1F, 0.5F, 1F, progress)
foregroundContainer.translationY =
(binding.foregroundContainer.height * 0.15F) * navProgress
profileImageView.scaleX = 1F - navProgress
profileImageView.scaleY = 1F - navProgress
profileImageView.alpha = 1F - navProgress
foregroundContainer.alpha = 1F - navProgress
accountRecyclerView.alpha = accProgress
foregroundShapeDrawable.interpolation = 1F - navProgress
// Animate the translationY of the backgroundContainer so just the account picker is
// peeked above the BottomAppBar.
backgroundContainer.translationY = progress *
((scrimView.bottom - accountRecyclerView.height
- resources.getDimension(R.dimen.bottom_app_bar_height)) -
(backgroundContainer.getTag(R.id.tag_view_top_snapshot) as Int))
}
// Call any actions which have been registered to run on progress changes.
sandwichSlideActions.forEach { it.onSlide(progress) }
}
/**
* Called when the [SandwichState] of the sandwiching account picker has changed.
*/
private fun onSandwichStateChanged(state: SandwichState) {
// Change visibility/clickability of views which obstruct user interaction with
// the account list.
when (state) {
SandwichState.OPEN -> {
binding.run {
foregroundContainer.visibility = View.GONE
profileImageView.isClickable = false
}
}
else -> {
binding.run {
foregroundContainer.visibility = View.VISIBLE
profileImageView.isClickable = true
}
}
}
}
} | apache-2.0 | 3a7270d144c292782d15cab1d1491df8 | 37.619681 | 99 | 0.64449 | 5.322581 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/widget/DetailItemView.kt | 2 | 2293 | package com.bennyhuo.github.view.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.bennyhuo.github.R
import com.bennyhuo.github.utils.subscribeIgnoreError
import com.bennyhuo.kotlin.opd.delegateOf
import kotlinx.android.synthetic.main.detail_item.view.*
import org.jetbrains.anko.sdk15.listeners.onClick
import rx.Observable
import kotlin.reflect.KProperty
typealias CheckEvent = (Boolean) -> Observable<Boolean>
class ObjectPropertyDelegate<T, R>(val receiver: R, val getter: ((R) -> T)? = null, val setter: ((R, T) -> Unit)? = null, defaultValue: T? = null) {
private var value: T? = defaultValue
operator fun getValue(ref: Any, property: KProperty<*>): T {
return getter?.invoke(receiver) ?: value!!
}
operator fun setValue(ref: Any, property: KProperty<*>, value: T) {
setter?.invoke(receiver, value)
this.value = value
}
}
class DetailItemView
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: RelativeLayout(context, attrs, defStyleAttr) {
init {
View.inflate(context, R.layout.detail_item, this)
}
var title by delegateOf(titleView::getText, titleView::setText)
var content by delegateOf(contentView::getText, contentView::setText, "")
var icon by delegateOf(iconView::setImageResource, 0)
var operatorIcon by delegateOf(operatorIconView::setBackgroundResource, 0)
var isChecked by delegateOf(operatorIconView::isChecked, operatorIconView::setChecked)
var checkEvent: CheckEvent? = null
init {
attrs?.let {
val a = context.obtainStyledAttributes(it, R.styleable.DetailItemView)
title = a.getString(R.styleable.DetailItemView_item_title) ?: ""
content = a.getString(R.styleable.DetailItemView_item_content) ?: ""
icon = a.getResourceId(R.styleable.DetailItemView_item_icon, 0)
operatorIcon = a.getResourceId(R.styleable.DetailItemView_item_op_icon, 0)
a.recycle()
}
onClick {
checkEvent?.invoke(isChecked)
?.subscribeIgnoreError {
isChecked = it
}
}
}
} | apache-2.0 | 404405319977941cc6dc03b283e24ea1 | 32.246377 | 148 | 0.680768 | 4.207339 | false | false | false | false |
rmnn/compiler | src/main/kotlin/ru/dageev/compiler/parser/visitor/statement/LocalVariableDeclarationVisitor.kt | 1 | 1617 | package ru.dageev.compiler.parser.visitor.statement
import ru.dageev.compiler.domain.node.statement.VariableDeclaration
import ru.dageev.compiler.domain.scope.LocalVariable
import ru.dageev.compiler.domain.scope.Scope
import ru.dageev.compiler.domain.type.PrimitiveType
import ru.dageev.compiler.grammar.ElaginBaseVisitor
import ru.dageev.compiler.grammar.ElaginParser
import ru.dageev.compiler.parser.CompilationException
import ru.dageev.compiler.parser.provider.TypeProvider
import ru.dageev.compiler.parser.visitor.expression.ExpressionVisitor
/**
* Created by dageev
* on 15-May-16.
*/
class LocalVariableDeclarationVisitor(val scope: Scope, val typeProvider: TypeProvider, val expressionVisitor: ExpressionVisitor) : ElaginBaseVisitor<VariableDeclaration>() {
override fun visitLocalVariableDeclarationStatement(ctx: ElaginParser.LocalVariableDeclarationStatementContext): VariableDeclaration {
val name = ctx.identifier().text
val type = typeProvider.getType(ctx.type())
if (type == PrimitiveType.VOID && ctx.type() != null) {
throw CompilationException("Variable '$name' could not have VOID type")
}
val expression = ctx.expression().accept(expressionVisitor)
if (ctx.type() == null && expression.type == PrimitiveType.VOID) {
throw CompilationException("Variable '$name' could not have VOID type")
}
val variableType = if (ctx.type() == null) expression.type else type
scope.addLocalVariable(LocalVariable(name, variableType))
return VariableDeclaration(name, variableType, expression)
}
} | apache-2.0 | cde179adc9573c54feacb7d3f45b6c35 | 48.030303 | 174 | 0.756957 | 4.633238 | false | false | false | false |
werelord/nullpod | nullpodApp/src/main/kotlin/com/cyrix/nullpod/data/NullpodConfig.kt | 1 | 3278 | /**
* NullpodConfig
*
* Copyright 2017 Joel Braun
*
* This file is part of nullPod.
*
* nullPod is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nullPod 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 nullPod. If not, see <http://www.gnu.org/licenses/>.
*/
package com.cyrix.nullpod.data
import com.cyrix.util.CxLogger
import com.cyrix.util.warn
import org.json.JSONArray
import org.json.JSONObject
data class NullpodConfig(val playlist: MutableList<PodcastTrack> = mutableListOf(), var maxDownloadedTracks: Int = 5) {
private val log = CxLogger<NullpodConfig>()
// todo: observable pattern for immediate commits?
companion object {
const val PLAYLIST_ARRAY = "playlist"
const val MAX_DOWNLOAD_TRACKS = "maxdownloadedtracks"
}
// initially, wanted to store playlist in objectbox as part of the serialized NullpodConfig class.. however, while objectbox does store
// the mutable list in the data store, the sort order is nuked on reloading the database (order comes back as ID asc).. which defeats the
// purpose..
// option would be to store a separate order of track IDs, but at that point might as well just use sharedPreferences for the list, storing them as
// a delimited string; loading and storing as necessary
// todo: other fields:
// todo: download limit
// todo: bool download wifi only
// todo: need to handle exceptions in serialization/deserialization
//---------------------------------------------------------------------------
fun serialize(): JSONObject {
val json = JSONObject()
// playlist
val jsonPlaylist = JSONArray()
playlist.forEach { track ->
jsonPlaylist.put(track.id)
}
json.put(PLAYLIST_ARRAY, jsonPlaylist)
json.put(MAX_DOWNLOAD_TRACKS, maxDownloadedTracks)
return json
}
//---------------------------------------------------------------------------
fun deserialize(json: JSONObject, getTrack: (Long) -> PodcastTrack?) {
playlist.clear()
val jsonPlaylist = json.optJSONArray(PLAYLIST_ARRAY)
if (jsonPlaylist == null) {
log.warn { "json playlist is null; cannot deserialize current playlist!" }
return // todo: shouldn't return here; need to init other fields
}
for (idx in 0 until jsonPlaylist.length()) {
//log.debug { "idx:$idx, val: ${jsonPlaylist.getInt(idx)}"}
val track = getTrack(jsonPlaylist.getLong(idx))
if (track != null) {
playlist.add(track)
} else {
log.warn { "couldn't add track to playlist with id ${jsonPlaylist.getInt(idx)}!!" }
}
}
maxDownloadedTracks = json.optInt(MAX_DOWNLOAD_TRACKS, 5)
}
}
| gpl-3.0 | 4353853208a4b4d6c3f82c3cce8f61f0 | 33.145833 | 151 | 0.633923 | 4.546463 | false | false | false | false |
Ribesg/anko | dsl/testData/functional/sdk19/PropertyTest.kt | 1 | 4222 | var android.view.View.backgroundColor: Int
get() = throw AnkoException("'android.view.View.backgroundColor' property does not have a getter")
set(v) = setBackgroundColor(v)
var android.view.View.backgroundResource: Int
get() = throw AnkoException("'android.view.View.backgroundResource' property does not have a getter")
set(v) = setBackgroundResource(v)
var android.widget.TextView.enabled: Boolean
get() = throw AnkoException("'android.widget.TextView.enabled' property does not have a getter")
set(v) = setEnabled(v)
var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(v)
var android.widget.TextView.hintTextColor: Int
get() = throw AnkoException("'android.widget.TextView.hintTextColor' property does not have a getter")
set(v) = setHintTextColor(v)
var android.widget.TextView.linkTextColor: Int
get() = throw AnkoException("'android.widget.TextView.linkTextColor' property does not have a getter")
set(v) = setLinkTextColor(v)
var android.widget.TextView.lines: Int
get() = throw AnkoException("'android.widget.TextView.lines' property does not have a getter")
set(v) = setLines(v)
var android.widget.TextView.singleLine: Boolean
get() = throw AnkoException("'android.widget.TextView.singleLine' property does not have a getter")
set(v) = setSingleLine(v)
var android.widget.ImageView.imageResource: Int
get() = throw AnkoException("'android.widget.ImageView.imageResource' property does not have a getter")
set(v) = setImageResource(v)
var android.widget.ImageView.imageURI: android.net.Uri?
get() = throw AnkoException("'android.widget.ImageView.imageURI' property does not have a getter")
set(v) = setImageURI(v)
var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
get() = throw AnkoException("'android.widget.ImageView.imageBitmap' property does not have a getter")
set(v) = setImageBitmap(v)
var android.widget.RelativeLayout.horizontalGravity: Int
get() = throw AnkoException("'android.widget.RelativeLayout.horizontalGravity' property does not have a getter")
set(v) = setHorizontalGravity(v)
var android.widget.RelativeLayout.verticalGravity: Int
get() = throw AnkoException("'android.widget.RelativeLayout.verticalGravity' property does not have a getter")
set(v) = setVerticalGravity(v)
var android.widget.LinearLayout.gravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
var android.widget.LinearLayout.horizontalGravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.horizontalGravity' property does not have a getter")
set(v) = setHorizontalGravity(v)
var android.widget.LinearLayout.verticalGravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.verticalGravity' property does not have a getter")
set(v) = setVerticalGravity(v)
var android.widget.Gallery.gravity: Int
get() = throw AnkoException("'android.widget.Gallery.gravity' property does not have a getter")
set(v) = setGravity(v)
var android.widget.AbsListView.selectorResource: Int
get() = throw AnkoException("'android.widget.AbsListView.selectorResource' property does not have a getter")
set(v) = setSelector(v)
var android.widget.CalendarView.selectedDateVerticalBarResource: Int
get() = throw AnkoException("'android.widget.CalendarView.selectedDateVerticalBarResource' property does not have a getter")
set(v) = setSelectedDateVerticalBar(v)
var android.widget.CheckedTextView.checkMarkDrawableResource: Int
get() = throw AnkoException("'android.widget.CheckedTextView.checkMarkDrawableResource' property does not have a getter")
set(v) = setCheckMarkDrawable(v)
var android.widget.TextView.hintResource: Int
get() = throw AnkoException("'android.widget.TextView.hintResource' property does not have a getter")
set(v) = setHint(v)
var android.widget.TextView.textResource: Int
get() = throw AnkoException("'android.widget.TextView.textResource' property does not have a getter")
set(v) = setText(v) | apache-2.0 | 7d5e6497b55f72464de899713ed808eb | 47.54023 | 128 | 0.759356 | 4.032474 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/lambda/higherOrderFun/DefaultParamFun.kt | 1 | 1531 | package lambda.higherOrderFun
/**
* 函数类型的 参数默认值
*/
fun <T> Collection<T>.joinToString1(
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val result = StringBuilder(prefix)
for ((index, element) in this.withIndex()) {
if (index > 0) result.append(separator)
result.append(element)//使用默认的toString方法将对象转换为字符串
}
result.append(postfix)
return result.toString()
}
/**
* 传递一个lambda 去指定如何将对象转换为字符串
*
* 声明函数类型的默认值并不需要特殊的语法 -- 只需要把lambda 作为值放在=号后面。
*/
fun <T> Collection<T>.joinToString2(
separator: String = ", ",
prefix: String = "",
postfix: String = "",
transform: (T) -> String = { it.toString() } //声明一个以lambda为默认值的函数类型的参数
): String {
val result = StringBuilder(prefix)
for ((index, element) in this.withIndex()) {
if (index > 0) result.append(separator)
result.append(transform(element)) //调用
}
result.append(postfix)
return result.toString()
}
fun main(args: Array<String>) {
val letters = listOf("Alpha", "Beta")
println(letters.joinToString2()) //Alpha, Beta
println(letters.joinToString2 { it.toLowerCase() }) //alpha, beta
println(letters.joinToString2(separator = "! ", postfix = "! ",
transform = { it.toUpperCase() })) //ALPHA! BETA!
} | apache-2.0 | a1c33a493ee67dc280d27a66174b45b5 | 26.346939 | 78 | 0.616878 | 3.542328 | false | false | false | false |
akvo/akvo-caddisfly | caddisfly-app/app/src/test/java/org/akvo/caddisfly/util/ClassUtil.kt | 1 | 2510 | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly 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 Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util
import org.assertj.core.api.Fail.fail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
//http://stackoverflow.com/questions/4520216/how-to-add-test-coverage-to-a-private-constructor
internal object ClassUtil {
/**
* Verifies that a utility class is well defined.
* https://github.com/trajano/maven-jee6/tree/master/maven-jee6-test
*
* @param clazz utility class to verify.
* @throws NoSuchMethodException if method does not exist
* @throws InvocationTargetException a checked exception
* @throws InstantiationException if unable to instantiate
* @throws IllegalAccessException if unable to access
*/
@Throws(NoSuchMethodException::class, InvocationTargetException::class,
InstantiationException::class, IllegalAccessException::class)
fun assertUtilityClassWellDefined(clazz: Class<*>) {
assertTrue("class must be final",
Modifier.isFinal(clazz.modifiers))
assertEquals("There must be only one constructor", 1,
clazz.declaredConstructors.size)
val constructor = clazz.getDeclaredConstructor()
if (constructor.isAccessible || !Modifier.isPrivate(constructor.modifiers)) {
fail("constructor is not private")
}
constructor.isAccessible = true
constructor.newInstance()
constructor.isAccessible = false
for (method in clazz.methods) {
if (!Modifier.isStatic(method.modifiers) && method.declaringClass == clazz) {
fail("there exists a non-static method:$method")
}
}
}
}
| gpl-3.0 | 6a62e39afccbae4afa0b7d6950a3ca17 | 39.483871 | 94 | 0.705578 | 4.605505 | false | false | false | false |
JosephCatrambone/ReBUILD | core/src/io/xoana/rebuild/MainGame.kt | 1 | 1464 | package io.xoana.rebuild
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.viewport.ScreenViewport
import java.net.InetSocketAddress
import java.util.*
/**
* Created by Jo on 2017-06-08.
*/
class MainGame : ApplicationAdapter() {
companion object {
var assets:AssetManager = AssetManager()
var atlas:TextureAtlas = TextureAtlas()
var stateStack = Stack<GameState>()
}
override fun create() {
//MainGame.atlas = TextureAtlas(Gdx.files.internal("atlas_image.atlas"));
// Initialize stage.
//mainStage = Stage(ScreenViewport())
stateStack.push(LevelEditor2D(this))
}
override fun render() {
super.render()
stateStack.peek().render()
stateStack.peek().update(Gdx.graphics.deltaTime)
}
override fun dispose() {
while(stateStack.isNotEmpty()) {
stateStack.pop().dispose()
}
}
override fun resize(width: Int, height: Int) {
// DO NOT RECOMPUTE THE CAMERA HERE! It will botch our config. Leave it alone.
//camera = new PerspectiveCamera(FOV, width, height);
stateStack.peek().resize(width, height)
}
}
abstract class GameState(val mainGameRef:MainGame) {
abstract fun render();
abstract fun update(deltaTime: Float);
abstract fun dispose();
abstract fun resize(width:Int, height:Int);
} | mit | 8fa8c04dca7421ad4dcb9b8aa70913d9 | 24.701754 | 82 | 0.74112 | 3.420561 | false | true | false | false |
kittinunf/Fuel | fuel/src/main/kotlin/com/github/kittinunf/fuel/core/interceptors/ParameterEncoder.kt | 1 | 3000 | package com.github.kittinunf.fuel.core.interceptors
import com.github.kittinunf.fuel.core.FoldableRequestInterceptor
import com.github.kittinunf.fuel.core.Headers
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.Parameters
import com.github.kittinunf.fuel.core.RequestTransformer
import java.net.URL
import java.net.URLEncoder
object ParameterEncoder : FoldableRequestInterceptor {
override fun invoke(next: RequestTransformer): RequestTransformer {
return inner@{ request ->
val contentType = request[Headers.CONTENT_TYPE].lastOrNull()
// Expect the parameters to be already encoded in the body
if (contentType?.startsWith("multipart/form-data") == true) {
return@inner next(request)
}
// If it can be added to the body
if (request.body.isEmpty() && allowParametersInBody(request.method)) {
if (contentType.isNullOrBlank() || contentType.startsWith("application/x-www-form-urlencoded")) {
return@inner next(
request
.header(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(encode(request.parameters))
.apply { parameters = emptyList() }
)
}
}
// Has to be added to the URL
next(
request
.apply { url = url.withParameters(parameters) }
.apply { parameters = emptyList() }
)
}
}
private fun encode(parameters: Parameters) =
parameters
.filterNot { (_, values) -> values == null }
.flatMap { (key, values) ->
// Deal with arrays
((values as? Iterable<*>)?.toList() ?: (values as? Array<*>)?.toList())?.let {
val encodedKey = "${URLEncoder.encode(key, "UTF-8")}[]"
it.map { value -> encodedKey to URLEncoder.encode(value.toString(), "UTF-8") }
// Deal with regular
} ?: listOf(URLEncoder.encode(key, "UTF-8") to URLEncoder.encode(values.toString(), "UTF-8"))
}
.joinToString("&") { (key, value) -> if (value.isBlank()) key else "$key=$value" }
private fun allowParametersInBody(method: Method) = when (method) {
Method.POST, Method.PATCH, Method.PUT -> true
else -> false
}
private fun URL.withParameters(parameters: Parameters): URL {
val encoded = ParameterEncoder.encode(parameters)
if (encoded.isEmpty()) {
return this
}
val joiner = if (toExternalForm().contains('?')) {
// There is already some query
if (query.isNotEmpty()) "&"
// There is already a trailing ?
else ""
} else "?"
return URL(toExternalForm() + joiner + encoded)
}
} | mit | b6adf5cee601cab0c01971d91d579aea | 38.486842 | 113 | 0.561 | 4.87013 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/inspector/LayoutInspectorTree.kt | 3 | 32467 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.inspection.inspector
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.tooling.CompositionData
import androidx.compose.runtime.tooling.CompositionGroup
import androidx.compose.ui.R
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.inspection.util.AnchorMap
import androidx.compose.ui.inspection.util.NO_ANCHOR_ID
import androidx.compose.ui.layout.GraphicLayerInfo
import androidx.compose.ui.layout.LayoutInfo
import androidx.compose.ui.node.Ref
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.platform.ViewRootForInspector
import androidx.compose.ui.semantics.SemanticsModifier
import androidx.compose.ui.semantics.getAllSemanticsNodes
import androidx.compose.ui.tooling.data.ContextCache
import androidx.compose.ui.tooling.data.ParameterInformation
import androidx.compose.ui.tooling.data.SourceContext
import androidx.compose.ui.tooling.data.SourceLocation
import androidx.compose.ui.tooling.data.UiToolingDataApi
import androidx.compose.ui.tooling.data.findParameters
import androidx.compose.ui.tooling.data.mapTree
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.toSize
import java.util.ArrayDeque
import java.util.Collections
import java.util.IdentityHashMap
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
val systemPackages = setOf(
-1,
packageNameHash("androidx.compose.animation"),
packageNameHash("androidx.compose.animation.core"),
packageNameHash("androidx.compose.desktop"),
packageNameHash("androidx.compose.foundation"),
packageNameHash("androidx.compose.foundation.layout"),
packageNameHash("androidx.compose.foundation.text"),
packageNameHash("androidx.compose.material"),
packageNameHash("androidx.compose.material.ripple"),
packageNameHash("androidx.compose.runtime"),
packageNameHash("androidx.compose.runtime.saveable"),
packageNameHash("androidx.compose.ui"),
packageNameHash("androidx.compose.ui.graphics.vector"),
packageNameHash("androidx.compose.ui.layout"),
packageNameHash("androidx.compose.ui.platform"),
packageNameHash("androidx.compose.ui.tooling"),
packageNameHash("androidx.compose.ui.selection"),
packageNameHash("androidx.compose.ui.semantics"),
packageNameHash("androidx.compose.ui.viewinterop"),
packageNameHash("androidx.compose.ui.window"),
)
/**
* The [InspectorNode.id] will be populated with:
* - the layerId from a LayoutNode if this exists
* - an id generated from an Anchor instance from the SlotTree if this exists
* - a generated id if none of the above ids are available
*
* The interval -10000..-2 is reserved for the generated ids.
*/
@VisibleForTesting
const val RESERVED_FOR_GENERATED_IDS = -10000L
const val PLACEHOLDER_ID = Long.MAX_VALUE
private val emptySize = IntSize(0, 0)
private val unwantedCalls = setOf(
"CompositionLocalProvider",
"Content",
"Inspectable",
"ProvideAndroidCompositionLocals",
"ProvideCommonCompositionLocals",
)
@VisibleForTesting
fun packageNameHash(packageName: String) =
packageName.fold(0) { hash, char -> hash * 31 + char.code }.absoluteValue
/**
* Generator of a tree for the Layout Inspector.
*/
@OptIn(UiToolingDataApi::class)
class LayoutInspectorTree {
@Suppress("MemberVisibilityCanBePrivate")
var hideSystemNodes = true
var includeNodesOutsizeOfWindow = true
var includeAllParameters = true
private var foundNode: InspectorNode? = null
private var windowSize = emptySize
private val inlineClassConverter = InlineClassConverter()
private val parameterFactory = ParameterFactory(inlineClassConverter)
private val cache = ArrayDeque<MutableInspectorNode>()
private var generatedId = -1L
private val subCompositions = SubCompositionRoots()
/** Map from [LayoutInfo] to the nearest [InspectorNode] that contains it */
private val claimedNodes = IdentityHashMap<LayoutInfo, InspectorNode>()
/** Map from parent tree to child trees that are about to be stitched together */
private val treeMap = IdentityHashMap<MutableInspectorNode, MutableList<MutableInspectorNode>>()
/** Map from owner node to child trees that are about to be stitched to this owner */
private val ownerMap = IdentityHashMap<InspectorNode, MutableList<MutableInspectorNode>>()
/** Map from semantics id to a list of merged semantics information */
private val semanticsMap = mutableMapOf<Int, List<RawParameter>>()
/** Set of tree nodes that were stitched into another tree */
private val stitched =
Collections.newSetFromMap(IdentityHashMap<MutableInspectorNode, Boolean>())
private val contextCache = ContextCache()
private val anchorMap = AnchorMap()
/**
* Converts the [CompositionData] set held by [view] into a list of root nodes.
*/
fun convert(view: View): List<InspectorNode> {
windowSize = IntSize(view.width, view.height)
parameterFactory.density = Density(view.context)
@Suppress("UNCHECKED_CAST")
val tables = view.getTag(R.id.inspection_slot_table_set) as?
Set<CompositionData>
?: return emptyList()
clear()
collectSemantics(view)
val result = convert(tables, view)
clear()
return result
}
fun findParameters(view: View, anchorId: Int): InspectorNode? {
windowSize = IntSize(view.width, view.height)
parameterFactory.density = Density(view.context)
val identity = anchorMap[anchorId] ?: return null
@Suppress("UNCHECKED_CAST")
val tables = view.getTag(R.id.inspection_slot_table_set) as?
Set<CompositionData>
?: return null
val node = newNode().apply { this.anchorId = anchorId }
val group = tables.firstNotNullOfOrNull { it.find(identity) } ?: return null
group.findParameters(contextCache).forEach {
val castedValue = castValue(it)
node.parameters.add(RawParameter(it.name, castedValue))
}
return buildAndRelease(node)
}
/**
* Add the roots to sub compositions that may have been collected from a different SlotTree.
*
* See [SubCompositionRoots] for details.
*/
fun addSubCompositionRoots(view: View, nodes: List<InspectorNode>): List<InspectorNode> =
subCompositions.addRoot(view, nodes)
/**
* Extract the merged semantics for this semantics owner such that they can be added
* to compose nodes during the conversion of Group nodes.
*/
private fun collectSemantics(view: View) {
val root = view as? RootForTest ?: return
val nodes = root.semanticsOwner.getAllSemanticsNodes(mergingEnabled = true)
nodes.forEach { node ->
semanticsMap[node.id] = node.config.map { RawParameter(it.key.name, it.value) }
}
}
/**
* Converts the [RawParameter]s of the [node] into displayable parameters.
*/
fun convertParameters(
rootId: Long,
node: InspectorNode,
kind: ParameterKind,
maxRecursions: Int,
maxInitialIterableSize: Int
): List<NodeParameter> {
val parameters = node.parametersByKind(kind)
return parameters.mapIndexed { index, parameter ->
parameterFactory.create(
rootId,
node.id,
node.anchorId,
parameter.name,
parameter.value,
kind,
index,
maxRecursions,
maxInitialIterableSize
)
}
}
/**
* Converts a part of the [RawParameter] identified by [reference] into a
* displayable parameter. If the parameter is some sort of a collection
* then [startIndex] and [maxElements] describes the scope of the data returned.
*/
fun expandParameter(
rootId: Long,
node: InspectorNode,
reference: NodeParameterReference,
startIndex: Int,
maxElements: Int,
maxRecursions: Int,
maxInitialIterableSize: Int
): NodeParameter? {
val parameters = node.parametersByKind(reference.kind)
if (reference.parameterIndex !in parameters.indices) {
return null
}
val parameter = parameters[reference.parameterIndex]
return parameterFactory.expand(
rootId,
node.id,
node.anchorId,
parameter.name,
parameter.value,
reference,
startIndex,
maxElements,
maxRecursions,
maxInitialIterableSize
)
}
/**
* Reset any state accumulated between windows.
*/
@Suppress("unused")
fun resetAccumulativeState() {
subCompositions.resetAccumulativeState()
parameterFactory.clearReferenceCache()
// Reset the generated id. Nodes are assigned an id if there isn't a layout node id present.
generatedId = -1L
}
private fun clear() {
cache.clear()
inlineClassConverter.clear()
claimedNodes.clear()
treeMap.clear()
ownerMap.clear()
semanticsMap.clear()
stitched.clear()
subCompositions.clear()
foundNode = null
}
private fun convert(tables: Set<CompositionData>, view: View): List<InspectorNode> {
val trees = tables.mapNotNull { convert(view, it) }
return when (trees.size) {
0 -> listOf()
1 -> addTree(mutableListOf(), trees.single())
else -> stitchTreesByLayoutInfo(trees)
}
}
/**
* Stitch separate trees together using the [LayoutInfo]s found in the [CompositionData]s.
*
* Some constructs in Compose (e.g. ModalDrawer) will result is multiple
* [CompositionData]s. This code will attempt to stitch the resulting [InspectorNode] trees
* together by looking at the parent of each [LayoutInfo].
*
* If this algorithm is successful the result of this function will be a list with a single
* tree.
*/
private fun stitchTreesByLayoutInfo(trees: List<MutableInspectorNode>): List<InspectorNode> {
val layoutToTreeMap = IdentityHashMap<LayoutInfo, MutableInspectorNode>()
trees.forEach { tree -> tree.layoutNodes.forEach { layoutToTreeMap[it] = tree } }
trees.forEach { tree ->
val layout = tree.layoutNodes.lastOrNull()
val parentLayout = generateSequence(layout) { it.parentInfo }.firstOrNull {
val otherTree = layoutToTreeMap[it]
otherTree != null && otherTree != tree
}
if (parentLayout != null) {
val ownerNode = claimedNodes[parentLayout]
val ownerTree = layoutToTreeMap[parentLayout]
if (ownerNode != null && ownerTree != null) {
ownerMap.getOrPut(ownerNode) { mutableListOf() }.add(tree)
treeMap.getOrPut(ownerTree) { mutableListOf() }.add(tree)
}
}
}
var parentTree = findDeepParentTree()
while (parentTree != null) {
addSubTrees(parentTree)
treeMap.remove(parentTree)
parentTree = findDeepParentTree()
}
val result = mutableListOf<InspectorNode>()
trees.asSequence().filter { !stitched.contains(it) }.forEach { addTree(result, it) }
return result
}
/**
* Return a parent tree where the children trees (to be stitched under the parent) are not
* a parent themselves. Do this to avoid rebuilding the same tree more than once.
*/
private fun findDeepParentTree(): MutableInspectorNode? =
treeMap.entries.asSequence()
.filter { (_, children) -> children.none { treeMap.containsKey(it) } }
.firstOrNull()?.key
private fun addSubTrees(tree: MutableInspectorNode) {
for ((index, child) in tree.children.withIndex()) {
tree.children[index] = addSubTrees(child) ?: child
}
}
/**
* Rebuild [node] with any possible sub trees added (stitched in).
* Return the rebuild node, or null if no changes were found in this node or its children.
* Lazily allocate the new node to avoid unnecessary allocations.
*/
private fun addSubTrees(node: InspectorNode): InspectorNode? {
var newNode: MutableInspectorNode? = null
for ((index, child) in node.children.withIndex()) {
val newChild = addSubTrees(child)
if (newChild != null) {
val newCopy = newNode ?: newNode(node)
newCopy.children[index] = newChild
newNode = newCopy
}
}
val trees = ownerMap[node]
if (trees == null && newNode == null) {
return null
}
val newCopy = newNode ?: newNode(node)
if (trees != null) {
trees.forEach { addTree(newCopy.children, it) }
stitched.addAll(trees)
}
return buildAndRelease(newCopy)
}
/**
* Add [tree] to the end of the [out] list.
* The root nodes of [tree] may be a fake node that hold a list of [LayoutInfo].
*/
private fun addTree(
out: MutableList<InspectorNode>,
tree: MutableInspectorNode
): List<InspectorNode> {
tree.children.forEach {
if (it.name.isNotEmpty()) {
out.add(it)
} else {
out.addAll(it.children)
}
}
return out
}
private fun convert(view: View, table: CompositionData): MutableInspectorNode? {
val fakeParent = newNode()
val group = table.mapTree(::convert, contextCache) ?: return null
addToParent(fakeParent, listOf(group), buildFakeChildNodes = true)
return if (belongsToView(fakeParent.layoutNodes, view)) fakeParent else null
}
private fun convert(
group: CompositionGroup,
context: SourceContext,
children: List<MutableInspectorNode>
): MutableInspectorNode {
val parent = parse(group, context, children)
subCompositions.captureNode(parent, context)
addToParent(parent, children)
return parent
}
/**
* Adds the nodes in [input] to the children of [parentNode].
* Nodes without a reference to a wanted Composable are skipped unless [buildFakeChildNodes].
* A single skipped render id and layoutNode will be added to [parentNode].
*/
private fun addToParent(
parentNode: MutableInspectorNode,
input: List<MutableInspectorNode>,
buildFakeChildNodes: Boolean = false
) {
if (parentNode.name == "AndroidView") {
// Special case:
// We may have captured the View id from an AndroidView Composable.
// Add the viewId to the child ComposeNode that should be present.
input.singleOrNull { it.name == "ComposeNode" }?.viewId = subCompositions.latestViewId()
}
var id: Long? = null
input.forEach { node ->
if (node.name.isEmpty() && !(buildFakeChildNodes && node.layoutNodes.isNotEmpty())) {
parentNode.children.addAll(node.children)
if (node.id > UNDEFINED_ID) {
// If multiple siblings with a render ids are dropped:
// Ignore them all. And delegate the drawing to a parent in the inspector.
id = if (id == null) node.id else UNDEFINED_ID
}
} else {
node.id = if (node.id != UNDEFINED_ID) node.id else --generatedId
val withSemantics = node.packageHash !in systemPackages
val resultNode = node.build(withSemantics)
// TODO: replace getOrPut with putIfAbsent which requires API level 24
node.layoutNodes.forEach { claimedNodes.getOrPut(it) { resultNode } }
parentNode.children.add(resultNode)
if (withSemantics) {
node.mergedSemantics.clear()
node.unmergedSemantics.clear()
}
}
if (node.bounds != null && parentNode.box == node.box) {
parentNode.bounds = node.bounds
}
parentNode.layoutNodes.addAll(node.layoutNodes)
parentNode.mergedSemantics.addAll(node.mergedSemantics)
parentNode.unmergedSemantics.addAll(node.unmergedSemantics)
release(node)
}
val nodeId = id
parentNode.id =
if (parentNode.id <= UNDEFINED_ID && nodeId != null) nodeId else parentNode.id
}
private fun parse(
group: CompositionGroup,
context: SourceContext,
children: List<MutableInspectorNode>
): MutableInspectorNode {
val node = newNode()
node.name = context.name ?: ""
node.key = group.key as? Int ?: 0
val layoutInfo = group.node as? LayoutInfo
if (layoutInfo != null) {
return parseLayoutInfo(layoutInfo, context, node)
}
if (unwantedOutsideWindow(node, children)) {
return markUnwanted(group, context, node)
}
node.box = context.bounds.emptyCheck()
if (unwantedName(node.name) || (node.box == emptyBox && !subCompositions.capturing)) {
return markUnwanted(group, context, node)
}
parseCallLocation(node, context.location)
if (isHiddenSystemNode(node)) {
return markUnwanted(group, context, node)
}
node.anchorId = anchorMap[group.identity]
node.id = syntheticId(node.anchorId)
if (includeAllParameters) {
addParameters(context, node)
}
return node
}
private fun IntRect.emptyCheck(): IntRect =
if (left >= right && top >= bottom) emptyBox else this
private fun IntRect.inWindow(): Boolean =
!(left > windowSize.width || right < 0 || top > windowSize.height || bottom < 0)
private fun IntRect.union(other: IntRect): IntRect {
if (this == outsideBox) return other else if (other == outsideBox) return this
return IntRect(
left = min(left, other.left),
top = min(top, other.top),
bottom = max(bottom, other.bottom),
right = max(right, other.right)
)
}
private fun parseLayoutInfo(
layoutInfo: LayoutInfo,
context: SourceContext,
node: MutableInspectorNode
): MutableInspectorNode {
val box = context.bounds
val size = box.size.toSize()
val coordinates = layoutInfo.coordinates
val topLeft = toIntOffset(coordinates.localToWindow(Offset.Zero))
val topRight = toIntOffset(coordinates.localToWindow(Offset(size.width, 0f)))
val bottomRight = toIntOffset(coordinates.localToWindow(Offset(size.width, size.height)))
val bottomLeft = toIntOffset(coordinates.localToWindow(Offset(0f, size.height)))
var bounds: QuadBounds? = null
if (topLeft.x != box.left || topLeft.y != box.top ||
topRight.x != box.right || topRight.y != box.top ||
bottomRight.x != box.right || bottomRight.y != box.bottom ||
bottomLeft.x != box.left || bottomLeft.y != box.bottom
) {
bounds = QuadBounds(
topLeft.x, topLeft.y,
topRight.x, topRight.y,
bottomRight.x, bottomRight.y,
bottomLeft.x, bottomLeft.y,
)
}
if (!includeNodesOutsizeOfWindow) {
// Ignore this node if the bounds are completely outside the window
node.outerBox = bounds?.outerBox ?: box
if (!node.outerBox.inWindow()) {
return node
}
}
node.box = box.emptyCheck()
node.bounds = bounds
node.layoutNodes.add(layoutInfo)
val modifierInfo = layoutInfo.getModifierInfo()
node.unmergedSemantics.addAll(
modifierInfo.asSequence()
.map { it.modifier }
.filterIsInstance<SemanticsModifier>()
.map { it.semanticsConfiguration }
.flatMap { config -> config.map { RawParameter(it.key.name, it.value) } }
)
val mergedSemantics = semanticsMap.get(layoutInfo.semanticsId)
if (mergedSemantics != null) {
node.mergedSemantics.addAll(mergedSemantics)
}
node.id = modifierInfo.asSequence()
.map { it.extra }
.filterIsInstance<GraphicLayerInfo>()
.map { it.layerId }
.firstOrNull() ?: UNDEFINED_ID
return node
}
private fun syntheticId(anchorId: Int): Long {
if (anchorId == NO_ANCHOR_ID) {
return UNDEFINED_ID
}
// The anchorId is an Int
return anchorId.toLong() - Int.MAX_VALUE.toLong() + RESERVED_FOR_GENERATED_IDS
}
private fun belongsToView(layoutNodes: List<LayoutInfo>, view: View): Boolean =
layoutNodes.asSequence().flatMap { node ->
node.getModifierInfo().asSequence()
.map { it.extra }
.filterIsInstance<GraphicLayerInfo>()
.map { it.ownerViewId }
}.contains(view.uniqueDrawingId)
private fun addParameters(context: SourceContext, node: MutableInspectorNode) {
context.parameters.forEach {
val castedValue = castValue(it)
node.parameters.add(RawParameter(it.name, castedValue))
}
}
private fun castValue(parameter: ParameterInformation): Any? {
val value = parameter.value ?: return null
if (parameter.inlineClass == null || !isPrimitive(value.javaClass)) return value
return inlineClassConverter.castParameterValue(parameter.inlineClass, value)
}
private fun isPrimitive(cls: Class<*>): Boolean =
cls.kotlin.javaPrimitiveType != null
private fun toIntOffset(offset: Offset): IntOffset =
IntOffset(offset.x.roundToInt(), offset.y.roundToInt())
private fun markUnwanted(
group: CompositionGroup,
context: SourceContext,
node: MutableInspectorNode
): MutableInspectorNode =
when (node.name) {
"rememberCompositionContext" ->
subCompositions.rememberCompositionContext(node, context)
"remember" ->
subCompositions.remember(node, group)
else ->
node.apply { markUnwanted() }
}
private fun parseCallLocation(node: MutableInspectorNode, location: SourceLocation?) {
val fileName = location?.sourceFile ?: return
node.fileName = fileName
node.packageHash = location.packageHash
node.lineNumber = location.lineNumber
node.offset = location.offset
node.length = location.length
}
private fun isHiddenSystemNode(node: MutableInspectorNode): Boolean =
node.packageHash in systemPackages && hideSystemNodes
private fun unwantedName(name: String): Boolean =
name.isEmpty() ||
name.startsWith("remember") ||
name in unwantedCalls
private fun unwantedOutsideWindow(
node: MutableInspectorNode,
children: List<MutableInspectorNode>
): Boolean {
if (includeNodesOutsizeOfWindow) {
return false
}
node.outerBox = if (children.isEmpty()) outsideBox else
children.map { g -> g.outerBox }.reduce { acc, box -> box.union(acc) }
return !node.outerBox.inWindow()
}
private fun newNode(): MutableInspectorNode =
if (cache.isNotEmpty()) cache.pop() else MutableInspectorNode()
private fun newNode(copyFrom: InspectorNode): MutableInspectorNode =
newNode().shallowCopy(copyFrom)
private fun release(node: MutableInspectorNode) {
node.reset()
cache.add(node)
}
private fun buildAndRelease(node: MutableInspectorNode): InspectorNode {
val result = node.build()
release(node)
return result
}
/**
* Keep track of sub-composition roots.
*
* Examples:
* - Popup, Dialog: When one of these is open an extra Android Window is created with
* its own AndroidComposeView. The contents of the Composable is a sub-composition that
* will be computed by calling convert.
*
* The Popup/Dialog composable itself, and a few helping composables (the root) will
* not be included in the SlotTree with the contents, instead these composables
* will be found in the SlotTree for the main app and they all have empty sizes.
* The aim is to collect these sub-composition roots such that they can be added to
* the [InspectorNode]s of the contents.
*
* - AndroidView: When this is used in a compose app we will see a similar pattern in
* the SlotTree except there isn't a sub-composition to stitch in. But we need to
* collect the view id separately from the "AndroidView" node itself.
*/
private inner class SubCompositionRoots {
/** Set to true when the nodes found should be added to a sub-composition root */
var capturing = false
private set
/** The `uniqueDrawingId` of the `AndroidComposeView` that owns the root being captured */
private var ownerView = UNDEFINED_ID
/** The node that represent the root of the sub-composition */
private var rootNode: MutableInspectorNode? = null
/** The depth of the parse tree the [rootNode] was found at */
private var rootNodeDepth = 0
/** Last captured view that is believed to be an embbed View under an AndroidView node */
private var androidView = UNDEFINED_ID
/**
* The sub-composition roots found.
*
* Map from View owner to a pair of [InspectorNode] indicating the actual root,
* and the node where the content should be stitched in.
*/
private val found = mutableMapOf<Long, InspectorNode>()
/** Call this before converting a SlotTree for an AndroidComposeView */
fun clear() {
capturing = false
ownerView = UNDEFINED_ID
rootNode?.markUnwanted()
rootNode?.id = UNDEFINED_ID
rootNode = null
rootNodeDepth = 0
}
/** Call this when starting converting a new set of windows */
fun resetAccumulativeState() {
found.clear()
}
/**
* When a "rememberCompositionContext" is found in the slot tree, it indicates
* that a sub-composition was started. We should capture all parent nodes with
* an empty size as the "root" of the sub-composition.
*/
fun rememberCompositionContext(
node: MutableInspectorNode,
context: SourceContext
): MutableInspectorNode {
if (capturing) {
save()
}
capturing = true
rootNode = node
rootNodeDepth = context.depth
node.id = PLACEHOLDER_ID
return node
}
/**
* When "remember" is found in the slot tree and we are currently capturing,
* the data of the [group] may contain the owner of the sub-composition.
*/
fun remember(node: MutableInspectorNode, group: CompositionGroup): MutableInspectorNode {
node.markUnwanted()
if (!capturing) {
return node
}
val root = findSingleRootInGroupData(group) ?: return node
val view = root.subCompositionView
if (view != null) {
val composeOwner = if (view.childCount == 1) view.getChildAt(0) else return node
ownerView = composeOwner.uniqueDrawingId
} else {
androidView = root.viewRoot?.uniqueDrawingId ?: UNDEFINED_ID
// Store the viewRoot such that we can move the View under the compose node
// in Studio. We do not need to capture the Groups found for this case, so
// we call "reset" here to stop capturing.
clear()
}
return node
}
private fun findSingleRootInGroupData(group: CompositionGroup): ViewRootForInspector? {
group.data.filterIsInstance<ViewRootForInspector>().singleOrNull()?.let { return it }
val refs = group.data.filterIsInstance<Ref<*>>().map { it.value }
return refs.filterIsInstance<ViewRootForInspector>().singleOrNull()
}
/**
* Capture the top node of the sub-composition root until a non empty node is found.
*/
fun captureNode(node: MutableInspectorNode, context: SourceContext) {
if (!capturing) {
return
}
if (node.box != emptyBox) {
save()
return
}
val depth = context.depth
if (depth < rootNodeDepth) {
rootNode = node
rootNodeDepth = depth
}
}
fun latestViewId(): Long {
val id = androidView
androidView = UNDEFINED_ID
return id
}
/**
* If a sub-composition root has been captured, save it now.
*/
private fun save() {
val node = rootNode
if (node != null && ownerView != UNDEFINED_ID) {
found[ownerView] = node.build()
}
node?.markUnwanted()
node?.id = UNDEFINED_ID
node?.children?.clear()
clear()
}
/**
* Add the root of the sub-composition to the found tree.
*
* If a root is not found for this [owner] or if the stitching fails just return [nodes].
*/
fun addRoot(owner: View, nodes: List<InspectorNode>): List<InspectorNode> {
val root = found[owner.uniqueDrawingId] ?: return nodes
val box = IntRect(0, 0, owner.width, owner.height)
val info = StitchInfo(nodes, box)
val result = listOf(stitch(root, info))
return if (info.added) result else nodes
}
private fun stitch(node: InspectorNode, info: StitchInfo): InspectorNode {
val children = node.children.map { stitch(it, info) }
val index = children.indexOfFirst { it.id == PLACEHOLDER_ID }
val newNode = newNode()
newNode.shallowCopy(node)
newNode.children.clear()
if (index < 0) {
newNode.children.addAll(children)
} else {
newNode.children.addAll(children.subList(0, index))
newNode.children.addAll(info.nodes)
newNode.children.addAll(children.subList(index + 1, children.size))
info.added = true
}
newNode.box = info.bounds
return buildAndRelease(newNode)
}
}
private class StitchInfo(
/** The nodes found that should be stitched into a sub-composition root. */
val nodes: List<InspectorNode>,
/** The bounds of the View containing the sub-composition */
val bounds: IntRect
) {
/** Set this to true when the [nodes] have been added to a sub-composition root */
var added: Boolean = false
}
}
| apache-2.0 | b52bca4e2a93f64b06a0ce0e0b555786 | 37.743437 | 100 | 0.625404 | 4.679591 | false | false | false | false |
AndroidX/androidx | biometric/integration-tests/testapp/src/main/java/androidx/biometric/integration/testapp/AuthPromptTestActivity.kt | 3 | 12341 | /*
* 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.biometric.integration.testapp
import android.os.Build
import android.os.Bundle
import android.widget.TextView
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators
import androidx.biometric.BiometricPrompt
import androidx.biometric.auth.AuthPrompt
import androidx.biometric.auth.AuthPromptCallback
import androidx.biometric.auth.startClass2BiometricAuthentication
import androidx.biometric.auth.startClass2BiometricOrCredentialAuthentication
import androidx.biometric.auth.authenticateWithClass3Biometrics
import androidx.biometric.auth.startClass3BiometricOrCredentialAuthentication
import androidx.biometric.auth.startCredentialAuthentication
import androidx.biometric.integration.testapp.R.string.biometric_prompt_description
import androidx.biometric.integration.testapp.R.string.biometric_prompt_negative_text
import androidx.biometric.integration.testapp.R.string.biometric_prompt_subtitle
import androidx.biometric.integration.testapp.R.string.biometric_prompt_title
import androidx.biometric.integration.testapp.databinding.AuthPromptTestActivityBinding
import androidx.fragment.app.FragmentActivity
import java.nio.charset.Charset
/**
* Interactive test activity for the [androidx.biometric.auth] APIs.
*/
class AuthPromptTestActivity : FragmentActivity() {
private lateinit var binding: AuthPromptTestActivityBinding
/**
* A handle to the prompt for an ongoing authentication session.
*/
private var authPrompt: AuthPrompt? = null
/**
* A bit field representing the currently allowed authenticator type(s).
*/
private val allowedAuthenticators: Int
get() {
var authenticators = 0
if (binding.class3BiometricButton.isChecked ||
binding.class3BiometricOrCredentialButton.isChecked
) {
authenticators = authenticators or Authenticators.BIOMETRIC_STRONG
}
if (binding.class2BiometricButton.isChecked ||
binding.class2BiometricOrCredentialButton.isChecked
) {
authenticators = authenticators or Authenticators.BIOMETRIC_WEAK
}
if (binding.class2BiometricOrCredentialButton.isChecked ||
binding.class3BiometricOrCredentialButton.isChecked ||
binding.credentialButton.isChecked
) {
authenticators = authenticators or Authenticators.DEVICE_CREDENTIAL
}
return authenticators
}
/**
* Whether the selected options allow for biometric authentication.
*/
private val isBiometricAllowed: Boolean
get() {
return binding.class2BiometricButton.isChecked ||
binding.class2BiometricOrCredentialButton.isChecked ||
binding.class3BiometricButton.isChecked ||
binding.class3BiometricOrCredentialButton.isChecked
}
/**
* Whether the selected options allow for device credential authentication.
*/
private val isCredentialAllowed: Boolean
get() {
return binding.class2BiometricOrCredentialButton.isChecked ||
binding.class3BiometricOrCredentialButton.isChecked ||
binding.credentialButton.isChecked
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = AuthPromptTestActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
// Disallow unsupported authentication type combinations.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
binding.class3BiometricOrCredentialButton.isEnabled = false
binding.credentialButton.isEnabled = false
}
// Crypto-based authentication is not supported prior to Android 6.0 (API 23).
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
binding.common.useCryptoAuthCheckbox.isEnabled = false
}
// Set button callbacks.
binding.authTypeGroup.setOnCheckedChangeListener { _, checkedId ->
updateCryptoCheckboxState(checkedId)
}
binding.common.canAuthenticateButton.setOnClickListener { canAuthenticate() }
binding.common.authenticateButton.setOnClickListener { authenticate() }
binding.common.clearLogButton.setOnClickListener { clearLog() }
// Restore logged messages on activity recreation (e.g. due to device rotation).
if (savedInstanceState != null) {
binding.common.logTextView.text = savedInstanceState.getCharSequence(KEY_LOG_TEXT, "")
}
}
override fun onStop() {
super.onStop()
// If option is selected, dismiss the prompt on rotation.
if (binding.common.cancelConfigChangeCheckbox.isChecked && isChangingConfigurations) {
authPrompt?.cancelAuthentication()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
// Save the current log messages to be restored on activity recreation.
outState.putCharSequence(KEY_LOG_TEXT, binding.common.logTextView.text)
}
/**
* Updates the state of the crypto-based auth checkbox when a given [checkedId] is selected
* from the authentication types radio group.
*/
private fun updateCryptoCheckboxState(checkedId: Int) {
// Crypto-based authentication is not supported prior to Android 6.0 (API 23).
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return
}
val isCheckboxEnabled = checkedId != R.id.class2_biometric_button &&
checkedId != R.id.class2_biometric_or_credential_button
binding.common.useCryptoAuthCheckbox.isEnabled = isCheckboxEnabled
if (!isCheckboxEnabled) {
binding.common.useCryptoAuthCheckbox.isChecked = false
}
}
/**
* Logs the authentication status given by [BiometricManager.canAuthenticate].
*/
private fun canAuthenticate() {
val result = BiometricManager.from(this).canAuthenticate(allowedAuthenticators)
log("canAuthenticate: ${result.toAuthenticationStatusString()}")
}
/**
* Launches the appropriate [AuthPrompt] to begin authentication.
*/
private fun authenticate() {
val title = getString(biometric_prompt_title)
val subtitle = getString(biometric_prompt_subtitle)
val description = getString(biometric_prompt_description)
val negativeButtonText = getString(biometric_prompt_negative_text)
val confirmationRequired = binding.common.requireConfirmationCheckbox.isChecked
val callback = AuthCallback()
authPrompt = when (val buttonId = binding.authTypeGroup.checkedRadioButtonId) {
R.id.class2_biometric_button ->
startClass2BiometricAuthentication(
title = title,
negativeButtonText = negativeButtonText,
callback = callback
)
R.id.class3_biometric_button ->
authenticateWithClass3Biometrics(
crypto = createCryptoOrNull(),
title = title,
subtitle = subtitle,
description = description,
negativeButtonText = negativeButtonText,
callback = callback
)
R.id.class2_biometric_or_credential_button ->
startClass2BiometricOrCredentialAuthentication(
title = title,
subtitle = subtitle,
description = description,
confirmationRequired = confirmationRequired,
callback = callback
)
R.id.class3_biometric_or_credential_button ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
startClass3BiometricOrCredentialAuthentication(
crypto = createCryptoOrNull(),
title = title,
subtitle = subtitle,
description = description,
confirmationRequired = confirmationRequired,
callback = callback
)
} else {
val sdkInt = Build.VERSION.SDK_INT
log("Error: Class 3 biometric or credential auth not supported on API $sdkInt.")
null
}
R.id.credential_button ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
startCredentialAuthentication(
crypto = createCryptoOrNull(),
title = title,
description = description,
callback = callback
)
} else {
val sdkInt = Build.VERSION.SDK_INT
log("Error: Credential-only auth not supported on API $sdkInt.")
null
}
else -> throw IllegalStateException("Invalid checked button ID: $buttonId")
}
}
/**
* Returns a new crypto object for authentication or `null`, based on the selected options.
*/
private fun createCryptoOrNull(): BiometricPrompt.CryptoObject? {
return if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
binding.common.useCryptoAuthCheckbox.isChecked
) {
createCryptoObject(isBiometricAllowed, isCredentialAllowed)
} else {
null
}
}
/**
* Logs a new [message] to the in-app [TextView].
*/
internal fun log(message: CharSequence) {
binding.common.logTextView.prependLogMessage(message)
}
/**
* Clears all logged messages from the in-app [TextView].
*/
private fun clearLog() {
binding.common.logTextView.text = ""
}
/**
* Sample callback that logs all authentication events.
*/
private class AuthCallback : AuthPromptCallback() {
override fun onAuthenticationError(
activity: FragmentActivity?,
errorCode: Int,
errString: CharSequence
) {
super.onAuthenticationError(activity, errorCode, errString)
if (activity is AuthPromptTestActivity) {
activity.log("onAuthenticationError $errorCode: $errString")
}
}
override fun onAuthenticationSucceeded(
activity: FragmentActivity?,
result: BiometricPrompt.AuthenticationResult
) {
super.onAuthenticationSucceeded(activity, result)
if (activity is AuthPromptTestActivity) {
activity.log("onAuthenticationSucceeded: ${result.toDataString()}")
// Encrypt a test payload using the result of crypto-based auth.
if (activity.binding.common.useCryptoAuthCheckbox.isChecked) {
val encryptedPayload = result.cryptoObject?.cipher?.doFinal(
PAYLOAD.toByteArray(Charset.defaultCharset())
)
activity.log("Encrypted payload: ${encryptedPayload?.contentToString()}")
}
}
}
override fun onAuthenticationFailed(activity: FragmentActivity?) {
super.onAuthenticationFailed(activity)
if (activity is AuthPromptTestActivity) {
activity.log("onAuthenticationFailed")
}
}
}
} | apache-2.0 | 101bd11ef64aeb9e0c08dc2b12267de1 | 38.305732 | 100 | 0.638279 | 5.38438 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/formatter/settings/FortranLanguageCodeStyleSettingsProvider.kt | 1 | 5583 | package org.jetbrains.fortran.ide.formatter.settings
import com.intellij.application.options.IndentOptionsEditor
import com.intellij.application.options.SmartIndentOptionsEditor
import com.intellij.lang.Language
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider
import org.jetbrains.fortran.FortranLanguage
class FortranLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getLanguage(): Language = FortranLanguage
override fun getCodeSample(settingsType: LanguageCodeStyleSettingsProvider.SettingsType): String
= when (settingsType) {
SettingsType.INDENT_SETTINGS -> INDENT_SAMPLE
SettingsType.SPACING_SETTINGS -> SPACING_SAMPLE
else /*SettingsType.BLANK_LINES_SETTINGS*/ -> BLANK_LINES_SAMPLE
}
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) {
when (settingsType) {
SettingsType.SPACING_SETTINGS -> {
consumer.showStandardOptions(
"SPACE_AROUND_ASSIGNMENT_OPERATORS",
"SPACE_AROUND_LOGICAL_OPERATORS",
"SPACE_AROUND_EQUALITY_OPERATORS",
"SPACE_AROUND_RELATIONAL_OPERATORS",
"SPACE_AROUND_ADDITIVE_OPERATORS",
"SPACE_AROUND_MULTIPLICATIVE_OPERATORS",
"SPACE_AROUND_UNARY_OPERATOR",
"SPACE_AFTER_COMMA",
"SPACE_BEFORE_COMMA",
"SPACE_BEFORE_COLON",
"SPACE_AFTER_COLON"
)
consumer.renameStandardOption("SPACE_AROUND_ASSIGNMENT_OPERATORS", "Space around assigment operators (=, =>)")
consumer.renameStandardOption("SPACE_AROUND_LOGICAL_OPERATORS", "Logical operators (.or., .and.)")
consumer.renameStandardOption("SPACE_AROUND_EQUALITY_OPERATORS", "Equality operators (==, .eq., ...)")
consumer.renameStandardOption("SPACE_AROUND_RELATIONAL_OPERATORS", "Relational operators (<, .lt., ...)")
consumer.renameStandardOption("SPACE_AROUND_MULTIPLICATIVE_OPERATORS", "Multiplicative operators (*, /)")
consumer.renameStandardOption("SPACE_AROUND_UNARY_OPERATOR", "Unary operators (+, -)")
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AROUND_NOT_OPERATOR", "Not operator (.not.)",
CodeStyleSettingsCustomizable.SPACES_AROUND_OPERATORS)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AROUND_POWER_OPERATOR", "Power operator (**)",
CodeStyleSettingsCustomizable.SPACES_AROUND_OPERATORS)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AROUND_EQUIVALENCE_OPERATOR", "Equivalence operators (.eqv., .neqv.)",
CodeStyleSettingsCustomizable.SPACES_AROUND_OPERATORS)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AROUND_CONCAT_OPERATOR", "Concatenation operator (//)",
CodeStyleSettingsCustomizable.SPACES_AROUND_OPERATORS)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AROUND_DEFINED_OPERATOR", "Defined operators",
CodeStyleSettingsCustomizable.SPACES_AROUND_OPERATORS)
consumer.moveStandardOption("SPACE_BEFORE_COLON", CodeStyleSettingsCustomizable.SPACES_OTHER)
consumer.moveStandardOption("SPACE_AFTER_COLON", CodeStyleSettingsCustomizable.SPACES_OTHER)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_BEFORE_DOUBLE_COLON", "Space before double-colon",
CodeStyleSettingsCustomizable.SPACES_OTHER)
consumer.showCustomOption(FortranCodeStyleSettings::class.java, "SPACE_AFTER_DOUBLE_COLON", "Space after double-colon",
CodeStyleSettingsCustomizable.SPACES_OTHER)
}
SettingsType.BLANK_LINES_SETTINGS -> {
consumer.showStandardOptions(
"KEEP_BLANK_LINES_IN_CODE",
"KEEP_BLANK_LINES_IN_DECLARATIONS"
)
consumer.renameStandardOption("KEEP_BLANK_LINES_IN_DECLARATIONS", "Between subprograms")
}
else -> {
}
}
}
override fun getIndentOptionsEditor(): IndentOptionsEditor = SmartIndentOptionsEditor()
override fun customizeDefaults(commonSettings: CommonCodeStyleSettings, indentOptions: CommonCodeStyleSettings.IndentOptions) {
commonSettings.KEEP_BLANK_LINES_IN_CODE = 1
commonSettings.BLOCK_COMMENT_AT_FIRST_COLUMN = false
}
private val INDENT_SAMPLE: String by lazy {
loadCodeSampleResource("codesamples/indents.f95")
}
private val BLANK_LINES_SAMPLE: String by lazy {
loadCodeSampleResource("codesamples/blanklines.f95")
}
private val SPACING_SAMPLE: String by lazy {
loadCodeSampleResource("codesamples/spacing.f95")
}
fun loadCodeSampleResource(resource: String): String {
val stream = javaClass.classLoader.getResourceAsStream(resource)
return StreamUtil.convertSeparators(StreamUtil.readText(stream, "UTF-8"))
}
} | apache-2.0 | 1a439d27c3aec2253eab56017de5baa4 | 53.213592 | 157 | 0.668637 | 5.212885 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/resolve/CargoTomlDependencyFeaturesReferenceProvider.kt | 3 | 1807 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.resolve
import com.intellij.psi.*
import com.intellij.util.ProcessingContext
import org.rust.toml.containingDependencyKey
import org.rust.toml.findDependencyTomlFile
import org.toml.lang.psi.TomlArray
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.ext.TomlLiteralKind
import org.toml.lang.psi.ext.kind
/**
* Consider `Cargo.toml`:
* ```
* [dependencies]
* foo = { version = "*", features = ["bar"] }
* #^ Provides a reference for "bar"
*
* [dependencies.foo]
* features = ["baz"]
* #^ Provides a reference for "baz"
* ```
*
* @see [org.rust.toml.completion.CargoTomlDependencyFeaturesCompletionProvider]
*/
class CargoTomlDependencyFeaturesReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
if (element !is TomlLiteral) return emptyArray()
return arrayOf(CargoTomlDependencyFeatureReference(element))
}
}
private class CargoTomlDependencyFeatureReference(element: TomlLiteral) : PsiPolyVariantReferenceBase<TomlLiteral>(element) {
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val literalValue = (element.kind as? TomlLiteralKind.String)?.value ?: return ResolveResult.EMPTY_ARRAY
val parentArray = element.parent as? TomlArray ?: return ResolveResult.EMPTY_ARRAY
val pkgName = parentArray.containingDependencyKey?.text ?: return ResolveResult.EMPTY_ARRAY
val depToml = findDependencyTomlFile(element, pkgName) ?: return ResolveResult.EMPTY_ARRAY
return depToml.resolveFeature(literalValue)
}
}
| mit | e034a603823dc1931880365b398b2590 | 37.446809 | 125 | 0.730493 | 4.281991 | false | false | false | false |
glung/DroidconFr | CounterCycle/app/src/main/java/com/glung/github/counter/cycle/ActivityDriver.kt | 1 | 1059 | package com.glung.github.counter.cycle
import android.app.Activity
import android.view.View
import com.jakewharton.rxbinding.view.RxView
import rx.Observable
data class ActivityIO(val observable: Observable<View>, val clickEvents: () -> Observable<Void>)
public fun makeActivityDriver(container: Activity): (view: Observable<View>) -> (Int) -> ActivityIO =
{
views ->
makeElementSelector(renderRootElement(views, container))
}
fun renderRootElement(views: Observable<View>, activity: Activity): Observable<View> =
views.doOnNext { view -> activity.setContentView(view) }
fun makeElementSelector(view: Observable<View>): (Int) -> ActivityIO =
{
id ->
ActivityIO(select(id, view), makeClickEventsSelector(select(id, view)))
}
private fun select(id: Int, views: Observable<View>) =
views.map { view -> view.findViewById(id) }
fun makeClickEventsSelector(view: Observable<View>): () -> Observable<Void> =
{ view.flatMap { RxView.clicks(it) }.share() }
| mit | f6e7490de410684a5574a8c49dca2a4c | 35.517241 | 101 | 0.680831 | 4.041985 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/ui/fragment/WorkFragment.kt | 2 | 2393 | package com.ddu.ui.fragment
import android.graphics.Color
import android.os.Bundle
import com.ddu.R
import com.ddu.icore.common.adapters.bindTextColor
import com.ddu.icore.ui.fragment.DefaultFragment
import kotlinx.android.synthetic.main.fragment_work.*
/**
* Created by yzbzz on 16/4/6.
*/
class WorkFragment : DefaultFragment() {
override fun getLayoutId(): Int {
return R.layout.fragment_work
}
override fun initView() {
setTitle(R.string.main_tab_work)
oiv_program_swift.setOnClickListener {
}
btn_get.setOnClickListener {
// SophixManager.getInstance().queryAndLoadNewPatch()
tv_html.isEnabled = false
}
tv_html.text = "LIMILIMILIMILIMILIMILIMILIMILIMILIMILIMILIMI"
tv_html.isClickable = true
tv_html.isFocusable = true
// tv_html.setTextColor( resources.getColorStateList(R.color.fragment_ui_navi_item_text_selector))
tv_html.bindTextColor(
resources.getColor(R.color.c_ff0000),
resources.getColor(R.color.c_4897fa),
Color.BLACK
)
1.toString()
}
fun ToDBC(input: String): String {
val c = input.toCharArray()
for (i in c.indices) {
if (c[i] == '\u3000') {
continue
}
if (c[i].toInt() == 12288) {
c[i] = 32.toChar()
continue
}
if (c[i].toInt() > 65280 && c[i].toInt() < 65375)
c[i] = (c[i].toInt() - 65248).toChar()
}
return String(c)
}
fun ToDBC1(input: String): String {
// 导致TextView异常换行的原因:安卓默认数字、字母不能为第一行以后每行的开头字符,因为数字、字母为半角字符
// 所以我们只需要将半角字符转换为全角字符即可
val c = input.toCharArray()
for (i in c.indices) {
if (c[i] == ' ') {
c[i] = '\u3000'
} else if (c[i] < '\u007f') {
c[i] = (c[i].toInt() + 65248).toChar()
}
}
return String(c)
}
companion object {
fun newInstance(): WorkFragment {
val fragment = WorkFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 2ec8484be87ab5fbc3cf701aaf2bb0af | 25.869048 | 105 | 0.542313 | 3.599681 | false | false | false | false |
jeremymailen/kotlinter-gradle | src/main/kotlin/org/jmailen/gradle/kotlinter/pluginapplier/AndroidSourceSetApplier.kt | 1 | 1502 | @file:Suppress("deprecation") // https://issuetracker.google.com/issues/170650362
package org.jmailen.gradle.kotlinter.pluginapplier
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.api.AndroidSourceSet
import org.gradle.api.Project
import org.gradle.api.file.FileTree
import org.jmailen.gradle.kotlinter.SourceSetAction
import org.jmailen.gradle.kotlinter.SourceSetApplier
import org.jmailen.gradle.kotlinter.id
internal object AndroidSourceSetApplier : SourceSetApplier {
override fun applyToAll(project: Project, action: SourceSetAction) {
val android = project.extensions.findByName("android") as? BaseExtension ?: return
android.sourceSets.configureEach { sourceSet ->
val id = sourceSet.name.id
action(id, project.provider { getKotlinFiles(project, sourceSet) })
}
}
private fun getKotlinFiles(project: Project, sourceSet: AndroidSourceSet): FileTree? {
val javaSources = sourceSet.java.srcDirs
// detect Kotlin source paths supported by AGP 7 and later
val kotlinSources = runCatching { (sourceSet.kotlin as? com.android.build.gradle.api.AndroidSourceDirectorySet)?.srcDirs }
.getOrNull()
.orEmpty()
val emptyFileTree = project.files().asFileTree
return (javaSources + kotlinSources)
.map { dir -> project.fileTree(dir) { it.include("**/*.kt") } }
.fold(emptyFileTree) { merged, tree -> merged + tree }
}
}
| apache-2.0 | 2e70e4bb84aaf4880895d513129f725b | 40.722222 | 130 | 0.711718 | 4.483582 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/action/GenerateOverwriteAction.kt | 1 | 5612 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.findMethods
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceMethod
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MIXIN_OVERWRITE_FALLBACK
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.realName
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiGenerationInfo
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.util.MemberChooser
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.codeStyle.CodeStyleManager
class GenerateOverwriteAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val methods = findMethods(psiClass, allowClinit = false)
?.map { classAndMethodNode ->
PsiMethodMember(
classAndMethodNode.method.findOrConstructSourceMethod(
classAndMethodNode.clazz,
project,
canDecompile = true
)
)
}?.toTypedArray() ?: return
if (methods.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No methods to overwrite have been found")
return
}
val chooser = MemberChooser(methods, false, true, project)
chooser.title = "Select Methods to Overwrite"
chooser.setCopyJavadocVisible(false)
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
val requiredMembers = LinkedHashSet<PsiMember>()
runWriteAction {
val newMethods = elements.map {
val method = it.element
val sourceClass = method.containingClass
val codeBlock = method.body
val newMethod: PsiMethod
if (sourceClass != null && codeBlock != null) {
// Source of method is available
// Collect all references to potential @Shadow members
requiredMembers.addAll(collectRequiredMembers(codeBlock, sourceClass))
}
// Create temporary (dummy) method
var tmpMethod =
JavaPsiFacade.getElementFactory(project).createMethod(method.name, method.returnType!!, psiClass)
// Replace temporary method with a copy of the original method
tmpMethod = tmpMethod.replace(method) as PsiMethod
// Remove Javadocs
OverrideImplementUtil.deleteDocComment(tmpMethod)
// Reformat the code with the project settings
newMethod = CodeStyleManager.getInstance(project).reformat(tmpMethod) as PsiMethod
if (codeBlock == null) {
// Generate fallback method body if source is not available
OverrideImplementUtil.setupMethodBody(
newMethod,
method,
psiClass,
FileTemplateManager.getInstance(project).getCodeTemplate(MIXIN_OVERWRITE_FALLBACK)
)
}
// TODO: Automatically add Javadoc comment for @Overwrite? - yes please
// Add @Overwrite annotation
val annotation = newMethod.modifierList.addAnnotation(MixinConstants.Annotations.OVERWRITE)
val realName = method.realName
if (realName != null && realName != method.name) {
val elementFactory = JavaPsiFacade.getElementFactory(project)
val value = elementFactory.createExpressionFromText(
"\"${StringUtil.escapeStringCharacters(realName)}\"",
annotation
)
annotation.setDeclaredAttributeValue("aliases", value)
}
PsiGenerationInfo(newMethod)
}
// Insert new methods
GenerateMembersUtil.insertMembersAtOffset(file, offset, newMethods)
// Select first element in editor
.first().positionCaret(editor, true)
}
if (!psiClass.isValid) {
return
}
// Generate needed shadows
val newShadows = createShadowMembers(project, psiClass, filterNewShadows(requiredMembers, psiClass))
disableAnnotationWrapping(project) {
runWriteAction {
// Insert shadows
insertShadows(psiClass, newShadows)
}
}
}
}
| mit | 875794fe928f963f4c07048c2acf5778 | 38.801418 | 117 | 0.635246 | 5.529064 | false | false | false | false |
ligi/SCR | android/src/main/java/org/ligi/scr/MainActivity.kt | 1 | 11209 | package org.ligi.scr
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.Menu
import android.view.MenuItem
import info.metadude.java.library.halfnarp.ApiModule
import info.metadude.java.library.halfnarp.model.CreateTalkPreferencesSuccessResponse
import info.metadude.java.library.halfnarp.model.GetTalksResponse
import info.metadude.java.library.halfnarp.model.TalkIds
import info.metadude.java.library.halfnarp.model.UpdateTalkPreferencesSuccessResponse
import kotlinx.android.synthetic.main.activity_main.*
import net.steamcrafted.loadtoast.LoadToast
import org.ligi.kaxt.startActivityFromClass
import org.ligi.kaxt.startActivityFromURL
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private var adapter: EventViewHolderAdapter? = null
var currentTab = 1
var groups: Map<Int, MutableList<GetTalksResponse>>? = null
inner class MyItemTouchHelper : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) =
makeMovementFlags(0, when (currentTab) {
0 -> ItemTouchHelper.RIGHT
2 -> ItemTouchHelper.LEFT
else -> ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
})
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?)
= false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val offset = when (direction) {
ItemTouchHelper.RIGHT -> 1
else -> -1
}
move(offset, viewHolder.adapterPosition)
}
}
private fun move(offset: Int, index: Int) {
val elementAt = adapter?.talkResponses?.elementAt(index)
adapter?.talkResponses?.removeAt(index)
groups?.get(currentTab)?.removeAt(index)
groups?.get(currentTab + offset).let {
it?.add(elementAt!!)
}
adapter?.notifyItemRemoved(index)
adapter?.notifyDataSetChanged()
setTabNames()
State.noIDs.clear()
State.noIDs.addAll(groups!!.get(0)!!.map { it.eventId.toString() })
State.yesIDs.clear()
State.yesIDs.addAll(groups!!.get(2)!!.map { it.eventId.toString() })
setStateChanged()
}
fun setTabNames() {
noTab.text = "NO (" + groups!![0]!!.size + ")"
maybeTab.text = "MAYBE (" + groups!![1]!!.size + ")"
yesTab.text = "YES (" + groups!![2]!!.size + ")"
}
val noTab by lazy { tabLayout.newTab().setTag(0) }
val yesTab by lazy { tabLayout.newTab().setTag(2) }
val maybeTab by lazy { tabLayout.newTab().setTag(1) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val layoutManager = StaggeredGridLayoutManager(resources.getInteger(R.integer.rows), OrientationHelper.VERTICAL)
trackRecycler.layoutManager = layoutManager
collapse_toolbar.isTitleEnabled = false
tabLayout.addTab(noTab)
tabLayout.addTab(maybeTab)
tabLayout.addTab(yesTab)
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabSelected(tab: TabLayout.Tab) {
currentTab = tab.tag as Int
setCurrentAdapter()
}
})
maybeTab.select()
fab.setOnClickListener {
//submitVotes()
transferToSchedule()
}
val itemTouchHelper = ItemTouchHelper(MyItemTouchHelper())
itemTouchHelper.attachToRecyclerView(trackRecycler)
loadData()
}
private fun submitVotes() {
val uuidOrNull = State.lastUUID
setStateSaved()
if (uuidOrNull == null) {
val loadToast = LoadToast(this).setText("Initial upload").show()
Handler().postDelayed({
ApiModule.getTalkPreferencesService().createTalkPreferences(getTalkIds(2)).enqueue(object : Callback<CreateTalkPreferencesSuccessResponse> {
override fun onResponse(call: Call<CreateTalkPreferencesSuccessResponse>, response: Response<CreateTalkPreferencesSuccessResponse>) {
State.lastUUID = response.body().uid
loadToast.success()
}
override fun onFailure(call: Call<CreateTalkPreferencesSuccessResponse>, t: Throwable?) {
loadToast.error()
setStateChanged()
}
})
}, 1500)
} else {
val loadToast = LoadToast(this).setText("Uploading new selection").show()
Handler().postDelayed({
ApiModule.getTalkPreferencesService().updateTalkPreferences(uuidOrNull, getTalkIds(2)).enqueue(object : Callback<UpdateTalkPreferencesSuccessResponse> {
override fun onResponse(call: Call<UpdateTalkPreferencesSuccessResponse>?, response: Response<UpdateTalkPreferencesSuccessResponse>?) {
loadToast.success()
}
override fun onFailure(call: Call<UpdateTalkPreferencesSuccessResponse>?, t: Throwable?) {
loadToast.error()
setStateChanged()
}
})
}, 1500)
}
}
private fun transferToSchedule() {
val sendIntent = Intent()
val res = getTalkIds(2).sortedTalkIds.joinToString(",")
sendIntent.putExtra("CSV", res)
sendIntent.setClassName("org.ligi.fahrplan", "org.ligi.fahrplan.TalkPrefsImportActivity")
try {
startActivity(sendIntent)
} catch (e: ActivityNotFoundException) {
AlertDialog.Builder(this).setMessage("Please install the latest version of 33c3 Fahrplan")
.setPositiveButton(android.R.string.ok, { dialogInterface: DialogInterface, i: Int ->
startActivityFromURL("https://play.google.com/store/apps/details?id=org.ligi.fahrplan")
})
.setNegativeButton(android.R.string.cancel, { dialogInterface: DialogInterface, i: Int ->
})
.show()
}
}
private fun getTalkIds(i: Int) = TalkIds().apply {
add(groups!![i]!!.map { it.eventId })
}
override fun onResume() {
super.onResume()
try {
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
trackRecycler.setBackgroundResource(R.drawable.bg_src)
} else {
val matrix = Matrix()
matrix.postRotate(90f)
val source = BitmapFactory.decodeResource(resources, R.drawable.bg_src)
val bitmap = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
ViewCompat.setBackground(trackRecycler, BitmapDrawable(resources, bitmap))
}
} catch (e: Exception) {
e.printStackTrace()
// form follows function
}
trackRecycler.layoutManager.scrollToPosition(State.lastPos)
if (State.lastUpdateSaved) {
fab.hide()
} else {
fab.show()
}
}
override fun onPause() {
State.lastPos = (trackRecycler.layoutManager as StaggeredGridLayoutManager).findFirstVisibleItemPositions(null)[0]
super.onPause()
}
private fun loadData() {
val service = ApiModule.getTalkPreferencesService()
service.talks.enqueue(object : DefaultRetrofitCallback<List<GetTalksResponse>>(true, this) {
override fun onResponse(call: Call<List<GetTalksResponse>>?, response: Response<List<GetTalksResponse>>) {
val body = response.body()
val _groups = body.groupBy {
when {
State.yesIDs.contains(it.eventId.toString()) -> 2
State.noIDs.contains(it.eventId.toString()) -> 0
else -> 1
}
}
groups = (0..2).associate { it to if (_groups.containsKey(it)) _groups[it]!!.toMutableList() else mutableListOf() }
setCurrentAdapter()
setTabNames()
AlertDialog.Builder(this@MainActivity).setMessage("The Halfnarp is over - you can now transfer your selection to the schedule app")
.setPositiveButton("transfer",{ dialogInterface: DialogInterface, i: Int ->
transferToSchedule()
})
.setNegativeButton(android.R.string.cancel,{ dialogInterface: DialogInterface, i: Int -> })
.show()
}
})
}
private fun setCurrentAdapter() {
if (groups != null)
groups?.get(currentTab).let {
val newList = it ?: mutableListOf()
if (adapter == null) {
adapter = EventViewHolderAdapter(newList, { offset: Int, index: Int -> move(offset, index) })
trackRecycler.adapter = adapter
} else {
(adapter as EventViewHolderAdapter).apply {
talkResponses.clear()
talkResponses.addAll(newList)
notifyDataSetChanged()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_help -> this.startActivityFromClass(ListActivity::class.java)
}
return super.onOptionsItemSelected(item)
}
private fun setStateChanged() {
fab.show()
State.lastUpdateSaved = false
}
private fun setStateSaved() {
fab.hide()
State.lastUpdateSaved = true
}
} | gpl-3.0 | ac104e7a35a9274d154b748a874e5921 | 35.633987 | 168 | 0.613792 | 5.081142 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/history/HistoryManager.kt | 1 | 13064 | package org.jetbrains.haskell.debugger.history
import org.jetbrains.haskell.debugger.actions.SwitchableAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.execution.ui.RunnerLayoutUi
import com.intellij.openapi.actionSystem.DefaultActionGroup
import org.jetbrains.haskell.debugger.highlighting.HsExecutionPointHighlighter
import com.intellij.ui.AppUIUtil
import org.jetbrains.haskell.debugger.frames.HsStackFrame
import java.util.ArrayList
import org.jetbrains.haskell.debugger.frames.HsHistoryFrame
import org.jetbrains.haskell.debugger.protocol.CommandCallback
import org.jetbrains.haskell.debugger.parser.MoveHistResult
import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo
import org.jetbrains.haskell.debugger.parser.HsHistoryFrameInfo
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import com.intellij.icons.AllIcons.Actions
import java.util.Deque
import java.util.ArrayDeque
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants
import org.jetbrains.haskell.debugger.utils.SyncObject
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.XDebugSession
/**
* Created by vlad on 8/5/14.
*/
public class HistoryManager(private val debugSession : XDebugSession,
private val debugProcess: HaskellDebugProcess) {
public val HISTORY_SIZE: Int = 20
public class StackState(public val historyIndex: Int,
public val realHistIndex: Int,
public val allFramesCollected: Boolean,
public val historyFrames: ArrayList<HsHistoryFrame>,
public val historyFramesLines: ArrayList<*>)
private val historyStack: HsHistoryStack = HsHistoryStack(debugProcess)
private var historyPanel: HistoryTab? = null;
private val historyHighlighter = HsExecutionPointHighlighter(debugProcess.getSession()!!.getProject(),
HsExecutionPointHighlighter.HighlighterType.HISTORY)
private val backAction: SwitchableAction = object : SwitchableAction("back", "Move back along history", Actions.Back) {
override fun actionPerformed(e: AnActionEvent?) {
enabled = false
forwardAction.enabled = false
update(e)
forwardAction.update(e)
if (historyStack.historyIndex - 1 > HISTORY_SIZE) {
historyStack.moveTo(historyStack.historyIndex + 1)
} else {
historyPanel?.shiftBack()
}
}
}
private val forwardAction: SwitchableAction = object : SwitchableAction("forward", "Move forward along history",
Actions.Forward) {
override fun actionPerformed(e: AnActionEvent?) {
enabled = false
backAction.enabled = false
update(e)
backAction.update(e)
if (historyStack.historyIndex > HISTORY_SIZE) {
historyStack.moveTo(historyStack.historyIndex - 1)
} else {
historyPanel?.shiftForward()
}
}
}
public fun initHistoryTab(debugSession : XDebugSessionImpl) {
historyPanel = HistoryTab(debugSession, debugProcess, this)
}
public fun withRealFrameUpdate(finalCallback: ((MoveHistResult?) -> Unit)?): Unit =
historyStack.withRealFrameUpdate(finalCallback)
public fun indexSelected(index: Int): Unit = historyStack.moveTo(index)
public fun setHistoryFramesInfo(initial: HsHistoryFrameInfo, others: ArrayList<HsHistoryFrameInfo>, full: Boolean) {
AppUIUtil.invokeLaterIfProjectAlive(debugProcess.getSession()!!.getProject(), Runnable({ ->
historyPanel!!.addHistoryLine(initial.toString())
for (info in others) {
historyPanel!!.addHistoryLine(info.toString())
}
if (!full) {
historyPanel!!.addHistoryLine("...")
}
}))
}
public fun registerContent(ui: RunnerLayoutUi) {
initHistoryTab(debugSession as XDebugSessionImpl)
val context = ui.createContent("history", historyPanel!!.getComponent(), "History", null, null)
context.setCloseable(false)
ui.addContent(context)
ui.getOptions().setToFocus(context, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION)
}
public fun registerActions(topToolbar: DefaultActionGroup) {
topToolbar.addSeparator()
topToolbar.add(backAction)
topToolbar.add(forwardAction)
}
public fun historyChanged(hasNext: Boolean, hasPrevious: Boolean, stackFrame: HsStackFrame?) {
AppUIUtil.invokeLaterIfProjectAlive(debugProcess.getSession()!!.getProject(), Runnable({ ->
backAction.enabled = hasPrevious
forwardAction.enabled = hasNext
historyPanel!!.stackChanged(stackFrame)
if (stackFrame != null) {
historyHighlighter.show(stackFrame, false, null)
} else {
historyHighlighter.hide()
}
}))
}
public fun clean(): Unit = historyChanged(false, false, null)
public fun historyFrameAppeared(frame: HsHistoryFrame): Unit = historyStack.addFrame(frame)
public fun resetHistoryStack(): Unit = historyStack.clear()
public fun markHistoryFramesAsObsolete(): Unit = historyStack.markFramesAsObsolete()
// save/load state managing
private val states: Deque<StackState> = ArrayDeque()
public fun saveState(): Unit = states.addLast(historyStack.save())
public fun loadState(): Unit = AppUIUtil.invokeLaterIfProjectAlive(debugProcess.getSession()!!.getProject(), {
historyStack.loadFrom(states.pollLast()!!)
})
public fun hasSavedStates(): Boolean = !states.isEmpty()
private inner class HsHistoryStack(private val debugProcess: HaskellDebugProcess) {
public var historyIndex: Int = 0
private set
private var realHistIndex: Int = 0
private var allFramesCollected = false
private val historyFrames: java.util.ArrayList<HsHistoryFrame> = ArrayList()
public fun addFrame(frame: HsHistoryFrame) {
historyFrames.add(frame)
}
public fun clear() {
historyIndex = 0
realHistIndex = 0
allFramesCollected = false
historyFrames.clear()
updateHistory()
}
public fun hasNext(): Boolean = historyIndex > 0
public fun hasPrevious(): Boolean = !allFramesCollected || historyIndex + 1 < historyFrames.size()
public fun currentFrame(): HsHistoryFrame? =
if (historyIndex < historyFrames.size()) historyFrames.get(historyIndex) else null
public fun moveTo(index: Int) {
if (index == -1 || index == historyIndex) {
} else if (index < historyIndex) {
val it = historyIndex - index
for (i in 1..it) {
moveForward()
}
} else {
val it = index - historyIndex
for (i in 1..it) {
moveBack()
}
}
updateHistory()
}
private fun moveForward() {
if (historyIndex > 0) {
if (historyFrames[historyIndex - 1].obsolete) {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.forward(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
--historyIndex
--realHistIndex
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
} else {
--historyIndex
}
}
}
private fun moveBack() {
if (historyIndex + 1 < historyFrames.size()) {
if (historyFrames[historyIndex + 1].obsolete) {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.back(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
++historyIndex
++realHistIndex
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
} else {
++historyIndex
}
} else if (allFramesCollected) {
} else {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.back(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
val frame = HsHistoryFrame(debugProcess.debugger, HsStackFrameInfo(result.filePosition, result.bindingList.list, null))
addFrame(frame)
++historyIndex
++realHistIndex
} else {
allFramesCollected = true
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
}
}
private fun updateHistory() = historyChanged(hasNext(), hasPrevious(), currentFrame())
public fun markFramesAsObsolete() {
for (frame in historyFrames) {
frame.obsolete = true
}
}
public fun withRealFrameUpdate(finalCallback: ((MoveHistResult?) -> Unit)?) {
if (realHistIndex == historyIndex) {
finalCallback?.invoke(null)
return
}
if (realHistIndex < historyIndex) {
debugProcess.debugger.back(SequentialBackCallback(historyIndex - realHistIndex, finalCallback))
} else {
debugProcess.debugger.forward(SequentialForwardCallback(realHistIndex - historyIndex, finalCallback))
}
}
public fun save(): StackState = StackState(historyIndex, realHistIndex, allFramesCollected, ArrayList(historyFrames),
historyPanel!!.getHistoryFramesModel().toArray().toArrayList())
public fun loadFrom(state: StackState) {
historyIndex = state.historyIndex
realHistIndex = state.realHistIndex
allFramesCollected = state.allFramesCollected
historyFrames.clear()
historyFrames.addAll(state.historyFrames)
historyPanel!!.getHistoryFramesModel().removeAllElements()
for (elem in state.historyFramesLines) {
historyPanel!!.addHistoryLine(elem.toString())
}
}
private inner class SequentialBackCallback(var toGo: Int,
val finalCallback: ((MoveHistResult?) -> Unit)?) : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
--toGo
++realHistIndex
if (toGo == 0 || result == null) {
finalCallback?.invoke(null)
} else {
debugProcess.debugger.back(this)
}
}
}
private inner class SequentialForwardCallback(var toGo: Int,
val finalCallback: ((MoveHistResult?) -> Unit)?) : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
--toGo
--realHistIndex
if (toGo == 0 || result == null) {
finalCallback?.invoke(null)
} else {
debugProcess.debugger.forward(this)
}
}
}
}
}
| apache-2.0 | 343899c64a61f5d145e5ceefc13bf082 | 40.473016 | 151 | 0.563457 | 5.507589 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/mangacatalog/readnoblessemanhwaonline/src/ReadNoblesseManhwaOnline.kt | 1 | 1938 | package eu.kanade.tachiyomi.extension.en.readnoblessemanhwaonline
import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Request
import rx.Observable
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
class ReadNoblesseManhwaOnline : MangaCatalog("Read Noblesse Manhwa Online", "https://ww2.readnoblesse.com", "en") {
override val sourceList = listOf(
Pair("Noblesse", "$baseUrl/manga/noblesse/"),
Pair("Rai’s Adventure", "$baseUrl/manga/noblesse-rais-adventure/"),
Pair("NOBLESSE S", "$baseUrl/manga/noblesse-s/"),
Pair("Ability", "$baseUrl/manga/ability/"),
).sortedBy { it.first }.distinctBy { it.second }
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
description = document.select("div.flex > div.py-2 > div:not(:first-child)").text()
title = document.select(".container h1").text()
thumbnail_url = document.select("img.rounded-full").attr("src")
}
override fun chapterListSelector(): String = "div.w-full > div > div.flex"
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
val name1 = element.select(".flex-col > a:not(.text-xs)").text()
val name2 = element.select(".text-xs:not(a)").text()
if (name2 == ""){
name = name1
} else {
name = "$name1 - $name2"
}
url = element.select(".flex-col > a:not(.text-xs)").attr("abs:href")
date_upload = System.currentTimeMillis()
}
}
| apache-2.0 | 762b36d3d1cdec88bd7e255f6f307f77 | 44.023256 | 116 | 0.694731 | 3.715931 | false | false | false | false |
JavaEden/Orchid | OrchidCore/src/main/kotlin/com/eden/orchid/api/server/OrchidServer.kt | 2 | 785 | package com.eden.orchid.api.server
import com.eden.orchid.api.OrchidContext
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
@JvmSuppressWildcards
class OrchidServer
@Inject
constructor(
val controllers: Set<OrchidController>,
val fileController: OrchidFileController
) {
var httpServerPort = 0
var websocketPort = 0
var server: OrchidWebserver? = null
var websocket: OrchidWebsocket? = null
@Throws(IOException::class)
fun start(context: OrchidContext, port: Int) {
server = OrchidWebserver(context, controllers, fileController, port)
httpServerPort = server!!.listeningPort
websocket = OrchidWebsocket(context, port)
websocketPort = websocket!!.listeningPort
}
}
| lgpl-3.0 | a24610e39010062fc52a38664ab24743 | 24.322581 | 76 | 0.738854 | 4.361111 | false | false | false | false |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/component/GDLinearProgressIndicator.kt | 1 | 2461 | //============================================================================
// Name : GDLinearProgressIndicator.kt
// Author : Matthias Gruenewald
// Copyright : Copyright 2010-2021 Matthias Gruenewald
//
// This file is part of GeoDiscoverer.
//
// GeoDiscoverer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>.
//
//============================================================================
package com.untouchableapps.android.geodiscoverer.ui.component
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.modifier.modifierLocalConsumer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.untouchableapps.android.geodiscoverer.ui.theme.Material2Theme
// Missing component in material3
// Replace later when eventually available
@Composable
fun GDLinearProgressIndicator(
/*@FloatRange(from = 0.0, to = 1.0)*/
progress: Float,
modifier: Modifier = Modifier
) {
Material2Theme {
LinearProgressIndicator(
progress = progress,
modifier = modifier
)
}
}
// Missing component in material3
// Replace later when eventually available
@Composable
fun GDLinearProgressIndicator(
modifier: Modifier = Modifier
) {
Material2Theme {
LinearProgressIndicator(
modifier = modifier
)
}
}
| gpl-3.0 | 1901d7fba54ef3aa2e92d8bd68b0c424 | 34.157143 | 78 | 0.734254 | 4.410394 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/TimeRangePickerDialog.kt | 1 | 5260 | package de.westnordost.streetcomplete.quests.opening_hours
import android.content.Context
import android.content.DialogInterface
import com.google.android.material.tabs.TabLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TimePicker
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.opening_hours.model.TimeRange
class TimeRangePickerDialog(
context: Context,
startTimeLabel: CharSequence,
endTimeLabel: CharSequence,
timeRange: TimeRange?,
is24HourView: Boolean,
private val callback: (TimeRange) -> Unit
) : AlertDialog(context, R.style.Theme_Bubble_Dialog) {
private val startPicker: TimePicker
private val endPicker: TimePicker
private val endPickerContainer: ViewGroup
private val viewPager: ViewPager
private val tabLayout: TabLayout
private val openEndCheckbox: CheckBox
private val minutesStart get() = startPicker.currentHour * 60 + startPicker.currentMinute
private val minutesEnd get() = endPicker.currentHour * 60 + endPicker.currentMinute
init {
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_time_range_picker, null)
setView(view)
setButton(
DialogInterface.BUTTON_POSITIVE,
context.getString(R.string.quest_openingHours_timeSelect_next),
null as DialogInterface.OnClickListener?
)
setButton(
DialogInterface.BUTTON_NEGATIVE,
context.getString(android.R.string.cancel),
null as DialogInterface.OnClickListener?
)
startPicker = inflater.inflate(R.layout.time_range_picker_start_picker, null) as TimePicker
startPicker.setIs24HourView(is24HourView)
endPickerContainer = inflater.inflate(R.layout.time_range_picker_end_picker, null) as ViewGroup
openEndCheckbox = endPickerContainer.findViewById(R.id.checkBox)
endPicker = endPickerContainer.findViewById(R.id.picker)
endPicker.setIs24HourView(is24HourView)
if (timeRange != null) {
startPicker.currentHour = timeRange.start / 60
startPicker.currentMinute = timeRange.start % 60
endPicker.currentHour = timeRange.end / 60
endPicker.currentMinute = timeRange.end % 60
openEndCheckbox.isChecked = timeRange.isOpenEnded
}
viewPager = view.findViewById(R.id.viewPager)
viewPager.adapter = CustomAdapter(startTimeLabel, endTimeLabel)
tabLayout = view.findViewById(R.id.tabLayout)
tabLayout.setupWithViewPager(viewPager)
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) { setCurrentTab(tab.position) }
override fun onTabUnselected(tab: TabLayout.Tab) { }
override fun onTabReselected(tab: TabLayout.Tab) { }
})
}
private fun setCurrentTab(position: Int) {
viewPager.currentItem = position
val buttonResId = if (position == END_TIME_TAB) android.R.string.ok else R.string.quest_openingHours_timeSelect_next
getButton(DialogInterface.BUTTON_POSITIVE).setText(buttonResId)
}
private inner class CustomAdapter(startTimeLabel: CharSequence, endTimeLabel: CharSequence) :
PagerAdapter() {
private val labels: Array<CharSequence> = arrayOf(startTimeLabel, endTimeLabel)
override fun getCount() = labels.size
override fun isViewFromObject(view: View, obj: Any) =
when(obj) {
START_TIME_TAB -> view === startPicker
END_TIME_TAB -> view === endPickerContainer
else -> false
}
override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
when(position) {
START_TIME_TAB -> container.removeView(startPicker)
END_TIME_TAB -> container.removeView(endPickerContainer)
}
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
when(position) {
START_TIME_TAB -> container.addView(startPicker)
END_TIME_TAB -> container.addView(endPickerContainer)
}
return position
}
override fun getPageTitle(position: Int) = labels[position]
}
override fun show() {
super.show()
// to override the default OK=dismiss() behavior
getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener {
when (tabLayout.selectedTabPosition) {
START_TIME_TAB -> setCurrentTab(END_TIME_TAB)
END_TIME_TAB -> applyAndDismiss()
}
}
}
private fun applyAndDismiss() {
callback(TimeRange(minutesStart, minutesEnd, openEndCheckbox.isChecked))
dismiss()
}
companion object {
private const val START_TIME_TAB = 0
private const val END_TIME_TAB = 1
}
}
| gpl-3.0 | a923ad0ec9328b3ebc8a62598b7078d0 | 36.042254 | 124 | 0.675095 | 4.696429 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2169.kt | 1 | 441 | package leetcode
/**
* https://leetcode.com/problems/count-operations-to-obtain-zero/
*/
class Problem2169 {
fun countOperations(num1: Int, num2: Int): Int {
var answer = 0
var n1 = num1
var n2 = num2
while (n1 > 0 && n2 > 0) {
if (n1 >= n2) {
n1 -= n2
} else {
n2 -= n1
}
answer++
}
return answer
}
}
| mit | b942827126b90e9d34f80eff203abba2 | 20 | 65 | 0.435374 | 3.528 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/building_type/AddBuildingType.kt | 1 | 1746 | package de.westnordost.streetcomplete.quests.building_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
class AddBuildingType : OsmFilterQuestType<BuildingType>() {
// in the case of man_made, historic, military and power, these tags already contain
// information about the purpose of the building, so no need to force asking it
// same goes (more or less) for tourism, amenity, leisure. See #1854, #1891
override val elementFilter = """
ways, relations with building = yes
and !man_made
and !historic
and !military
and !power
and !tourism
and !attraction
and !amenity
and !leisure
and location != underground
and abandoned != yes
and abandoned != building
and abandoned:building != yes
and ruins != yes and ruined != yes
"""
override val commitMessage = "Add building types"
override val wikiLink = "Key:building"
override val icon = R.drawable.ic_quest_building
override fun getTitle(tags: Map<String, String>) = R.string.quest_buildingType_title
override fun createForm() = AddBuildingTypeForm()
override fun applyAnswerTo(answer: BuildingType, changes: StringMapChangesBuilder) {
if (answer.osmKey == "man_made") {
changes.delete("building")
changes.add("man_made", answer.osmValue)
} else if (answer.osmKey != "building") {
changes.addOrModify(answer.osmKey, answer.osmValue)
} else {
changes.modify("building", answer.osmValue)
}
}
}
| gpl-3.0 | 4e95337e340f1a85195e3c99ee851268 | 36.956522 | 88 | 0.664376 | 4.60686 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/trending/TrendingActivity.kt | 1 | 2070 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.trending
import android.content.Context
import android.content.Intent
import android.os.Bundle
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.base.BaseDrawerActivity
import kotlinx.android.synthetic.main.base_activity.*
import kotlinx.android.synthetic.main.base_activity_drawer.*
/**
* Created by giulio on 18/05/2017.
*/
class TrendingActivity : BaseDrawerActivity() {
private val TRENDING_FRAGMENT_TAG = "TRENDING_FRAGMENT_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
layoutInflater.inflate(R.layout.trending_activity, content_frame)
var trendingFragment: TrendingFragment? = supportFragmentManager.findFragmentByTag(TRENDING_FRAGMENT_TAG) as TrendingFragment?
if (trendingFragment == null) {
trendingFragment = TrendingFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.trending_activity_frame, trendingFragment, TRENDING_FRAGMENT_TAG)
.commit()
}
}
override fun onResume() {
super.onResume()
nav_view.menu.getItem(4).isChecked = true
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(0,0)
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, TrendingActivity::class.java)
}
}
} | apache-2.0 | e86268692e9614c517b04d9bac0e122e | 31.359375 | 134 | 0.699034 | 4.549451 | false | false | false | false |
apollostack/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/introspection/schema_to_introspection.kt | 1 | 7685 | package com.apollographql.apollo3.compiler.introspection
import com.apollographql.apollo3.api.BooleanExpression
import com.apollographql.apollo3.compiler.introspection.IntrospectionSchema
import com.apollographql.apollo3.graphql.ast.*
private class IntrospectionSchemaBuilder(private val schema: Schema) {
private val typeDefinitions = schema.typeDefinitions
fun toIntrospectionSchema(): IntrospectionSchema {
return IntrospectionSchema(
queryType = schema.queryTypeDefinition.name,
mutationType = schema.mutationTypeDefinition?.name,
subscriptionType = schema.subscriptionTypeDefinition?.name,
types = typeDefinitions.values.map {
it.name to when (it) {
is GQLObjectTypeDefinition -> it.toSchemaType()
is GQLInputObjectTypeDefinition -> it.toSchemaType()
is GQLInterfaceTypeDefinition -> it.toSchemaType()
is GQLScalarTypeDefinition -> it.toSchemaType()
is GQLEnumTypeDefinition -> it.toSchemaType()
is GQLUnionTypeDefinition -> it.toSchemaType()
}
}.toMap()
)
}
private fun GQLObjectTypeDefinition.toSchemaType(): IntrospectionSchema.Type.Object {
return IntrospectionSchema.Type.Object(
name = name,
description = description,
fields = fields.map { it.toSchemaField() }
)
}
private fun GQLFieldDefinition.toSchemaField(): IntrospectionSchema.Field {
val deprecationReason = directives.findDeprecationReason()
return IntrospectionSchema.Field(
name = name,
description = description,
isDeprecated = deprecationReason != null,
deprecationReason = deprecationReason,
type = type.toSchemaType(schema),
args = arguments.map { it.toSchemaArgument() }
)
}
private fun GQLDocument.typeDefinition(name: String): GQLTypeDefinition? {
return definitions.filterIsInstance<GQLTypeDefinition>().firstOrNull { it.name == name }
}
private fun GQLDocument.rootOperationTypeName(operationType: String): String? {
val schemaDefinition = definitions.filterIsInstance<GQLSchemaDefinition>()
.firstOrNull()
if (schemaDefinition == null) {
// 3.3.1
// No schema definition, look for an object type named after the operationType
// i.e. Query, Mutation, ...
return definitions.filterIsInstance<GQLObjectTypeDefinition>()
.firstOrNull { it.name == operationType.capitalize() }
?.name
}
val namedType = schemaDefinition.rootOperationTypeDefinitions.firstOrNull {
it.operationType == operationType
}?.namedType
return namedType
}
private fun GQLInputValueDefinition.toSchemaArgument(): IntrospectionSchema.Field.Argument {
val deprecationReason = directives.findDeprecationReason()
return IntrospectionSchema.Field.Argument(
name = name,
description = description,
isDeprecated = deprecationReason != null,
deprecationReason = deprecationReason,
type = type.toSchemaType(schema),
defaultValue = defaultValue?.toKotlinValue(true) // TODO: difference between null and absent
)
}
private fun GQLInputObjectTypeDefinition.toSchemaType(): IntrospectionSchema.Type.InputObject {
return IntrospectionSchema.Type.InputObject(
name = name,
description = description,
inputFields = inputFields.map { it.toSchemaInputField() }
)
}
private fun GQLInputValueDefinition.toSchemaInputField(): IntrospectionSchema.InputField {
val deprecationReason = directives.findDeprecationReason()
return IntrospectionSchema.InputField(
name = name,
description = description,
isDeprecated = deprecationReason != null,
deprecationReason = deprecationReason,
type = type.toSchemaType(schema),
defaultValue = defaultValue?.toKotlinValue(true),
)
}
private fun GQLInterfaceTypeDefinition.toSchemaType(): IntrospectionSchema.Type.Interface {
return IntrospectionSchema.Type.Interface(
name = name,
description = description,
fields = fields.map { it.toSchemaField() },
possibleTypes = typeDefinitions.values
.filter { typeDefinition ->
typeDefinition is GQLObjectTypeDefinition && typeDefinition.implementsInterfaces.contains(name)
}
.map { typeDefinition ->
IntrospectionSchema.TypeRef(
kind = IntrospectionSchema.Kind.OBJECT,
name = typeDefinition.name
)
}
)
}
private fun GQLEnumTypeDefinition.toSchemaType(): IntrospectionSchema.Type.Enum {
return IntrospectionSchema.Type.Enum(
name = name,
description = description,
enumValues = enumValues.map { it.toSchemaEnumValue() }
)
}
private fun GQLEnumValueDefinition.toSchemaEnumValue(): IntrospectionSchema.Type.Enum.Value {
val deprecationReason = directives.findDeprecationReason()
return IntrospectionSchema.Type.Enum.Value(
name = name,
description = description,
isDeprecated = deprecationReason != null,
deprecationReason = deprecationReason
)
}
private fun GQLScalarTypeDefinition.toSchemaType(): IntrospectionSchema.Type.Scalar {
return IntrospectionSchema.Type.Scalar(
name = this.name,
description = this.description
)
}
private fun GQLUnionTypeDefinition.toSchemaType(): IntrospectionSchema.Type.Union {
return IntrospectionSchema.Type.Union(
name = name,
description = description,
fields = null,
possibleTypes = memberTypes.map { it.toSchemaType(schema) }
)
}
}
internal fun GQLType.toSchemaType(schema: Schema): IntrospectionSchema.TypeRef {
return when (this) {
is GQLNonNullType -> {
IntrospectionSchema.TypeRef(
kind = IntrospectionSchema.Kind.NON_NULL,
name = "", // why "" and not null ?
ofType = type.toSchemaType(schema)
)
}
is GQLListType -> {
IntrospectionSchema.TypeRef(
kind = IntrospectionSchema.Kind.LIST,
name = "", // why "" and not null ?
ofType = type.toSchemaType(schema))
}
is GQLNamedType -> {
IntrospectionSchema.TypeRef(
kind = schema.typeDefinition(name).schemaKind(),
name = name,
ofType = null
)
}
}
}
internal fun GQLTypeDefinition.schemaKind() = when (this) {
is GQLEnumTypeDefinition -> IntrospectionSchema.Kind.ENUM
is GQLUnionTypeDefinition -> IntrospectionSchema.Kind.UNION
is GQLObjectTypeDefinition -> IntrospectionSchema.Kind.OBJECT
is GQLInputObjectTypeDefinition -> IntrospectionSchema.Kind.INPUT_OBJECT
is GQLScalarTypeDefinition -> IntrospectionSchema.Kind.SCALAR
is GQLInterfaceTypeDefinition -> IntrospectionSchema.Kind.INTERFACE
}
fun Schema.toIntrospectionSchema() = IntrospectionSchemaBuilder(this).toIntrospectionSchema()
fun GQLValue.toKotlinValue(constContext: Boolean): Any? {
return when (this) {
is GQLIntValue -> value
is GQLFloatValue -> value
is GQLStringValue -> value
is GQLNullValue -> null
is GQLListValue -> values.map { it.toKotlinValue(constContext) }
is GQLObjectValue -> fields.map { it.name to it.value.toKotlinValue(constContext) }.toMap()
is GQLBooleanValue -> value
is GQLEnumValue -> value // Could we use something else in Kotlin?
is GQLVariableValue -> {
if (constContext) {
throw ConversionException("Value cannot be a variable in a const context", sourceLocation)
} else {
BooleanExpression.Variable(name)
}
}
}
}
| mit | 6f4ba0ecd693c3017b2b6a8475443851 | 35.079812 | 109 | 0.691087 | 4.904276 | false | false | false | false |
SirLYC/Android-Gank-Share | app/src/main/java/com/lyc/gank/utils/IntentExt.kt | 1 | 1375 | package com.lyc.gank.utils
import android.content.Intent
import com.lyc.data.resp.GankItem
/**
* Created by Liu Yuchuan on 2018/2/25.
*/
//GankItem
private const val KEY_ID = "KEY_ID"
private const val KEY_URL = "KEY_URL"
private const val KEY_IMAGE = "KEY_IMAGE"
private const val KEY_WHO = "KEY_WHO"
private const val KEY_TIME = "KEY_TIME"
private const val KEY_TYPE = "KEY_TYPE"
private const val KEY_DESC = "KEY_DESC"
fun Intent.putGankItem(gankItem: GankItem) =
putExtra(KEY_ID, gankItem.idOnServer)
.putExtra(KEY_URL, gankItem.url)
.putExtra(KEY_IMAGE, gankItem.imgUrl)
.putExtra(KEY_WHO, gankItem.author)
.putExtra(KEY_TIME, gankItem.publishTime)
.putExtra(KEY_TYPE, gankItem.type)
.putExtra(KEY_DESC, gankItem.title)
fun Intent.getGankItem(): GankItem? {
val id = getStringExtra(KEY_ID)
val url = getStringExtra(KEY_URL)
val image = getStringExtra(KEY_IMAGE)
val who = getStringExtra(KEY_WHO)
val time = getStringExtra(KEY_TIME)
val type = getStringExtra(KEY_TYPE)
val desc = getStringExtra(KEY_DESC)
if (id == null || url == null || who == null
|| time == null || type == null || desc == null)
return null
return GankItem(id, desc, time, type, url, who, null)
.apply { imgUrl = image }
} | apache-2.0 | 61e1b2b3a04426ed43922a28672a665c | 32.560976 | 60 | 0.637091 | 3.454774 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetStepBolusInformation.kt | 1 | 2111 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import info.nightscout.shared.logging.LTag
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import javax.inject.Inject
class DanaRSPacketBolusGetStepBolusInformation(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val error = intFromBuff(data, 0, 1)
val bolusType = intFromBuff(data, 1, 1)
danaPump.initialBolusAmount = intFromBuff(data, 2, 2) / 100.0
val hours = intFromBuff(data, 4, 1)
val minutes = intFromBuff(data, 5, 1)
if (danaPump.usingUTC) danaPump.lastBolusTime = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(hours).withMinuteOfHour(minutes).millis
else danaPump.lastBolusTime = DateTime.now().withHourOfDay(hours).withMinuteOfHour(minutes).millis
danaPump.lastBolusAmount = intFromBuff(data, 6, 2) / 100.0
danaPump.maxBolus = intFromBuff(data, 8, 2) / 100.0
danaPump.bolusStep = intFromBuff(data, 10, 1) / 100.0
failed = error != 0
aapsLogger.debug(LTag.PUMPCOMM, "Result: $error")
aapsLogger.debug(LTag.PUMPCOMM, "BolusType: $bolusType")
aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount: " + danaPump.initialBolusAmount + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeString(danaPump.lastBolusTime))
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaPump.lastBolusAmount)
aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaPump.maxBolus + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaPump.bolusStep + " U")
}
override val friendlyName: String = "BOLUS__GET_STEP_BOLUS_INFORMATION"
} | agpl-3.0 | d55aaa59674fd32397efc7109b3cd3fc | 47 | 151 | 0.718143 | 4.180198 | false | false | false | false |
Saketme/JRAW | lib/src/test/kotlin/net/dean/jraw/test/unit/StreamTest.kt | 2 | 3463 | package net.dean.jraw.test.unit
import com.winterbe.expekt.should
import net.dean.jraw.models.Listing
import net.dean.jraw.models.UniquelyIdentifiable
import net.dean.jraw.pagination.BackoffStrategy
import net.dean.jraw.pagination.ConstantBackoffStrategy
import net.dean.jraw.pagination.RedditIterable
import net.dean.jraw.pagination.Stream
import net.dean.jraw.test.expectException
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.it
class StreamTest : Spek({
lateinit var dataSource: FakePaginator
lateinit var stream: Stream<Foo>
beforeEachTest {
dataSource = FakePaginator()
stream = Stream(dataSource, PirateBackoffStrategy())
}
it("should yield the first page and then nothing after that") {
val initialAmount = 5
dataSource.addNewData(startId = 0, amount = initialAmount)
// Request the first page. There should only be `initialAmount` elements in the list once we call toList()
stream
.asSequence()
.take(initialAmount)
.map { it.uniqueId.toInt() }
.toList()
.should.equal((0 until initialAmount).toList())
expectException(NoMoreBootyException::class) {
stream.next()
}
val newStartId = 10
val newData = 3
dataSource.addNewData(startId = newStartId, amount = newData)
for (i in 0 until newData) {
stream
.next()
.uniqueId.toInt().should.equal(newStartId + i)
}
}
it("should throw an exception when the BackoffStrategy returns a negative integer") {
stream = Stream(dataSource, backoff = ConstantBackoffStrategy(-1L))
expectException(IllegalArgumentException::class) {
stream.next()
}
}
})
private class FakePaginator(val limit: Int = 5) : RedditIterable<Foo> {
override val current: Listing<Foo>? = null
override val pageNumber: Int get() = _pageNumber
private var _pageNumber: Int = 0
private val allData = mutableListOf<Foo>()
private var lastEnd: Int = -1
fun addNewData(startId: Int, amount: Int) {
for (i in startId until startId + amount) {
this.allData.add(0, Foo(i.toString()))
}
}
override fun next(): Listing<Foo> {
val endIndex = Math.min(lastEnd + 1 + limit, allData.size)
val next = Listing.create(pageNumber.toString(), allData.subList(lastEnd + 1, endIndex))
lastEnd = endIndex
return next
}
override fun restart() {
lastEnd = -1
_pageNumber = 0
}
override fun hasStarted(): Boolean = pageNumber == 0
// We don't care about these things here
override fun accumulate(maxPages: Int): List<Listing<Foo>> = throw NotImplementedError()
override fun accumulateMerged(maxPages: Int): List<Foo> = throw NotImplementedError()
override fun iterator(): Iterator<Listing<Foo>> = throw NotImplementedError()
}
private data class Foo(override val uniqueId: String) : UniquelyIdentifiable
/** Throws an [NoMoreBootyException] if there are no new items. */
private class PirateBackoffStrategy : BackoffStrategy {
override fun delayRequest(newItems: Int, totalItems: Int): Long {
if (newItems == 0)
throw NoMoreBootyException()
// No delay
return 0L
}
}
private class NoMoreBootyException : RuntimeException("no more booty in this here Stream")
| mit | ca0e6c7f1c8264bd90e844434c3ad6d9 | 31.980952 | 114 | 0.663009 | 4.378003 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/PluginIdExtensions.kt | 3 | 3782 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl.codegen
import org.gradle.kotlin.dsl.support.appendReproducibleNewLine
import org.gradle.plugin.use.PluginDependenciesSpec
import org.gradle.plugin.use.PluginDependencySpec
import java.io.File
import java.io.IOException
import java.lang.IllegalArgumentException
import java.util.Properties
import java.util.jar.JarEntry
import java.util.jar.JarFile
internal
fun writeBuiltinPluginIdExtensionsTo(file: File, gradleJars: Iterable<File>) {
file.bufferedWriter().use {
it.apply {
appendReproducibleNewLine(fileHeader)
pluginIdExtensionDeclarationsFor(gradleJars).forEach { extension ->
write("\n")
appendReproducibleNewLine(extension)
}
}
}
}
private
fun pluginIdExtensionDeclarationsFor(jars: Iterable<File>): Sequence<String> {
val extendedType = PluginDependenciesSpec::class.qualifiedName!!
val extensionType = PluginDependencySpec::class.qualifiedName!!
return pluginExtensionsFrom(jars)
.map { (memberName, pluginId, implementationClass) ->
"""
/**
* The builtin Gradle plugin implemented by [$implementationClass].
*
* @see $implementationClass
*/
inline val $extendedType.`$memberName`: $extensionType
get() = id("$pluginId")
""".trimIndent()
}
}
private
data class PluginExtension(
val memberName: String,
val pluginId: String,
val implementationClass: String
)
private
fun pluginExtensionsFrom(jars: Iterable<File>): Sequence<PluginExtension> =
jars
.asSequence()
.filter { it.name.startsWith("gradle-") }
.flatMap(::pluginExtensionsFrom)
private
fun pluginExtensionsFrom(file: File): Sequence<PluginExtension> =
pluginEntriesFrom(file)
.asSequence()
.map { (id, implementationClass) ->
val simpleId = id.substringAfter("org.gradle.")
// One plugin extension for the simple id, e.g., "application"
PluginExtension(simpleId, id, implementationClass)
}
internal
data class PluginEntry(val pluginId: String, val implementationClass: String)
internal
fun pluginEntriesFrom(jar: File): List<PluginEntry> = try {
JarFile(jar, false).use { jarFile ->
jarFile.entries().asSequence().filter {
isGradlePluginPropertiesFile(it)
}.map { pluginEntry ->
val pluginProperties = jarFile.getInputStream(pluginEntry).use { Properties().apply { load(it) } }
val id = pluginEntry.name.substringAfterLast("/").substringBeforeLast(".properties")
val implementationClass = pluginProperties.getProperty("implementation-class")
PluginEntry(id, implementationClass)
}.toList()
}
} catch (cause: IOException) {
throw IllegalArgumentException(
"Failed to extract plugin metadata from '" + jar.path + "'",
cause
)
}
private
fun isGradlePluginPropertiesFile(entry: JarEntry) = entry.run {
isFile && name.run { startsWith("META-INF/gradle-plugins/") && endsWith(".properties") }
}
| apache-2.0 | 2339358ecf380ff7433ef046cff6bcc7 | 30.781513 | 110 | 0.680328 | 4.674907 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/component/input/Input.kt | 1 | 6759 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.component.input
import com.acornui.component.Div
import com.acornui.component.UiComponent
import com.acornui.component.UiComponentImpl
import com.acornui.component.connected
import com.acornui.di.Context
import com.acornui.dom.createElement
import com.acornui.input.ChangeSignal
import com.acornui.observe.Observable
import com.acornui.own
import com.acornui.recycle.Clearable
import com.acornui.signal.Signal
import com.acornui.signal.SignalImpl
import com.acornui.signal.SignalSubscription
import com.acornui.signal.event
import org.w3c.dom.HTMLFormElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.ValidityState
import org.w3c.dom.events.Event
import org.w3c.dom.events.InputEvent
/**
* The common interface to all [HTMLInputElement] types.
*/
interface Input : UiComponent, Observable, Clearable {
/**
* Dispatched on each input character.
* Note - this does not invoke when the text is programmatically changed.
*/
val input: Signal<InputEvent>
/**
* Dispatched when the parent form has been reset.
*/
val formReset: Signal<Event>
/**
* Indicates that the user must fill in a value before submitting a form.
*/
var required: Boolean
/**
* Returns the element's current validity state.
*/
val validity: ValidityState
/**
* Returns a localized message that describes the validation constraints that the control does not satisfy (if any).
* This is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or
* it satisfies its constraints. This value can be set by the setCustomValidity method.
*/
val validationMessage: String
/**
* Returns whether the element is a candidate for constraint validation.
*/
val willValidate: Boolean
/**
* Sets the element's disabled attribute, indicating that the control is not available for interaction.
* The input values will not be submitted with the form.
*/
var disabled: Boolean
/**
* The [HTMLInputElement]'s name.
*/
var name: String
fun checkValidity(): Boolean
fun reportValidity(): Boolean
fun setCustomValidity(error: String)
}
open class InputImpl(owner: Context, type: String) :
UiComponentImpl<HTMLInputElement>(owner, createElement("input") { this.type = type }), Input {
/**
* Dispatched on value commit.
* This is only dispatched on a user interaction, such as pressing ENTER or TAB. It is not dispatched when
* the text is programmatically changed.
*/
final override val changed = ChangeSignal(this)
final override val input: Signal<InputEvent>
get() = event("input")
final override val formReset: Signal<Event> by lazy {
own(object : SignalImpl<Event>() {
private val connectedSub: SignalSubscription
private var resetSub: SignalSubscription? = null
init {
connectedSub = connected.listen {
form = dom.form
}
}
private var form: HTMLFormElement? = null
set(value) {
if (field == value) return
resetSub?.dispose()
field = value
resetSub = value?.event<Event>("reset")?.listen {
dispatch(it)
}
}
override fun dispose() {
super.dispose()
connectedSub.dispose()
form = null
}
})
}
/**
* Indicates that the user must fill in a value before submitting a form.
*/
final override var required: Boolean
get() = dom.required
set(value) {
dom.required = value
}
/**
* Returns the element's current validity state.
*/
final override val validity: ValidityState
get() = dom.validity
/**
* Returns a localized message that describes the validation constraints that the control does not satisfy (if any).
* This is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or
* it satisfies its constraints. This value can be set by the setCustomValidity method.
*/
final override val validationMessage: String
get() = dom.validationMessage
/**
* Returns whether the element is a candidate for constraint validation.
*/
final override val willValidate: Boolean
get() = dom.willValidate
/**
* Sets the element's disabled attribute, indicating that the control is not available for interaction.
* The input values will not be submitted with the form.
*/
final override var disabled: Boolean
get() = dom.disabled
set(value) {
dom.disabled = value
}
/**
* The [HTMLInputElement]'s name.
*/
final override var name: String
get() = dom.name
set(value) {
dom.name = value
}
final override fun checkValidity() = dom.checkValidity()
final override fun reportValidity() = dom.reportValidity()
final override fun setCustomValidity(error: String) = dom.setCustomValidity(error)
val form: HTMLFormElement?
get() = dom.form
override fun clear() {
dom.value = dom.defaultValue
}
}
/**
* If an input component is encapsulated, it may be convenient to delegate its [Input] methods.
*/
abstract class DivWithInputComponent(owner: Context) : Div(owner), Input {
protected abstract val inputComponent: Input
final override val changed: Signal<Observable>
get() = inputComponent.changed
final override val input: Signal<InputEvent>
get() = inputComponent.input
final override val formReset: Signal<Event>
get() = inputComponent.formReset
override var required: Boolean
get() = inputComponent.required
set(value) {
inputComponent.required = value
}
override val validity: ValidityState
get() = inputComponent.validity
override val validationMessage: String
get() = inputComponent.validationMessage
override val willValidate: Boolean
get() = inputComponent.willValidate
final override var name: String
get() = inputComponent.name
set(value) {
inputComponent.name = value
}
override var disabled: Boolean
get() = inputComponent.disabled
set(value) {
inputComponent.disabled = value
}
override fun checkValidity(): Boolean = inputComponent.checkValidity()
override fun reportValidity(): Boolean = inputComponent.reportValidity()
override fun setCustomValidity(error: String) = inputComponent.setCustomValidity(error)
override fun clear() = inputComponent.clear()
} | apache-2.0 | b0f930220d286333a1b17c20aeb9186c | 26.04 | 117 | 0.733688 | 4.008897 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/backup/download/usecases/PostDismissBackupDownloadUseCase.kt | 1 | 1965 | package org.wordpress.android.ui.jetpack.backup.download.usecases
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.ActivityLogStore
import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadPayload
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.NetworkUtilsWrapper
import javax.inject.Inject
import javax.inject.Named
import kotlin.math.max
class PostDismissBackupDownloadUseCase @Inject constructor(
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val activityLogStore: ActivityLogStore,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher
) {
private val tag = javaClass.simpleName
@Suppress("ComplexMethod", "LoopWithTooManyJumpStatements")
suspend fun dismissBackupDownload(
downloadId: Long,
site: SiteModel
): Boolean = withContext(bgDispatcher) {
var retryAttempts = 0
var dismissed = false
while (true) {
if (!networkUtilsWrapper.isNetworkAvailable()) {
val retryAttemptsExceeded = handleError(retryAttempts++)
if (retryAttemptsExceeded) break else continue
}
val result = activityLogStore.dismissBackupDownload(DismissBackupDownloadPayload(site, downloadId))
if (result.isError) break
dismissed = true
break
}
dismissed
}
private suspend fun handleError(retryAttempts: Int) = if (retryAttempts >= MAX_RETRY) {
AppLog.d(T.JETPACK_BACKUP, "$tag: Exceeded $MAX_RETRY retries while dismiss download backup file")
true
} else {
delay(DELAY_MILLIS * max(1, DELAY_FACTOR * retryAttempts))
false
}
}
| gpl-2.0 | b4d5d25e79c2b0bc4d2a7cc6525fb31e | 37.529412 | 111 | 0.728753 | 4.924812 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrameItems.kt | 1 | 4705 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.data
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.memory.utils.StackFrameItem
import com.intellij.xdebugger.frame.XStackFrame
import com.sun.jdi.Location
import org.jetbrains.kotlin.idea.debugger.base.util.safeKotlinPreferredLineNumber
import org.jetbrains.kotlin.idea.debugger.base.util.safeLineNumber
import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod
import org.jetbrains.kotlin.idea.debugger.base.util.safeSourceName
import org.jetbrains.kotlin.idea.debugger.core.invokeInManagerThread
import org.jetbrains.kotlin.idea.debugger.coroutine.util.findPosition
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
/**
* Creation frame of coroutine either in RUNNING or SUSPENDED state.
*/
class CreationCoroutineStackFrameItem(
val stackTraceElement: StackTraceElement,
location: Location,
val first: Boolean
) : CoroutineStackFrameItem(location, emptyList()) {
override fun createFrame(debugProcess: DebugProcessImpl): XStackFrame? {
return debugProcess.invokeInManagerThread {
val frame = debugProcess.findFirstFrame() ?: return@invokeInManagerThread null
val position = location.findPosition(debugProcess.project)
CreationCoroutineStackFrame(frame, position, first, location)
}
}
}
/**
* Restored frame in SUSPENDED coroutine, not attached to any thread.
*/
class SuspendCoroutineStackFrameItem(
val stackTraceElement: StackTraceElement,
location: Location,
spilledVariables: List<JavaValue> = emptyList()
) : CoroutineStackFrameItem(location, spilledVariables) {
override fun createFrame(debugProcess: DebugProcessImpl): XStackFrame? {
return debugProcess.invokeInManagerThread {
val frame = debugProcess.findFirstFrame() ?: return@invokeInManagerThread null
val position = location.findPosition(debugProcess.project)
CoroutineStackFrame(frame, position, spilledVariables, includeFrameVariables = false, location)
}
}
}
/**
* Restored from memory dump
*/
class DefaultCoroutineStackFrameItem(location: Location, spilledVariables: List<JavaValue>) :
CoroutineStackFrameItem(location, spilledVariables) {
override fun createFrame(debugProcess: DebugProcessImpl): XStackFrame? {
return debugProcess.invokeInManagerThread {
val frame = debugProcess.findFirstFrame() ?: return@invokeInManagerThread null
val position = location.findPosition(debugProcess.project)
CoroutineStackFrame(frame, position, spilledVariables, false, location)
}
}
}
/**
* Original frame appeared before resumeWith call.
*
* Sequence is the following
*
* - KotlinStackFrame
* - invokeSuspend(KotlinStackFrame) -|
* | replaced with CoroutinePreflightStackFrame
* - resumeWith(KotlinStackFrame) ----|
* - Kotlin/JavaStackFrame -> PreCoroutineStackFrameItem : CoroutinePreflightStackFrame.threadPreCoroutineFrames
*
*/
open class RunningCoroutineStackFrameItem(
val frame: StackFrameProxyImpl,
location: Location,
spilledVariables: List<JavaValue> = emptyList()
) : CoroutineStackFrameItem(location, spilledVariables) {
override fun createFrame(debugProcess: DebugProcessImpl): XStackFrame? {
return debugProcess.invokeInManagerThread {
val position = location.findPosition(debugProcess.project)
CoroutineStackFrame(frame, position)
}
}
}
sealed class CoroutineStackFrameItem(val location: Location, val spilledVariables: List<JavaValue>) :
StackFrameItem(location, spilledVariables) {
val log by logger
override fun createFrame(debugProcess: DebugProcessImpl): XStackFrame? {
return debugProcess.invokeInManagerThread {
val frame = debugProcess.findFirstFrame() ?: return@invokeInManagerThread null
val position = location.findPosition(debugProcess.project)
CoroutineStackFrame(frame, position, spilledVariables, false, location)
}
}
fun uniqueId() =
location.safeSourceName() + ":" + location.safeMethod().toString() + ":" +
location.safeLineNumber() + ":" + location.safeKotlinPreferredLineNumber()
}
fun DebugProcessImpl.findFirstFrame(): StackFrameProxyImpl? =
suspendManager.pausedContext.thread?.forceFrames()?.firstOrNull()
| apache-2.0 | 5e05ed68a6f5620b5799e4ba08445803 | 40.637168 | 158 | 0.747715 | 5.075512 | false | false | false | false |
micolous/metrodroid | src/iOSMain/kotlin/au/id/micolous/metrodroid/card/classic/PlusCardReaderIOS.kt | 1 | 2087 | /*
* PlusCardReaderIOS.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.card.classic
import au.id.micolous.metrodroid.card.Card
import au.id.micolous.metrodroid.card.ultralight.UltralightTransceiverIOS
import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface
import au.id.micolous.metrodroid.key.CardKeysDummy
import au.id.micolous.metrodroid.multi.*
import au.id.micolous.metrodroid.time.TimestampFull
import kotlinx.coroutines.runBlocking
object PlusCardReaderIOS {
@NativeThrows
fun dump(wrapper: UltralightTransceiverIOS.SwiftWrapper,
feedback: TagReaderFeedbackInterface): Card = logAndSwiftWrap (TAG, "Failed to dump") {
val xfer = UltralightTransceiverIOS(wrapper)
Log.d(TAG, "Start dump ${xfer.uid}")
runBlocking {
Log.d(TAG, "Start async")
feedback.updateStatusText(Localizer.localizeString(R.string.mfp_reading))
feedback.showCardType(null)
val techWrapper = PlusProtocol.connect(xfer) ?: throw Exception("Unknown MifarePlus")
val keyRetriever = CardKeysDummy()
val p = ClassicReader.readCard(
keyRetriever, techWrapper, feedback)
Card(tagId = xfer.uid?.let { if (it.size == 10) it.sliceOffLen(0, 7) else it }!!,
scannedAt = TimestampFull.now(), mifareClassic = p)
}
}
private const val TAG = "PlusCardReaderIOS"
}
| gpl-3.0 | caf2f7e9c215f6a2cca0eb77cd0563ae | 38.377358 | 100 | 0.712027 | 4.100196 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/friends/feed/sideeffect/PostSideEffectHandler.kt | 1 | 6522 | package io.ipoli.android.friends.feed.sideeffect
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.feed.post.AddPostAction
import io.ipoli.android.friends.feed.post.AddPostViewState
import io.ipoli.android.friends.feed.post.PostAction
import io.ipoli.android.friends.usecase.SavePostReactionUseCase
import io.ipoli.android.friends.usecase.SavePostsUseCase
import io.ipoli.android.player.usecase.RewardPlayerUseCase
import io.ipoli.android.quest.job.RewardScheduler
import io.ipoli.android.quest.show.sideeffect.QuestSideEffectHandler
import io.ipoli.android.quest.show.usecase.SplitDurationForPomodoroTimerUseCase
import kotlinx.coroutines.experimental.channels.Channel
import space.traversal.kapsule.required
object PostSideEffectHandler : AppSideEffectHandler() {
private val postRepository by required { postRepository }
private val savePostsUseCase by required { savePostsUseCase }
private val savePostReactionUseCase by required { savePostReactionUseCase }
private val splitDurationForPomodoroTimerUseCase by required { splitDurationForPomodoroTimerUseCase }
private val playerRepository by required { playerRepository }
private val challengeRepository by required { challengeRepository }
private val habitRepository by required { habitRepository }
private val questRepository by required { questRepository }
private val rewardPlayerUseCase by required { rewardPlayerUseCase }
private val rewardScheduler by required { rewardScheduler }
private var postChangedChannel: Channel<Post>? = null
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is PostAction.Load -> {
listenForChanges(
oldChannel = postChangedChannel,
channelCreator = {
postChangedChannel = postRepository.listen(action.postId)
postChangedChannel!!
},
onResult = { post ->
dispatch(DataLoadedAction.PostChanged(post))
}
)
}
is PostAction.SaveComment -> {
if (action.text.isNotBlank()) {
postRepository.saveComment(action.postId, action.text.trim())
}
}
is AddPostAction.Load -> {
val p = playerRepository.find()!!
val c = action.challengeId?.let {
challengeRepository.findById(it)!!
}
val h = action.habitId?.let {
habitRepository.findById(it)!!
}
val q = action.questId?.let {
val r = questRepository.findById(it)!!
val splitResult = splitDurationForPomodoroTimerUseCase.execute(
SplitDurationForPomodoroTimerUseCase.Params(r)
)
val totalPomodoros =
if (splitResult == SplitDurationForPomodoroTimerUseCase.Result.DurationNotSplit) {
r.timeRanges.size / 2
} else {
(splitResult as SplitDurationForPomodoroTimerUseCase.Result.DurationSplit).timeRanges.size / 2
}
r.copy(totalPomodoros = totalPomodoros)
}
dispatch(DataLoadedAction.AddPostDataChanged(p, q, h, c))
}
is AddPostAction.Save -> {
val s = state.stateFor(AddPostViewState::class.java)
val player = state.dataState.player
savePostsUseCase.execute(
if (s.quest != null && s.quest.isFromChallenge) {
SavePostsUseCase.Params.QuestFromChallengeComplete(
quest = s.quest,
challenge = s.challenge!!,
description = action.playerMessage,
imageData = action.imageData,
player = player
)
} else if (s.quest != null) {
SavePostsUseCase.Params.QuestComplete(
quest = s.quest,
description = action.playerMessage,
imageData = action.imageData,
player = player
)
} else if (s.habit != null) {
SavePostsUseCase.Params.HabitCompleted(
habit = s.habit,
challenge = s.challenge,
description = action.playerMessage,
imageData = action.imageData,
player = player
)
} else if (!s.challenge!!.isCompleted) {
SavePostsUseCase.Params.ChallengeShared(
challenge = s.challenge,
description = action.playerMessage,
imageData = action.imageData,
player = player
)
} else {
SavePostsUseCase.Params.ChallengeComplete(
challenge = s.challenge,
description = action.playerMessage,
imageData = action.imageData,
player = player
)
}
)
val r = rewardPlayerUseCase.execute(RewardPlayerUseCase.Params.ForAddPost()).reward
rewardScheduler.schedule(r, true, RewardScheduler.Type.ADD_POST, null)
}
is PostAction.Remove ->
postRepository.delete(action.postId)
is PostAction.React ->
savePostReactionUseCase.execute(
SavePostReactionUseCase.Params(
postId = action.postId,
reactionType = action.reaction
)
)
}
}
override fun canHandle(action: Action) = action is PostAction || action is AddPostAction
} | gpl-3.0 | 087003567fd2e6cf16b479ec7cee96df | 44.298611 | 122 | 0.551058 | 5.776794 | false | false | false | false |
kerie/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt | 1 | 6534 | /*
* 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.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiBinaryExpression
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.util.IncorrectOperationException
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import com.siyeh.ig.PsiReplacementUtil
import com.siyeh.ig.fixes.EqualityToEqualsFix
import com.siyeh.ig.psiutils.ComparisonUtils
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.annotations.NonNls
/**
*
* Batch QuickFix Supported
* @author caikang
* @date 2017/02/27
*/
class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
constructor()
/**
* For Javassist
*/
constructor(any: Any?) : this()
val familyName = "$replaceWith equals"
override fun buildErrorString(vararg infos: Any?): String {
return P3cBundle.getMessage("com.alibaba.p3c.idea.inspection.rule.WrapperTypeEqualityRule.errMsg")
}
override fun buildVisitor(): BaseInspectionVisitor {
return ObjectComparisonVisitor()
}
override fun ruleName(): String {
return "WrapperTypeEqualityRule"
}
override fun getDisplayName(): String {
return RuleInspectionUtils.getRuleMessage(ruleName())
}
override fun getShortName(): String {
return "AliWrapperTypeEquality"
}
override fun getStaticDescription(): String? {
return RuleInspectionUtils.getRuleStaticDescription(ruleName())
}
override fun getDefaultLevel(): HighlightDisplayLevel {
return RuleInspectionUtils.getHighlightDisplayLevel(ruleName())
}
public override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
if (infos.isEmpty()) {
return DecorateInspectionGadgetsFix(EqualityToEqualsFix(), familyName)
}
val type = infos[0] as PsiArrayType
val componentType = type.componentType
val fix = ArrayEqualityFix(componentType is PsiArrayType)
return DecorateInspectionGadgetsFix(fix, fix.name, familyName)
}
private inner class ObjectComparisonVisitor : BaseInspectionVisitor() {
override fun visitBinaryExpression(expression: PsiBinaryExpression) {
if (!ComparisonUtils.isEqualityComparison(expression)) {
return
}
checkForWrapper(expression)
}
private fun checkForWrapper(expression: PsiBinaryExpression) {
val rhs = expression.rOperand ?: return
val lhs = expression.lOperand
if (!isWrapperType(lhs) || !isWrapperType(rhs)) {
return
}
registerError(expression.operationSign)
}
private fun isWrapperType(expression: PsiExpression): Boolean {
if (hasNumberType(expression)) {
return true
}
return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_BOOLEAN)
|| TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER)
}
private fun hasNumberType(expression: PsiExpression): Boolean {
return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_NUMBER)
}
/**
* checkForNumber end
*/
}
private class ArrayEqualityFix(private val deepEquals: Boolean) : InspectionGadgetsFix() {
override fun getName(): String {
if (deepEquals) {
return "$replaceWith 'Arrays.deepEquals()'"
} else {
return "$replaceWith 'Arrays.equals()'"
}
}
override fun getFamilyName(): String {
return familyName
}
@Throws(IncorrectOperationException::class)
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val parent = element.parent as? PsiBinaryExpression ?: return
val tokenType = parent.operationTokenType
@NonNls val newExpressionText = StringBuilder()
if (JavaTokenType.NE == tokenType) {
newExpressionText.append('!')
} else if (JavaTokenType.EQEQ != tokenType) {
return
}
if (deepEquals) {
newExpressionText.append("java.util.Arrays.deepEquals(")
} else {
newExpressionText.append("java.util.Arrays.equals(")
}
newExpressionText.append(parent.lOperand.text)
newExpressionText.append(',')
val rhs = parent.rOperand ?: return
newExpressionText.append(rhs.text)
newExpressionText.append(')')
PsiReplacementUtil.replaceExpressionAndShorten(parent,
newExpressionText.toString())
}
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? {
val expression = psiElement.parent as? PsiBinaryExpression ?: return null
val rhs = expression.rOperand ?: return null
val lhs = expression.lOperand
val lhsType = lhs.type
if (lhsType !is PsiArrayType || rhs.type !is PsiArrayType) {
return buildFix()
}
return buildFix(lhsType)
}
companion object {
val replaceWith = P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.replace.with")
}
}
| apache-2.0 | 2650bb25317a0e9cd517a1fc1cca3167 | 34.901099 | 109 | 0.67539 | 5.037779 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt | 2 | 4226 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils.canBeSimplified
import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils.simplify
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
binaryExpressionVisitor(fun(expression) {
if (expression.operationToken != KtTokens.ELVIS) return
val lhs = expression.left ?: return
val rhs = expression.right ?: return
if (!KtPsiUtil.isBooleanConstant(rhs)) return
val lhsType = lhs.analyze(BodyResolveMode.PARTIAL).getType(lhs) ?: return
if (TypeUtils.isNullableType(lhsType) && lhsType.isBooleanOrNullableBoolean()) {
val condition = when (val parentIfOrWhile =
PsiTreeUtil.getParentOfType(expression, KtIfExpression::class.java, KtWhileExpressionBase::class.java)) {
is KtIfExpression -> parentIfOrWhile.condition
is KtWhileExpressionBase -> parentIfOrWhile.condition
else -> null
}
val (highlightType, verb) = if (condition != null && condition in expression.parentsWithSelf)
GENERIC_ERROR_OR_WARNING to KotlinBundle.message("text.should")
else
INFORMATION to KotlinBundle.message("text.can")
holder.registerProblemWithoutOfflineInformation(
expression,
KotlinBundle.message("equality.check.0.be.used.instead.of.elvis.for.nullable.boolean.check", verb),
isOnTheFly,
highlightType,
ReplaceWithEqualityCheckFix()
)
}
})
private class ReplaceWithEqualityCheckFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.equality.check.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtBinaryExpression ?: return
if (element.operationToken != KtTokens.ELVIS) return
val constPart = element.right as? KtConstantExpression ?: return
val exprPart = element.left ?: return
val constValue = when {
KtPsiUtil.isTrueConstant(constPart) -> true
KtPsiUtil.isFalseConstant(constPart) -> false
else -> return
}
val equalityCheckExpression = element.replaced(KtPsiFactory(constPart).buildExpression {
appendExpression(exprPart)
appendFixedText(if (constValue) " != false" else " == true")
})
val prefixExpression = equalityCheckExpression.getParentOfType<KtPrefixExpression>(strict = true) ?: return
if (prefixExpression.canBeSimplified()) {
prefixExpression.simplify()
}
}
}
}
| apache-2.0 | 164f1d5a22df9b9943637ee1aa183b47 | 51.825 | 125 | 0.692144 | 5.342604 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/database/model/IdentityStoreRecord.kt | 2 | 766 | package org.thoughtcrime.securesms.database.model
import org.signal.libsignal.protocol.IdentityKey
import org.thoughtcrime.securesms.database.IdentityDatabase
import org.thoughtcrime.securesms.recipients.RecipientId
data class IdentityStoreRecord(
val addressName: String,
val identityKey: IdentityKey,
val verifiedStatus: IdentityDatabase.VerifiedStatus,
val firstUse: Boolean,
val timestamp: Long,
val nonblockingApproval: Boolean
) {
fun toIdentityRecord(recipientId: RecipientId): IdentityRecord {
return IdentityRecord(
recipientId = recipientId,
identityKey = identityKey,
verifiedStatus = verifiedStatus,
firstUse = firstUse,
timestamp = timestamp,
nonblockingApproval = nonblockingApproval
)
}
}
| gpl-3.0 | 9784c7c88a83bd9389aaa172947f894c | 29.64 | 66 | 0.775457 | 4.614458 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/database/DonationReceiptDatabase.kt | 1 | 3142 | package org.thoughtcrime.securesms.database
import android.content.Context
import android.database.Cursor
import androidx.core.content.contentValuesOf
import org.signal.core.util.CursorUtil
import org.signal.core.util.SqlUtil
import org.signal.core.util.money.FiatMoney
import org.thoughtcrime.securesms.database.model.DonationReceiptRecord
import java.math.BigDecimal
import java.util.Currency
class DonationReceiptDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) {
companion object {
private const val TABLE_NAME = "donation_receipt"
private const val ID = "_id"
private const val TYPE = "receipt_type"
private const val DATE = "receipt_date"
private const val AMOUNT = "amount"
private const val CURRENCY = "currency"
private const val SUBSCRIPTION_LEVEL = "subscription_level"
@JvmField
val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$TYPE TEXT NOT NULL,
$DATE INTEGER NOT NULL,
$AMOUNT TEXT NOT NULL,
$CURRENCY TEXT NOT NULL,
$SUBSCRIPTION_LEVEL INTEGER NOT NULL
)
""".trimIndent()
val CREATE_INDEXS = arrayOf(
"CREATE INDEX IF NOT EXISTS donation_receipt_type_index ON $TABLE_NAME ($TYPE)",
"CREATE INDEX IF NOT EXISTS donation_receipt_date_index ON $TABLE_NAME ($DATE)"
)
}
fun addReceipt(record: DonationReceiptRecord) {
require(record.id == -1L)
val values = contentValuesOf(
AMOUNT to record.amount.amount.toString(),
CURRENCY to record.amount.currency.currencyCode,
DATE to record.timestamp,
TYPE to record.type.code,
SUBSCRIPTION_LEVEL to record.subscriptionLevel
)
writableDatabase.insert(TABLE_NAME, null, values)
}
fun getReceipt(id: Long): DonationReceiptRecord? {
readableDatabase.query(TABLE_NAME, null, ID_WHERE, SqlUtil.buildArgs(id), null, null, null).use { cursor ->
return if (cursor.moveToNext()) {
readRecord(cursor)
} else {
null
}
}
}
fun getReceipts(type: DonationReceiptRecord.Type?): List<DonationReceiptRecord> {
val (where, whereArgs) = if (type != null) {
"$TYPE = ?" to SqlUtil.buildArgs(type.code)
} else {
null to null
}
readableDatabase.query(TABLE_NAME, null, where, whereArgs, null, null, "$DATE DESC").use { cursor ->
val results = ArrayList<DonationReceiptRecord>(cursor.count)
while (cursor.moveToNext()) {
results.add(readRecord(cursor))
}
return results
}
}
private fun readRecord(cursor: Cursor): DonationReceiptRecord {
return DonationReceiptRecord(
id = CursorUtil.requireLong(cursor, ID),
type = DonationReceiptRecord.Type.fromCode(CursorUtil.requireString(cursor, TYPE)),
amount = FiatMoney(
BigDecimal(CursorUtil.requireString(cursor, AMOUNT)),
Currency.getInstance(CursorUtil.requireString(cursor, CURRENCY))
),
timestamp = CursorUtil.requireLong(cursor, DATE),
subscriptionLevel = CursorUtil.requireInt(cursor, SUBSCRIPTION_LEVEL)
)
}
}
| gpl-3.0 | 2a4052d0d321da86f499a015d4a932c8 | 32.073684 | 117 | 0.693507 | 4.269022 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/metadata/impl/BaseRowResultImpl.kt | 1 | 2467 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.kotlinsql.metadata.impl
import io.github.pdvrieze.kotlinsql.UnmanagedSql
import java.sql.DatabaseMetaData
import java.sql.ResultSet
@Suppress("unused", "MemberVisibilityCanBePrivate")
@OptIn(UnmanagedSql::class)
internal abstract class BaseRowResultImpl<R: BaseRowResult<D>, D:BaseRowResult.Data<D>>
@UnmanagedSql
constructor(rs: ResultSet) : AbstractMetadataResultSet<R, D>(rs), BaseRowResult<D> {
private val idxColumnName by lazyColIdx("COLUMN_NAME")
private val idxDataType by lazyColIdx("DATA_TYPE")
private val idxTypeName by lazyColIdx("TYPE_NAME")
private val idxColumnSize by lazyColIdx("COLUMN_SIZE")
private val idxDecimalDigits by lazyColIdx("DECIMAL_DIGITS")
private val idxPseudoColumn by lazyColIdx("PSEUDO_COLUMN")
override val columnName: String get() = resultSet.getString(idxColumnName)
override val dataType: String get() = resultSet.getString(idxDataType)
override val typeName: String get() = resultSet.getString(idxTypeName)
override val precision: String get() = resultSet.getString(idxColumnSize)
override val decimalDigits: Short get() = resultSet.getShort(idxDecimalDigits)
override val pseudoColumn: BaseRowResult.PseudoColumn = when (resultSet.getShort(idxPseudoColumn).toInt()) {
DatabaseMetaData.bestRowUnknown -> BaseRowResult.PseudoColumn.BESTROWUNKNOWN
DatabaseMetaData.bestRowPseudo -> BaseRowResult.PseudoColumn.BESTROWPSEUDO
DatabaseMetaData.bestRowNotPseudo -> BaseRowResult.PseudoColumn.BESTROWNOTPSEUDO
else -> throw IllegalArgumentException(
"Unexpected pseudoColumn value ${resultSet.getShort(idxPseudoColumn)}")
}
} | apache-2.0 | a5b31785e66c804bc580e75a2b24b903 | 43.872727 | 112 | 0.753547 | 4.290435 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/manage/ManageDonationsFragment.kt | 1 | 10470 | package org.thoughtcrime.securesms.components.settings.app.subscription.manage
import android.content.Intent
import android.text.SpannableStringBuilder
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import org.signal.core.util.DimensionUnit
import org.signal.core.util.money.FiatMoney
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.gifts.ExpiredGiftSheet
import org.thoughtcrime.securesms.badges.gifts.flow.GiftFlowActivity
import org.thoughtcrime.securesms.badges.models.BadgePreview
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity
import org.thoughtcrime.securesms.components.settings.app.subscription.SubscriptionsRepository
import org.thoughtcrime.securesms.components.settings.app.subscription.models.NetworkFailure
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.components.settings.models.IndeterminateLoadingCircle
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.help.HelpFragment
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.subscription.Subscription
import org.thoughtcrime.securesms.util.FeatureFlags
import org.thoughtcrime.securesms.util.SpanUtil
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription
import java.util.Currency
import java.util.concurrent.TimeUnit
/**
* Fragment displayed when a user enters "Subscriptions" via app settings but is already
* a subscriber. Used to manage their current subscription, view badges, and boost.
*/
class ManageDonationsFragment : DSLSettingsFragment(), ExpiredGiftSheet.Callback {
private val supportTechSummary: CharSequence by lazy {
SpannableStringBuilder(requireContext().getString(R.string.SubscribeFragment__make_a_recurring_monthly_donation))
.append(" ")
.append(
SpanUtil.readMore(requireContext(), ContextCompat.getColor(requireContext(), R.color.signal_button_secondary_text)) {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToSubscribeLearnMoreBottomSheetDialog())
}
)
}
private val viewModel: ManageDonationsViewModel by viewModels(
factoryProducer = {
ManageDonationsViewModel.Factory(SubscriptionsRepository(ApplicationDependencies.getDonationsService()))
}
)
override fun onResume() {
super.onResume()
viewModel.refresh()
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
ActiveSubscriptionPreference.register(adapter)
IndeterminateLoadingCircle.register(adapter)
BadgePreview.register(adapter)
NetworkFailure.register(adapter)
val expiredGiftBadge = SignalStore.donationsValues().getExpiredGiftBadge()
if (expiredGiftBadge != null) {
SignalStore.donationsValues().setExpiredGiftBadge(null)
ExpiredGiftSheet.show(childFragmentManager, expiredGiftBadge)
}
viewModel.state.observe(viewLifecycleOwner) { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
private fun getConfiguration(state: ManageDonationsState): DSLConfiguration {
return configure {
customPref(
BadgePreview.BadgeModel.FeaturedModel(
badge = state.featuredBadge
)
)
space(DimensionUnit.DP.toPixels(8f).toInt())
sectionHeaderPref(
title = DSLSettingsText.from(
R.string.SubscribeFragment__signal_is_powered_by_people_like_you,
DSLSettingsText.CenterModifier, DSLSettingsText.Title2BoldModifier
)
)
if (state.transactionState is ManageDonationsState.TransactionState.NotInTransaction) {
val activeSubscription = state.transactionState.activeSubscription.activeSubscription
if (activeSubscription != null) {
val subscription: Subscription? = state.availableSubscriptions.firstOrNull { activeSubscription.level == it.level }
if (subscription != null) {
presentSubscriptionSettings(activeSubscription, subscription, state.getRedemptionState())
} else {
customPref(IndeterminateLoadingCircle)
}
} else {
presentNoSubscriptionSettings()
}
} else if (state.transactionState == ManageDonationsState.TransactionState.NetworkFailure) {
presentNetworkFailureSettings(state.getRedemptionState())
} else {
customPref(IndeterminateLoadingCircle)
}
}
}
private fun DSLConfiguration.presentNetworkFailureSettings(redemptionState: ManageDonationsState.SubscriptionRedemptionState) {
if (SignalStore.donationsValues().isLikelyASustainer()) {
presentSubscriptionSettingsWithNetworkError(redemptionState)
} else {
presentNoSubscriptionSettings()
}
}
private fun DSLConfiguration.presentSubscriptionSettingsWithNetworkError(redemptionState: ManageDonationsState.SubscriptionRedemptionState) {
presentSubscriptionSettingsWithState(redemptionState) {
customPref(
NetworkFailure.Model(
onRetryClick = {
viewModel.retry()
}
)
)
}
}
private fun DSLConfiguration.presentSubscriptionSettings(
activeSubscription: ActiveSubscription.Subscription,
subscription: Subscription,
redemptionState: ManageDonationsState.SubscriptionRedemptionState
) {
presentSubscriptionSettingsWithState(redemptionState) {
val activeCurrency = Currency.getInstance(activeSubscription.currency)
val activeAmount = activeSubscription.amount.movePointLeft(activeCurrency.defaultFractionDigits)
customPref(
ActiveSubscriptionPreference.Model(
price = FiatMoney(activeAmount, activeCurrency),
subscription = subscription,
renewalTimestamp = TimeUnit.SECONDS.toMillis(activeSubscription.endOfCurrentPeriod),
redemptionState = redemptionState,
onContactSupport = {
requireActivity().finish()
requireActivity().startActivity(AppSettingsActivity.help(requireContext(), HelpFragment.DONATION_INDEX))
},
activeSubscription = activeSubscription
)
)
}
}
private fun DSLConfiguration.presentSubscriptionSettingsWithState(
redemptionState: ManageDonationsState.SubscriptionRedemptionState,
subscriptionBlock: DSLConfiguration.() -> Unit
) {
space(DimensionUnit.DP.toPixels(32f).toInt())
noPadTextPref(
title = DSLSettingsText.from(
R.string.ManageDonationsFragment__my_subscription,
DSLSettingsText.Body1BoldModifier, DSLSettingsText.BoldModifier
)
)
space(DimensionUnit.DP.toPixels(12f).toInt())
subscriptionBlock()
clickPref(
title = DSLSettingsText.from(R.string.ManageDonationsFragment__manage_subscription),
icon = DSLSettingsIcon.from(R.drawable.ic_person_white_24dp),
isEnabled = redemptionState != ManageDonationsState.SubscriptionRedemptionState.IN_PROGRESS,
onClick = {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToSubscribeFragment())
}
)
clickPref(
title = DSLSettingsText.from(R.string.ManageDonationsFragment__badges),
icon = DSLSettingsIcon.from(R.drawable.ic_badge_24),
onClick = {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToManageBadges())
}
)
presentOtherWaysToGive()
sectionHeaderPref(R.string.ManageDonationsFragment__more)
presentDonationReceipts()
externalLinkPref(
title = DSLSettingsText.from(R.string.ManageDonationsFragment__subscription_faq),
icon = DSLSettingsIcon.from(R.drawable.ic_help_24),
linkId = R.string.donate_url
)
}
private fun DSLConfiguration.presentNoSubscriptionSettings() {
space(DimensionUnit.DP.toPixels(16f).toInt())
noPadTextPref(
title = DSLSettingsText.from(supportTechSummary, DSLSettingsText.CenterModifier)
)
space(DimensionUnit.DP.toPixels(16f).toInt())
primaryButton(
text = DSLSettingsText.from(R.string.ManageDonationsFragment__make_a_monthly_donation),
onClick = {
findNavController().safeNavigate(R.id.action_manageDonationsFragment_to_subscribeFragment)
}
)
presentOtherWaysToGive()
sectionHeaderPref(R.string.ManageDonationsFragment__receipts)
presentDonationReceipts()
}
private fun DSLConfiguration.presentOtherWaysToGive() {
dividerPref()
sectionHeaderPref(R.string.ManageDonationsFragment__other_ways_to_give)
clickPref(
title = DSLSettingsText.from(R.string.preferences__one_time_donation),
icon = DSLSettingsIcon.from(R.drawable.ic_boost_24),
onClick = {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToBoosts())
}
)
if (FeatureFlags.giftBadges() && Recipient.self().giftBadgesCapability == Recipient.Capability.SUPPORTED) {
clickPref(
title = DSLSettingsText.from(R.string.ManageDonationsFragment__gift_a_badge),
icon = DSLSettingsIcon.from(R.drawable.ic_gift_24),
onClick = {
startActivity(Intent(requireContext(), GiftFlowActivity::class.java))
}
)
}
}
private fun DSLConfiguration.presentDonationReceipts() {
clickPref(
title = DSLSettingsText.from(R.string.ManageDonationsFragment__donation_receipts),
icon = DSLSettingsIcon.from(R.drawable.ic_receipt_24),
onClick = {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToDonationReceiptListFragment())
}
)
}
override fun onMakeAMonthlyDonation() {
findNavController().safeNavigate(ManageDonationsFragmentDirections.actionManageDonationsFragmentToSubscribeFragment())
}
}
| gpl-3.0 | 3c60e185cde943c6b21c006e5df7b3a2 | 37.921933 | 146 | 0.759885 | 5.160177 | false | true | false | false |
NiciDieNase/chaosflix | common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/recording/persistence/ConferenceGroupDao.kt | 1 | 1188 | package de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
@Dao
abstract class ConferenceGroupDao : BaseDao<ConferenceGroup>() {
@Query("SELECT * FROM conference_group ORDER BY order_index")
abstract fun getAll(): LiveData<List<ConferenceGroup>>
@Query("SELECT * FROM conference_group WHERE name = :name LIMIT 1")
abstract suspend fun getConferenceGroupByName(name: String): ConferenceGroup?
@Query("DELETE FROM conference_group WHERE id NOT IN (SELECT conference.conferenceGroupId FROM conference)")
abstract fun deleteEmptyGroups()
@Query("DElETE FROM conference_group")
abstract fun delete()
override suspend fun updateOrInsertInternal(item: ConferenceGroup): Long {
if (item.id != 0L) {
update(item)
} else {
val existingGroup = getConferenceGroupByName(item.name)
if (existingGroup != null) {
item.id = existingGroup.id
update(item)
} else {
item.id = insert(item)
}
}
return item.id
}
}
| mit | dba70ccbabf6416199ea319f64d9dcda | 32.942857 | 112 | 0.665825 | 4.640625 | false | false | false | false |
marukami/RxKotlin-Android-Samples | app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/rxbus/RxBusDemo_Bottom3Fragment.kt | 1 | 2852 | package au.com.tilbrook.android.rxkotlin.rxbus
import android.os.Bundle
import android.support.v4.view.ViewCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import au.com.tilbrook.android.rxkotlin.MainActivity
import au.com.tilbrook.android.rxkotlin.fragments.BaseFragment
import org.jetbrains.anko.support.v4.UI
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
import java.util.concurrent.TimeUnit
class RxBusDemo_Bottom3Fragment : BaseFragment() {
private lateinit var _tapEventTxtShow: TextView
private lateinit var _tapEventCountShow: TextView
private lateinit var _rxBus: RxBus
private lateinit var _subscriptions: CompositeSubscription
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View {
val ui = RxBusBottomUi()
val layout = ui.createView(UI { })
_tapEventTxtShow = ui.tapEventTxtShow
_tapEventCountShow = ui.tapEventCountShow
return layout;
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
_rxBus = (getActivity() as MainActivity).rxBusSingleton
}
override fun onStart() {
super.onStart()
_subscriptions = CompositeSubscription()
val tapEventEmitter = _rxBus.toObserverable().publish()
_subscriptions.add(tapEventEmitter.subscribe { event ->
if (event is RxBusDemoFragment.TapEvent) {
_showTapText()
}
})
_subscriptions.add(
tapEventEmitter
.publish { stream ->
stream.buffer(stream.debounce(1, TimeUnit.SECONDS))
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe { taps -> _showTapCount(taps.size) })
_subscriptions.add(tapEventEmitter.connect())
}
override fun onStop() {
super.onStop()
_subscriptions.clear()
}
// -----------------------------------------------------------------------------------
// Helper to show the text via an animation
private fun _showTapText() {
_tapEventTxtShow.visibility = View.VISIBLE
_tapEventTxtShow.alpha = 1f
ViewCompat.animate(_tapEventTxtShow).alphaBy(-1f).setDuration(400)
}
private fun _showTapCount(size: Int) {
_tapEventCountShow.text = size.toString()
_tapEventCountShow.visibility = View.VISIBLE
_tapEventCountShow.scaleX = 1f
_tapEventCountShow.scaleY = 1f
ViewCompat.animate(_tapEventCountShow).scaleXBy(-1f).scaleYBy(-1f).setDuration(
800).setStartDelay(100)
}
}
| apache-2.0 | e8629f60a07827a0f47574f8b0b5180b | 32.952381 | 90 | 0.646213 | 4.721854 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1Handler.kt | 1 | 5399 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty.http1
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.netty.cio.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import io.netty.channel.*
import io.netty.handler.codec.http.*
import io.netty.util.concurrent.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import java.io.*
import kotlin.coroutines.*
internal class NettyHttp1Handler(
private val enginePipeline: EnginePipeline,
private val environment: ApplicationEngineEnvironment,
private val callEventGroup: EventExecutorGroup,
private val engineContext: CoroutineContext,
private val userContext: CoroutineContext,
private val runningLimit: Int
) : ChannelInboundHandlerAdapter(), CoroutineScope {
private val handlerJob = CompletableDeferred<Nothing>()
override val coroutineContext: CoroutineContext get() = handlerJob
private var skipEmpty = false
private lateinit var responseWriter: NettyHttpResponsePipeline
private val state = NettyHttpHandlerState(runningLimit)
override fun channelActive(context: ChannelHandlerContext) {
responseWriter = NettyHttpResponsePipeline(
context,
state,
coroutineContext
)
context.channel().config().isAutoRead = false
context.channel().read()
context.pipeline().apply {
addLast(RequestBodyHandler(context))
addLast(callEventGroup, NettyApplicationCallHandler(userContext, enginePipeline))
}
context.fireChannelActive()
}
override fun channelRead(context: ChannelHandlerContext, message: Any) {
if (message is LastHttpContent) {
state.isCurrentRequestFullyRead.compareAndSet(expect = false, update = true)
}
when {
message is HttpRequest -> {
if (message !is LastHttpContent) {
state.isCurrentRequestFullyRead.compareAndSet(expect = true, update = false)
}
state.isChannelReadCompleted.compareAndSet(expect = true, update = false)
state.activeRequests.incrementAndGet()
handleRequest(context, message)
callReadIfNeeded(context)
}
message is LastHttpContent && !message.content().isReadable && skipEmpty -> {
skipEmpty = false
message.release()
callReadIfNeeded(context)
}
else -> {
context.fireChannelRead(message)
}
}
}
override fun channelInactive(context: ChannelHandlerContext) {
context.pipeline().remove(NettyApplicationCallHandler::class.java)
context.fireChannelInactive()
}
@Suppress("OverridingDeprecatedMember")
override fun exceptionCaught(context: ChannelHandlerContext, cause: Throwable) {
if (cause is IOException || cause is ChannelIOException) {
environment.application.log.debug("I/O operation failed", cause)
handlerJob.cancel()
} else {
handlerJob.completeExceptionally(cause)
}
context.close()
}
override fun channelReadComplete(context: ChannelHandlerContext?) {
state.isChannelReadCompleted.compareAndSet(expect = false, update = true)
responseWriter.flushIfNeeded()
super.channelReadComplete(context)
}
private fun handleRequest(context: ChannelHandlerContext, message: HttpRequest) {
val call = prepareCallFromRequest(context, message)
context.fireChannelRead(call)
responseWriter.processResponse(call)
}
/**
* Returns netty application call with [message] as a request
* and channel for request body
*/
private fun prepareCallFromRequest(
context: ChannelHandlerContext,
message: HttpRequest
): NettyHttp1ApplicationCall {
val requestBodyChannel = when {
message is LastHttpContent && !message.content().isReadable -> null
message.method() === HttpMethod.GET &&
!HttpUtil.isContentLengthSet(message) && !HttpUtil.isTransferEncodingChunked(message) -> {
skipEmpty = true
null
}
else -> prepareRequestContentChannel(context, message)
}
return NettyHttp1ApplicationCall(
environment.application,
context,
message,
requestBodyChannel,
engineContext,
userContext
)
}
private fun prepareRequestContentChannel(
context: ChannelHandlerContext,
message: HttpRequest
): ByteReadChannel {
val bodyHandler = context.pipeline().get(RequestBodyHandler::class.java)
val result = bodyHandler.newChannel()
if (message is HttpContent) {
bodyHandler.channelRead(context, message)
}
return result
}
private fun callReadIfNeeded(context: ChannelHandlerContext) {
if (state.activeRequests.value < runningLimit) {
context.read()
state.skippedRead.value = false
} else {
state.skippedRead.value = true
}
}
}
| apache-2.0 | bcc76b2655669357ad480e024f8153be | 32.534161 | 119 | 0.650306 | 5.206365 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonPageHolder.kt | 1 | 10981 | package eu.kanade.tachiyomi.ui.reader.viewer.webtoon
import android.content.res.Resources
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.core.view.updateMargins
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import eu.kanade.tachiyomi.databinding.ReaderErrorBinding
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderProgressIndicator
import eu.kanade.tachiyomi.ui.webview.WebViewActivity
import eu.kanade.tachiyomi.util.system.ImageUtil
import eu.kanade.tachiyomi.util.system.dpToPx
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.InputStream
import java.util.concurrent.TimeUnit
/**
* Holder of the webtoon reader for a single page of a chapter.
*
* @param frame the root view for this holder.
* @param viewer the webtoon viewer.
* @constructor creates a new webtoon holder.
*/
class WebtoonPageHolder(
private val frame: ReaderPageImageView,
viewer: WebtoonViewer
) : WebtoonBaseHolder(frame, viewer) {
/**
* Loading progress bar to indicate the current progress.
*/
private val progressIndicator = createProgressIndicator()
/**
* Progress bar container. Needed to keep a minimum height size of the holder, otherwise the
* adapter would create more views to fill the screen, which is not wanted.
*/
private lateinit var progressContainer: ViewGroup
/**
* Error layout to show when the image fails to load.
*/
private var errorLayout: ReaderErrorBinding? = null
/**
* Getter to retrieve the height of the recycler view.
*/
private val parentHeight
get() = viewer.recycler.height
/**
* Page of a chapter.
*/
private var page: ReaderPage? = null
/**
* Subscription for status changes of the page.
*/
private var statusSubscription: Subscription? = null
/**
* Subscription for progress changes of the page.
*/
private var progressSubscription: Subscription? = null
/**
* Subscription used to read the header of the image. This is needed in order to instantiate
* the appropiate image view depending if the image is animated (GIF).
*/
private var readImageHeaderSubscription: Subscription? = null
init {
refreshLayoutParams()
frame.onImageLoaded = { onImageDecoded() }
frame.onImageLoadError = { onImageDecodeError() }
frame.onScaleChanged = { viewer.activity.hideMenu() }
}
/**
* Binds the given [page] with this view holder, subscribing to its state.
*/
fun bind(page: ReaderPage) {
this.page = page
observeStatus()
refreshLayoutParams()
}
private fun refreshLayoutParams() {
frame.layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
if (!viewer.isContinuous) {
bottomMargin = 15.dpToPx
}
val margin = Resources.getSystem().displayMetrics.widthPixels * (viewer.config.sidePadding / 100f)
marginEnd = margin.toInt()
marginStart = margin.toInt()
}
}
/**
* Called when the view is recycled and added to the view pool.
*/
override fun recycle() {
unsubscribeStatus()
unsubscribeProgress()
unsubscribeReadImageHeader()
removeErrorLayout()
frame.recycle()
progressIndicator.setProgress(0, animated = false)
}
/**
* Observes the status of the page and notify the changes.
*
* @see processStatus
*/
private fun observeStatus() {
unsubscribeStatus()
val page = page ?: return
val loader = page.chapter.pageLoader ?: return
statusSubscription = loader.getPage(page)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { processStatus(it) }
addSubscription(statusSubscription)
}
/**
* Observes the progress of the page and updates view.
*/
private fun observeProgress() {
unsubscribeProgress()
val page = page ?: return
progressSubscription = Observable.interval(100, TimeUnit.MILLISECONDS)
.map { page.progress }
.distinctUntilChanged()
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { value -> progressIndicator.setProgress(value) }
addSubscription(progressSubscription)
}
/**
* Called when the status of the page changes.
*
* @param status the new status of the page.
*/
private fun processStatus(status: Int) {
when (status) {
Page.QUEUE -> setQueued()
Page.LOAD_PAGE -> setLoading()
Page.DOWNLOAD_IMAGE -> {
observeProgress()
setDownloading()
}
Page.READY -> {
setImage()
unsubscribeProgress()
}
Page.ERROR -> {
setError()
unsubscribeProgress()
}
}
}
/**
* Unsubscribes from the status subscription.
*/
private fun unsubscribeStatus() {
removeSubscription(statusSubscription)
statusSubscription = null
}
/**
* Unsubscribes from the progress subscription.
*/
private fun unsubscribeProgress() {
removeSubscription(progressSubscription)
progressSubscription = null
}
/**
* Unsubscribes from the read image header subscription.
*/
private fun unsubscribeReadImageHeader() {
removeSubscription(readImageHeaderSubscription)
readImageHeaderSubscription = null
}
/**
* Called when the page is queued.
*/
private fun setQueued() {
progressContainer.isVisible = true
progressIndicator.show()
removeErrorLayout()
}
/**
* Called when the page is loading.
*/
private fun setLoading() {
progressContainer.isVisible = true
progressIndicator.show()
removeErrorLayout()
}
/**
* Called when the page is downloading
*/
private fun setDownloading() {
progressContainer.isVisible = true
progressIndicator.show()
removeErrorLayout()
}
/**
* Called when the page is ready.
*/
private fun setImage() {
progressIndicator.setProgress(0)
removeErrorLayout()
unsubscribeReadImageHeader()
val streamFn = page?.stream ?: return
var openStream: InputStream? = null
readImageHeaderSubscription = Observable
.fromCallable {
val stream = streamFn().buffered(16)
openStream = process(stream)
ImageUtil.isAnimatedAndSupported(stream)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { isAnimated ->
frame.setImage(
openStream!!,
isAnimated,
ReaderPageImageView.Config(
zoomDuration = viewer.config.doubleTapAnimDuration,
minimumScaleType = SubsamplingScaleImageView.SCALE_TYPE_FIT_WIDTH,
cropBorders = viewer.config.imageCropBorders
)
)
}
// Keep the Rx stream alive to close the input stream only when unsubscribed
.flatMap { Observable.never<Unit>() }
.doOnUnsubscribe { openStream?.close() }
.subscribe({}, {})
addSubscription(readImageHeaderSubscription)
}
private fun process(imageStream: InputStream): InputStream {
if (!viewer.config.dualPageSplit) {
return imageStream
}
val isDoublePage = ImageUtil.isDoublePage(imageStream)
if (!isDoublePage) {
return imageStream
}
val upperSide = if (viewer.config.dualPageInvert) ImageUtil.Side.LEFT else ImageUtil.Side.RIGHT
return ImageUtil.splitAndMerge(imageStream, upperSide)
}
/**
* Called when the page has an error.
*/
private fun setError() {
progressContainer.isVisible = false
initErrorLayout(withOpenInWebView = false)
}
/**
* Called when the image is decoded and going to be displayed.
*/
private fun onImageDecoded() {
progressContainer.isVisible = false
}
/**
* Called when the image fails to decode.
*/
private fun onImageDecodeError() {
progressContainer.isVisible = false
initErrorLayout(withOpenInWebView = true)
}
/**
* Creates a new progress bar.
*/
private fun createProgressIndicator(): ReaderProgressIndicator {
progressContainer = FrameLayout(context)
frame.addView(progressContainer, MATCH_PARENT, parentHeight)
val progress = ReaderProgressIndicator(context).apply {
updateLayoutParams<FrameLayout.LayoutParams> {
gravity = Gravity.CENTER_HORIZONTAL
updateMargins(top = parentHeight / 4)
}
}
progressContainer.addView(progress)
return progress
}
/**
* Initializes a button to retry pages.
*/
private fun initErrorLayout(withOpenInWebView: Boolean): ReaderErrorBinding {
if (errorLayout == null) {
errorLayout = ReaderErrorBinding.inflate(LayoutInflater.from(context), frame, true)
errorLayout?.root?.layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, (parentHeight * 0.8).toInt())
errorLayout?.actionRetry?.setOnClickListener {
page?.let { it.chapter.pageLoader?.retryPage(it) }
}
val imageUrl = page?.imageUrl
if (imageUrl.orEmpty().startsWith("http", true)) {
errorLayout?.actionOpenInWebView?.setOnClickListener {
val intent = WebViewActivity.newIntent(context, imageUrl!!)
context.startActivity(intent)
}
}
}
errorLayout?.actionOpenInWebView?.isVisible = withOpenInWebView
return errorLayout!!
}
/**
* Removes the decode error layout from the holder, if found.
*/
private fun removeErrorLayout() {
errorLayout?.let {
frame.removeView(it.root)
errorLayout = null
}
}
}
| apache-2.0 | 0f379d93f3b642ac07513fe96175c5fd | 29.502778 | 114 | 0.627994 | 5.102695 | false | false | false | false |
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/GeneratorTarget.kt | 3 | 13923 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
import java.nio.file.*
internal const val HEADER = """/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
"""
internal val JAVA_KEYWORDS = setOf(
// Java keywords
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum",
"extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package",
"private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
"try", "void", "volatile", "while"
)
// Character sequence used for alignment
const val t = " " // 4 spaces
internal class Preamble {
companion object {
data class NativeDefine(
val expression: String,
val beforeIncludes: Boolean
)
private val EMPTY_IMPORTS = ArrayList<String>(0)
private val EMPTY_DIRECTIVES = ArrayList<NativeDefine>(0)
}
private var javaImports: MutableList<String> = EMPTY_IMPORTS
private var nativeImports: MutableList<String> = EMPTY_IMPORTS
private var nativeDirectives: MutableList<NativeDefine> = EMPTY_DIRECTIVES
internal val hasNativeDirectives get() = nativeImports.isNotEmpty() || nativeDirectives.isNotEmpty()
fun javaImport(vararg classes: String) {
if (javaImports === EMPTY_IMPORTS)
javaImports = ArrayList(classes.size)
classes.forEach {
javaImports.add(it)
}
}
fun nativeImport(vararg files: String) {
if (nativeImports === EMPTY_IMPORTS)
nativeImports = ArrayList(files.size)
files.forEach {
nativeImports.add(if (it.startsWith('<'))
it
else
"\"$it\"")
}
}
fun nativeDirective(expression: String, beforeIncludes: Boolean) {
if (nativeDirectives === EMPTY_DIRECTIVES)
nativeDirectives = ArrayList()
nativeDirectives.add(NativeDefine(expression, beforeIncludes))
}
fun printJava(writer: PrintWriter) {
if (javaImports.isEmpty())
return
fun List<String>.print() = this.forEach { writer.println("import $it;") }
val static = javaImports.filter { it.startsWith("static ") }
if (static.isNotEmpty() && static.size < javaImports.size) {
// Separate plain from static imports
javaImports.filter { !it.startsWith("static ") }.print()
writer.println()
static.print()
} else
javaImports.print()
writer.println()
}
internal fun printNative(writer: PrintWriter) {
nativeDirectives.filter { it.beforeIncludes }.forEach {
writer.println(it.expression)
}
writer.println("#include \"common_tools.h\"")
nativeImports.forEach {
writer.println("#include $it")
}
nativeDirectives.filter { !it.beforeIncludes }.forEach {
writer.println(it.expression)
}
}
}
private val JNI_UNDERSCORE_ESCAPE_PATTERN = "_".toRegex()
internal val String.asJNIName
get() = if (this.indexOf('_') == -1)
this
else
this.replace(JNI_UNDERSCORE_ESCAPE_PATTERN, "_1")
enum class Access(val modifier: String) {
PUBLIC("public "),
INTERNAL(""),
PRIVATE("private ")
}
@DslMarker
annotation class GeneratorDslMarker
@GeneratorDslMarker
abstract class GeneratorTarget(
val module: Module,
val className: String
) {
companion object {
private val LINKS = Pair(
"""\p{javaJavaIdentifierStart}\p{javaJavaIdentifierPart}*(?:\.\p{javaJavaIdentifierStart}\p{javaJavaIdentifierPart}*)*""",
"""\p{javaJavaIdentifierPart}+""" // Must match tokens like GL_3_BYTES (the link is #3_BYTES)
).let { (JAVA, NATIVE) -> """($JAVA)?(?<!&)([@\\]?#{1,2})($NATIVE+(?:\((?:(?:, )?$JAVA)*\))?)""".toRegex() }
}
private fun getSourceFileName(): String? {
// Nasty hack to retrieve the source file that defines this template, without having to specify it explictly.
// This enables incremental builds to work even with arbitrary file names or when multiple templates are bundled
// in the same file (e.g. ExtensionFlags).
try {
throw RuntimeException()
} catch (t: Throwable) {
return t.stackTrace.asSequence()
.filter { !it.className.startsWith("org.lwjgl.generator.") }
.mapNotNull { it.fileName }
.filter { it.endsWith(".kt") && !(this is NativeClass && it.endsWith("Binding.kt")) }
.firstOrNull()
}
}
internal val sourceFile = getSourceFileName()
internal open fun getLastModified(root: String): Long = Paths.get(root, sourceFile).let {
if (Files.isRegularFile(it)) it else
throw IllegalStateException("The source file for template ${module.packageKotlin}.$className does not exist ($it).")
}.lastModified
var subpackage: String? = null
val packageName get() = if (subpackage == null) module.packageName else "${module.packageName}.$subpackage"
var access = Access.PUBLIC
set(access) {
require(access !== Access.PRIVATE) {
"The private access modifier is illegal on top-level classes."
}
field = access
}
var documentation: String? = null
var see: Array<String>? = null
var since: String = ""
internal val preamble = Preamble()
fun <T : GeneratorTarget> T.javaImport(vararg classes: String): T {
preamble.javaImport(*classes)
return this
}
fun <T : GeneratorTarget> T.nativeDirective(expression: String, beforeIncludes: Boolean = false): T {
preamble.nativeDirective(expression, beforeIncludes)
return this
}
protected fun linksFromRegex(pattern: String) = pattern.toRegex().let { regex ->
Generator.tokens[module]!!
.asSequence()
.mapNotNull { if (regex.matches(it.key)) it.key else null }
.joinToString(" #", prefix = "#")
.let {
if (it.length == 1)
throw IllegalStateException("Failed to match any tokens with regex: $pattern")
else
it
}
}
infix fun Int.x(other: Int) = this * other
protected fun PrintWriter.generateJavaPreamble() {
print(HEADER)
println("package $packageName;\n")
preamble.printJava(this)
val documentation = [email protected]
if (documentation != null)
println(processDocumentation(documentation).toJavaDoc(indentation = "", see = see, since = since))
}
abstract fun PrintWriter.generateJava()
open fun processDocumentation(documentation: String, forcePackage: Boolean = false): String {
processSeeLinks("", "", forcePackage)
return processDocumentation(documentation, "", "", forcePackage)
}
open fun getFieldLink(field: String): String? = null
open fun getMethodLink(method: String): String? = null
protected fun processSeeLinks(prefixConstant: String, prefixMethod: String, forcePackage: Boolean = false) {
val see = this.see
if (see != null) {
for (i in see.indices) {
see[i] = processDocumentation(see[i], prefixConstant, prefixMethod, forcePackage, false)
}
}
}
protected fun processDocumentation(
documentation: String,
prefixConstant: String,
prefixMethod: String,
forcePackage: Boolean = false,
javadocLinkWrap: Boolean = true
) = documentation.replace(LINKS) { match ->
/*
# - normal link, apply prefix
## - custom link, do not transform
@# or @## - like above, but add "see " in front
\# - escape, replace with #
*/
val linkMethod = match.groupValues[2]
if (linkMethod[0] == '\\') {
match.value.replace("\\#", "#")
} else {
var className = match.groupValues[1]
var classElement = match.groupValues[3]
if (classElement == "NULL")
return@replace "{@code NULL}"
val linkType = if (classElement.endsWith(')')) LinkType.METHOD else LinkType.FIELD
var prefix = if (linkType === LinkType.FIELD) prefixConstant else prefixMethod
linkMethod.count { it == '#' }.let { hashes ->
if (hashes == 1) {
if (className.isEmpty()) {
val qualifiedLink = if (linkType === LinkType.FIELD)
getFieldLink(classElement) ?: Generator.tokens[module]!![classElement]
else
classElement.substring(0, classElement.lastIndexOf('(')).let {
getMethodLink(it) ?: Generator.functions[module]!![it]
}
if (qualifiedLink != null) {
val hashIndex = qualifiedLink.indexOf('#')
className = qualifiedLink.substring(0, hashIndex)
if (forcePackage)
className = "$packageName.$className"
prefix = qualifiedLink.substring(hashIndex + 1, qualifiedLink.length - if (linkType === LinkType.FIELD)
classElement.length
else
classElement.lastIndexOf('(') + 2
)
} else {
throw IllegalStateException("Failed to resolve link: ${match.value} in ${this.className}")
}
} else {
if (classElement.startsWith(prefix))
classElement = classElement.substring(prefix.length)
else
prefix = ""
}
linkType.create(this.className, prefix, className, classElement, if (this is NativeClass) this.postfix else "", !javadocLinkWrap)
} else if (hashes == 2 && className.isEmpty() && linkType === LinkType.FIELD)
classElement
else
throw IllegalStateException("Unsupported link syntax: ${match.value} in ${this.className}")
}.let {
val link = if (javadocLinkWrap) "{@link $it}" else it
if (linkMethod[0] == '@')
"see $link"
else
link
}
}
}
private enum class LinkType {
FIELD {
override fun create(sourceName: String, sourcePrefix: String, className: String?, classElement: String, postfix: String, skipAlias: Boolean): String {
val source = if (className == null || className == sourceName) "" else className
return "$source#$sourcePrefix$classElement${if (skipAlias || sourcePrefix.isEmpty()) "" else " $classElement"}"
}
},
METHOD {
override fun create(sourceName: String, sourcePrefix: String, className: String?, classElement: String, postfix: String, skipAlias: Boolean): String {
val source = if (className == null || className == sourceName) "" else className
val parentheses = classElement.indexOf('(')
check(parentheses != -1) {
"Invalid method link: $this#$sourcePrefix$classElement"
}
val name = classElement.substring(0, parentheses)
val hasParams = parentheses < classElement.length - 2
return "$source#$sourcePrefix$name${if (hasParams) classElement.substring(parentheses) else ""}${when {
hasParams || skipAlias || sourcePrefix.isEmpty()
-> ""
else -> " $name"
}}"
}
};
abstract fun create(sourceName: String, sourcePrefix: String, className: String?, classElement: String, postfix: String, skipAlias: Boolean): String
}
}
abstract class GeneratorTargetNative(
module: Module,
className: String,
val nativeSubPath: String = ""
) : GeneratorTarget(module, className) {
internal val nativeFileName
get() = "${this.packageName.replace('.', '_')}_${this.className}"
internal val nativeFileNameJNI = packageName
.splitToSequence('.')
.plus(className)
.map { it.asJNIName }
.joinToString("_")
open val skipNative = false
var cpp = false
fun <T : GeneratorTargetNative> T.nativeImport(vararg files: String): T {
preamble.nativeImport(*files)
return this
}
protected fun PrintWriter.generateNativePreamble() {
print(HEADER)
preamble.printNative(this)
}
abstract fun PrintWriter.generateNative()
}
// ------------------------------------
fun packageInfo(
module: Module,
documentation: String
) {
Generator.register(object : GeneratorTarget(module, "package-info") {
override fun PrintWriter.generateJava() {
print(HEADER)
println()
println(processDocumentation(documentation, forcePackage = true).toJavaDoc(indentation = "", see = see, since = since))
println("""@org.lwjgl.system.NonnullDefault
package $packageName;
""")
}
})
} | bsd-3-clause | d2d357ae375bff7422e4e2cb46eba975 | 35.072539 | 162 | 0.573871 | 4.935484 | false | false | false | false |
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/JavaDoc.kt | 4 | 13198 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import kotlin.math.*
private val REDUNDANT_WHITESPACE = "^[ \\t]+$".toRegex(RegexOption.MULTILINE)
private const val BLOCK_NODE = "(?:div|h[1-6]|pre|table|thead|tfoot|tbody|td|tr|ul|li|ol|dl|dt|dd)" // TODO: add more here if necessary
private val FRAGMENT = "(</?$BLOCK_NODE(?:\\s[^>]+)?>|^)([\\s\\S]*?)(?=</?$BLOCK_NODE(?:\\s[^>]+)?>|$)".toRegex()
private val CHILD_NODE = "<(?:tr|thead|tfoot|tbody|li|dt|dd)>".toRegex()
private val PARAGRAPH_PATTERN = "\\n\\n(?:\\n?[ \\t]*[\\S][^\\n]*)+".toRegex(RegexOption.MULTILINE)
private val PREFIX_PATTERN = "^(?:\uFFFF|[ \t]++(?![*]))".toRegex(RegexOption.MULTILINE)
/*
Here we perform the following transformation:
<block> <block>
text text
text => <p>text</p>
text <p>text</p>
<div> <div>
text text
text <p>text</p>
</div> </div>
text <p>text</p>
</block> </block>
The first text sub-block is not wrapped in <p> because:
a) It is not strictly necessary, renders fine in browsers and IDEs.
b) It improves readability of the source javadoc.
For the purposes of this transformation, the javadoc root is an implicit block.
*/
private fun String.cleanup(linePrefix: String = "$t * "): String {
val dom = trim().replace(REDUNDANT_WHITESPACE, "")
return StringBuilder(dom.length)
.layoutDOM(dom, linePrefix)
.replace(PREFIX_PATTERN, linePrefix)
}
private fun StringBuilder.layoutDOM(dom: String, linePrefix: String): StringBuilder {
FRAGMENT.findAll(dom).forEach { match ->
val (tag, text) = match.destructured
if (tag.isNotEmpty()) {
if (startNewLine(dom, match.range.first)) {
if (!tag.startsWith("</") && !tag.matches(CHILD_NODE)) {
append('\n')
append(linePrefix)
}
append('\n')
append(linePrefix)
}
append(tag)
}
text.trim().let {
if (it.isNotEmpty())
layoutText(it, linePrefix, forceParagraph = tag.isNotEmpty() && tag.startsWith("</"))
}
}
return this
}
private fun startNewLine(dom: String, index: Int): Boolean {
if (index == 0)
return false
for (i in (index - 1) downTo 0) {
if (dom[i] == '\n')
return true
if (!dom[i].isWhitespace())
break
}
return false
}
private fun StringBuilder.layoutText(text: String, linePrefix: String, forceParagraph: Boolean = false) {
var to: Int = -1
PARAGRAPH_PATTERN.findAll(text).forEach { match ->
val from = match.range.first
if (to == -1 && from > 0)
appendParagraphFirst(linePrefix, text, from, forceParagraph)
to = match.range.last + 1
appendParagraph(linePrefix, text, from, to)
}
if (to == -1)
appendParagraphFirst(linePrefix, text, text.length, forceParagraph)
else if (to < text.length)
appendParagraph(linePrefix, text, to, text.length)
}
private fun StringBuilder.appendParagraphFirst(linePrefix: String, text: String, end: Int, forceParagraph: Boolean = false) {
if (forceParagraph)
appendParagraph(linePrefix, text, 0, end)
else
append(text, 0, end)
}
private fun StringBuilder.appendParagraph(linePrefix: String, text: String, start: Int, end: Int) {
append('\n')
append(linePrefix)
append('\n')
append(linePrefix)
append("<p>")
append(text.substring(start, end).trim())
append("</p>")
}
private fun String.layoutJavadoc(indentation: String = t): String {
return if (this.indexOf('\n') == -1)
"$indentation/** $this */"
else
"$indentation/**\n$indentation * $this\n$indentation */"
}
fun String.toJavaDoc(indentation: String = t, see: Array<String>? = null, since: String = "") =
if (see == null && since.isEmpty()) {
this
.cleanup("$indentation * ")
.layoutJavadoc(indentation)
} else {
StringBuilder(if (this.isEmpty()) "" else this.cleanup("$indentation * "))
.apply {
if (see != null) {
if (isNotEmpty()) append("\n$indentation *")
see.forEach {
if (isNotEmpty()) append("\n$indentation * ")
append("@see ")
append(it)
}
}
if (since.isNotEmpty()) {
if (isNotEmpty()) append("\n$indentation *\n$indentation * ")
append("@since ")
append(since)
}
}
.toString()
.layoutJavadoc(indentation)
}
/** Specialized formatting for methods. */
internal fun GeneratorTarget.toJavaDoc(
documentation: String,
params: Sequence<Parameter>,
returns: NativeType,
returnDoc: String,
see: Array<String>?,
since: String,
indentation: String = t
): String {
if (returnDoc.isEmpty() && see == null && since.isEmpty()) {
if (documentation.isEmpty() && params.all { it.documentation == null })
return ""
if (params.none())
return documentation.toJavaDoc(indentation)
}
return StringBuilder(if (documentation.isEmpty()) "" else documentation.cleanup())
.apply {
val paramsWithJavadoc = params.filter { it.documentation != null }
val returnsStructValue = returnDoc.isNotEmpty() && returns is StructType
if (paramsWithJavadoc.any() || returnsStructValue) {
// Find maximum param name length
var alignment = paramsWithJavadoc
.map { it.name.length }
.fold(0) { left, right -> max(left, right) }
if (returnsStructValue)
alignment = max(alignment, RESULT.length)
val multilineAligment = paramMultilineAligment(alignment)
if (isNotEmpty()) append("\n$indentation *")
paramsWithJavadoc
.forEach {
printParam(it.name, it.documentation.let { doc -> if (doc == null) "" else processDocumentation(doc()) }, indentation, alignment, multilineAligment)
}
if (returnsStructValue)
printParam(RESULT, processDocumentation(returnDoc), indentation, alignment, multilineAligment)
}
if (returnDoc.isNotEmpty() && !returnsStructValue) {
if (isNotEmpty()) append("\n$indentation *\n$indentation * ")
append("@return ")
append(processDocumentation(returnDoc).cleanup("$indentation * "))
}
if (see != null) {
if (isNotEmpty()) append("\n$indentation *")
see.forEach {
if (isNotEmpty()) append("\n$indentation * ")
append("@see ")
append(it)
}
}
if (since.isNotEmpty()) {
if (isNotEmpty()) append("\n$indentation *\n$indentation * ")
append("@since ")
append(since)
}
}
.toString()
.layoutJavadoc(indentation)
}
// Used for aligning parameter javadoc when it spans multiple lines.
private fun paramMultilineAligment(alignment: Int): String {
val whitespace = " @param ".length + alignment + 1
return StringBuilder("$t *".length + whitespace).apply {
append("$t *")
for (i in 0 until whitespace)
append(' ')
}.toString()
}
private fun StringBuilder.printParam(name: String, documentation: String, indentation: String, alignment: Int, multilineAligment: String) {
if (isNotEmpty()) append("\n$indentation * ")
append("@param $name")
// Align
for (i in 0..(alignment - name.length))
append(' ')
append(documentation.cleanup(multilineAligment))
}
enum class LinkMode {
SINGLE {
override fun print(multi: Boolean): String = if (multi) "One of:" else "Must be:"
},
SINGLE_CNT {
override fun print(multi: Boolean): String = if (multi) "one of:" else "must be:"
},
BITFIELD {
override fun print(multi: Boolean): String = "One or more of:"
},
BITFIELD_CNT {
override fun print(multi: Boolean): String = "one or more of:"
};
companion object {
private val WHITESPACE = "\\s+".toRegex()
}
protected abstract fun print(multi: Boolean): String
internal fun appendLinks(documentation: String, links: String): String {
val trimmed = documentation.trim()
val builder = StringBuilder(trimmed.length + 16 + links.length) // Rough estimate to reduce mallocs. TODO: validate
val effectiveLinkMode: LinkMode
if (trimmed.isEmpty()) {
effectiveLinkMode = when (this) {
SINGLE -> SINGLE_CNT
BITFIELD -> BITFIELD_CNT
else -> this
}
} else {
effectiveLinkMode = this
builder.append(trimmed)
if (this == SINGLE || this == BITFIELD) {
if (!trimmed.endsWith('.'))
builder.append('.')
}
builder.append(' ')
}
builder.append(effectiveLinkMode.print(links.any { Character.isWhitespace(it) }))
builder.append("<br><table><tr>")
val theLinks = WHITESPACE.split(links.trim()).asSequence()
val columns = max(1, 80 / theLinks.map { it.length - it.indexOf('#') - 1 }.average().roundToInt())
theLinks.forEachIndexed { i, link ->
if (i > 0 && i % columns == 0)
builder.append("</tr><tr>")
builder
.append("<td>")
.append(link)
.append("</td>")
}
builder.append("</tr></table>")
return builder.toString()
}
}
// DSL extensions
infix fun String.mergeLargeLiteral(other: String): String = this.plus(other)
private val HTML_ESCAPE_PATTERN = """[<>]=?|&(?!#|(?:amp|hellip|ge|gt|le|lt);)""".toRegex()
private val String.htmlEscaped: String
get() = this.replace(HTML_ESCAPE_PATTERN) {
when (it.value) {
"<" -> "<"
"<=" -> "≤"
">" -> ">"
">=" -> "≥"
"&" -> "&"
else -> throw IllegalStateException()
}
}
/** Useful for simple expressions. HTML markup is allowed. */
fun code(code: String) = """<code>$code</code>"""
private val CODE_BLOCK_TRIM_PATTERN = """^\s*\n|\n\s*$""".toRegex() // first and/or last empty lines
private val CODE_BLOCK_ESCAPE_PATTERN = "^".toRegex(RegexOption.MULTILINE) // line starts
private val CODE_BLOCK_TAB_PATTERN = "\t".toRegex() // tabs
/** Useful for pre-formatted code blocks. HTML markup is not allowed and will be escaped. */
fun codeBlock(code: String) = """<pre><code>
${code
.htmlEscaped
.replace(CODE_BLOCK_TRIM_PATTERN, "") // ...trim
.replace(CODE_BLOCK_ESCAPE_PATTERN, "\uFFFF") // ...escape
.replace(CODE_BLOCK_TAB_PATTERN, " ") // ...replace with 4 spaces for consistent formatting.
}</code></pre>"""
fun note(content: String) = "<div style=\"margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;\"><h5>Note</h5>\n$content</div>"
fun url(href: String, innerHTML: String = href) = """<a target="_blank" href="$href">$innerHTML</a>"""
fun table(vararg rows: String) = StringBuilder(512).run {
append("<table class=striped>")
for (row in rows) {
append("\n$t")
append(row)
}
append("\n$t</table>")
toString()
}
fun tr(vararg columns: String) = StringBuilder().run {
append("<tr>")
for (column in columns)
append(column)
append("</tr>")
toString()
}
fun th(content: String = "", colspan: Int = 1, rowspan: Int = 1) = td(content, colspan, rowspan, "th")
fun td(content: String = "", colspan: Int = 1, rowspan: Int = 1, tag: String = "td", className: String? = null) = StringBuilder().run {
append("<$tag")
if (1 < colspan)
append(" colspan=$colspan")
if (1 < rowspan)
append(" rowspan=$rowspan")
if (className != null)
append(" class=\"$className\"")
append(">")
append(content.trim())
append("</$tag>")
toString()
}
private fun htmlList(tag: String, attributes: String, vararg items: String) = StringBuilder(512).run {
append("<$tag")
if (attributes.isNotEmpty())
append(" $attributes")
append(">")
for (li in items) {
append("\n$t<li>")
append(li.trim())
append("</li>")
}
append("\n$t</$tag>")
toString()
}
fun ul(vararg items: String) = htmlList("ul", "", *items)
fun ol(vararg items: String, marker: Char = '1') = htmlList("ol", if (marker == '1') "" else "type=$marker", *items) | bsd-3-clause | 932cc53cc7e5410449ab3420c69a8c99 | 32.080201 | 172 | 0.555387 | 4.162094 | false | false | false | false |
octarine-noise/BetterFoliage | src/main/kotlin/mods/betterfoliage/client/integration/ForestryIntegration.kt | 1 | 7838 | package mods.betterfoliage.client.integration
import mods.betterfoliage.BetterFoliageMod
import mods.betterfoliage.client.Client
import mods.betterfoliage.client.config.Config
import mods.betterfoliage.client.render.LogRegistry
import mods.betterfoliage.client.render.StandardLogRegistry
import mods.betterfoliage.client.render.column.ColumnTextureInfo
import mods.betterfoliage.client.render.column.SimpleColumnInfo
import mods.betterfoliage.client.texture.LeafInfo
import mods.betterfoliage.client.texture.LeafRegistry
import mods.betterfoliage.client.texture.StandardLeafKey
import mods.betterfoliage.loader.Refs
import mods.octarinecore.client.resource.ModelRenderKey
import mods.octarinecore.client.resource.ModelRenderRegistry
import mods.octarinecore.client.resource.ModelRenderRegistryBase
import mods.octarinecore.getTileEntitySafe
import mods.octarinecore.metaprog.ClassRef
import mods.octarinecore.metaprog.FieldRef
import mods.octarinecore.metaprog.MethodRef
import mods.octarinecore.metaprog.allAvailable
import net.minecraft.block.state.IBlockState
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.block.model.ModelResourceLocation
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraftforge.client.event.TextureStitchEvent
import net.minecraftforge.client.model.IModel
import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.eventhandler.EventPriority
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import org.apache.logging.log4j.Level
import kotlin.collections.Map
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.emptyMap
import kotlin.collections.find
import kotlin.collections.forEach
import kotlin.collections.get
import kotlin.collections.listOf
import kotlin.collections.mapValues
import kotlin.collections.mutableMapOf
import kotlin.collections.set
@SideOnly(Side.CLIENT)
object ForestryIntegration {
val TextureLeaves = ClassRef("forestry.arboriculture.models.TextureLeaves")
val TeLleafTextures = FieldRef(TextureLeaves, "leafTextures", Refs.Map)
val TeLplain = FieldRef(TextureLeaves, "plain", Refs.ResourceLocation)
val TeLfancy = FieldRef(TextureLeaves, "fancy", Refs.ResourceLocation)
val TeLpollplain = FieldRef(TextureLeaves, "pollinatedPlain", Refs.ResourceLocation)
val TeLpollfancy = FieldRef(TextureLeaves, "pollinatedFancy", Refs.ResourceLocation)
val TileLeaves = ClassRef("forestry.arboriculture.tiles.TileLeaves")
val TiLgetLeaveSprite = MethodRef(TileLeaves, "getLeaveSprite", Refs.ResourceLocation, ClassRef.boolean)
val PropertyWoodType = ClassRef("forestry.arboriculture.blocks.PropertyWoodType")
val IWoodType = ClassRef("forestry.api.arboriculture.IWoodType")
val barkTex = MethodRef(IWoodType, "getBarkTexture", Refs.String)
val heartTex = MethodRef(IWoodType, "getHeartTexture", Refs.String)
val PropertyTreeType = ClassRef("forestry.arboriculture.blocks.PropertyTreeType")
val TreeDefinition = ClassRef("forestry.arboriculture.genetics.TreeDefinition")
val IAlleleTreeSpecies = ClassRef("forestry.api.arboriculture.IAlleleTreeSpecies")
val ILeafSpriteProvider = ClassRef("forestry.api.arboriculture.ILeafSpriteProvider")
val TdSpecies = FieldRef(TreeDefinition, "species", IAlleleTreeSpecies)
val getLeafSpriteProvider = MethodRef(IAlleleTreeSpecies, "getLeafSpriteProvider", ILeafSpriteProvider)
val getSprite = MethodRef(ILeafSpriteProvider, "getSprite", Refs.ResourceLocation, ClassRef.boolean, ClassRef.boolean)
init {
if (Loader.isModLoaded("forestry") && allAvailable(TiLgetLeaveSprite, getLeafSpriteProvider, getSprite)) {
Client.log(Level.INFO, "Forestry support initialized")
LeafRegistry.addRegistry(ForestryLeafRegistry)
LogRegistry.addRegistry(ForestryLogRegistry)
}
}
}
object ForestryLeafRegistry : ModelRenderRegistry<LeafInfo> {
val logger = BetterFoliageMod.logDetail
val textureToKey = mutableMapOf<ResourceLocation, ModelRenderKey<LeafInfo>>()
var textureToValue = emptyMap<ResourceLocation, LeafInfo>()
override fun get(state: IBlockState, world: IBlockAccess, pos: BlockPos): LeafInfo? {
// check variant property (used in decorative leaves)
state.properties.entries.find {
ForestryIntegration.PropertyTreeType.isInstance(it.key) && ForestryIntegration.TreeDefinition.isInstance(it.value)
} ?.let {
val species = ForestryIntegration.TdSpecies.get(it.value)
val spriteProvider = ForestryIntegration.getLeafSpriteProvider.invoke(species!!)
val textureLoc = ForestryIntegration.getSprite.invoke(spriteProvider!!, false, Minecraft.isFancyGraphicsEnabled())
return textureToValue[textureLoc]
}
// extract leaf texture information from TileEntity
val tile = world.getTileEntitySafe(pos) ?: return null
if (!ForestryIntegration.TileLeaves.isInstance(tile)) return null
val textureLoc = ForestryIntegration.TiLgetLeaveSprite.invoke(tile, Minecraft.isFancyGraphicsEnabled()) ?: return null
return textureToValue[textureLoc]
}
@SubscribeEvent
fun handlePreStitch(event: TextureStitchEvent.Pre) {
textureToValue = emptyMap()
val allLeaves = ForestryIntegration.TeLleafTextures.getStatic() as Map<*, *>
allLeaves.entries.forEach {
logger.log(Level.DEBUG, "ForestryLeavesSupport: base leaf type ${it.key.toString()}")
listOf(
ForestryIntegration.TeLplain.get(it.value) as ResourceLocation,
ForestryIntegration.TeLfancy.get(it.value) as ResourceLocation,
ForestryIntegration.TeLpollplain.get(it.value) as ResourceLocation,
ForestryIntegration.TeLpollfancy.get(it.value) as ResourceLocation
).forEach { textureLocation ->
val key = StandardLeafKey(logger, textureLocation.toString()).apply { onPreStitch(event.map) }
textureToKey[textureLocation] = key
}
}
}
@SubscribeEvent(priority = EventPriority.LOW)
fun handlePostStitch(event: TextureStitchEvent.Post) {
textureToValue = textureToKey.mapValues { (_, key) -> key.resolveSprites(event.map) }
textureToKey.clear()
}
}
object ForestryLogRegistry : ModelRenderRegistryBase<ColumnTextureInfo>() {
override val logger = BetterFoliageMod.logDetail
override fun processModel(state: IBlockState, modelLoc: ModelResourceLocation, model: IModel): ModelRenderKey<ColumnTextureInfo>? {
// respect class list to avoid triggering on fences, stairs, etc.
if (!Config.blocks.logClasses.matchesClass(state.block)) return null
// find wood type property
val woodType = state.properties.entries.find {
ForestryIntegration.PropertyWoodType.isInstance(it.key) && ForestryIntegration.IWoodType.isInstance(it.value)
} ?: return null
logger.log(Level.DEBUG, "ForestryLogRegistry: block state $state")
logger.log(Level.DEBUG, "ForestryLogRegistry: variant ${woodType.value}")
// get texture names for wood type
val bark = ForestryIntegration.barkTex.invoke(woodType.value) as String?
val heart = ForestryIntegration.heartTex.invoke(woodType.value) as String?
logger.log(Level.DEBUG, "ForestryLogSupport: textures [heart=$heart, bark=$bark]")
if (bark != null && heart != null) return SimpleColumnInfo.Key(logger, StandardLogRegistry.getAxis(state), listOf(heart, heart, bark))
return null
}
} | mit | cebcb3e9ade2981bb8cb28d234bea280 | 49.902597 | 142 | 0.766139 | 4.164718 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/utils/ExtractsNatives.kt | 1 | 5903 | package graphics.scenery.utils;
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.util.jar.JarFile
import java.io.ByteArrayOutputStream
import java.io.IOException
/**
* Helper interface for classes which might need to extract native libraries.
*
* @author Ulrik Günther <[email protected]>
*/
interface ExtractsNatives {
enum class Platform {
UNKNOWN, WINDOWS, LINUX, MACOS
}
companion object {
/**
* Returns the platform based on the os.name system property.
*/
@JvmStatic fun getPlatform(): Platform {
val os = System.getProperty("os.name").lowercase()
return when {
os.contains("win") -> Platform.WINDOWS
os.contains("linux") -> Platform.LINUX
os.contains("mac") -> Platform.MACOS
else -> Platform.UNKNOWN
}
}
}
/**
* Cleans old temporary native libraries, e.g. all directories in the temporary directory,
* which have "scenery-natives-tmp" in their name, and do not have a lock file present.
*/
fun cleanTempFiles() {
File(System.getProperty("java.io.tmpdir")).listFiles().forEach { file ->
if (file.isDirectory && file.name.contains("scenery-natives-tmp")) {
val lock = File(file, ".lock")
// delete the temporary directory only if the lock does not exist
if (!lock.exists()) {
file.deleteRecursively()
}
}
}
}
/**
* Utility function to extract native libraries from a given JAR, store them in a
* temporary directory and modify the JRE's library path such that it can find
* these libraries.
*
* @param[paths] A list of JAR paths to extract natives from.
* @param[replace] Whether or not the java.library.path should be replaced.
*/
fun extractLibrariesFromJar(paths: List<String>, replace: Boolean = false, load: Boolean = false): String {
// FIXME: Kotlin bug, revert to LazyLogger as soon as https://youtrack.jetbrains.com/issue/KT-19690 is fixed.
// val logger by LazyLogger()
val logger = LoggerFactory.getLogger(this.javaClass.simpleName)
val tmpDir = Files.createTempDirectory("scenery-natives-tmp").toFile()
val lock = File(tmpDir, ".lock")
lock.createNewFile()
lock.deleteOnExit()
cleanTempFiles()
val files = ArrayList<String>()
val nativeLibraryExtensions = hashMapOf(
Platform.WINDOWS to listOf("dll"),
Platform.LINUX to listOf("so"),
Platform.MACOS to listOf("dylib", "jnilib"))
logger.debug("Got back ${paths.joinToString(", ")}")
paths.filter { it.lowercase().endsWith("jar") }.forEach {
logger.debug("Extracting $it...")
val jar = JarFile(it)
val enumEntries = jar.entries()
while (enumEntries.hasMoreElements()) {
val file = enumEntries.nextElement()
if(file.getName().substringAfterLast(".") !in nativeLibraryExtensions[getPlatform()]!!) {
continue
}
files.add(tmpDir.absolutePath + File.separator + file.getName())
val f = File(files.last())
// create directory, if needed
if (file.isDirectory()) {
f.mkdir()
continue
}
val ins = jar.getInputStream(file)
val baos = ByteArrayOutputStream()
val fos = FileOutputStream(f)
val buffer = ByteArray(1024)
var len: Int = ins.read(buffer)
while (len > -1) {
baos.write(buffer, 0, len)
len = ins.read(buffer)
}
baos.flush()
fos.write(baos.toByteArray())
if(getPlatform() == Platform.MACOS && file.name.substringAfterLast(".") == "jnilib") {
logger.debug("macOS: Making dylib copy of jnilib file for compatibility")
try {
f.copyTo(File(tmpDir.absolutePath + File.separator + file.name.substringBeforeLast(".") + ".dylib"), false)
} catch (e: IOException) {
logger.warn("Failed to create copy of ${file.name} to ${file.name.substringBeforeLast(".")}.dylib")
}
}
fos.close()
baos.close()
ins.close()
}
}
if(load) {
files.forEach { lib ->
logger.debug("Loading native library $lib")
System.load(lib)
}
}
return tmpDir.absolutePath
}
/**
* Utility function to search the current class path for JARs with native libraries
*
* @param[searchName] The string to match the JAR's name against
* @param[hint] A file name to look for, for the ImageJ classpath hack
* @return A list of JARs matching [searchName]
*/
fun getNativeJars(searchName: String, hint: String = ""): List<String> {
val res = Thread.currentThread().contextClassLoader.getResource(hint)
if (res == null) {
LoggerFactory.getLogger(this.javaClass.simpleName).error("Could not find JAR matching \"" + searchName + "\" with native libraries (${getPlatform()}, $hint).")
return listOf()
}
var jar = res.path
var pathOffset = 5
if (getPlatform() == Platform.WINDOWS) {
pathOffset = 6
}
jar = jar.substring(jar.indexOf("file:/") + pathOffset).substringBeforeLast("!")
return jar.split(File.pathSeparator)
}
}
| lgpl-3.0 | 49dea0f431bfa195ea4b748891620868 | 34.130952 | 171 | 0.560996 | 4.873658 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/MinecraftModuleType.kt | 1 | 1076 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.creator.MinecraftModuleBuilder
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.ModuleTypeManager
class MinecraftModuleType : JavaModuleType() {
override fun createModuleBuilder() = MinecraftModuleBuilder()
override fun getIcon() = PlatformAssets.MINECRAFT_ICON
override fun getNodeIcon(isOpened: Boolean) = PlatformAssets.MINECRAFT_ICON
override fun getName() = NAME
override fun getDescription() = "Minecraft modules are used for developing plugins or mods for <b>Minecraft</b> (Java Edition, also known as the PC Edition)."
companion object {
private const val ID = "MINECRAFT_MODULE_TYPE"
const val NAME = "Minecraft"
val instance: MinecraftModuleType
get() = ModuleTypeManager.getInstance().findByID(ID) as MinecraftModuleType
}
}
| mit | ffb458bed97b059b9d5f66a267249dcf | 31.606061 | 162 | 0.743494 | 4.559322 | false | false | false | false |
mdanielwork/intellij-community | python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.kt | 3 | 1855 | // 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.jetbrains.python.statistics
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.jetbrains.python.packaging.PyPIPackageCache
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.sdk.PythonSdkType
/**
* Reports usages like Django.2.0.6 or Flask.null (if latest)
*/
object PyPackageVersionUsagesCollector : ProjectUsagesCollector() {
override fun getUsages(project: Project) = getUsagesInt(project, true)
override fun getGroupId() = "statistics.python.packages.versions"
}
object PyPackageUsagesCollector : ProjectUsagesCollector() {
override fun getUsages(project: Project) = getUsagesInt(project, false)
override fun getGroupId() = "statistics.python.packages"
}
private fun getUsagesInt(project: Project, addVersion: Boolean): Set<UsageDescriptor> {
val result = HashSet<UsageDescriptor>()
val app = ApplicationManager.getApplication()
for (module in ModuleManager.getInstance(project).modules) {
val sdk = PythonSdkType.findPythonSdk(module) ?: continue
app.runReadAction {
PyPackageManager.getInstance(sdk).getRequirements(module)?.apply {
val packageNames = PyPIPackageCache.getInstance().packageNames
filter { it.name in packageNames }.forEach { req ->
val value = req.name + if (addVersion) "." + req.versionSpecs.firstOrNull()?.version?.trim() else ""
result.add(UsageDescriptor(value, 1))
}
}
}
}
return result
}
| apache-2.0 | fa1b79deeddc9a4ada6e6e85c6852d4c | 40.222222 | 140 | 0.766038 | 4.46988 | false | false | false | false |
programmerr47/ganalytics | ganalytics-core/src/main/java/com/github/programmerr47/ganalytics/core/GanalyticsSettings.kt | 1 | 1923 | package com.github.programmerr47.ganalytics.core
class ConcatList(private val origin: HashMap<Class<out Any>, TypedLabelConverter<out Any>>) {
operator fun plus(item: Pair<Class<out Any>, TypedLabelConverter<out Any>>) = apply {
origin.put(item.first, item.second)
}
operator fun plusAssign(item: ConcatList) {
origin.putAll(item.origin)
}
fun lookup(clazz: Class<Any>) = origin[clazz]
}
fun <T : Any> converters(vararg elements: TypedConverterPair<T>) = ConcatList(hashMapOf(*elements))
class GanalyticsSettings {
var prefixSplitter: String = ""
var postfixSplitter: String = ""
var namingConvention: NamingConvention = NamingConventions.LOWER_CASE
var cutOffAnalyticsClassPrefix: Boolean = true
var labelTypeConverters: ConcatList = converters<Any>()
var useTypeConvertersForSubType: Boolean = true
fun <T : Any> addTypeConverter(type: Class<T>, converter: (T) -> String) = apply {
labelTypeConverters += type to TypeConverter(converter)
}
}
inline fun GanalyticsSettings(init: GanalyticsSettings.() -> Unit) = GanalyticsSettings().apply { init() }
fun GanalyticsSettings.createGroup(eventProvider: EventProvider) = AnalyticsGroupWrapper(eventProvider, this)
inline fun GanalyticsSettings.createGroup(crossinline eventProvider: (Event) -> Unit) = AnalyticsGroupWrapper(eventProvider, this)
fun GanalyticsSettings.createSingle(eventProvider: EventProvider) = AnalyticsSingleWrapper(eventProvider, this)
inline fun GanalyticsSettings.createSingle(crossinline eventProvider: (Event) -> Unit) = AnalyticsSingleWrapper(eventProvider, this)
inline fun Ganalytics(eventProvider: EventProvider, init: GanalyticsSettings.() -> Unit) = GanalyticsSettings(init).createGroup(eventProvider)
inline fun Ganalytics(crossinline eventProvider: (Event) -> Unit, init: GanalyticsSettings.() -> Unit) = GanalyticsSettings(init).createGroup(eventProvider) | mit | e324316b767186b63f636d00f6090efc | 47.1 | 156 | 0.763911 | 4.321348 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/util.kt | 8 | 2635 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.highlighter
import com.intellij.codeHighlighting.TextEditorHighlightingPass
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
internal fun PsiFile.getGroovyFile(): GroovyFileBase? = viewProvider.getPsi(GroovyLanguage) as? GroovyFileBase
internal abstract class GroovyHighlightingPass(val myFile: PsiFile, document: Document)
: TextEditorHighlightingPass(myFile.project, document) {
private val myInfos = mutableListOf<HighlightInfo>()
override fun doApplyInformationToEditor() {
if (myInfos.isEmpty()) return
UpdateHighlightersUtil.setHighlightersToEditor(
myProject, myDocument, 0, myFile.textLength, myInfos, colorsScheme, id
)
}
protected fun addInfo(element: PsiElement, attribute: TextAttributesKey) {
val builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION)
builder.range(element).needsUpdateOnTyping(false).textAttributes(attribute).create()?.let {
myInfos.add(it)
}
}
protected fun addInfo(info : HighlightInfo) {
myInfos.add(info)
}
}
internal fun PsiMethod.isMethodWithLiteralName() = this is GrMethod && nameIdentifierGroovy.isStringNameElement()
internal fun GrReferenceElement<*>.isReferenceWithLiteralName() = referenceNameElement.isStringNameElement()
private fun PsiElement?.isStringNameElement() = this?.node?.elementType in TokenSets.STRING_LITERAL_SET
internal fun GrReferenceElement<*>.isAnonymousClassReference(): Boolean {
return (parent as? GrAnonymousClassDefinition)?.baseClassReferenceGroovy == this
}
internal fun PsiElement.isThisOrSuper() = node?.elementType?.let {
it == GroovyTokenTypes.kTHIS || it == GroovyTokenTypes.kSUPER
} ?: false
| apache-2.0 | b046aa19fdae4811f439783f092a40c4 | 43.661017 | 120 | 0.814421 | 4.519726 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/usecases/creating_message_application/src/main/kotlin/com/example/sqs/App.kt | 1 | 2158 | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.sqs
import kotlinx.coroutines.runBlocking
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@SpringBootApplication
open class App
fun main(args: Array<String>) {
runApplication<App>(*args)
}
@CrossOrigin(origins = ["*"])
@RestController
@RequestMapping("chat/")
class MessageResource {
// Get messages from the FIFO queue.
@GetMapping("msgs")
fun getItems(request: HttpServletRequest?, response: HttpServletResponse?): List<MessageData?>? = runBlocking {
val msgService = SendReceiveMessages()
return@runBlocking msgService.getMessages()
}
// Purge the queue.
@GetMapping("purge")
fun purgeMessages(request: HttpServletRequest?, response: HttpServletResponse?): String? = runBlocking {
val msgService = SendReceiveMessages()
msgService.purgeMyQueue()
return@runBlocking "Queue is purged"
}
// Adds a new message to the FIFO queue.
@PostMapping("add")
fun addItems(request: HttpServletRequest, response: HttpServletResponse?): List<MessageData?>? = runBlocking {
val user = request.getParameter("user")
val message = request.getParameter("message")
val msgService = SendReceiveMessages()
// Generate the ID.
val uuid = UUID.randomUUID()
val msgId = uuid.toString()
val messageOb = MessageData()
messageOb.id = msgId
messageOb.name = user
messageOb.body = message
msgService.processMessage(messageOb)
return@runBlocking msgService.getMessages()
}
}
| apache-2.0 | 8e95d17f428fec826a7538b8642fc2ef | 32.71875 | 115 | 0.731233 | 4.660907 | false | false | false | false |
flesire/ontrack | ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/RunInfoJdbcRepository.kt | 1 | 3846 | package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.structure.RunInfo
import net.nemerosa.ontrack.model.structure.RunInfoInput
import net.nemerosa.ontrack.model.structure.RunnableEntityType
import net.nemerosa.ontrack.model.structure.Signature
import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository
import net.nemerosa.ontrack.repository.support.getNullableInt
import org.springframework.stereotype.Repository
import javax.sql.DataSource
@Repository
class RunInfoJdbcRepository(
dataSource: DataSource
) : AbstractJdbcRepository(dataSource), RunInfoRepository {
override fun getRunInfo(runnableEntityType: RunnableEntityType, id: Int): RunInfo? {
return getFirstItem(
"SELECT * FROM RUN_INFO WHERE ${runnableEntityType.name.toUpperCase()} = :entityId",
params("entityId", id),
{ rs, _ ->
RunInfo(
rs.getInt("ID"),
rs.getString("SOURCE_TYPE"),
rs.getString("SOURCE_URI"),
rs.getString("TRIGGER_TYPE"),
rs.getString("TRIGGER_DATA"),
rs.getNullableInt("RUN_TIME"),
readSignature(rs)
)
}
)
}
override fun deleteRunInfo(runnableEntityType: RunnableEntityType, id: Int): Ack {
val runInfo = getRunInfo(runnableEntityType, id)
namedParameterJdbcTemplate.update(
"DELETE FROM RUN_INFO WHERE ${runnableEntityType.name.toUpperCase()} = :entityId",
params("entityId", id)
)
return Ack.validate(runInfo != null)
}
override fun setRunInfo(
runnableEntityType: RunnableEntityType,
id: Int,
input: RunInfoInput,
signature: Signature
): RunInfo {
// Gets the existing run info if any
val runInfo = getRunInfo(runnableEntityType, id)
// Parameters
val params = params("runTime", input.runTime)
.addValue("sourceType", input.sourceType)
.addValue("sourceUri", input.sourceUri)
.addValue("triggerType", input.triggerType)
.addValue("triggerData", input.triggerData)
.addValue("creation", Time.forStorage(signature.time))
.addValue("creator", signature.user.name)
// If existing, updates it
if (runInfo != null) {
namedParameterJdbcTemplate.update(
"UPDATE RUN_INFO " +
"SET SOURCE_TYPE = :sourceType, " +
"SOURCE_URI = :sourceUri, " +
"TRIGGER_TYPE = :triggerType, " +
"TRIGGER_DATA = :triggerData, " +
"CREATION = :creation, " +
"CREATOR = :creator, " +
"RUN_TIME = :runTime " +
"WHERE ID = :id",
params.addValue("id", runInfo.id)
)
}
// Else, creates it
else {
namedParameterJdbcTemplate.update(
"INSERT INTO RUN_INFO(${runnableEntityType.name.toUpperCase()}, SOURCE_TYPE, SOURCE_URI, TRIGGER_TYPE, TRIGGER_DATA, RUN_TIME, CREATION, CREATOR) " +
"VALUES (:entityId, :sourceType, :sourceUri, :triggerType, :triggerData, :runTime, :creation, :creator)",
params.addValue("entityId", id)
)
}
// OK
return getRunInfo(runnableEntityType, id) ?: throw IllegalStateException("Run info should have been created")
}
}
| mit | dd9e7b3324f5586b25756edd1055c4c0 | 43.206897 | 169 | 0.562663 | 5.134846 | false | false | false | false |
olegarx/restler | jar-executor-plugin/src/main/kotlin/org/restler/StartProcessMojo.kt | 3 | 2783 | package org.restler
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.MojoFailureException
import org.apache.maven.plugins.annotations.LifecyclePhase
import org.apache.maven.plugins.annotations.Mojo
import org.apache.maven.plugins.annotations.Parameter
import java.io.*
import java.util.concurrent.CompletableFuture
import java.util.regex.Pattern
import kotlin.concurrent.thread
@Mojo(name = "start", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST)
class StartProcessMojo : AbstractMojo() {
@Parameter(required = true, defaultValue = "")
private lateinit var jar: String
@Parameter(defaultValue = "")
private var waitingLine: String = ""
@Parameter(defaultValue = "0")
private val delay: Long = 0
private var waitingFutureLine: CompletableFuture<Void> = CompletableFuture()
private lateinit var waitingLinePattern: Pattern
override fun execute() {
try {
if (!jar.endsWith(".jar")) {
log.error("File must be jar.")
throw MojoFailureException("File must be jar.")
} else if (!File(jar).exists()) {
log.error("Can't find file " + jar)
throw MojoFailureException("Can't find file " + jar)
}
val newProcess = Runtime.getRuntime().exec("java -jar $jar")
if (newProcess.isAlive) {
log.info("Process is started.")
}
CurrentProcess.setProcess(newProcess);
waitingLinePattern = Pattern.compile(waitingLine)
runInputStreamReader(newProcess.inputStream) { checkWaitingLine(it); log.info(it) }
runInputStreamReader(newProcess.errorStream) { log.error(it) }
if (delay > 0) {
log.info("Start waiting " + delay + "ms ...")
Thread.sleep(delay)
if (newProcess.isAlive) {
log.info("Stop waiting.")
}
}
if(!waitingLine.isEmpty()) {
waitingFutureLine.get()
}
if (!newProcess.isAlive) {
log.info("Process is stopped.")
}
} catch (e: IOException) {
log.error(e.message)
} catch (e: InterruptedException) {
log.error(e.message)
}
}
private fun checkWaitingLine(line: String) {
if(waitingLinePattern.matcher(line).matches()) {
waitingFutureLine.complete(null)
}
}
private fun runInputStreamReader(inputStream: InputStream, printMessage: (String) -> Unit) {
thread(isDaemon = true) {
BufferedReader(InputStreamReader(inputStream)).use { br ->
br.forEachLine(printMessage)
}
}
}
}
| apache-2.0 | 40029567262bb5f6522792a69dba129b | 31.741176 | 96 | 0.599353 | 4.562295 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/storage/file/FileStore.kt | 1 | 1968 | package io.georocket.storage.file
import io.georocket.constants.ConfigConstants
import io.georocket.storage.Store
import io.georocket.util.PathUtils
import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.core.file.OpenOptions
import io.vertx.kotlin.coroutines.await
import java.io.FileNotFoundException
/**
* Stores chunks on the file system
* @author Michel Kraemer
*/
class FileStore(private val vertx: Vertx, storagePath: String? = null) : Store {
/**
* The folder where the chunks should be saved
*/
private val root: String
init {
val actualStoragePath = storagePath ?: vertx.orCreateContext.config().getString(
ConfigConstants.STORAGE_FILE_PATH) ?: throw IllegalArgumentException(
"""Missing configuration item "${ConfigConstants.STORAGE_FILE_PATH}"""")
root = PathUtils.join(actualStoragePath, "file")
}
override suspend fun add(chunk: Buffer, path: String) {
val filepath = PathUtils.join(root, path)
val parent = filepath.substring(0, filepath.lastIndexOf('/'))
// create storage folder
val fs = vertx.fileSystem()
fs.mkdirs(parent).await()
// open new file
val f = fs.open(filepath, OpenOptions()).await()
// write contents to file
f.write(chunk).await()
f.close().await()
}
override suspend fun getOne(path: String): Buffer {
val absolutePath = PathUtils.join(root, path)
// check if chunk exists
val fs = vertx.fileSystem()
if (!fs.exists(absolutePath).await()) {
throw FileNotFoundException("Could not find chunk: $path")
}
return fs.readFile(absolutePath).await()
}
override suspend fun delete(paths: Collection<String>): Long {
var result = 0L
val fs = vertx.fileSystem()
for (path in paths) {
val absolutePath = PathUtils.join(root, path)
if (fs.exists(absolutePath).await()) {
fs.delete(absolutePath).await()
result++
}
}
return result
}
}
| apache-2.0 | 990a024536f78015241456b468138193 | 27.521739 | 84 | 0.686992 | 4.125786 | false | true | false | false |
google/intellij-community | platform/core-api/src/com/intellij/openapi/util/registry/EarlyAccessRegistryManager.kt | 1 | 4086 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.openapi.util.registry
import com.intellij.diagnostic.LoadingState
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.components.serviceOrNull
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.annotations.ApiStatus
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* Use only after consultation and approval - ask core team.
*/
@ApiStatus.Internal
@ApiStatus.Experimental
object EarlyAccessRegistryManager {
private val configFile: Path by lazy {
PathManager.getConfigDir().resolve("early-access-registry.txt")
}
private val lazyMap = lazy {
val result = ConcurrentHashMap<String, String>()
val lines = try {
Files.lines(configFile)
}
catch (ignore: NoSuchFileException) {
return@lazy result
}
lines.use { lineStream ->
val iterator = lineStream.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
if (!iterator.hasNext()) {
break
}
result.put(key, iterator.next())
}
}
result
}
private val map: ConcurrentHashMap<String, String>?
get() {
return if (lazyMap.isInitialized()) {
val map = lazyMap.value
if (map.isEmpty()) null else map
}
else
null
}
private val LOG get() = Logger.getInstance(EarlyAccessRegistryManager::class.java)
fun getBoolean(key: String): Boolean {
if (key.isEmpty()) {
LOG.error("Empty key")
return false
}
val map = lazyMap.value
val registryManager = if (LoadingState.APP_STARTED.isOccurred)
// see com.intellij.ide.plugins.PluginDescriptorLoader.loadForCoreEnv
ApplicationManager.getApplication().serviceOrNull<RegistryManager>()
else
null
if (registryManager == null) {
return java.lang.Boolean.parseBoolean(map.get(key) ?: System.getProperty(key))
}
// use RegistryManager to make sure that Registry is fully loaded
val value = registryManager.`is`(key)
// ensure that even if for some reason key was not early accessed, it is stored for early access on next start-up
map.putIfAbsent(key, value.toString())
return value
}
fun syncAndFlush() {
// Why do we sync? get (not yet loaded) -> not changed by a user but actually in a registry -> no explicit put
// Why maybe in a registry but not in our store?
// Because store file deleted / removed / loaded from ICS or registry value was set before using EarlyAccessedRegistryManager
val map = map ?: return
val registryManager = ApplicationManager.getApplication().serviceIfCreated<RegistryManager>() ?: return
try {
val lines = mutableListOf<String>()
for (key in map.keys.sorted()) {
try {
val value = registryManager.get(key).asString()
lines.add(key)
lines.add(value)
}
catch (ignore: MissingResourceException) { }
}
if (lines.isEmpty()) {
Files.deleteIfExists(configFile)
}
else {
Files.createDirectories(configFile.parent)
Files.write(configFile, lines, StandardCharsets.UTF_8)
}
}
catch (e: Throwable) {
LOG.error("cannot save early access registry", e)
}
}
@Suppress("unused") // registered in an `*.xml` file
private class MyListener : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) {
val map = map ?: return
// store only if presented - do not store alien keys
val key = value.key
if (map.containsKey(key)) {
map.put(key, value.asString())
}
}
}
} | apache-2.0 | 4091ee6dbeb85e94257f67d74f8503f4 | 29.729323 | 129 | 0.681106 | 4.374732 | false | false | false | false |
google/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/searchHelpers.kt | 2 | 5031 | // 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.search.usagesSearch
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.LightClassUtil.PropertyAccessorsPsiMethods
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
fun PsiNamedElement.getAccessorNames(readable: Boolean = true, writable: Boolean = true): List<String> {
fun PropertyAccessorsPsiMethods.toNameList(): List<String> {
val getter = getter
val setter = setter
val result = ArrayList<String>()
if (readable && getter != null) result.add(getter.name)
if (writable && setter != null) result.add(setter.name)
return result
}
if (this !is KtDeclaration || KtPsiUtil.isLocal(this)) return Collections.emptyList()
when (this) {
is KtProperty ->
return LightClassUtil.getLightClassPropertyMethods(this).toNameList()
is KtParameter ->
if (hasValOrVar()) {
return LightClassUtil.getLightClassPropertyMethods(this).toNameList()
}
}
return Collections.emptyList()
}
fun PsiNamedElement.getClassNameForCompanionObject(): String? {
return if (this is KtObjectDeclaration && this.isCompanion()) {
getNonStrictParentOfType<KtClass>()?.name
} else {
null
}
}
fun KtParameter.dataClassComponentFunction(): FunctionDescriptor? {
if (!isDataClassProperty()) return null
val context = this.analyze()
val paramDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? ValueParameterDescriptor
val constructor = paramDescriptor?.containingDeclaration as? ConstructorDescriptor ?: return null
val index = constructor.valueParameters.indexOf(paramDescriptor)
val correspondingComponentName = DataClassDescriptorResolver.createComponentName(index + 1)
val dataClass = constructor.containingDeclaration as? ClassDescriptor ?: return null
dataClass.unsubstitutedMemberScope.getContributedFunctions(correspondingComponentName, NoLookupLocation.FROM_IDE)
return context[BindingContext.DATA_CLASS_COMPONENT_FUNCTION, paramDescriptor]
}
fun KtParameter.isDataClassProperty(): Boolean {
if (!hasValOrVar()) return false
return this.containingClassOrObject?.hasModifier(KtTokens.DATA_KEYWORD) ?: false
}
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> {
val ktCallableDeclaration =
target.safeAs<KtCallableDeclaration>()?.takeIf { it.hasModifier(KtTokens.OVERRIDE_KEYWORD) } ?: return emptyList()
val callableDescriptor = ktCallableDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val descriptorsToHighlight = if (callableDescriptor is ParameterDescriptor)
listOf(callableDescriptor)
else
callableDescriptor?.findOriginalTopMostOverriddenDescriptors() ?: emptyList()
return descriptorsToHighlight.mapNotNull { it.source.getPsi() }.filter { it != target }
}
val KtDeclaration.descriptor: DeclarationDescriptor?
get() = if (this is KtParameter) this.descriptor else this.resolveToDescriptorIfAny(BodyResolveMode.FULL)
val KtParameter.descriptor: ValueParameterDescriptor?
get() = this.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)
fun isCallReceiverRefersToCompanionObject(element: KtElement, companionObject: KtObjectDeclaration): Boolean {
val companionObjectDescriptor = companionObject.descriptor
val bindingContext = element.analyze()
val resolvedCall = bindingContext[BindingContext.CALL, element]?.getResolvedCall(bindingContext) ?: return false
return (resolvedCall.dispatchReceiver as? ImplicitClassReceiver)?.declarationDescriptor == companionObjectDescriptor ||
(resolvedCall.extensionReceiver as? ImplicitClassReceiver)?.declarationDescriptor == companionObjectDescriptor
}
| apache-2.0 | 325185b066d5dd9545b2249cacb90c86 | 46.462264 | 158 | 0.786921 | 5.21888 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2018/Day16.kt | 1 | 4104 | package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day16 : Day {
private val samples = resourceLines(2018, 16).windowed(4, 4)
.takeWhile { it[0].startsWith("Before") }
.map(::parse)
private val program = resourceLines(2018, 16).windowed(3, step = 1, partialWindows = true)
.dropWhile { it.any { !it.matches("[0-9 ]+".toRegex()) } }
.map { it.first().split(" ").map { it.toInt() } }
val opCodes = mapOf(
"addr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] + reg[b] },
"addi" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] + b },
"mulr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] * reg[b] },
"muli" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] * b },
"banr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] and reg[b] },
"bani" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] and b },
"borr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] or reg[b] },
"bori" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] or b },
"setr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = reg[a] },
"seti" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = a },
"gtir" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (a > reg[b]) 1 else 0 },
"gtri" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (reg[a] > b) 1 else 0 },
"gtrr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (reg[a] > reg[b]) 1 else 0 },
"eqir" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (a == reg[b]) 1 else 0 },
"eqri" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (reg[a] == b) 1 else 0 },
"eqrr" to { a: Int, b: Int, c: Int, reg: MutableList<Int> -> reg[c] = if (reg[a] == reg[b]) 1 else 0 }
)
private fun parse(sample: List<String>): Sample {
val before = sample[0].let { it.removePrefix("Before: [").removeSuffix("]").split(", ").map { it.toInt() } }
val opcode = sample[1].let { it.split(" ").map { it.toInt() } }
val after = sample[2].let { it.removePrefix("After: [").removeSuffix("]").split(", ").map { it.toInt() } }
return Sample(before, opcode, after)
}
private fun match(sample: Sample, f: (Int, Int, Int, MutableList<Int>) -> Unit): Boolean {
val reg = sample.before.toMutableList()
f(sample.a, sample.b, sample.c, reg)
return reg == sample.after
}
private fun find(sample: Sample) = opCodes.filter { match(sample, it.value) }
data class Sample(val before: List<Int>, val instruction: List<Int>, val after: List<Int>) {
val op = instruction[0]
val a = instruction[1]
val b = instruction[2]
val c = instruction[3]
}
override fun part1() = samples.map { find(it) }.count { it.size >= 3 }
override fun part2(): Int {
val opNumberMap = mutableMapOf<Int, String>()
do {
val result = samples
.filterNot { opNumberMap.keys.contains(it.op) }
.map { it to find(it).filterNot { opNumberMap.values.contains(it.key) } }
.filter { it.second.size == 1 }
.map { it.first.op to it.second.keys.first() }
opNumberMap.putAll(result)
} while (samples.any { !opNumberMap.keys.contains(it.op) })
val register = mutableListOf(0, 0, 0, 0)
program.map { opNumberMap[it.first()] to it.drop(1) }
.filterNot { it.first == null }
.map { opCodes[it.first]!! to it.second }
.forEach { it.first(it.second[0], it.second[1], it.second[2], register) }
return register.first()
}
} | mit | 5da2522700553a6b0853e64bd304c654 | 49.060976 | 116 | 0.530702 | 3.116173 | false | false | false | false |
vhromada/Catalog | web/src/main/kotlin/com/github/vhromada/catalog/web/controller/RoleController.kt | 1 | 4349 | package com.github.vhromada.catalog.web.controller
import com.github.vhromada.catalog.web.connector.AccountConnector
import com.github.vhromada.catalog.web.connector.RoleConnector
import com.github.vhromada.catalog.web.fo.RoleFO
import com.github.vhromada.catalog.web.mapper.RoleMapper
import com.github.vhromada.catalog.web.service.AccountProvider
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.Errors
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import javax.validation.Valid
/**
* A class represents controller for roles.
*
* @author Vladimir Hromada
*/
@Controller("roleController")
@RequestMapping("/accounts/{accountUuid}/roles")
class RoleController(
/**
* Connector for roles
*/
private val connector: RoleConnector,
/**
* Connector for accounts
*/
private val accountConnector: AccountConnector,
/**
* Mapper for roles
*/
private val mapper: RoleMapper,
/**
* Provider for account
*/
private val accountProvider: AccountProvider
) {
/**
* Shows page for editing roles.
*
* @param model model
* @param accountUuid account UUID
* @return view for page for editing account
*/
@GetMapping("/edit")
fun showEdit(model: Model, @PathVariable("accountUuid") accountUuid: String): String {
val account = accountConnector.get(uuid = accountUuid)
return createFormView(model = model, role = RoleFO(roles = account.roles), accountUuid = accountUuid)
}
/**
* Process editing roles.
*
* @param model model
* @param accountUuid account UUID
* @param role FO for role
* @param errors errors
* @return view for redirect to page with list of accounts (no errors) or view for page for editing account (errors)
*/
@PostMapping(value = ["/edit"], params = ["update"])
fun processEdit(model: Model, @PathVariable("accountUuid") accountUuid: String, @ModelAttribute("role") @Valid role: RoleFO, errors: Errors): String {
if (errors.hasErrors()) {
return createFormView(model = model, role = role, accountUuid = accountUuid)
}
var loggedAccount = accountProvider.getAccount()
val stored = accountConnector.updateRoles(uuid = accountUuid, request = mapper.map(source = role))
if (loggedAccount!!.uuid == accountUuid) {
loggedAccount = loggedAccount.copy(roles = stored.roles)
SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken(loggedAccount, null, loggedAccount.roles.map { SimpleGrantedAuthority(it) })
}
return ACCOUNTS_REDIRECT_URL
}
/**
* Cancel editing roles.
*
* @param accountUuid account UUID
* @return view for redirect to page with list of accounts
*/
@PostMapping(value = ["/edit"], params = ["cancel"])
fun processEdit(@PathVariable("accountUuid") accountUuid: String): String {
accountConnector.get(uuid = accountUuid)
return ACCOUNTS_REDIRECT_URL
}
/**
* Returns page's view with form.
*
* @param model model
* @param role FO for role
* @param accountUuid account UUID
* @return page's view with form
*/
private fun createFormView(model: Model, role: RoleFO, accountUuid: String): String {
val roles = connector.getRoles()
model.addAttribute("role", role)
model.addAttribute("account", accountUuid)
model.addAttribute("roles", roles)
model.addAttribute("title", "Edit roles")
return "roles/form"
}
companion object {
/**
* Redirect URL to accounts
*/
private const val ACCOUNTS_REDIRECT_URL = "redirect:/accounts"
}
}
| mit | dcebf5cf0ca138a0894b2fdd17b1d0d4 | 33.515873 | 176 | 0.689584 | 4.671321 | false | false | false | false |
silvertern/nox | src/main/kotlin/nox/compilation/AjcTask.kt | 1 | 2661 | /**
* Copyright (c) Profidata AG 2017
*/
package nox.compilation
import org.gradle.api.DefaultTask
import org.gradle.api.JavaVersion
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.LogLevel
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskAction
import org.slf4j.LoggerFactory
open class AjcTask : DefaultTask() {
@Internal var sourceSet: SourceSet? = null
@Internal var aspectpath: FileCollection? = null
@Internal var ajInpath: FileCollection? = null
// ignore or warning
@Internal var xlint = "ignore"
@Internal var maxmem: String? = null
@Internal var additionalAjcArgs = mutableMapOf<String, String>()
init {
logging.captureStandardOutput(LogLevel.INFO)
}
@TaskAction
fun compile() {
logger.info("Compining AspectJ. Classpath: {}, srcDirs: {}",
sourceSet!!.compileClasspath.asPath,
sourceSet!!.java.srcDirs)
val ant = ant
val taskdefArgs = mutableMapOf<String, Any>()
taskdefArgs.put("resource", "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties")
taskdefArgs.put("classpath", project.configurations.getByName("ajtools").asPath)
ant.invokeMethod("taskdef", taskdefArgs)
val javaConv = project.convention.plugins["java"] as JavaPluginConvention
val sourceVersion = toAspectJVersion(javaConv.sourceCompatibility)
val targetVersion = toAspectJVersion(javaConv.targetCompatibility)
logger.info("AspectJ source version: ${sourceVersion}")
logger.info("AspectJ target version: ${targetVersion}")
val ajcArgs = mutableMapOf<String, Any>()
ajcArgs.put("classpath", sourceSet!!.compileClasspath.asPath)
ajcArgs.put("destDir", sourceSet!!.output.classesDirs.singleFile.absolutePath)
ajcArgs.put("s", sourceSet!!.output.classesDirs.singleFile.absolutePath)
ajcArgs.put("source", sourceVersion)
ajcArgs.put("target", targetVersion)
ajcArgs.put("inpath", ajInpath!!.asPath)
ajcArgs.put("xlint", xlint)
ajcArgs.put("fork", "true")
ajcArgs.put("aspectPath", aspectpath!!.asPath)
ajcArgs.put("sourceRootCopyFilter", "**/*.java,**/*.aj")
ajcArgs.put("showWeaveInfo", "true")
ajcArgs.put("sourceRoots", sourceSet!!.java.sourceDirectories.asPath)
if (maxmem != null) {
ajcArgs.put("maxmem", maxmem!!)
}
ajcArgs.putAll(additionalAjcArgs)
ant.invokeMethod("iajc", ajcArgs)
}
fun toAspectJVersion(version: JavaVersion): String {
if (version.majorVersion.toInt() >= 10) {
return version.majorVersion
}
return version.toString()
}
companion object {
private val logger = LoggerFactory.getLogger(AjcTask::class.java)
}
}
| mit | 54204d32b8e556ea44a5b87bf2d52d94 | 28.566667 | 90 | 0.749342 | 3.552737 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/course_news/reducer/CourseNewsReducer.kt | 1 | 6832 | package org.stepik.android.presentation.course_news.reducer
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_news.exception.NotEnrolledException
import org.stepik.android.presentation.course_news.CourseNewsFeature.State
import org.stepik.android.presentation.course_news.CourseNewsFeature.Message
import org.stepik.android.presentation.course_news.CourseNewsFeature.Action
import ru.nobird.app.core.model.slice
import ru.nobird.app.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CourseNewsReducer
@Inject
constructor() : StateReducer<State, Message, Action> {
companion object {
private const val PAGE_SIZE = 20
}
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.InitMessage -> {
val sourceType = if (state is State.Idle && !state.mustFetchRemote) {
DataSourceType.CACHE
} else {
DataSourceType.REMOTE
}
val fetchAnnouncementIds = message.announcementIds.slice(0, PAGE_SIZE)
if (fetchAnnouncementIds.isEmpty()) {
State.Empty(message.announcementIds, message.isTeacher) to emptySet()
} else {
State.LoadingAnnouncements(message.announcementIds, message.isTeacher, sourceType) to
setOf(Action.FetchAnnouncements(fetchAnnouncementIds, message.isTeacher, sourceType))
}
}
is Message.OnScreenOpenedMessage -> {
when (state) {
/**
* Necessary for the case, when CourseActivity is launched with News tab
*/
is State.Idle -> {
State.Idle(mustFetchRemote = true) to emptySet()
}
is State.Empty -> {
State.LoadingAnnouncements(state.announcementIds, state.isTeacher, DataSourceType.REMOTE) to
setOf(Action.FetchAnnouncements(state.announcementIds.slice(0, PAGE_SIZE), state.isTeacher, DataSourceType.REMOTE))
}
is State.LoadingAnnouncements -> {
if (state.sourceType == DataSourceType.CACHE) {
State.LoadingAnnouncements(state.announcementIds, state.isTeacher, DataSourceType.REMOTE) to
setOf(Action.FetchAnnouncements(state.announcementIds.slice(0, PAGE_SIZE), state.isTeacher, DataSourceType.REMOTE))
} else {
null
}
}
is State.Content -> {
if (state.sourceType == DataSourceType.CACHE) {
state.copy(isLoadingRemote = true) to
setOf(Action.FetchAnnouncements(state.announcementIds.slice(0, PAGE_SIZE), state.isTeacher, DataSourceType.REMOTE))
} else {
null
}
}
else ->
null
}
}
is Message.FetchAnnouncementIdsFailure -> {
if (state is State.Idle) {
if (message.throwable is NotEnrolledException) {
State.NotEnrolled to emptySet()
} else {
State.Error to emptySet()
}
} else {
null
}
}
is Message.FetchCourseNewsSuccess -> {
when (state) {
is State.LoadingAnnouncements -> {
if (message.courseNewsListItems.isEmpty()) {
State.Empty(state.announcementIds, state.isTeacher) to emptySet()
} else {
State.Content(
state.announcementIds,
message.courseNewsListItems,
state.isTeacher,
state.sourceType,
isLoadingRemote = false,
isLoadingNextPage = false
) to emptySet()
}
}
is State.Content -> {
state.copy(
courseNewsListItems = message.courseNewsListItems,
sourceType = DataSourceType.REMOTE,
isLoadingRemote = false
) to emptySet()
}
else ->
null
}
}
is Message.FetchCourseNewsFailure -> {
if (state is State.LoadingAnnouncements) {
if (state.sourceType == DataSourceType.REMOTE) {
state.copy(sourceType = DataSourceType.CACHE) to
setOf(Action.FetchAnnouncements(state.announcementIds.slice(0, PAGE_SIZE), state.isTeacher, DataSourceType.CACHE))
} else {
State.Error to emptySet()
}
} else {
null
}
}
is Message.FetchNextPage -> {
if (state is State.Content && !state.isLoadingRemote && !state.isLoadingNextPage) {
val offset = state.courseNewsListItems.size
val fetchAnnouncementIds = state.announcementIds.slice(offset, offset + PAGE_SIZE)
if (fetchAnnouncementIds.isNotEmpty()) {
state.copy(isLoadingNextPage = true) to setOf(Action.FetchAnnouncements(fetchAnnouncementIds, state.isTeacher, state.sourceType, isNextPage = true))
} else {
null
}
} else {
null
}
}
is Message.FetchCourseNewsNextPageSuccess -> {
if (state is State.Content) {
state.copy(courseNewsListItems = state.courseNewsListItems + message.courseNewsListItems, isLoadingNextPage = false) to emptySet()
} else {
null
}
}
is Message.FetchCourseNewsNextPageFailure -> {
if (state is State.Content) {
state.copy(isLoadingNextPage = false) to emptySet()
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 22e011dad92af33bd4e52953ebf2082e | 45.80137 | 172 | 0.492535 | 5.819421 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.