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
EMResearch/EvoMaster
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/logintoken/LoginTokenRest.kt
1
1037
package com.foo.rest.examples.spring.openapi.v3.logintoken import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.* @RestController @RequestMapping(path = ["/api/logintoken"]) class LoginTokenRest { private val SECRET = "a complex secret..." @PostMapping(path = ["/login"], consumes = [MediaType.APPLICATION_JSON_VALUE]) open fun login(@RequestBody login : LoginDto) : ResponseEntity<AuthDto>{ if(login.userId == "foo" && login.password == "123"){ return ResponseEntity.ok(AuthDto("foo", TokenDto(SECRET))) } return ResponseEntity.status(400).build() } @GetMapping(path = ["/check"]) open fun check(@RequestHeader("Authorization") authorization: String?) : ResponseEntity<String>{ if(authorization == "Bearer $SECRET"){ return ResponseEntity.ok("OK") } return ResponseEntity.status(401).build() } }
lgpl-3.0
f625ce8872790a6f348ce525d6dda9b7
30.454545
100
0.689489
4.357143
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/test/testdata/filetypes/properties/refactor/KotlinFile.kt
1
903
import com.badlogic.gdx.utils.I18NBundle import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets internal class JavaClass { @GDXAssets(propertiesFiles = arrayOf("src/messages.properties" )) var i18NBundle: I18NBundle = I18NBundle() @GDXAssets(propertiesFiles = ["src/doesnotexist.properties" ]) var i18NBundle2: I18NBundle = I18NBundle() @GDXAssets(propertiesFiles = ["src/extra.properties", "src/messages.properties" ]) var i18NBundle3: I18NBundle = I18NBundle() @GDXAssets(propertiesFiles = arrayOf"src/extra.properties", "src/test.properties" )) var i18NBundle4: I18NBundle = I18NBundle() var s = i18NBundle.get("newName1") fun m() { I18NBundle().get("newName1") i18NBundle.format("newName1", "", Any()) i18NBundle.format("newName1", "newName1", "") i18NBundle2.get("newName1") i18NBundle3.format("newName1") i18NBundle4.format("oldName") } }
apache-2.0
1803e537ef079a5052e99d0f3d6726c1
35.16
86
0.72979
3.555118
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/GdxJsonParserUtil.kt
1
2618
@file:Suppress("FunctionName") package com.gmail.blueboxware.libgdxplugin.filetypes.json import com.gmail.blueboxware.libgdxplugin.filetypes.json.GdxJsonElementTypes.COMMA import com.intellij.lang.PsiBuilder import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.psi.TokenType /* * Copyright 2016 Blue Box Ware * * 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. */ object GdxJsonParserUtil : GeneratedParserUtilBase() { @JvmStatic fun no_comment_or_newline(builder: PsiBuilder, @Suppress("UNUSED_PARAMETER") level: Int): Boolean { var i = 1 while (builder.rawTokenIndex() - i >= 0) { val token = builder.rawLookup(-i) if (token == GdxJsonElementTypes.BLOCK_COMMENT) { return false } else if (token == TokenType.WHITE_SPACE) { for (j in builder.rawTokenTypeStart(-i) until builder.rawTokenTypeStart(-i + 1)) { if (builder.originalText[j] == '\n') { return false } } } else { break } i++ } return true } @JvmStatic fun parseSeparator(builder: PsiBuilder, @Suppress("UNUSED_PARAMETER") level: Int): Boolean { if (builder.tokenType == COMMA) { builder.advanceLexer() return true } var i = builder.currentOffset - 1 var inComment = false while (i >= 0) { if (inComment) { if (builder.originalText[i] == '/' && builder.originalText[i + 1] == '*') { inComment = false } } else { if (i > 0 && builder.originalText[i - 1] == '*' && builder.originalText[i] == '/') { inComment = true } else if (builder.originalText[i] == '\n') { return true } else if (!builder.originalText[i].isWhitespace()) { break } } i-- } return false } }
apache-2.0
5e6941af70246cf058686ad1206ea21e
30.926829
103
0.567609
4.625442
false
false
false
false
interedition/collatex
collatex-core/src/main/java/eu/interedition/collatex/dekker/PhraseMatchDetector.kt
1
3198
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX 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. * * CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.dekker import eu.interedition.collatex.Token import eu.interedition.collatex.VariantGraph import java.util.* /** * @author Ronald Haentjens Dekker * @author Bram Buitendijk */ class PhraseMatchDetector { fun detect(linkedTokens: Map<Token, VariantGraph.Vertex>, base: VariantGraph, tokens: Iterable<Token>): List<List<Match>> { val phraseMatches: MutableList<List<Match>> = ArrayList() val basePhrase: MutableList<VariantGraph.Vertex> = ArrayList() val witnessPhrase: MutableList<Token> = ArrayList() var previous = base.start for (token in tokens) { if (!linkedTokens.containsKey(token)) { addNewPhraseMatchAndClearBuffer(phraseMatches, basePhrase, witnessPhrase) continue } val baseVertex = linkedTokens[token] // requirements: // - previous and base vertex should have the same witnesses // - previous and base vertex should either be in the same transposition(s) or both aren't in any transpositions // - there should be a directed edge between previous and base vertex // - there may not be a longer path between previous and base vertex val sameTranspositions = HashSet(previous!!.transpositions()) == HashSet(baseVertex!!.transpositions()) val sameWitnesses = previous.witnesses() == baseVertex.witnesses() val directedEdge = previous.outgoing().containsKey(baseVertex) val isNear = sameTranspositions && sameWitnesses && directedEdge && (previous.outgoing().size == 1 || baseVertex.incoming().size == 1) if (!isNear) { addNewPhraseMatchAndClearBuffer(phraseMatches, basePhrase, witnessPhrase) } basePhrase.add(baseVertex) witnessPhrase.add(token) previous = baseVertex } if (!basePhrase.isEmpty()) { phraseMatches.add(Match.createPhraseMatch(basePhrase, witnessPhrase)) } return phraseMatches } private fun addNewPhraseMatchAndClearBuffer(phraseMatches: MutableList<List<Match>>, basePhrase: MutableList<VariantGraph.Vertex>, witnessPhrase: MutableList<Token>) { if (!basePhrase.isEmpty()) { phraseMatches.add(Match.createPhraseMatch(basePhrase, witnessPhrase)) basePhrase.clear() witnessPhrase.clear() } } }
gpl-3.0
a46adf5d51389af21230a16d89c75d35
44.7
171
0.677611
4.655022
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/router/RouteManager.kt
1
5250
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.router /** * Interface of internal routing manager inside the Core Platform. * * * The routing manager is responsible for forwarding messages between containers. One * implementation of this interface is based on Apache Camel, others might follow. * * @author Julian Schuette ([email protected]) */ interface RouteManager { /** * Returns a list of currently installed routes. * * @return All installed rules */ val routes: List<RouteObject> /** * Returns a RouteObject for a given route ID. * * @param id The ID of the route to fetch * @return The queried route or null */ fun getRoute(id: String): RouteObject? /** * Starts a route. * * @param routeId ID of the route to start * @throws RouteException If starting the route failed */ @Throws(RouteException::class) fun startRoute(routeId: String) /** * Sends a request to stop a route. Camel will try to gracefully shut down the route and deliver * pending exchanges. * * @param routeId ID of the route to stop * @throws RouteException If stopping the route failed */ @Throws(RouteException::class) fun stopRoute(routeId: String) /** * List all supported components, i.e. supported endpoint protocols. * * @return List of supported components */ fun listComponents(): List<RouteComponent> /** * List all route endpoints, i.e. all URIs of routes existing in loaded Camel contexts * * @return Map of Camel context names to contained endpoint URIs */ val endpoints: Map<String, Collection<String>> fun listEndpoints(): Map<String, String> /** * Save a route, replacing it with a new representation within the same context * * @param routeId ID of the route to save * @param routeRepresentation The new textual representation of the route (XML etc.) * @return The object representing the modified route * @throws RouteException If the route does not exist or some Exception was thrown during route * replacement. */ @Throws(RouteException::class) fun saveRoute(routeId: String, routeRepresentation: String): RouteObject /** * Adds a route and starts it. * * * Endpoint declarations must be supported by the underlying implementation. * * * If the route id already exists, this method will throw a RouteException and not overwrite * the existing route. * * @param routeDefinition Textual representation of the route (XML etc.) * @throws RouteException if a route with the same id already exists or if any Exception is thrown * during loading and starting the route. */ @Throws(RouteException::class) fun addRoute(routeDefinition: String) /** * Removes a route from one endpoint to another. * * * The deletion becomes immediately effective. * * * Endpoint declarations must be supported by the underlying implementation. * * @param routeId ID of the route to delete */ fun delRoute(routeId: String) /** * Returns the given route in its original representation of the implementing engine. * * * Note that this method may return null if the implementing engine does not support a textual * route configuration. * * * For Apache Camel, this method will return the XML-based Camel DSL configuration file. * * @param routeId ID of the route to retrieve the String representation for * @return String representation of the route */ fun getRouteAsString(routeId: String): String? /** * Returns a List of URIs of the given route's inputs (from definitions) * * @param routeId The identifier of the route * @return The from (input) URIs of the route */ fun getRouteInputUris(routeId: String): List<String> /** * Returns aggregated runtime metrics of all installed routes. * * @return Map&lt;k,v&gt; where k is a string indicating the route id. */ val routeMetrics: Map<String, RouteMetrics> /** * Returns the given route configuration in a Prolog representation. * * @param routeId ID of route to retrieve prolog representation for * @return Route represented as prolog */ fun getRouteAsProlog(routeId: String): String }
apache-2.0
27e776cace23a75bc89e9cabdc39a1c0
31.8125
102
0.656952
4.674978
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/cm/Direction.kt
1
856
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.cm enum class Direction { OUTBOUND, INBOUND }
apache-2.0
0d380c5531a7419d899dcced46987add
34.666667
75
0.620327
4.412371
false
false
false
false
rori-dev/lunchbox
backend-spring-kotlin/src/main/kotlin/lunchbox/util/facebook/FacebookGraphApiImpl.kt
1
1102
package lunchbox.util.facebook import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import reactor.util.retry.Retry.backoff import java.time.Duration @ConstructorBinding @ConfigurationProperties("external.facebook") data class FacebookConfigProperties( val appId: String = "", val appSecret: String = "" ) /** * Ruft eine Resource der Facebook GraphApi ab. */ @Component class FacebookGraphApiImpl( val config: FacebookConfigProperties ) : FacebookGraphApi { override fun <T : GraphApiResource> query(url: String, clazz: Class<T>): T? { val resource = url.replaceFirst(Regex("^/"), "") val accessToken = "access_token=${config.appId}|{${config.appSecret}}" return WebClient.create("https://graph.facebook.com/v2.10/$resource?$accessToken") .get() .retrieve() .bodyToMono(clazz) .retryWhen(backoff(5, Duration.ofSeconds(5))) .block() } }
mit
2e81cf7f2e44f887faf9fd1ecea1f3a1
29.611111
86
0.747731
4.142857
false
true
false
false
j2ghz/tachiyomi-extensions
src/en/shoujosense/src/en/kanade/tachiyomi/extension/en/shoujosense/ShoujoSense.kt
1
4894
package eu.kanade.tachiyomi.extension.en.shoujosense import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar import java.util.regex.Pattern class ShoujoSense : ParsedHttpSource() { override val name = "ShoujoSense" override val baseUrl = "http://reader.shoujosense.com" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient companion object { val dateFormat by lazy { SimpleDateFormat("yyyy.MM.dd") } val pagesUrlPattern by lazy { Pattern.compile("""\"url\":\"(.*?)\"""") } } override fun popularMangaSelector() = "div.list > div.group > div.title > a" override fun latestUpdatesSelector() = popularMangaSelector() override fun popularMangaRequest(page: Int) = GET("$baseUrl/directory/$page", headers) override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/latest/$page", headers) override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.setUrlWithoutDomain(element.attr("href")) manga.title = element.text().trim() return manga } override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun popularMangaNextPageSelector() = "div.next > a:contains(Next »)" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val form = FormBody.Builder().apply { add("search", query) } return POST("$baseUrl/search", headers, form.build()) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun searchMangaNextPageSelector() = null override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.info").first() val manga = SManga.create() manga.author = infoElement.select("b:contains(Author)").first()?.nextSibling()?.toString()?.substringAfterLast(": ") // ShoujoSense does not have genre tags manga.genre = "" manga.description = infoElement.select("b:contains(Synopsis)").first()?.nextSibling()?.toString()?.substringAfterLast(": ") manga.status = SManga.UNKNOWN manga.thumbnail_url = infoElement.select("img").attr("src") return manga } fun parseStatus(status: String) = when { status.contains("Ongoing") -> SManga.ONGOING status.contains("Completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "div.list div.element" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = element.select("div.meta_r").text()?.substringAfterLast(", ")?.let { parseChapterDate(it) } ?: 0 return chapter } private fun parseChapterDate(date: String): Long { return if ("Today" in date) { Calendar.getInstance().timeInMillis } else if ("Yesterday" in date) { Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -1) }.timeInMillis } else { try { dateFormat.parse(date).time } catch (e: ParseException) { 0L } } } override fun pageListRequest(chapter: SChapter) = POST(baseUrl + chapter.url, headers) override fun pageListParse(response: Response): List<Page> { val body = response.body()!!.string() val pages = mutableListOf<Page>() val p = pagesUrlPattern val m = p.matcher(body) var i = 0 while (m.find()) { val url = m.group(1) pages.add(Page(i++, "", url.replace("""\\""", "/"))) } return pages } override fun pageListParse(document: Document): List<Page> { throw Exception("Not used") } override fun imageUrlRequest(page: Page) = GET(page.url) override fun imageUrlParse(document: Document) = "" }
apache-2.0
0be8ceca5c7ebf0b428521ab4228b564
31.403974
131
0.645821
4.769006
false
false
false
false
LorittaBot/Loritta
web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/EmbedEditor.kt
1
11095
package net.perfectdreams.loritta.embededitor import kotlinx.browser.document import kotlinx.browser.window import kotlinx.dom.addClass import kotlinx.dom.clear import kotlinx.html.* import kotlinx.html.dom.append import kotlinx.html.js.onInputFunction import kotlinx.html.stream.createHTML import kotlinx.serialization.json.Json import net.perfectdreams.loritta.embededitor.data.DiscordEmbed import net.perfectdreams.loritta.embededitor.data.DiscordMessage import net.perfectdreams.loritta.embededitor.data.crosswindow.* import net.perfectdreams.loritta.embededitor.editors.* import net.perfectdreams.loritta.embededitor.utils.MessageTagSection import net.perfectdreams.loritta.embededitor.utils.ShowdownConverter import net.perfectdreams.loritta.embededitor.utils.discordH5Heading import net.perfectdreams.loritta.embededitor.utils.lovelyButton import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLTextAreaElement import org.w3c.dom.MessageEvent class EmbedEditor { var activeMessage: DiscordMessage? = null val json = Json { prettyPrint = true encodeDefaults = false prettyPrintIndent = " " ignoreUnknownKeys = true } val markdownConverter = ShowdownConverter().apply { setOption("simpleLineBreaks", true) setOption("strikethrough", true) } var placeholders: List<Placeholder> = listOf() var isInEditMode = true var connectedViaExternalSources = false fun start() { /* window.addEventListener("keydown", { event -> event as KeyboardEvent println(event.key) if (event.key == "Control") { isInEditMode = !isInEditMode generateMessageAndUpdateJson(activeMessage!!, isInEditMode) } }) */ activeMessage = DiscordMessage("OwO whats this?") val body = document.body!! body.addClass("theme-light") body.append { div { id = "content-wrapper" discordH5Heading("Preview da Mensagem") div { id = "message-preview" } div { discordH5Heading("Código JSON") textArea(classes = "text-input inputDefault-_djjkz input-cIJ7To textArea-1Lj-Ns scrollbarDefault-3COgCQ scrollbar-3dvm_9") { id = "json-code" style = "resize: vertical; min-height: 100px;" onInputFunction = { // Load from JSON parseAndLoadFromJson((it.target as HTMLTextAreaElement).value) } } } } } generateMessageAndUpdateJson(activeMessage!!) val opener = window.opener println("Casted opener") println("Opener is... something") println("Is it null? ${opener == null}") if (opener != null) { println("Sending ready packet to opener") // I know that there is a "Window" object in Kotlin/JS, but casting it causes issues in Chromium browsers // "IllegalCastException" // So we use the good old asDynamic call opener.asDynamic().postMessage( EmbedEditorCrossWindow.communicationJson.encodeToString( PacketWrapper.serializer(), PacketWrapper( ReadyPacket() ) ), "*" ) window.addEventListener("message", { event -> event as MessageEvent println("Received message ${event.data}") if (event.source == opener) { println("Received message from our target source, yay!") val packetWrapper = EmbedEditorCrossWindow.communicationJson.decodeFromString(PacketWrapper.serializer(), event.data as String) val packet = packetWrapper.m if (packet is MessageSetupPacket) { placeholders = packet.placeholders generateMessageAndUpdateJson(packet.message) // Load our cool message connectedViaExternalSources = true } } }) } } fun parseAndLoadFromJson(rawJson: String) { val result = json.decodeFromString(DiscordMessage.serializer(), rawJson) generateMessageAndUpdateJson(result) } fun generateMessageAndUpdateJson(discordMessage: DiscordMessage, editMode: Boolean = isInEditMode) { this.activeMessage = discordMessage val editMessageTags = if (editMode) mapOf( MessageTagSection.EMBED_AUTHOR_NOT_NULL to EmbedAuthorEditor.isNotNull, MessageTagSection.EMBED_AUTHOR_NULL to EmbedAuthorEditor.isNull, MessageTagSection.EMBED_DESCRIPTION_NOT_NULL to EmbedDescriptionEditor.isNotNull, MessageTagSection.EMBED_DESCRIPTION_NULL to EmbedDescriptionEditor.isNull, MessageTagSection.EMBED_TITLE_NOT_NULL to EmbedTitleEditor.isNotNull, MessageTagSection.EMBED_TITLE_NULL to EmbedTitleEditor.isNull, MessageTagSection.EMBED_FOOTER_NOT_NULL to EmbedFooterEditor.isNotNull, MessageTagSection.EMBED_FOOTER_NULL to EmbedFooterEditor.isNull, MessageTagSection.EMBED_IMAGE_NOT_NULL to EmbedImageEditor.isNotNull, MessageTagSection.EMBED_IMAGE_NULL to EmbedImageEditor.isNull, MessageTagSection.EMBED_THUMBNAIL_NOT_NULL to EmbedThumbnailEditor.isNotNull, MessageTagSection.EMBED_THUMBNAIL_NULL to EmbedThumbnailEditor.isNull, MessageTagSection.EMBED_FIELDS_FIELD to EmbedFieldEditor.changeField, MessageTagSection.EMBED_AFTER_FIELDS to EmbedFieldEditor.addMoreFields, MessageTagSection.EMBED_PILL to EmbedPillEditor.pillCallback, MessageTagSection.MESSAGE_CONTENT to MessageContentEditor.changeContent ) else mapOf() document.select<HTMLDivElement>("#message-preview").apply { clear() append { div { style = "background-color: white;" val renderer = EmbedRenderer(discordMessage, placeholders) renderer.generateMessagePreview( this ) { currentElement, tag, renderInfo -> attributes["message-tag-section"] = tag.name editMessageTags[tag]?.invoke(this, this@EmbedEditor, discordMessage, currentElement, renderInfo) } if (editMode) { if (discordMessage.embed != null) { lovelyButton("fas fa-times", "Remover Embed", "red") { generateMessageAndUpdateJson( activeMessage!!.copy( embed = null ) ) } } else { lovelyButton("far fa-window-maximize", "Adicionar Embed") { generateMessageAndUpdateJson( activeMessage!!.copy( embed = DiscordEmbed() ) ) } } } } } } document.select<HTMLTextAreaElement>("#json-code").value = json.encodeToString(DiscordMessage.serializer(), discordMessage) if (connectedViaExternalSources) { val opener = window.opener // Same thing here, can't cast opener because "IllegalCastException" :sad_cat: opener?.asDynamic().postMessage( EmbedEditorCrossWindow.communicationJson.encodeToString( PacketWrapper.serializer(), PacketWrapper( UpdatedMessagePacket( json.encodeToString( DiscordMessage.serializer(), discordMessage ) ) ) ), "*" ) } } fun parseDiscordText(text: String, parseMarkdown: Boolean = true, convertDiscordEmotes: Boolean = true, parsePlaceholders: Boolean = true): String { var output = text if (parseMarkdown) { output = markdownConverter.makeHtml(output) } if (parsePlaceholders) { for (placeholder in placeholders) { when (placeholder.renderType) { RenderType.TEXT -> output = output.replace(placeholder.name, placeholder.replaceWith) RenderType.MENTION -> output = output.replace( placeholder.name, createHTML().span(classes = "mention wrapper-3WhCwL mention interactive") { + placeholder.replaceWith } ) else -> {} } } } if (convertDiscordEmotes) { // EMOTES // Nós fazemos uma vez antes e depois uma depois, para evitar bugs (já que :emoji: também existe dentro de <:emoji:...> val regex = Regex("<(a)?:([A-z0-9_-]+):([0-9]+)>", RegexOption.MULTILINE) output = regex.replace(output) { matchResult: MatchResult -> // <img class="inline-emoji" src="https://cdn.discordapp.com/emojis/$2.png?v=1"> val extension = if (matchResult.groups[1]?.value == "a") "gif" else "png" "<img class=\"inline-emoji\" src=\"https://cdn.discordapp.com/emojis/${matchResult.groups[3]?.value}.$extension?v=1\">" } } return output } fun HTMLTag.parseAndAppendDiscordText(text: String, parseMarkdown: Boolean = true, convertDiscordEmotes: Boolean = true) { unsafe { raw(parseDiscordText(text, parseMarkdown, convertDiscordEmotes)) } } fun parseAndAppendDiscordText(content: HTMLTag, text: String, parseMarkdown: Boolean = true, convertDiscordEmotes: Boolean = true) { content.unsafe { raw(parseDiscordText(text, parseMarkdown, convertDiscordEmotes)) } } }
agpl-3.0
be64a879741952ab570b3b12bb51fe6c
39.630037
152
0.543504
5.782586
false
false
false
false
google/xplat
j2kt/jre/java/native/kotlin/jvm/Class.kt
1
1586
/* * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package kotlin.jvm import java.lang.Class import kotlin.reflect.KClass private val objectClassMap: MutableMap<KClass<*>, Class<*>> = mutableMapOf() private val primitiveClassMap: MutableMap<KClass<*>, Class<*>> = mutableMapOf() // TODO(b/227166206): Add synchronization to make it thread-safe. val <T : Any> KClass<T>.javaObjectType: Class<T> get() = objectClassMap.getOrPut(this) { Class<T>(this, isPrimitive0 = false) } as Class<T> // TODO(b/227166206): Add synchronization to make it thread-safe. val <T : Any> KClass<T>.javaPrimitiveType: Class<T>? get() = if (hasJavaPrimitiveType) primitiveClassMap.getOrPut(this) { Class<T>(this, isPrimitive0 = true) } as Class<T> else null private val KClass<*>.hasJavaPrimitiveType: Boolean get() = when (this) { Boolean::class, Char::class, Byte::class, Short::class, Int::class, Long::class, Float::class, Double::class, Unit::class -> true else -> false }
apache-2.0
2e79fee39980a001bbdd253f556f3979
32.041667
92
0.693569
3.906404
false
false
false
false
toastkidjp/Jitte
rss/src/main/java/jp/toastkid/rss/suggestion/RssAddingSuggestion.kt
1
2234
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.rss.suggestion import android.view.View import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.rss.R import jp.toastkid.rss.extractor.RssUrlValidator import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * @author toastkidjp */ class RssAddingSuggestion( private val preferenceApplier: PreferenceApplier, private val rssUrlValidator: RssUrlValidator = RssUrlValidator(), private val contentViewModelFactory: (ViewModelStoreOwner) -> ContentViewModel? = { ViewModelProvider(it).get(ContentViewModel::class.java) }, private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main, private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.Default ) { operator fun invoke(view: View, url: String) { CoroutineScope(mainDispatcher).launch { val shouldShow = withContext(backgroundDispatcher) { shouldShow(url) } if (!shouldShow) { return@launch } toast(view, url) } } private fun toast(view: View, url: String) { (view.context as? FragmentActivity)?.let { contentViewModelFactory(it) ?.snackWithAction( view.context.getString(R.string.message_add_rss_target), view.context.getString(R.string.add), { preferenceApplier.saveNewRssReaderTargets(url) } ) } } private fun shouldShow(url: String) = rssUrlValidator.invoke(url) && !preferenceApplier.containsRssTarget(url) }
epl-1.0
87dd4ee300c05b3fcbc07165cd359b26
35.048387
88
0.707699
4.90989
false
false
false
false
tcshao/kotlin-kickstart
src/test/kotlin/CalculatorSpek.kt
1
1186
package com.example import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.amshove.kluent.shouldEqual class CalculatorSpek : Spek({ describe("the calculator") { var calculator: Calculator? = null beforeEachTest { calculator = Calculator(NullResult()) } it("should add two numbers") { var result = calculator?.add(12, 13) result shouldEqual 25 } it("should accumulate one number") { calculator?.accumulate(23) calculator?.total shouldEqual 23 } it("should accumulate two numbers") { calculator?.accumulate(2) calculator?.accumulate(4) calculator?.total shouldEqual 6 } } describe("the output should be written correctly") { var result: Result = mock() val calculator = Calculator(result) it("should write the correct amount") { calculator.accumulate(23) verify(result).write(23) } } })
mit
77a7f32cb1d09ff83a165e4bb244bbcb
25.954545
56
0.614671
4.687747
false
false
false
false
googlemaps/android-samples
ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/TagsDemoActivity.kt
1
8764
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.kotlindemos import android.graphics.Color import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.Circle import com.google.android.gms.maps.model.CircleOptions import com.google.android.gms.maps.model.GroundOverlay import com.google.android.gms.maps.model.GroundOverlayOptions import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import com.google.android.gms.maps.model.Polygon import com.google.android.gms.maps.model.PolygonOptions import com.google.android.gms.maps.model.Polyline import com.google.android.gms.maps.model.PolylineOptions /** * This shows how to use setTag/getTag on API objects. */ class TagsDemoActivity : AppCompatActivity(), GoogleMap.OnCircleClickListener, GoogleMap.OnGroundOverlayClickListener, GoogleMap.OnMarkerClickListener, OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener, GoogleMap.OnPolygonClickListener, GoogleMap.OnPolylineClickListener { private lateinit var map: GoogleMap private lateinit var tagText: TextView private val places = mapOf( "BRISBANE" to LatLng(-27.47093, 153.0235), "MELBOURNE" to LatLng(-37.81319, 144.96298), "DARWIN" to LatLng(-12.4634, 130.8456), "SYDNEY" to LatLng(-33.87365, 151.20689), "ADELAIDE" to LatLng(-34.92873, 138.59995), "PERTH" to LatLng(-31.952854, 115.857342), "ALICE_SPRINGS" to LatLng(-24.6980, 133.8807), "HOBART" to LatLng(-42.8823388, 147.311042) ) /** * Class to store a tag to attach to a map object to keep track of * how many times it has been clicked */ private class CustomTag(private val description: String) { private var clickCount: Int = 0 fun incrementClickCount() { clickCount++ } override fun toString() = "The $description has been clicked $clickCount times." } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tags_demo) tagText = findViewById(R.id.tag_text) val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment OnMapAndViewReadyListener(mapFragment, this) } override fun onMapReady(googleMap: GoogleMap?) { // return early if the map was not initialised properly map = googleMap ?: return // Add a circle, a ground overlay, a marker, a polygon and a polyline to the googleMap. addObjectsToMap() with(map.uiSettings) { // Turn off the map toolbar. isMapToolbarEnabled = false // Disable interaction with the map - other than clicking. isZoomControlsEnabled = false isScrollGesturesEnabled = false isZoomGesturesEnabled = false isTiltGesturesEnabled = false isRotateGesturesEnabled = false } with(map) { // Set listeners for click events. See the bottom of this class for their behavior. setOnCircleClickListener(this@TagsDemoActivity) setOnGroundOverlayClickListener(this@TagsDemoActivity) setOnMarkerClickListener(this@TagsDemoActivity) setOnPolygonClickListener(this@TagsDemoActivity) setOnPolylineClickListener(this@TagsDemoActivity) // Override the default content description on the view, for accessibility mode. // Ideally this string would be localised. setContentDescription(getString(R.string.tags_demo_map_description)) // include all places we have markers for in the initial view of the map val boundsBuilder = LatLngBounds.Builder() places.keys.map { boundsBuilder.include(places.getValue(it)) } // Move the camera to view all listed locations moveCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 100)) } } private fun addObjectsToMap() { with(map) { // A circle centered on Adelaide. addCircle(CircleOptions().apply { center(places.getValue("ADELAIDE")) radius(500000.0) fillColor(Color.argb(150, 66, 173, 244)) strokeColor(Color.rgb(66, 173, 244)) clickable(true) }).run { // add a tag to the circle to count clicks //tag = String("Adelaide circle") tag = "hello" } // A ground overlay at Sydney. addGroundOverlay(GroundOverlayOptions().apply { image(BitmapDescriptorFactory.fromResource(R.drawable.harbour_bridge)) position(places.getValue("SYDNEY"), 700000f) clickable(true) })?.run { // add a tag to the overlay to count clicks tag = CustomTag("Sydney ground overlay") } // A marker at Hobart. addMarker(MarkerOptions().apply { position(places.getValue("HOBART")) })?.run { // add a tag to the marker to count clicks tag = CustomTag("Hobart marker") } // A polygon centered at Darwin. addPolygon(PolygonOptions().apply{ add(LatLng(places.getValue("DARWIN").latitude + 3, places.getValue("DARWIN").longitude - 3), LatLng(places.getValue("DARWIN").latitude + 3, places.getValue("DARWIN").longitude + 3), LatLng(places.getValue("DARWIN").latitude - 3, places.getValue("DARWIN").longitude + 3), LatLng(places.getValue("DARWIN").latitude - 3, places.getValue("DARWIN").longitude - 3)) fillColor(Color.argb(150, 34, 173, 24)) strokeColor(Color.rgb(34, 173, 24)) clickable(true) }).run { // add a tag to the marker to count clicks tag = CustomTag("Darwin polygon") } // A polyline from Perth to Brisbane. addPolyline(PolylineOptions().apply{ add(places.getValue("PERTH"), places.getValue("BRISBANE")) color(Color.rgb(103, 24, 173)) width(30f) clickable(true) }).run { // add a tag to the polyline to count clicks tag = CustomTag("Perth to Brisbane polyline") } } } // Click event listeners. private fun onClick(tag: CustomTag) { tag.incrementClickCount() tagText.text = tag.toString() } override fun onCircleClick(circle: Circle) { onClick(circle.tag as? CustomTag ?: return) } override fun onGroundOverlayClick(groundOverlay: GroundOverlay) { onClick(groundOverlay.tag as? CustomTag ?: return) } override fun onMarkerClick(marker: Marker): Boolean { onClick(marker.tag as? CustomTag ?: return false) // We return true to indicate that we have consumed the event and that we do not wish // for the default behavior to occur (which is for the camera to move such that the // marker is centered and for the marker's info window to open, if it has one). return true } override fun onPolygonClick(polygon: Polygon) { onClick(polygon.tag as? CustomTag ?: return) } override fun onPolylineClick(polyline: Polyline) { onClick(polyline.tag as? CustomTag ?: return) } }
apache-2.0
7895df9b10326b33db3ed852946dd540
37.783186
97
0.630534
4.791689
false
false
false
false
Agusyc/DayCounter
app/src/main/java/com/agusyc/daycounter/WidgetUpdater.kt
1
8215
package com.agusyc.daycounter import android.app.NotificationManager import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.graphics.Color import android.util.Log import android.view.View import android.widget.RemoteViews import org.joda.time.DateTime import org.joda.time.Days import java.text.DecimalFormat import java.util.* class WidgetUpdater : AppWidgetProvider() { override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) // The receiver caught a broadcast: Log.d("WidgetUpdater", "Broadcast received!") Log.d("WidgetUpdater", "The action is: " + intent.action!!) // We check if the broadcast is telling us that a widget has been deleted if ("android.appwidget.action.APPWIDGET_DELETED" == intent.action) { // We call the deleteWidget method, that deletes the widget from the prefs deleteWidget(context, intent.extras!!.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID)) } else if (intent.action != null && intent.action!!.startsWith(WIDGET_BUTTON)) { // We get the widget's id which reset button was clicked val id_s = intent.action!!.replace(WIDGET_BUTTON, "") Log.d("WidgetUpdater", "The reset counter button was clicked for id " + id_s) val prefs = context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) // We set the date to today's prefs.edit().putLong(id_s + "date", DateTime.now().withTime(0, 0, 0, 0).millis).apply() // We tell the Notificator to update this counter val updaterIntent = Intent(context, CounterNotificator::class.java) updaterIntent.action = CounterNotificator.ACTION_UPDATE_NOTIFICATIONS updaterIntent.putExtra("widget_ids", intArrayOf(Integer.parseInt(id_s))) context.sendBroadcast(updaterIntent) // We update this widget onUpdate(context, AppWidgetManager.getInstance(context), intArrayOf(Integer.parseInt(id_s))) } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE == intent.action) { // We update all the widgets that are in the EXTRA_APPWIDGET_IDS array Log.d("WidgetUpdater", "Updating widgets...") val ids = intent.extras!!.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS) onUpdate(context, AppWidgetManager.getInstance(context), ids) } } private fun getPendingSelfIntent(context: Context, action: String, id: Int): PendingIntent { val intent = Intent(context, javaClass) intent.action = action + id return PendingIntent.getBroadcast(context, 0, intent, 0) } private fun deleteWidget(context: Context, id: Int) { Log.d("MainActivity", "Removing widget with id " + id) // We dismiss the notification (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(id) // We remove all the counter's data from the notifications val prefs = context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) prefs.edit().remove(id.toString() + "label").apply() prefs.edit().remove(id.toString() + "date").apply() prefs.edit().remove(id.toString() + "color").apply() prefs.edit().remove(id.toString() + "color_index").apply() prefs.edit().remove(id.toString() + "notification").apply() val ids_set = prefs.getStringSet("ids", HashSet<String>()) // We iterate trough the whole set, when we find the widget that is being deleted, we take it out of the set without mercy! val iterator = ids_set!!.iterator() while (iterator.hasNext()) { if (iterator.next() == Integer.toString(id)) { iterator.remove() break } } // We put the new set to the prefs prefs.edit().putStringSet("ids", ids_set).apply() } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val res = context.resources // We go trough each widget that is being updated for (appWidgetId in appWidgetIds) { val views: RemoteViews // / We get all the needed data val counter = Counter(context, appWidgetId, true) val label = counter.label val date = counter.date val currentTime = System.currentTimeMillis() val color = counter.color val hsv = FloatArray(3) Color.colorToHSV(color, hsv) val brightness = (1 - hsv[1] + hsv[2]) / 2 val difference = Days.daysBetween(DateTime(date), DateTime(currentTime)).days val formatter = DecimalFormat("#,###,###") val absDifference = Math.abs(difference) // We check the sign of the number (Positive or negative). So we know if we use "since" or "until" if (difference > 0) { // We set the right layout views = RemoteViews(context.packageName, R.layout.daycounter_since) // We update all the views views.setTextViewText(R.id.txtThereAreHaveBeen, res.getQuantityString(R.plurals.there_is_are, absDifference)) views.setTextViewText(R.id.txtLabel, res.getQuantityString(R.plurals.days_since, absDifference, if (label.length >= 17) label.substring(0, 16) + "..." else label)) views.setTextViewText(R.id.txtDays, formatter.format(absDifference)) views.setOnClickPendingIntent(R.id.btnReset, getPendingSelfIntent(context, WIDGET_BUTTON, appWidgetId)) // We check the brightness and auto-color the texts and icons accordingly if (brightness < 0.61) { views.setTextColor(R.id.txtThereAreHaveBeen, Color.WHITE) views.setTextColor(R.id.txtLabel, Color.WHITE) views.setTextColor(R.id.txtDays, Color.WHITE) views.setInt(R.id.btnReset, "setColorFilter", Color.WHITE) } } else if (difference < 0) { // We set the right layout views = RemoteViews(context.packageName, R.layout.daycounter_until) // We update all the views views.setTextViewText(R.id.txtThereAreHaveBeen, res.getQuantityString(R.plurals.there_is_are, absDifference)) views.setTextViewText(R.id.txtLabel, res.getQuantityString(R.plurals.days_until, absDifference, if (label.length >= 17) label.substring(0, 16) + "..." else label)) views.setTextViewText(R.id.txtDays, formatter.format(absDifference)) // We check the brightness and auto-color the texts accordingly if (brightness < 0.61) { views.setTextColor(R.id.txtThereAreHaveBeen, Color.WHITE) views.setTextColor(R.id.txtLabel, Color.WHITE) views.setTextColor(R.id.txtDays, Color.WHITE) } } else { // We set the right layout and the noDays text views = RemoteViews(context.packageName, R.layout.daycounter_nodays) views.setTextViewText(R.id.txtNoDays, context.getString(R.string.there_are_no_days_since, if (label.length >= 17) label.substring(0, 16) + "..." else label)) // We check the brightness and auto-color the texts accordingly if (brightness < 0.61) views.setTextColor(R.id.txtNoDays, Color.WHITE) } // We set the background color and we make the widget visible views.setInt(R.id.bkgView, "setColorFilter", color) views.setInt(R.id.lytWidget, "setVisibility", View.VISIBLE) // We actually tell the widget manager to perform all the previous updates appWidgetManager.updateAppWidget(appWidgetId, views) } } companion object { var WIDGET_BUTTON = "com.agusyc.daycounter.RESET_COUNTER" } }
mit
33eb68e35c243b43f3dfa7180b5cccfd
49.398773
179
0.635788
4.566426
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/IdentityPreferenceView.kt
1
2315
package com.garpr.android.features.settings import android.content.Context import android.content.DialogInterface import android.util.AttributeSet import android.view.View.OnClickListener import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import com.garpr.android.R import com.garpr.android.data.models.FavoritePlayer import com.garpr.android.features.common.views.SimplePreferenceView class IdentityPreferenceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : SimplePreferenceView(context, attrs), DialogInterface.OnClickListener { var listeners: Listeners? = null private val deleteIdentityClickListener = OnClickListener { AlertDialog.Builder(context) .setMessage(R.string.are_you_sure_you_want_to_delete_your_identity) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.yes, this) .show() } private val setIdentityClickListener = OnClickListener { listeners?.onSetIdentityClick(this) } interface Listeners { fun onDeleteIdentityClick(v: IdentityPreferenceView) fun onSetIdentityClick(v: IdentityPreferenceView) } init { setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_face_white_24dp)) setLoading() } override fun onClick(dialog: DialogInterface, which: Int) { listeners?.onDeleteIdentityClick(this) } fun setContent(identity: FavoritePlayer?) { isEnabled = true if (identity == null) { titleText = resources.getText(R.string.identity) descriptionText = resources.getText(R.string.easily_find_yourself_throughout_the_app) setOnClickListener(setIdentityClickListener) } else { titleText = resources.getText(R.string.delete_identity) descriptionText = resources.getString(R.string.name_region_format, identity.name, identity.region.displayName) setOnClickListener(deleteIdentityClickListener) } } fun setLoading() { isEnabled = false titleText = resources.getText(R.string.loading_identity_) descriptionText = resources.getText(R.string.please_wait_) } }
unlicense
1a2eee71db527ddeed2b7821f3e0005d
33.552239
97
0.699784
4.853249
false
false
false
false
kmmiller10/ratatouille
app/src/main/java/com/alife/geoff/kevin/alife/DNA.kt
1
3426
package com.alife.geoff.kevin.alife import java.util.concurrent.atomic.AtomicInteger /** * Created by Kevin on 8/23/2017. */ class DNA(seed: Double, creationTime: Double) { /* Companion Objects */ private class DNAIdGenerator { companion object { var uniqueId = AtomicInteger() fun getId(): Int = uniqueId.getAndIncrement() } } /* Properties */ val mId = DNAIdGenerator.getId() val mEnergy = createEnergy(seed, creationTime) val mPleasantness = createPleasantness(seed, creationTime) val mSociability = createSociability(seed, creationTime) val mVitality = createVitality(seed, creationTime) /** * | _______________________ | * | √( (t/s)² - ((t-s)/t)² | MOD 100 * --------------------------------------- * 100 * * Formula for energy based on time and initial seed * * @param seed - The random start seed for the cell between 1 - 10000 * @param double - The time of birth of the cell * @return A double between 0 and 1 */ fun createEnergy(seed: Double, time: Double): Double = (Math.abs(Math.sqrt(Math.pow((time / seed), 2.0) - Math.pow((time - seed) / time, 2.0))).rem(100)) / 100 /** * | ______________________________________________ | * | √( ((t-s²)/(s * t)² - time MOD seed + (t/s²) | MOD 100 * -------------------------------------------------------------- * 100 * * Formula for pleasantness based on time and initial seed * * @param seed - The random start seed for the cell between 1 - 10000 * @param double - The time of birth of the cell * @return A double between 0 and 1 */ private fun createPleasantness(seed: Double, time: Double): Double = (Math.abs(Math.sqrt((time - Math.pow(seed, 2.0)) / (seed * time)) - (time.rem(seed)) + (time / Math.pow(seed, 2.0))).rem(100)) / 100 /** * | | * | s³/(t-s) + t | MOD 100 * ---------------------------- * 100 * * Formula for sociability based on time and initial seed * * @param seed - The random start seed for the cell between 1 - 10000 * @param double - The time of birth of the cell * @return A double between 0 and 1 */ private fun createSociability(seed: Double, time: Double): Double = ((Math.abs(Math.pow(seed, 3.0) / (time - seed) + time)).rem(100)) / 100 /** * | | * | t² - s² - t/2 | MOD 100 * ------------------------------- * 100 * * Formula for vitality based on time and initial seed * * @param seed - The random start seed for the cell between 1 - 10000 * @param double - The time of birth of the cell * @return A double between 0 and 1 */ private fun createVitality(seed: Double, time: Double): Double = (Math.abs(Math.pow(time, 2.0) - Math.pow(seed, 2.0) - time / 2.0).rem(100)) / 100 }
apache-2.0
6e9887751615205a483c9c5da87df641
40.144578
144
0.46075
4.108303
false
false
false
false
drimachine/grakmat
src/main/kotlin/org/drimachine/grakmat/grammars/GrammarDefinitionLanguage.kt
1
19284
/* * Copyright (c) 2016 Drimachine.org * * 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.drimachine.grakmat.grammars import org.drimachine.grakmat.* import org.drimachine.grakmat.ast.* import java.io.File object GrammarDefinitionLanguage { private val expressionRef: Parser<Node> = ref { expression } // fragment inRangeCombinator = '(' -> expression <- ')' <- '{', NUMBER <- ',', NUMBER <- '}' { ... }; private val inRangeCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ LEFT_BRACE _and_ NUMBER _before_ COMMA _and_ NUMBER _before_ RIGHT_BRACE) .map { (expressionAndMin, max: String) -> val (expression: Node, min: String) = expressionAndMin astNode("inRange") { +astNode("min", min) +astNode("max", max) +astNode("expression", listOf(expression)) } } // fragment spacedInRangeCombinator = '(' -> expression <- ')' <- '-' <- '{', NUMBER <- ',', NUMBER <- '}' { ... }; private val spacedInRangeCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ MINUS _before_ LEFT_BRACE _and_ NUMBER _before_ COMMA _and_ NUMBER _before_ RIGHT_BRACE) .map { (expressionAndMin, max: String) -> val (expression: Node, min: String) = expressionAndMin astNode("_inRange_") { +astNode("min", min) +astNode("max", max) +astNode("expression", listOf(expression)) } } // fragment atLeastCombinator = '(' -> expression <- ')' <- '{', NUMBER <- ',' <- '}' { ... }; private val atLeastCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ LEFT_BRACE _and_ NUMBER _before_ COMMA _before_ RIGHT_BRACE) .map { (expression: Node, number: String) -> astNode("atLeast") { +astNode("times", number) +astNode("expression", listOf(expression)) } } // fragment spacedAtLeastCombinator = '(' -> expression <- ')' <- '-' <- '{', NUMBER <- ',' <- '}' { ... }; private val spacedAtLeastCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ MINUS _before_ LEFT_BRACE _and_ NUMBER _before_ COMMA _before_ RIGHT_BRACE) .map { (expression: Node, number: String) -> astNode("_atLeast_") { +astNode("times", number) +astNode("expression", listOf(expression)) } } // fragment repeatCombinator = '(' -> expression <- ')' <- '{', NUMBER <- '}' { ... }; private val repeatCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ LEFT_BRACE _and_ NUMBER _before_ RIGHT_BRACE) .map { (expression: Node, number: String) -> astNode("repeat") { +astNode("times", number) +astNode("expression", listOf(expression)) } } // fragment spacedRepeatCombinator = '(' -> expression <- ')' <- '-' <- '{', NUMBER <- '}' { ... }; private val spacedRepeatCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ MINUS _before_ LEFT_BRACE _and_ NUMBER _before_ RIGHT_BRACE) .map { (expression: Node, number: String) -> astNode("_repeat_") { +astNode("times", number) +astNode("expression", listOf(expression)) } } // fragment optionalCombinator = '(' -> expression <- ')' <- '?' { ... }; private val optionalCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ QUESTION_MARK) .map { expression: Node -> astNode("optional") { +astNode("expression", listOf(expression)) } } // fragment requiredCombinator = '(' -> expression <- ')' <- '!' { ... }; private val requiredCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ EXCLAMATION_MARK) .map { expression: Node -> astNode("required") { +astNode("expression", listOf(expression)) } } // fragment zeroOrMoreCombinator = '(' -> expression <- ')' <- '*' { ... }; private val zeroOrMoreCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ ASTERISK) .map { expression: Node -> astNode("zeroOrMore") { +astNode("expression", listOf(expression)) } } // fragment spacedZeroOrMoreCombinator = '(' -> expression <- ')' <- '-' <- '*' { ... }; private val spacedZeroOrMoreCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ MINUS _before_ ASTERISK) .map { expression: Node -> astNode("_zeroOrMore_") { +astNode("expression", listOf(expression)) } } // fragment oneOrMoreCombinator = '(' -> expression <- ')' <- '+' { ... }; private val oneOrMoreCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ PLUS) .map { expression: Node -> astNode("oneOrMore") { +astNode("expression", listOf(expression)) } } // fragment spacedOneOrMoreCombinator = '(' -> expression <- ')' <- '-' <- '+' { ... }; private val spacedOneOrMoreCombinator: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN _before_ MINUS _before_ PLUS) .map { expression: Node -> astNode("_oneOrMore_") { +astNode("expression", listOf(expression)) } } // countCombinator = requiredCombinator | optionalCombinator | zeroOrMoreCombinator | spacedZeroOrMoreCombinator | oneOrMoreCombinator | spacedOneOrMoreCombinator | spacedRepeatCombinator | repeatCombinator | spacedAtLeastCombinator | atLeastCombinator | spacedInRangeCombinator | inRangeCombinator; private val countCombinator: Parser<Node> = (requiredCombinator or optionalCombinator or zeroOrMoreCombinator or spacedZeroOrMoreCombinator or oneOrMoreCombinator or spacedOneOrMoreCombinator or spacedRepeatCombinator or repeatCombinator or spacedAtLeastCombinator or atLeastCombinator or spacedInRangeCombinator or inRangeCombinator) .withName("count combinator") // fragment escapedCharacter: Char = '\\' > ["'\\bnrt] { ... }; private val escapedCharacter: Parser<Char> = (char('\\') then anyOf('\"', '\'', '\\', 'b', 'n', 'r', 't')) .map { when (it) { '\"' -> '\"' '\'' -> '\'' '\\' -> '\\' 'b' -> '\b' 'n' -> '\n' 'r' -> '\r' 't' -> '\t' else -> error("unreachable code") } } // fragment stringCharacter: (Char) = [^"\\] | escapedCharacter; private val stringCharacter: Parser<Char> = (except('\"', '\\') or escapedCharacter) // stringLiteral = '"' > (stringCharacter)* < '"' { ... }; private val stringLiteral: Parser<Node> = (DOUBLE_QUOTE then zeroOrMore(stringCharacter) before DOUBLE_QUOTE) .map { chars: List<Char> -> astNode("string", chars.joinToString("")) } .withName("string literal") // characterLiteral = '\'' > stringCharacter < '\'' { ... }; private val characterLiteral: Parser<Node> = (QUOTE then stringCharacter before QUOTE) .map { char: Char -> astNode("string", char.toString()) } .withName("character literal") // fragment groupEscapedCharacter: (Char) = '\\' > [\^]\\-bnrt] { ... }; private val groupEscapedCharacter: Parser<Char> = (char('\\') then anyOf('^', ']', '\\', '-', 'b', 'n', 'r', 't')) .map { when (it) { '^' -> '^' ']' -> ']' '\\' -> '\\' '-' -> '-' 'b' -> '\b' 'n' -> '\n' 'r' -> '\r' 't' -> '\t' else -> error("unreachable code") } } // groupCharacter: (Char) = [^\]\\] or groupEscapedCharacter; private val groupCharacter: Parser<Char> = (except(']', '\\') or groupEscapedCharacter) .withName("character") // groupCharacterNode = groupCharacter { ... }; private val groupCharacterNode: Parser<Node> = groupCharacter map { astNode("char", it.toString()) } // rangeExpression = groupCharacter < '-' groupCharacter { ... }; private val rangeExpression: Parser<Node> = (groupCharacter before MINUS and groupCharacter) .map { (firstChar: Char, lastChar: Char) -> astNode("range", listOf(astNode("firstChar", firstChar.toString()), astNode("lastChar", lastChar.toString()))) } .withName("range expression") // anyOfParser = '[' > (groupCharacterNode | rangeExpression)+ < ']' { ... }; private val anyOfParser: Parser<Node> = (LEFT_BRACKET then oneOrMore(groupCharacterNode or rangeExpression) before RIGHT_BRACKET) .map { chars: List<Node> -> astNode("anyOf", chars) } .withName("including group") // exceptParser = '[' > '^' > (groupCharacterNode | rangeExpression)+ < ']' { ... }; private val exceptParser: Parser<Node> = (LEFT_BRACKET then CARET then oneOrMore(groupCharacterNode or rangeExpression) before RIGHT_BRACKET) .map { chars: List<Node> -> astNode("except", chars) } .withName("excluding group") // anyCharacter = '*'; private val anyCharParser: Parser<Node> = ASTERISK .map { astNode("anyChar") } .withName("any character") // grouping = '(' -> expression <- ')' { ... }; private val grouping: Parser<Node> = (LEFT_PAREN _then_ expressionRef _before_ RIGHT_PAREN) .map { expression: Node -> astNode("grouping", listOf(expression)) } .withName("grouping") // parserCreator = stringLiteral | characterLiteral | exceptParser | anyOfParser | anyCharParser; private val parserCreator: Parser<Node> = (stringLiteral or characterLiteral or exceptParser or anyOfParser or anyCharParser) .withName("parser creator") // ruleReference = IDENTIFIER { ... }; private val ruleReference: Parser<Node> = (IDENTIFIER) .map { ruleName: String -> astNode("ruleReference", ruleName) } .withName("rule reference") // baseExpression = countCombinator | ruleReference | parserCreator | grouping; private val baseExpression: Parser<Node> = (countCombinator or ruleReference or parserCreator or grouping) .withName("base expression") // fragment thenCombinator = baseExpression <- '>', expression { ... }; private val thenCombinator: Parser<Node> = (baseExpression _before_ GREATER_THAN_SIGN _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("then") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment spacedThenCombinator = baseExpression <- '-' < '>', expression { ... }; private val spacedThenCombinator: Parser<Node> = (baseExpression _before_ MINUS before GREATER_THAN_SIGN _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("_then_") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment beforeCombinator = baseExpression <- '<' expression { ... }; private val beforeCombinator: Parser<Node> = (baseExpression _before_ LESS_THAN_SIGN _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("before") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment spacedBeforeCombinator = baseExpression <- '<' < '-', expression { ... }; private val spacedBeforeCombinator: Parser<Node> = (baseExpression _before_ LESS_THAN_SIGN before MINUS _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("_before_") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment andCombinator = expression < SPACES expression { ... }; private val andCombinator: Parser<Node> = (baseExpression before SPACES and expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("and") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment spacedAndCombinator = baseExpression <- ',', expression { ... }; private val spacedAndCombinator: Parser<Node> = (baseExpression _before_ COMMA _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("_and_") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // fragment orCombinator = expression <- '|', expression { ... }; private val orCombinator: Parser<Node> = (baseExpression _before_ VERTICAL_BAR _and_ expressionRef) .map { (leftExpression: Node, rightExpression: Node) -> astNode("or") { +astNode("left", listOf(leftExpression)) +astNode("right", listOf(rightExpression)) } } // combinator = orCombinator | spacedAndCombinator | andCombinator | spacedThenCombinator | thenCombinator | beforeCombinator | spacedBeforeCombinator; private val combinator: Parser<Node> = (orCombinator or spacedAndCombinator or andCombinator or spacedThenCombinator or thenCombinator or beforeCombinator or spacedBeforeCombinator) .withName("combinator") // expression = combinator | baseExpression; private val expression: Parser<Node> = (combinator or baseExpression) .withName("expression") private val nestedBlockRef: Parser<String> = ref { nestedBlock } // fragment codeChar: (String) = [^{}]; private val codeChar: Parser<String> = except('{', '}') map Char::toString // fragment nestedBlock: (String) = '{' > (nestedBlock | codeChar) < '}'; private val nestedBlock: Parser<String> = (LEFT_BRACE then zeroOrMore(nestedBlockRef or codeChar) before RIGHT_BRACE) .map { it: List<String> -> "{${it.joinToString("")}}" } // code: (String) = '{' > (nestedBlock | codeChar)* < '}' { ... }; private val code: Parser<String> = (LEFT_BRACE then zeroOrMore(nestedBlock or codeChar) before RIGHT_BRACE) .map { it: List<String> -> it.joinToString("") } .withName("code") // ruleType: (String) = '(' -> ([^)])+ <- ')' { ... }; private val ruleType: Parser<String> = (char('(') _then_ oneOrMore(except(')')) _before_ char(')')) .map { it: List<Char> -> it.joinToString("") } .withName("type") // rule = ("fragment")? < SPACES IDENTIFIER, (':' -> ruleType) <- '=', expression, (code)? { ... }; private val rule: Parser<Node> = (optional(str("fragment")) before SPACES and IDENTIFIER _and_ optional(COLON _then_ ruleType) _before_ EQUALS_SIGN _and_ expression _and_ optional(code)) .map { it: Pair<Pair<Pair<Pair<String?, String>, String?>, Node>, String?> -> val (left1, code: String?) = it val (left2, expression: Node) = left1 val (left3, type: String?) = left2 val (fragment: String?, name: String) = left3 astNode("rule") { if (fragment != null) +astNode("fragment") +astNode("name", name) if (type != null) +astNode("type", type) +astNode("expression", listOf(expression)) if (code != null) +astNode("code", code) } } .withName("rule") // rule = IDENTIFIER, (':' -> ruleType) <- '=', expression, (code)? { ... }; private val mainRule: Parser<Node> = (IDENTIFIER _and_ optional(COLON _then_ ruleType) _before_ EQUALS_SIGN _and_ expression _and_ code) .map { it: Pair<Pair<Pair<String, String?>, Node>, String?> -> val (left1, code: String?) = it val (left2, expression: Node) = left1 val (name: String, type: String?) = left2 astNode("mainRule") { +astNode("name", name) if (type != null) +astNode("type", type) +astNode("expression", listOf(expression)) if (code != null) +astNode("code", code) } } .withName("main rule") // grammarName = "grammar" < SPACES > IDENTIFIER { ... }; private val grammarName: Parser<Node> = (str("grammar") before SPACES then IDENTIFIER) .map { name: String -> astNode("name", name) } .withName("grammar name") // grammar = OPTIONAL_SPACES > grammarName <- ';', mainRule <- ';', (rule <- ';')* { ... }; private val grammar: Parser<Node> = (OPTIONAL_SPACES then grammarName _before_ SEMICOLON _and_ mainRule _before_ SEMICOLON _and_ _zeroOrMore_(rule _before_ SEMICOLON) before OPTIONAL_SPACES) .map { grammarParts: Pair<Pair<Node, Node>, List<Node>> -> val (left1, rules: List<Node>) = grammarParts val (grammarName: Node, mainRule: Node) = left1 astNode("grammar") { +grammarName +mainRule +astNode("rules", rules) } } .withName("grammar") @JvmStatic fun parse(json: String): Node = grammar.parse(json) @JvmStatic fun parseFile(file: File): Node = grammar.parseFile(file) }
apache-2.0
516c0d3a05ecfb9067ac3d2b6c5990ee
55.884956
338
0.559272
4.788676
false
false
false
false
square/moshi
moshi-kotlin-tests/codegen-only/src/test/kotlin/com/squareup/moshi/kotlin/codegen/MultipleMasksTest.kt
1
3618
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.squareup.moshi.kotlin.codegen import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi import org.intellij.lang.annotations.Language import org.junit.Assert.assertEquals import org.junit.Test /** * This test explicitly tests mask generation for classes with more than 32 parameters. Each mask * can only indicate up to 32 parameters, so constructors with more than 32 parameters have to use * multiple masks. * * This covers a few cases of this: * - Ensuring values from json are matched to properties correctly * - Some `@Transient` parameters (which participate in the constructor signature and mask indices) * - This example has 3 total masks generated. * * Regression test for https://github.com/square/moshi/issues/977 */ class MultipleMasksTest { @Test fun testMultipleMasks() { // Set some arbitrary values to make sure offsets are aligning correctly @Language("JSON") val json = """{"arg50":500,"arg3":34,"arg11":11,"arg65":67}""" val instance = Moshi.Builder().build().adapter<MultipleMasks>() .fromJson(json)!! assertEquals(instance.arg2, 2) assertEquals(instance.arg3, 34) assertEquals(instance.arg11, 11) assertEquals(instance.arg49, 49) assertEquals(instance.arg50, 500) assertEquals(instance.arg65, 67) assertEquals(instance.arg64, 64) } } @JsonClass(generateAdapter = true) class MultipleMasks( val arg0: Long = 0, val arg1: Long = 1, val arg2: Long = 2, val arg3: Long = 3, val arg4: Long = 4, val arg5: Long = 5, val arg6: Long = 6, val arg7: Long = 7, val arg8: Long = 8, val arg9: Long = 9, val arg10: Long = 10, val arg11: Long, val arg12: Long = 12, val arg13: Long = 13, val arg14: Long = 14, val arg15: Long = 15, val arg16: Long = 16, val arg17: Long = 17, val arg18: Long = 18, val arg19: Long = 19, @Suppress("UNUSED_PARAMETER") arg20: Long = 20, val arg21: Long = 21, val arg22: Long = 22, val arg23: Long = 23, val arg24: Long = 24, val arg25: Long = 25, val arg26: Long = 26, val arg27: Long = 27, val arg28: Long = 28, val arg29: Long = 29, val arg30: Long = 30, val arg31: Long = 31, val arg32: Long = 32, val arg33: Long = 33, val arg34: Long = 34, val arg35: Long = 35, val arg36: Long = 36, val arg37: Long = 37, val arg38: Long = 38, @Transient val arg39: Long = 39, val arg40: Long = 40, val arg41: Long = 41, val arg42: Long = 42, val arg43: Long = 43, val arg44: Long = 44, val arg45: Long = 45, val arg46: Long = 46, val arg47: Long = 47, val arg48: Long = 48, val arg49: Long = 49, val arg50: Long = 50, val arg51: Long = 51, val arg52: Long = 52, @Transient val arg53: Long = 53, val arg54: Long = 54, val arg55: Long = 55, val arg56: Long = 56, val arg57: Long = 57, val arg58: Long = 58, val arg59: Long = 59, val arg60: Long = 60, val arg61: Long = 61, val arg62: Long = 62, val arg63: Long = 63, val arg64: Long = 64, val arg65: Long = 65 )
apache-2.0
2dedde5c535201bebbd9bca28e4f5c90
27.944
99
0.668878
3.295082
false
true
false
false
RettyEng/redux-kt
redux-kt-rxjava-bindings/src/main/kotlin/me/retty/reduxkt/bindings/rxjava/RxJavaBindings.kt
1
2227
package me.retty.reduxkt.bindings.rxjava import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject import me.retty.reduxkt.Action import me.retty.reduxkt.Middleware import me.retty.reduxkt.Reducer import me.retty.reduxkt.StateType import me.retty.reduxkt.Store import me.retty.reduxkt.StoreDelegate import java.util.WeakHashMap object RxJavaBindings { fun <T: StateType> newStore(initialState: T, reducer: Reducer<T>, middlewares: List<Middleware<T>>): Store<T> = this.newStore(initialState, object : StoreDelegate<T> { override fun getReducer(): Reducer<T> = reducer override fun getMiddlewares(): List<Middleware<T>> = middlewares }) fun <T: StateType> newStore(initialState: T, delegate: StoreDelegate<T>): Store<T> { val fields = Fields(BehaviorSubject.createDefault (initialState)) var store: Store<T>? = null store = Store(initialState, object : StoreDelegate<T> { override fun getReducer(): Reducer<T> = delegate.getReducer() override fun getMiddlewares(): List<Middleware<T>> { val rxjavaPublisher: Middleware<T> = { _ -> { dispatcher: (Action) -> Unit -> { action: Action -> dispatcher(action) fields.subject.onNext(store!!.state) } } } return listOf(rxjavaPublisher) + delegate.getMiddlewares() } }) fieldsStore[store] = fields return store } } private class Fields<T: StateType>(val subject: BehaviorSubject<T>) { val observable: Observable<T> by lazy { this.subject.hide() } } private val fieldsStore: MutableMap<Store<*>, Fields<*>> = WeakHashMap() val <T: StateType> Store<T>.observable: Observable<T> @Suppress("unchecked_cast") get() = (fieldsStore[this] as? Fields<T>)?.observable ?: throw IllegalStateException( "Calling accessor of observable for store that is not prepare for RxJava binding." + " Use RxJavaBindings#newStore to create instance of Store")
mit
722979ad800d0f7279c1a973bd6a5605
37.396552
96
0.616075
4.554192
false
false
false
false
facebook/react-native
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt
1
2094
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.utils import com.android.build.api.variant.AndroidComponentsExtension import com.facebook.react.utils.ProjectUtils.isHermesEnabled import com.facebook.react.utils.ProjectUtils.isNewArchEnabled import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.plugins.AppliedPlugin @Suppress("UnstableApiUsage") internal object AgpConfiguratorUtils { fun configureBuildConfigFields(project: Project) { val action = Action<AppliedPlugin> { project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> ext.defaultConfig.buildConfigField( "boolean", "IS_NEW_ARCHITECTURE_ENABLED", project.isNewArchEnabled.toString()) ext.defaultConfig.buildConfigField( "boolean", "IS_HERMES_ENABLED", project.isHermesEnabled.toString()) } } project.pluginManager.withPlugin("com.android.application", action) project.pluginManager.withPlugin("com.android.library", action) } fun configureDevPorts(project: Project) { val devServerPort = project.properties["reactNativeDevServerPort"]?.toString() ?: DEFAULT_DEV_SERVER_PORT val inspectorProxyPort = project.properties["reactNativeInspectorProxyPort"]?.toString() ?: devServerPort val action = Action<AppliedPlugin> { project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> ext.defaultConfig.resValue("integer", "react_native_dev_server_port", devServerPort) ext.defaultConfig.resValue( "integer", "react_native_inspector_proxy_port", inspectorProxyPort) } } project.pluginManager.withPlugin("com.android.application", action) project.pluginManager.withPlugin("com.android.library", action) } } const val DEFAULT_DEV_SERVER_PORT = "8081"
mit
e2092d3e17a973ee5ddd7bbed6978ca2
37.777778
99
0.719675
4.512931
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/sync/UnifiedTrustManager.kt
1
3195
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki.sync import timber.log.Timber import java.security.KeyStore import java.security.KeyStoreException import java.security.NoSuchAlgorithmException import java.security.cert.CertificateException import java.security.cert.X509Certificate import java.util.* import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager // https://stackoverflow.com/questions/27562666/programmatically-add-a-certificate-authority-while-keeping-android-system-ssl-ce // Changes: // We try the local manager first. // Cached the accepted issuers. // Did not ignore NoSuchAlgorithmException internal class UnifiedTrustManager(localKeyStore: KeyStore?) : X509TrustManager { private val mDefaultTrustManager: X509TrustManager private val mLocalTrustManager: X509TrustManager private val mAcceptedIssuers: Array<X509Certificate> @Throws(NoSuchAlgorithmException::class, KeyStoreException::class) private fun createTrustManager(store: KeyStore?): X509TrustManager { val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm() val tmf = TrustManagerFactory.getInstance(tmfAlgorithm) tmf.init(store) val trustManagers = tmf.trustManagers return trustManagers[0] as X509TrustManager } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { try { mLocalTrustManager.checkServerTrusted(chain, authType) } catch (ce: CertificateException) { Timber.w(ce) mDefaultTrustManager.checkServerTrusted(chain, authType) } } @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { try { mLocalTrustManager.checkClientTrusted(chain, authType) } catch (ce: CertificateException) { Timber.w(ce) mDefaultTrustManager.checkClientTrusted(chain, authType) } } override fun getAcceptedIssuers(): Array<X509Certificate> { return mAcceptedIssuers } init { mDefaultTrustManager = createTrustManager(null) mLocalTrustManager = createTrustManager(localKeyStore) val first = mDefaultTrustManager.acceptedIssuers val second = mLocalTrustManager.acceptedIssuers mAcceptedIssuers = Arrays.copyOf(first, first.size + second.size) System.arraycopy(second, 0, mAcceptedIssuers, first.size, second.size) } }
gpl-3.0
bc05f51db4e35774ad01488351c9ebf4
39.443038
128
0.747418
4.804511
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/BackendUndo.kt
1
2865
/*************************************************************************************** * Copyright (c) 2022 Ankitects Pty Ltd <https://apps.ankiweb.net> * * * * 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.ichi2.libanki import anki.collection.OpChangesAfterUndo import net.ankiweb.rsdroid.RustCleanup import anki.collection.UndoStatus as UndoStatusProto /** * If undo/redo available, a localized string describing the action will be set. */ data class UndoStatus( val undo: String?, val redo: String?, // not currently used val lastStep: Int ) { companion object { fun from(proto: UndoStatusProto): UndoStatus { return UndoStatus( undo = proto.undo.ifEmpty { null }, redo = proto.redo.ifEmpty { null }, lastStep = proto.lastStep ) } } } /** * Undo the last backend operation. * * Should be called via collection.op(), which will notify * [ChangeManager.Subscriber] of the changes. * * Will throw if no undo operation is possible (due to legacy code * directly mutating the database). */ @RustCleanup("Once fully migrated, and v2 scheduler dropped, rename to undo()") fun CollectionV16.undoNew(): OpChangesAfterUndo { val changes = backend.undo() // clear legacy undo log clearUndo() return changes } /** Redoes the previously-undone operation. See the docs for [CollectionV16.undoOperation] */ fun CollectionV16.redo(): OpChangesAfterUndo { val changes = backend.redo() // clear legacy undo log clearUndo() return changes } /** See [UndoStatus] */ fun CollectionV16.undoStatus(): UndoStatus { return UndoStatus.from(backend.getUndoStatus()) }
gpl-3.0
5be9762d325f0863f3be16e24d585c79
38.246575
90
0.543805
5.134409
false
false
false
false
huhanpan/smart
app/src/main/java/com/etong/smart/Main/ControlLightFragment.kt
1
6866
package com.etong.smart.Main import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.etong.smart.CustomView.LightButton import com.etong.smart.CustomView.LightSwitch import com.etong.smart.Other.toDp import com.etong.smart.R import kotlinx.android.synthetic.main.fragment_control_light.* class ControlLightFragment : Fragment() { private val HEAD = 0 private val MAP = 1 private val ITEM = 2 data class Items(var isOpen: Boolean, val name: String, val items: List<Item>) data class Item(val id: Int, var value: Int, val x: Int, val y: Int) data class ListData(val type: Int, val data: Any) private val dataList = mutableListOf<ListData>() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater!!.inflate(R.layout.fragment_control_light, container, false) override fun onStart() { super.onStart() val sourceData = (0..4).map { i -> Items(false, "房间\t$i", arrayListOf<Item>( Item(i * 5 + 1, 5, 40, 75), Item(i * 5 + 2, 6, 125, 55), Item(i * 5 + 3, 5, 90, 145) )) } sourceData.forEach { dataList.add(ListData(HEAD, it)) } recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = Adapter(dataList) } /////////////////////////////////////////////////////////////////////////// // RecyclerAdapter /////////////////////////////////////////////////////////////////////////// inner class Adapter(val dataList: MutableList<ListData>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { HEAD -> { HeadViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_control_light_head, parent, false)) } MAP -> { MapViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_control_light_map, parent, false)) } else -> { ItemViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_control_light, parent, false)) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (getItemViewType(position)) { HEAD -> { (holder as HeadViewHolder).bindView(dataList, position) } MAP -> { (holder as MapViewHolder).bindView(position) } ITEM -> { (holder as ItemViewHolder).bindView(position) } } } override fun getItemCount() = dataList.size override fun getItemViewType(position: Int) = dataList[position].type } /////////////////////////////////////////////////////////////////////////// // RecyclerViewHolder /////////////////////////////////////////////////////////////////////////// inner class HeadViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val roomName = itemView.findViewById(R.id.tv_name) as TextView private val cursor = itemView.findViewById(R.id.cursor) as ImageView fun bindView(dataList: MutableList<ListData>, position: Int) { val item = dataList[position].data as Items roomName.text = item.name cursor.setImageLevel(if (item.isOpen) 1 else 0) val adapter = recyclerView.adapter val count = item.items.count() itemView.setOnClickListener { if (item.isOpen) { for (i in 0..count) { dataList.removeAt(position + 1) } adapter.notifyItemRangeRemoved(position + 1, count + 1) } else { val list = mutableListOf(ListData(MAP, item)) item.items.mapTo(list) { ListData(ITEM, it) } dataList.addAll(position + 1, list) adapter.notifyItemRangeInserted(position + 1, count + 1) } adapter.notifyItemChanged(position) item.isOpen = !item.isOpen } } } inner class MapViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindView(position: Int) { val lights = dataList[position].data as Items val viewGroup = itemView as ViewGroup lights.items.forEach { var light: LightButton? = null light = itemView.findViewWithTag(it.id) as LightButton? if (light == null) { light = LightButton(context) val layout = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) layout.leftMargin = it.x.toDp(context).toInt() layout.topMargin = it.y.toDp(context).toInt() light.layoutParams = layout light.tag = it.id viewGroup.addView(light) } light.setValue(it.value) val that = it light.addChangeListener { that.value = it (position until dataList.size) .filter { dataList[it].data == that } .forEach { recyclerView.adapter.notifyItemChanged(it) } } } } } inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val lightName = itemView.findViewById(R.id.tv_name) as TextView private val lightSwitch = itemView.findViewById(R.id.lightSwitch) as LightSwitch fun bindView(position: Int) { val item = dataList[position].data as Item lightName.text = "灯泡${item.id}" lightSwitch.setValue(item.value) lightSwitch.setChangeListener { item.value = it for (i in position.downTo(0)) { if (dataList[i].type == MAP) { recyclerView.adapter.notifyItemChanged(i) break } } } } } }
gpl-2.0
22268b32222ce64598d6db4a9aae456a
41.333333
144
0.54112
5.133234
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/viewModel/MainViewModel.kt
1
1825
package com.toshi.viewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import com.toshi.extensions.isLocalStatusMessage import com.toshi.model.local.network.Networks import com.toshi.util.logging.LogUtil import com.toshi.view.BaseApplication import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription class MainViewModel : ViewModel() { private val chatManager by lazy { BaseApplication.get().chatManager } private val subscriptions by lazy { CompositeSubscription() } val unreadMessages by lazy { MutableLiveData<Boolean>() } init { attachUnreadMessagesSubscription() } private fun attachUnreadMessagesSubscription() { val allChangesSubscription = chatManager .registerForAllConversationChanges() .filter { !it.latestMessage.isLocalStatusMessage() } .flatMap { chatManager.areUnreadMessages().toObservable() } .observeOn(AndroidSchedulers.mainThread()) .subscribe( { unreadMessages.value = it }, { LogUtil.exception("Error while fetching unread messages $it") } ) val firstTimeSubscription = chatManager .areUnreadMessages() .toObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribe( { unreadMessages.value = it }, { LogUtil.exception("Error while fetching unread messages $it") } ) subscriptions.addAll(allChangesSubscription, firstTimeSubscription) } fun getNetworks() = Networks.getInstance() override fun onCleared() { super.onCleared() subscriptions.clear() } }
gpl-3.0
4b3c33dbfd47676f09615206a62ae4a8
34.803922
89
0.650959
5.721003
false
false
false
false
strykeforce/thirdcoast
src/main/kotlin/org/strykeforce/telemetry/measurable/CanifierMeasurable.kt
1
3464
package org.strykeforce.telemetry.measurable import com.ctre.phoenix.CANifier import com.ctre.phoenix.CANifier.PWMChannel.* import java.util.function.DoubleSupplier internal const val PWM0_PULSE_WIDTH = "PWM0_PULSE_WIDTH" internal const val PWM0_PERIOD = "PWM0_PERIOD" internal const val PWM0_PULSE_WIDTH_POSITION = "PWM0_PULSE_WIDTH_POSITION" internal const val PWM1_PULSE_WIDTH = "PWM1_PULSE_WIDTH" internal const val PWM1_PERIOD = "PWM1_PERIOD" internal const val PWM1_PULSE_WIDTH_POSITION = "PWM1_PULSE_WIDTH_POSITION" internal const val PWM2_PULSE_WIDTH = "PWM2_PULSE_WIDTH" internal const val PWM2_PERIOD = "PWM2_PERIOD" internal const val PWM2_PULSE_WIDTH_POSITION = "PWM2_PULSE_WIDTH_POSITION" internal const val PWM3_PULSE_WIDTH = "PWM3_PULSE_WIDTH" internal const val PWM3_PERIOD = "PWM3_PERIOD" internal const val PWM3_PULSE_WIDTH_POSITION = "PWM3_PULSE_WIDTH_POSITION" internal const val QUAD_POSITION = "QUAD_POSITION" internal const val QUAD_VELOCITY = "QUAD_VELOCITY" /** Represents a `CANifier` telemetry-enable `Measurable` item. */ class CanifierMeasurable @JvmOverloads constructor( private val canifier: CANifier, override val description: String = "CANifier ${canifier.deviceID}" ) : Measurable { override val deviceId = canifier.deviceID override val measures = setOf( Measure(PWM0_PULSE_WIDTH, "PWM 0 Pulse Width"){ pulseWidthFor(PWMChannel0) }, Measure(PWM0_PERIOD, "PWM 0 Period"){ periodFor(PWMChannel0) }, Measure(PWM0_PULSE_WIDTH_POSITION, "PWM 0 Pulse Width Position"){ pulseWidthPositionFor(PWMChannel0) }, Measure(PWM1_PULSE_WIDTH, "PWM 1 Pulse Width"){ pulseWidthFor(PWMChannel1) }, Measure(PWM1_PERIOD, "PWM 1 Period"){ periodFor(PWMChannel1) }, Measure(PWM1_PULSE_WIDTH_POSITION, "PWM 1 Pulse Width Position"){ pulseWidthPositionFor(PWMChannel1) }, Measure(PWM2_PULSE_WIDTH, "PWM 2 Pulse Width"){ pulseWidthFor(PWMChannel2) }, Measure(PWM2_PERIOD, "PWM 2 Period"){ periodFor(PWMChannel2) }, Measure(PWM2_PULSE_WIDTH_POSITION, "PWM 2 Pulse Width Position"){ pulseWidthPositionFor(PWMChannel2) }, Measure(PWM3_PULSE_WIDTH, "PWM 3 Pulse Width"){ pulseWidthFor(PWMChannel3) }, Measure(PWM3_PERIOD, "PWM 3 Period"){ periodFor(PWMChannel3) }, Measure(PWM3_PULSE_WIDTH_POSITION, "PWM 3 Pulse Width Position"){ pulseWidthPositionFor(PWMChannel3) }, Measure(QUAD_POSITION, "Quadrature Position"){ canifier.quadraturePosition.toDouble() }, Measure(QUAD_VELOCITY, "Quadrature Velocity"){ canifier.quadratureVelocity.toDouble() } ) private fun pulseWidthFor(channel: CANifier.PWMChannel): Double { val pulseWidthAndPeriod = DoubleArray(2) canifier.getPWMInput(channel, pulseWidthAndPeriod) return pulseWidthAndPeriod[0] } private fun periodFor(channel: CANifier.PWMChannel): Double { val pulseWidthAndPeriod = DoubleArray(2) canifier.getPWMInput(channel, pulseWidthAndPeriod) return pulseWidthAndPeriod[1] } private fun pulseWidthPositionFor(channel: CANifier.PWMChannel): Double { val pulseWidthAndPeriod = DoubleArray(2) canifier.getPWMInput(channel, pulseWidthAndPeriod) return 4096.0 * pulseWidthAndPeriod[0] / pulseWidthAndPeriod[1] } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as CanifierMeasurable if (deviceId != other.deviceId) return false return true } override fun hashCode() = deviceId }
mit
102b2741e655f70f4cd6ff9fe41343a7
43.987013
107
0.754042
3.958857
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/Chapter.kt
1
1834
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("chapters") @JsonIgnoreProperties(ignoreUnknown = true) class Chapter : BaseJsonModel(JsonType("chapters")) { companion object FieldNames { val CREATED_AT = "createdAt" val UPDATED_AT = "updatedAt" val TITLES = "titles" val CANONICAL_TITLE = "canonicalTitle" val VOLUME_NUMBER = "volumeNumber" val NUMBER = "number" val SYNOPSIS = "synopsis" val PUBLISHED = "published" val LENGTH = "length" val THUMBNAIL = "thumbnail" val MANGA = "manga" } var createdAt: String? = null var updatedAt: String? = null var titles: Titles? = null var canonicalTitle: String? = null var volumeNumber: Int? = null var number: Int? = null var synopsis: String? = null var published: String? = null var length: Int? = null /* * Thumbnail is an object with a single field ("original") in the api. * This method prevents the need for creating a new object for this one property. * If the thumbnail object one day includes new properties (pretty much guaranteed to be strings) * this method should still work as expected. */ var thumbnail: String? = null @JsonProperty("thumbnail") fun setThumbnail(m: Map<String, String>?) { if (m != null) thumbnail = m["original"] } @Relationship("manga") var manga: Manga? = null @RelationshipLinks("manga") var mangaLinks: Links? = null }
gpl-3.0
996dc61a4db145b07d8abef7b891b951
27.671875
101
0.676663
4.305164
false
false
false
false
sabi0/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubAccountsPanel.kt
1
15629
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.application.ModalityState import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.* import com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN import com.intellij.ui.SimpleTextAttributes.STYLE_UNDERLINE import com.intellij.ui.components.JBList import com.intellij.util.progress.ProgressVisibilityManager import com.intellij.util.ui.* import com.intellij.util.ui.components.BorderLayoutPanel import icons.GithubIcons import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.api.data.GithubUserDetailed import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener private const val ACCOUNT_PICTURE_SIZE: Int = 40 private const val LINK_TAG = "EDIT_LINK" internal class GithubAccountsPanel(private val project: Project, private val executorFactory: GithubApiRequestExecutor.Factory, private val accountInformationProvider: GithubAccountInformationProvider) : BorderLayoutPanel(), Disposable { private val accountListModel = CollectionListModel<GithubAccountDecorator>().apply { // disable link handler when there are no errors addListDataListener(object : ListDataListener { override fun contentsChanged(e: ListDataEvent?) = setLinkHandlerEnabled(items.any { it.loadingError != null }) override fun intervalRemoved(e: ListDataEvent?) {} override fun intervalAdded(e: ListDataEvent?) {} }) } private val accountList = JBList<GithubAccountDecorator>(accountListModel).apply { cellRenderer = GithubAccountDecoratorRenderer() selectionMode = ListSelectionModel.SINGLE_SELECTION selectionForeground = UIUtil.getListForeground() selectionBackground = JBColor(0xE9EEF5, 0x464A4D) emptyText.apply { appendText("No GitHub accounts added.") appendSecondaryText("Add account", SimpleTextAttributes.LINK_ATTRIBUTES, { addAccount() }) appendSecondaryText(" (${KeymapUtil.getFirstKeyboardShortcutText(CommonShortcuts.getNew())})", StatusText.DEFAULT_ATTRIBUTES, null) } } private val progressManager = createListProgressManager() private val errorLinkHandler = createLinkActivationListener() private var errorLinkHandlerInstalled = false private var currentTokensMap = mapOf<GithubAccount, String?>() private val newTokensMap = mutableMapOf<GithubAccount, String>() init { addToCenter(ToolbarDecorator.createDecorator(accountList) .disableUpDownActions() .setPanelBorder(IdeBorderFactory.createBorder(SideBorder.TOP or SideBorder.BOTTOM)) .setAddAction { addAccount() } .addExtraAction(object : ToolbarDecorator.ElementActionButton("Set default", AllIcons.Actions.Checked) { override fun actionPerformed(e: AnActionEvent) { if (accountList.selectedValue.projectDefault) return for (accountData in accountListModel.items) { if (accountData == accountList.selectedValue) { accountData.projectDefault = true accountListModel.contentsChanged(accountData) } else if (accountData.projectDefault) { accountData.projectDefault = false accountListModel.contentsChanged(accountData) } } } override fun updateButton(e: AnActionEvent?) { isEnabled = isEnabled && !accountList.selectedValue.projectDefault } }) .createPanel()) Disposer.register(this, progressManager) } private fun addAccount() { val dialog = GithubLoginDialog(executorFactory, project, this, ::isAccountUnique) if (dialog.showAndGet()) { val githubAccount = GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer()) newTokensMap[githubAccount] = dialog.getToken() val accountData = GithubAccountDecorator(githubAccount, false) accountListModel.add(accountData) loadAccountDetails(accountData) } } private fun editAccount(decorator: GithubAccountDecorator) { val dialog = GithubLoginDialog(executorFactory, project, this).apply { withServer(decorator.account.server.toString(), false) withCredentials(decorator.account.name) } if (dialog.showAndGet()) { decorator.account.name = dialog.getLogin() newTokensMap[decorator.account] = dialog.getToken() loadAccountDetails(decorator) } } private fun isAccountUnique(login: String, server: GithubServerPath) = accountListModel.items.none { it.account.name == login && it.account.server == server } /** * Manages link hover and click for [GithubAccountDecoratorRenderer.loadingError] * Sets the proper cursor and underlines the link on hover * * @see [GithubAccountDecorator.loadingError] * @see [GithubAccountDecorator.showLoginLink] * @see [GithubAccountDecorator.errorLinkPointedAt] */ private fun createLinkActivationListener() = object : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { val decorator = findDecoratorWithLoginLinkAt(e.point) if (decorator != null) { UIUtil.setCursor(accountList, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)) } else { UIUtil.setCursor(accountList, Cursor.getDefaultCursor()) } var hasChanges = false for (item in accountListModel.items) { val isLinkPointedAt = item == decorator hasChanges = hasChanges || isLinkPointedAt != item.errorLinkPointedAt item.errorLinkPointedAt = isLinkPointedAt } if (hasChanges) accountListModel.allContentsChanged() } override fun mouseClicked(e: MouseEvent) { findDecoratorWithLoginLinkAt(e.point)?.run(::editAccount) } /** * Checks if mouse is pointed at decorator error link * * @return decorator with error link under mouse pointer or null */ private fun findDecoratorWithLoginLinkAt(point: Point): GithubAccountDecorator? { val idx = accountList.locationToIndex(point) if (idx < 0) return null val cellBounds = accountList.getCellBounds(idx, idx) if (!cellBounds.contains(point)) return null val decorator = accountListModel.getElementAt(idx) if (decorator?.loadingError == null) return null val rendererComponent = accountList.cellRenderer.getListCellRendererComponent(accountList, decorator, idx, true, true) rendererComponent.setBounds(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height) layoutRecursively(rendererComponent) val rendererRelativeX = point.x - cellBounds.x val rendererRelativeY = point.y - cellBounds.y val childComponent = UIUtil.getDeepestComponentAt(rendererComponent, rendererRelativeX, rendererRelativeY) if (childComponent !is SimpleColoredComponent) return null val childRelativeX = rendererRelativeX - childComponent.parent.x - childComponent.x return if (childComponent.getFragmentTagAt(childRelativeX) == LINK_TAG) decorator else null } } private fun setLinkHandlerEnabled(enabled: Boolean) { if (enabled) { if (!errorLinkHandlerInstalled) { accountList.addMouseListener(errorLinkHandler) accountList.addMouseMotionListener(errorLinkHandler) errorLinkHandlerInstalled = true } } else if (errorLinkHandlerInstalled) { accountList.removeMouseListener(errorLinkHandler) accountList.removeMouseMotionListener(errorLinkHandler) errorLinkHandlerInstalled = false } } fun loadExistingAccountsDetails() { for (accountData in accountListModel.items) { loadAccountDetails(accountData) } } private fun loadAccountDetails(accountData: GithubAccountDecorator) { val account = accountData.account val token = newTokensMap[account] ?: currentTokensMap[account] if (token == null) { accountListModel.contentsChanged(accountData.apply { loadingError = "Missing access token" showLoginLink = true }) return } progressManager.run(object : Task.Backgroundable(project, "Not Visible") { lateinit var data: Pair<GithubUserDetailed, Image?> override fun run(indicator: ProgressIndicator) { val executor = executorFactory.create(token) val details = accountInformationProvider.getInformation(executor, indicator, account) val image = details.avatarUrl?.let { accountInformationProvider.getAvatar(executor, indicator, account, it) } data = details to image } override fun onSuccess() { accountListModel.contentsChanged(accountData.apply { fullName = data.first.name profilePicture = data.second loadingError = null showLoginLink = false }) } override fun onThrowable(error: Throwable) { accountListModel.contentsChanged(accountData.apply { loadingError = error.message.toString() showLoginLink = error is GithubAuthenticationException }) } }) } private fun createListProgressManager() = object : ProgressVisibilityManager() { override fun setProgressVisible(visible: Boolean) = accountList.setPaintBusy(visible) override fun getModalityState() = ModalityState.any() } fun setAccounts(accounts: Map<GithubAccount, String?>, defaultAccount: GithubAccount?) { accountListModel.removeAll() accountListModel.addAll(0, accounts.keys.map { GithubAccountDecorator(it, it == defaultAccount) }) currentTokensMap = accounts } /** * @return list of accounts and associated tokens if new token was created and selected default account */ fun getAccounts(): Pair<Map<GithubAccount, String?>, GithubAccount?> { return accountListModel.items.associate { it.account to newTokensMap[it.account] } to accountListModel.items.find { it.projectDefault }?.account } fun clearNewTokens() = newTokensMap.clear() fun isModified(accounts: Set<GithubAccount>, defaultAccount: GithubAccount?): Boolean { return accountListModel.items.find { it.projectDefault }?.account != defaultAccount || accountListModel.items.map { it.account }.toSet() != accounts || newTokensMap.isNotEmpty() } override fun dispose() {} companion object { private fun layoutRecursively(component: Component) { if (component is JComponent) { component.doLayout() for (child in component.components) { layoutRecursively(child) } } } } } private class GithubAccountDecoratorRenderer : ListCellRenderer<GithubAccountDecorator>, JPanel() { private val accountName = JLabel() private val serverName = JLabel() private val profilePicture = JLabel() private val fullName = JLabel() private val loadingError = SimpleColoredComponent() /** * UPDATE [createLinkActivationListener] IF YOU CHANGE LAYOUT */ init { layout = FlowLayout(FlowLayout.LEFT, 0, 0) border = JBUI.Borders.empty(5, 8) val namesPanel = JPanel().apply { layout = GridBagLayout() border = JBUI.Borders.empty(0, 6, 4, 6) val bag = GridBag() .setDefaultInsets(JBUI.insetsRight(UIUtil.DEFAULT_HGAP)) .setDefaultAnchor(GridBagConstraints.WEST) .setDefaultFill(GridBagConstraints.VERTICAL) add(fullName, bag.nextLine().next()) add(accountName, bag.next()) add(loadingError, bag.next()) add(serverName, bag.nextLine().coverLine()) } add(profilePicture) add(namesPanel) } override fun getListCellRendererComponent(list: JList<out GithubAccountDecorator>, value: GithubAccountDecorator, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { UIUtil.setBackgroundRecursively(this, if (isSelected) list.selectionBackground else list.background) val textColor = if (isSelected) list.selectionForeground else list.foreground val grayTextColor = if (isSelected) list.selectionForeground else Gray._120 accountName.apply { text = value.account.name setBold(if (value.fullName == null) value.projectDefault else false) foreground = if (value.fullName == null) textColor else grayTextColor } serverName.apply { text = value.account.server.toString() foreground = grayTextColor } profilePicture.apply { icon = value.profilePicture?.let { val size = JBUI.scale(ACCOUNT_PICTURE_SIZE) JBImageIcon(it.getScaledInstance(size, size, java.awt.Image.SCALE_FAST)) } ?: GithubIcons.DefaultAvatar_40 } fullName.apply { text = value.fullName setBold(value.projectDefault) isVisible = value.fullName != null foreground = textColor } loadingError.apply { clear() value.loadingError?.let { append(it, SimpleTextAttributes.ERROR_ATTRIBUTES) append(" ") if (value.showLoginLink) append("Log In", if (value.errorLinkPointedAt) SimpleTextAttributes(STYLE_UNDERLINE, JBColor.link()) else SimpleTextAttributes(STYLE_PLAIN, JBColor.link()), LINK_TAG) } } return this } companion object { private fun JLabel.setBold(isBold: Boolean) { font = font.deriveFont(if (isBold) font.style or Font.BOLD else font.style and Font.BOLD.inv()) } } } /** * Account + auxillary info + info loading error */ private class GithubAccountDecorator(val account: GithubAccount, var projectDefault: Boolean) { var fullName: String? = null var profilePicture: Image? = null var loadingError: String? = null var showLoginLink = false var errorLinkPointedAt = false override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GithubAccountDecorator if (account != other.account) return false return true } override fun hashCode(): Int { return account.hashCode() } }
apache-2.0
da5fbb955c93e0d29eece9096cb3df1e
37.878109
140
0.692239
5.359739
false
false
false
false
devmil/PaperLaunch
app/src/main/java/de/devmil/paperlaunch/MainActivity.kt
1
2816
/* * Copyright 2015 Devmil Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.devmil.paperlaunch import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toolbar import de.devmil.paperlaunch.service.LauncherOverlayService import de.devmil.paperlaunch.utils.PermissionUtils import de.devmil.paperlaunch.view.fragments.EditFolderFragment class MainActivity : Activity() { private var toolbar: Toolbar? = null private var fragment: EditFolderFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) LauncherOverlayService.launch(this) setContentView(R.layout.activity_main) toolbar = findViewById(R.id.activity_main_toolbar) fragment = fragmentManager.findFragmentById(R.id.activity_main_editfolder_fragment) as EditFolderFragment setActionBar(toolbar) PermissionUtils.checkOverlayPermissionAndRouteToSettingsIfNeeded(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode) { PermissionUtils.REQUEST_DRAW_OVERLAY_PERMISSION -> { LauncherOverlayService.permissionChanged(this) finish() startActivity(intent) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { val result = super.onCreateOptionsMenu(menu) val itemSettings = menu.add(R.string.title_activity_settings) itemSettings.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) itemSettings.icon = getDrawable(R.mipmap.ic_settings_black_48dp) itemSettings.setOnMenuItemClickListener { val settingsIntent = Intent(this@MainActivity, SettingsActivity::class.java) startActivity(settingsIntent) true } val itemAbout = menu.add(R.string.title_activity_about) itemAbout.setOnMenuItemClickListener { val settingsIntent = Intent(this@MainActivity, AboutActivity::class.java) startActivity(settingsIntent) true } return result } }
apache-2.0
0f478bfbe77d380185fe976c893e37cd
35.102564
113
0.713423
4.805461
false
false
false
false
debop/debop4k
debop4k-spring-jdbc/src/main/kotlin/debop4k/spring/jdbc/core/config/Configx.kt
1
1661
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("Configx") package debop4k.spring.jdbc.core.config import org.springframework.jdbc.datasource.embedded.* import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2 import javax.sql.DataSource /** * Embeded Database 에 대한 DataSource 를 빌드합니다. */ fun EmbeddedDatabaseType.buildDataSource(body: EmbeddedDatabaseTag.() -> Unit): DataSource { val tag = EmbeddedDatabaseTag().apply { body() } // val scripts = tag.scripts val factory = EmbeddedDatabaseFactory().apply { setDatabaseType(this@buildDataSource) } return factory.database } fun embeddedDatabase(type: EmbeddedDatabaseType = H2, body: EmbeddedDatabaseTag.() -> Unit): DataSource { val tag = EmbeddedDatabaseTag().apply { body() } val scripts = tag.scripts.map { s -> s.location } return EmbeddedDatabaseBuilder() .setType(type) .generateUniqueName(true) .generateUniqueName(true) .addScripts(*scripts.toTypedArray<String>()) .build() }
apache-2.0
dea2dac81598a791d755ba7f7f7caa78
28.890909
92
0.718807
4.097257
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/ui/drawer/NavDrawerListAdapter.kt
1
2537
package fr.geobert.radis.ui.drawer import android.content.Context 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.geobert.radis.R import java.util.* class NavDrawerListAdapter(private val context: Context, private val navDrawerItems: ArrayList<NavDrawerItem>) : BaseAdapter() { private inner class ViewHolder internal constructor(v: View) { internal var icon: ImageView internal var header: TextView internal var title: TextView internal var headerCont: LinearLayout internal var itemCont: LinearLayout init { icon = v.findViewById(R.id.drawer_item_img) as ImageView title = v.findViewById(R.id.drawer_item_lbl) as TextView header = v.findViewById(R.id.drawer_header_lbl) as TextView headerCont = v.findViewById(R.id.drawer_header) as LinearLayout itemCont = v.findViewById(R.id.drawer_item) as LinearLayout } } override fun getCount(): Int { return navDrawerItems.size } override fun getItem(i: Int): Any { return navDrawerItems.get(i) } override fun isEnabled(position: Int): Boolean { return !(getItem(position) as NavDrawerItem).isHeader } override fun getItemId(i: Int): Long { return i.toLong() } override fun getView(i: Int, v: View?, viewGroup: ViewGroup): View { var view = v val h: ViewHolder if (view == null) { val l = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater view = l.inflate(R.layout.drawer_item, null, false) h = ViewHolder(view) view?.tag = h } else { h = view.tag as ViewHolder } val item = navDrawerItems.get(i) if (item.isHeader) { h.itemCont.visibility = View.GONE h.headerCont.visibility = View.VISIBLE h.header.text = item.title } else { h.itemCont.visibility = View.VISIBLE h.headerCont.visibility = View.GONE h.title.text = item.title if (item.icon != 0) { h.icon.setImageResource(item.icon) h.icon.visibility = View.VISIBLE } else { h.icon.visibility = View.GONE } } return view as View } }
gpl-2.0
b9c9ec869e99089dcb02fa89f81a4891
31.525641
128
0.623571
4.366609
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/activities/CallActivity.kt
1
23418
package com.quickblox.sample.videochat.kotlin.activities import android.annotation.TargetApi import android.app.Activity import android.app.KeyguardManager import android.content.* import android.net.Uri import android.os.* import android.preference.PreferenceManager import android.provider.Settings import android.util.Log import android.view.View import android.view.WindowManager import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import com.quickblox.core.QBEntityCallbackImpl import com.quickblox.sample.videochat.kotlin.R import com.quickblox.sample.videochat.kotlin.db.QbUsersDbManager import com.quickblox.sample.videochat.kotlin.fragments.* import com.quickblox.sample.videochat.kotlin.services.CallService import com.quickblox.sample.videochat.kotlin.services.MIN_OPPONENT_SIZE import com.quickblox.sample.videochat.kotlin.utils.* import com.quickblox.users.QBUsers import com.quickblox.users.model.QBUser import com.quickblox.videochat.webrtc.* import com.quickblox.videochat.webrtc.callbacks.QBRTCClientSessionCallbacks import com.quickblox.videochat.webrtc.callbacks.QBRTCClientVideoTracksCallbacks import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionEventsCallback import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionStateCallback import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack import org.jivesoftware.smack.AbstractConnectionListener import org.jivesoftware.smack.ConnectionListener import org.webrtc.CameraVideoCapturer import java.util.* import kotlin.collections.ArrayList private const val INCOME_CALL_FRAGMENT = "income_call_fragment" private const val REQUEST_PERMISSION_SETTING = 545 class CallActivity : BaseActivity(), IncomeCallFragmentCallbackListener, QBRTCSessionStateCallback<QBRTCSession>, QBRTCClientSessionCallbacks, ConversationFragmentCallback, ScreenShareFragment.OnSharingEvents { private var TAG = CallActivity::class.java.simpleName private val callStateListeners = hashSetOf<CallStateListener>() private val updateOpponentsListeners = hashSetOf<UpdateOpponentsListener>() private val callTimeUpdateListeners = hashSetOf<CallTimeUpdateListener>() private lateinit var showIncomingCallWindowTaskHandler: Handler private var connectionListener: ConnectionListenerImpl? = null private lateinit var callServiceConnection: ServiceConnection private lateinit var showIncomingCallWindowTask: Runnable private var opponentIds: List<Int>? = null private lateinit var callService: CallService private var connectionView: LinearLayout? = null private var isInComingCall: Boolean = false private var isVideoCall: Boolean = false companion object { fun start(context: Context, isIncomingCall: Boolean) { val intent = Intent(context, CallActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra(EXTRA_IS_INCOMING_CALL, isIncomingCall) SharedPrefsHelper.save(EXTRA_IS_INCOMING_CALL, isIncomingCall) context.startActivity(intent) CallService.start(context) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { setShowWhenLocked(true) setTurnScreenOn(true) val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager keyguardManager.requestDismissKeyguard(this, null) } else { this.window.addFlags( WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON ) } connectionView = View.inflate(this, R.layout.connection_popup, null) as LinearLayout } private fun initScreen() { callService.setCallTimerCallback(CallTimerCallback()) isVideoCall = callService.isVideoCall() opponentIds = callService.getOpponents() applyMediaSettings() addListeners() isInComingCall = if (intent != null && intent.extras != null) { intent?.extras?.getBoolean(EXTRA_IS_INCOMING_CALL) ?: false } else { SharedPrefsHelper.get(EXTRA_IS_INCOMING_CALL, false) } if (callService.isConnectedCall()) { checkPermission() if (callService.isSharingScreenState()) { startScreenSharing(null) return } addConversationFragment(isInComingCall) } else { if (!isInComingCall) { callService.playRingtone() } startSuitableFragment(isInComingCall) } } private fun addListeners() { addSessionEventsListener(this) addSessionStateListener(this) connectionListener = ConnectionListenerImpl() addConnectionListener(connectionListener) } private fun removeListeners() { removeSessionEventsListener(this) removeSessionStateListener(this) removeConnectionListener(connectionListener) callService.removeCallTimerCallback() } private fun bindCallService() { callServiceConnection = CallServiceConnection() Intent(this, CallService::class.java).also { intent -> bindService(intent, callServiceConnection, Context.BIND_AUTO_CREATE) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) Log.i(TAG, "onActivityResult requestCode=$requestCode, resultCode= $resultCode") if (resultCode == EXTRA_LOGIN_RESULT_CODE) { data?.let { val isLoginSuccess = it.getBooleanExtra(EXTRA_LOGIN_RESULT, false) if (isLoginSuccess) { initScreen() } else { finish() } } } if (requestCode == QBRTCScreenCapturer.REQUEST_MEDIA_PROJECTION && resultCode == Activity.RESULT_OK) { data?.let { startScreenSharing(it) Log.i(TAG, "Starting screen capture") } } } private fun startScreenSharing(data: Intent?) { val fragmentByTag = supportFragmentManager.findFragmentByTag(ScreenShareFragment::class.simpleName) if (fragmentByTag !is ScreenShareFragment) { addFragment( supportFragmentManager, R.id.fragment_container, ScreenShareFragment.newInstance(), ScreenShareFragment::class.java.simpleName ) data?.let { callService.startScreenSharing(it) } } } private fun startSuitableFragment(isInComingCall: Boolean) { val session = WebRtcSessionManager.getCurrentSession() if (session != null) { loadAbsentUsers() if (isInComingCall) { initIncomingCallTask() addIncomeCallFragment() checkPermission() } else { addConversationFragment(isInComingCall) intent.removeExtra(EXTRA_IS_INCOMING_CALL) SharedPrefsHelper.save(EXTRA_IS_INCOMING_CALL, false) } } else { finish() } } private fun checkPermission() { val cam = SharedPrefsHelper.get(PERMISSIONS[0], true) val mic = SharedPrefsHelper.get(PERMISSIONS[1], true) Log.d(TAG, "CAMERA => $cam; MICROPHONE => $mic") if (isVideoCall && checkPermissions(PERMISSIONS)) { if (cam) { PermissionsActivity.startForResult(this, false, PERMISSIONS) } else { val rootView = window.decorView.findViewById<View>(android.R.id.content) showErrorSnackbar( rootView, getString(R.string.error_permission_video), R.string.dlg_allow, object : View.OnClickListener { override fun onClick(v: View?) { startPermissionSystemSettings() } }) } } else if (checkPermission(PERMISSIONS[1])) { if (mic) { PermissionsActivity.startForResult(this, true, PERMISSIONS) } else { val rootView = window.decorView.findViewById<View>(android.R.id.content) showErrorSnackbar( rootView, R.string.error_permission_audio, "Allow Permission", R.string.dlg_allow, object : View.OnClickListener { override fun onClick(v: View?) { startPermissionSystemSettings() } }) } } } private fun startPermissionSystemSettings() { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri = Uri.fromParts("package", packageName, null) intent.data = uri startActivityForResult(intent, REQUEST_PERMISSION_SETTING) } private fun loadAbsentUsers() { val usersFromDb = QbUsersDbManager.allUsers val allParticipantsOfCall = ArrayList<Int>() opponentIds?.let { allParticipantsOfCall.addAll(it) } if (isInComingCall) { val callerId = callService.getCallerId() callerId?.let { allParticipantsOfCall.add(it) } } val idsNotLoadedUsers = ArrayList<Int>() for (userId in allParticipantsOfCall) { val user = QBUser(userId) user.fullName = userId.toString() if (!usersFromDb.contains(user)) { idsNotLoadedUsers.add(userId) } } if (idsNotLoadedUsers.isNotEmpty()) { QBUsers.getUsersByIDs(idsNotLoadedUsers, null) .performAsync(object : QBEntityCallbackImpl<ArrayList<QBUser>>() { override fun onSuccess(users: ArrayList<QBUser>, params: Bundle) { QbUsersDbManager.saveAllUsers(users, false) notifyOpponentsUpdated(users) } }) } } private fun initIncomingCallTask() { showIncomingCallWindowTaskHandler = Handler(Looper.getMainLooper()) showIncomingCallWindowTask = Runnable { if (callService.currentSessionExist()) { longToast("Call was stopped by UserNoActions timer") callService.clearCallState() callService.clearButtonsState() WebRtcSessionManager.setCurrentSession(null) CallService.stop(this@CallActivity) finish() } } } private fun hangUpCurrentSession() { callService.stopRingtone() if (!callService.hangUpCurrentSession(HashMap())) { finish() } } private fun startIncomeCallTimer(time: Long) { showIncomingCallWindowTaskHandler.postAtTime(showIncomingCallWindowTask, SystemClock.uptimeMillis() + time) } private fun stopIncomeCallTimer() { Log.d(TAG, "stopIncomeCallTimer") showIncomingCallWindowTaskHandler.removeCallbacks(showIncomingCallWindowTask) } override fun onResume() { super.onResume() bindCallService() } override fun onPause() { super.onPause() unbindService(callServiceConnection) if (::callService.isInitialized) { removeListeners() } } override fun finish() { // fix bug when user returns to call from service and the backstack doesn't have any screens OpponentsActivity.start(this) CallService.stop(this) super.finish() } override fun onBackPressed() { // to prevent returning from Call Fragment } private fun addIncomeCallFragment() { if (callService.currentSessionExist()) { val fragment = IncomeCallFragment() if (supportFragmentManager.findFragmentByTag(INCOME_CALL_FRAGMENT) == null) { addFragment(supportFragmentManager, R.id.fragment_container, fragment, INCOME_CALL_FRAGMENT) } } else { Log.d(TAG, "SKIP addIncomeCallFragment method") } } private fun addConversationFragment(isIncomingCall: Boolean) { val baseConversationFragment: BaseConversationFragment = if (isVideoCall) { VideoConversationFragment() } else { AudioConversationFragment() } val conversationFragment = BaseConversationFragment.newInstance(baseConversationFragment, isIncomingCall) addFragment( supportFragmentManager, R.id.fragment_container, conversationFragment, conversationFragment.javaClass.simpleName ) } private fun showConnectionPopUp() { runOnUiThread { val fragmentContainer: FrameLayout = findViewById(R.id.fragment_container) val connectionNotificationView: TextView? = connectionView?.findViewById(R.id.notification) connectionNotificationView?.setText(R.string.connection_was_lost) if (connectionView?.parent == null) { fragmentContainer.addView(connectionView) } } } private fun hideConnectionPopUp() { runOnUiThread { val fragmentContainer: FrameLayout = findViewById(R.id.fragment_container) fragmentContainer.removeView(connectionView) } } private inner class ConnectionListenerImpl : AbstractConnectionListener() { override fun connectionClosedOnError(e: Exception?) { showConnectionPopUp() } override fun reconnectionSuccessful() { hideConnectionPopUp() } } override fun onDisconnectedFromUser(session: QBRTCSession?, userId: Int?) { // empty } override fun onConnectedToUser(session: QBRTCSession?, userId: Int?) { notifyCallStarted() if (isInComingCall) { stopIncomeCallTimer() } Log.d(TAG, "onConnectedToUser() is started") } override fun onConnectionClosedForUser(session: QBRTCSession?, userId: Int?) { // empty } override fun onStateChanged(session: QBRTCSession?, sessiontState: BaseSession.QBRTCSessionState?) { // empty } override fun onUserNotAnswer(session: QBRTCSession?, userId: Int?) { if (callService.isCurrentSession(session)) { callService.stopRingtone() } } override fun onSessionStartClose(session: QBRTCSession?) { if (callService.isCurrentSession(session)) { callService.removeSessionStateListener(this) notifyCallStopped() } } override fun onReceiveHangUpFromUser(session: QBRTCSession?, userId: Int?, map: MutableMap<String, String>?) { if (callService.isCurrentSession(session)) { val numberOpponents = session?.opponents?.size if (numberOpponents == MIN_OPPONENT_SIZE) { hangUpCurrentSession() } val participant = QbUsersDbManager.getUserById(userId) val participantName = if (participant != null) participant.fullName else userId.toString() shortToast("User " + participantName + " " + getString(R.string.text_status_hang_up) + " conversation") } } override fun onCallAcceptByUser(session: QBRTCSession?, userId: Int?, map: MutableMap<String, String>?) { if (callService.isCurrentSession(session)) { callService.stopRingtone() } } override fun onReceiveNewSession(session: QBRTCSession?) { // empty } override fun onUserNoActions(session: QBRTCSession?, userId: Int?) { startIncomeCallTimer(0) } override fun onSessionClosed(session: QBRTCSession?) { if (callService.isCurrentSession(session)) { callService.stopForeground(true) finish() } } override fun onCallRejectByUser(session: QBRTCSession?, userId: Int?, map: MutableMap<String, String>?) { // empty } override fun onAcceptCurrentSession() { if (callService.currentSessionExist()) { addConversationFragment(true) } else { Log.d(TAG, "SKIP addConversationFragment method") } } override fun onRejectCurrentSession() { callService.rejectCurrentSession(HashMap()) } override fun addConnectionListener(connectionCallback: ConnectionListener?) { callService.addConnectionListener(connectionCallback) } override fun removeConnectionListener(connectionCallback: ConnectionListener?) { callService.removeConnectionListener(connectionCallback) } override fun addSessionStateListener(clientConnectionCallbacks: QBRTCSessionStateCallback<*>?) { callService.addSessionStateListener(clientConnectionCallbacks) } override fun addSessionEventsListener(eventsCallback: QBRTCSessionEventsCallback?) { callService.addSessionEventsListener(eventsCallback) } override fun onSetAudioEnabled(isAudioEnabled: Boolean) { callService.setAudioEnabled(isAudioEnabled) } override fun onHangUpCurrentSession() { hangUpCurrentSession() } @TargetApi(21) override fun onStartScreenSharing() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return } QBRTCScreenCapturer.requestPermissions(this) } override fun onSwitchCamera(cameraSwitchHandler: CameraVideoCapturer.CameraSwitchHandler) { callService.switchCamera(cameraSwitchHandler) } override fun onSetVideoEnabled(isNeedEnableCam: Boolean) { callService.setVideoEnabled(isNeedEnableCam) } override fun onSwitchAudio() { callService.switchAudio() } override fun removeSessionStateListener(clientConnectionCallbacks: QBRTCSessionStateCallback<*>?) { callService.removeSessionStateListener(clientConnectionCallbacks) } override fun removeSessionEventsListener(eventsCallback: QBRTCSessionEventsCallback?) { callService.removeSessionEventsListener(eventsCallback) } override fun addCallStateListener(callStateListener: CallStateListener) { callStateListeners.add(callStateListener) } override fun removeCallStateListener(callStateListener: CallStateListener) { callStateListeners.remove(callStateListener) } override fun addUpdateOpponentsListener(updateOpponentsListener: UpdateOpponentsListener) { updateOpponentsListeners.add(updateOpponentsListener) } override fun removeUpdateOpponentsListener(updateOpponentsListener: UpdateOpponentsListener) { updateOpponentsListeners.remove(updateOpponentsListener) } override fun addCallTimeUpdateListener(callTimeUpdateListener: CallTimeUpdateListener) { callTimeUpdateListeners.add(callTimeUpdateListener) } override fun removeCallTimeUpdateListener(callTimeUpdateListener: CallTimeUpdateListener) { callTimeUpdateListeners.remove(callTimeUpdateListener) } override fun addOnChangeAudioDeviceListener(onChangeDynamicCallback: OnChangeAudioDevice?) { // empty } override fun removeOnChangeAudioDeviceListener(onChangeDynamicCallback: OnChangeAudioDevice?) { // empty } override fun acceptCall(userInfo: Map<String, String>) { callService.acceptCall(userInfo) } override fun startCall(userInfo: Map<String, String>) { callService.startCall(userInfo) } override fun currentSessionExist(): Boolean { return callService.currentSessionExist() } override fun getOpponents(): List<Int>? { return callService.getOpponents() } override fun getCallerId(): Int? { return callService.getCallerId() } override fun addVideoTrackListener(callback: QBRTCClientVideoTracksCallbacks<QBRTCSession>?) { callService.addVideoTrackListener(callback) } override fun removeVideoTrackListener(callback: QBRTCClientVideoTracksCallbacks<QBRTCSession>?) { callService.removeVideoTrackListener(callback) } override fun getCurrentSessionState(): BaseSession.QBRTCSessionState? { return callService.getCurrentSessionState() } override fun getPeerChannel(userId: Int): QBRTCTypes.QBRTCConnectionState? { return callService.getPeerChannel(userId) } override fun isMediaStreamManagerExist(): Boolean { return callService.isMediaStreamManagerExist() } override fun isConnectedCall(): Boolean { return callService.isConnectedCall() } override fun getVideoTrackMap(): MutableMap<Int, QBRTCVideoTrack> { return callService.getVideoTrackMap() } override fun getVideoTrack(userId: Int): QBRTCVideoTrack? { return callService.getVideoTrack(userId) } override fun onStopPreview() { callService.stopScreenSharing() addConversationFragment(isInComingCall) } private fun notifyCallStarted() { for (listener in callStateListeners) { listener.startedCall() } } private fun notifyCallStopped() { for (listener in callStateListeners) { listener.stoppedCall() } } private fun notifyOpponentsUpdated(opponents: ArrayList<QBUser>) { for (listener in updateOpponentsListeners) { listener.updatedOpponents(opponents) } } private fun notifyCallTimeUpdated(callTime: String) { for (listener in callTimeUpdateListeners) { listener.updatedCallTime(callTime) } } private inner class CallServiceConnection : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { // empty } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { val binder = service as CallService.CallServiceBinder callService = binder.getService() if (callService.currentSessionExist()) { initScreen(); } else { finish() } } } private inner class CallTimerCallback : CallService.CallTimerListener { override fun onCallTimeUpdate(time: String) { runOnUiThread { notifyCallTimeUpdated(time) } } } interface OnChangeAudioDevice { fun audioDeviceChanged(newAudioDevice: AppRTCAudioManager.AudioDevice) } interface CallStateListener { fun startedCall() fun stoppedCall() } interface UpdateOpponentsListener { fun updatedOpponents(updatedOpponents: ArrayList<QBUser>) } interface CallTimeUpdateListener { fun updatedCallTime(time: String) } }
bsd-3-clause
a2d4d8eb7fccd962c3315c90e0dde847
33.901639
115
0.656888
5.44478
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/searchusers/SearchUsersActivity.kt
1
6518
package com.quickblox.sample.conference.kotlin.presentation.screens.searchusers import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.databinding.ActivitySearchUsersBinding import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseActivity import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.newchat.UsersSearchAdapter import com.quickblox.sample.conference.kotlin.presentation.screens.login.LoginActivity import dagger.hilt.android.AndroidEntryPoint private const val EXTRA_DIALOG_ID = "EXTRA_DIALOG_ID" /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ @AndroidEntryPoint class SearchUsersActivity : BaseActivity<SearchUserViewModel>(SearchUserViewModel::class.java) { private lateinit var binding: ActivitySearchUsersBinding private var usersSearchAdapter: UsersSearchAdapter? = null private val onScrollListenerImpl = OnScrollListenerImpl() companion object { fun start(context: Context, dialogId: String) { val intent = Intent(context, SearchUsersActivity::class.java) intent.putExtra(EXTRA_DIALOG_ID, dialogId) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySearchUsersBinding.inflate(layoutInflater) setContentView(binding.root) val dialogId = intent.getStringExtra(EXTRA_DIALOG_ID) dialogId?.let { viewModel.loadDialogById(it) } ?: run { Toast.makeText(baseContext, getString(R.string.dialogId_error), Toast.LENGTH_SHORT).show() finish() } initToolbar() initAdapter() initScrollListeners() binding.toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.done -> { viewModel.addUsers(viewModel.selectedUsers) } } return@setOnMenuItemClickListener true } viewModel.liveData.observe(this, { result -> result?.let { (state, data) -> when (state) { ViewState.PROGRESS -> { showProgress() } ViewState.ERROR -> { hideProgress() Toast.makeText(this, "$data", Toast.LENGTH_SHORT).show() } ViewState.DIALOG_LOADED -> { viewModel.loadOccupants() } ViewState.OCCUPANTS_LOADED -> { viewModel.loadUsers() } ViewState.SHOW_USERS -> { hideProgress() if (viewModel.users.isEmpty()) { binding.tvPlaceHolder.visibility = View.VISIBLE binding.rvUsers.visibility = View.GONE } else { binding.tvPlaceHolder.visibility = View.GONE binding.rvUsers.visibility = View.VISIBLE } usersSearchAdapter?.notifyDataSetChanged() } ViewState.MOVE_TO_BACK -> { hideProgress() onBackPressed() } ViewState.SHOW_LOGIN_SCREEN -> { LoginActivity.start(this) finish() } } } }) } private fun initToolbar() { binding.toolbar.inflateMenu(R.menu.menu_searche_users) binding.toolbar.menu?.getItem(0)?.isVisible = false binding.flBack.setOnClickListener { onBackPressed() } binding.toolbarTitle.setText(R.string.add_members) binding.searchView.setOnQueryTextListener(SearchQueryListener()) } private fun changeToolbar() { val selectedCounter = viewModel.selectedUsers.size binding.toolbar.menu?.getItem(0)?.isVisible = selectedCounter > 0 if (selectedCounter == 0) { binding.tvSubTitle.visibility = View.GONE return } else { binding.tvSubTitle.visibility = View.VISIBLE } binding.tvSubTitle.text = if (selectedCounter > 1) { getString(R.string.subtitle_new_chat_users, selectedCounter.toString()) } else { getString(R.string.subtitle_new_chat_user, selectedCounter.toString()) } } private fun initAdapter() { usersSearchAdapter = UsersSearchAdapter(viewModel.users, object : UsersSearchAdapter.UsersAdapterListener { override fun onSelected() { changeToolbar() } }, viewModel.selectedUsers) binding.rvUsers.adapter = usersSearchAdapter } private fun initScrollListeners() { val mLayoutManager = LinearLayoutManager(this) binding.rvUsers.layoutManager = mLayoutManager binding.rvUsers.addOnScrollListener(onScrollListenerImpl) } override fun showProgress() { binding.progressBar.visibility = View.VISIBLE } override fun hideProgress() { onScrollListenerImpl.isLoad = false binding.progressBar.visibility = View.GONE } private inner class SearchQueryListener : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { return false } override fun onQueryTextChange(newText: String): Boolean { viewModel.onQueryTextChange(newText) return false } } inner class OnScrollListenerImpl : RecyclerView.OnScrollListener() { var isLoad: Boolean = false override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (!recyclerView.canScrollVertically(1) || isLoad) { isLoad = true viewModel.loadUsers() } } } }
bsd-3-clause
d027a2a8c8207e4753f25df1461eae04
35.617978
115
0.605033
5.467282
false
false
false
false
hotpodata/Blockelganger
app/src/main/java/com/hotpodata/blockelganger/view/BlockelgangerGameBoard.kt
1
32520
package com.hotpodata.blockelganger.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.annotation.TargetApi import android.content.Context import android.graphics.PorterDuff import android.graphics.RectF import android.os.Build import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.OvershootInterpolator import android.widget.FrameLayout import com.hotpodata.blockelganger.BuildConfig import com.hotpodata.blockelganger.R import com.hotpodata.blockelganger.helpers.ColorBlockDrawer import com.hotpodata.blockelganger.helpers.GameGridHelper import com.hotpodata.blockelganger.helpers.GameHelper import com.hotpodata.blockelganger.helpers.GridTouchListener import com.hotpodata.blocklib.Grid import com.hotpodata.blocklib.GridHelper import com.hotpodata.blocklib.view.GridBinderView import com.hotpodata.common.view.SizeAwareFrameLayout import kotlinx.android.synthetic.main.blockelganger_game_board.view.* import timber.log.Timber import java.util.* /** * Created by jdrotos on 1/29/16. * * This is the class that manages positioning and sizing the various grids. * It also handles animating between board states * */ class BlockelgangerGameBoard : SizeAwareFrameLayout, GridTouchListener.ITouchCoordinator { interface IGangerTouchListener { fun onGangerTouched() } var gridOne = GameGridHelper.genFullGrid(1, 1, true) set(grd: Grid) { field = grd gridbinderview_one.grid = grd } var gridTwo = GameGridHelper.genFullGrid(1, 1, true) set(grd: Grid) { field = grd gridbinderview_two.grid = grd } var gangerOneGrid = GameGridHelper.genFullGrid(1, 1, true) set(grd: Grid) { field = grd gridbinderview_blockelganger_one.grid = grd } var gangerTwoGrid = GameGridHelper.genFullGrid(1, 1, true) set(grd: Grid) { field = grd gridbinderview_blockelganger_two.grid = grd } private var chapter: GameHelper.Chapter = GameHelper.Chapter.ONE var touchHintAnims = HashMap<View, Animator>() var parentTouchCoordinator: GridTouchListener.ITouchCoordinator? = null var gangerTouchListener: IGangerTouchListener? = null constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(context) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context) } fun init(context: Context) { var inflater = LayoutInflater.from(context) inflater.inflate(R.layout.blockelganger_game_board, this, true); gridbinderview_one.blockDrawer = ColorBlockDrawer(resources.getColor(R.color.top_grid)) gridbinderview_two.blockDrawer = ColorBlockDrawer(resources.getColor(R.color.btm_grid)) gridbinderview_animation_coordinator.blockDrawer = ColorBlockDrawer(resources.getColor(R.color.ganger_grid)) gridbinderview_blockelganger_one.blockDrawer = ColorBlockDrawer(resources.getColor(R.color.ganger_grid)) gridbinderview_blockelganger_two.blockDrawer = ColorBlockDrawer(resources.getColor(R.color.ganger_grid)) gridbinderview_one.setOnTouchListener(GridTouchListener(this, object : GridTouchListener.IGridChangedListener { override fun onGridChanged(grid: Grid) { gridOne = grid } })) gridbinderview_two.setOnTouchListener(GridTouchListener(this, object : GridTouchListener.IGridChangedListener { override fun onGridChanged(grid: Grid) { gridTwo = grid } })) gridbinderview_blockelganger_one.setOnClickListener { gangerTouchListener?.onGangerTouched() } gridbinderview_blockelganger_two.setOnClickListener { gangerTouchListener?.onGangerTouched() } } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) prepareGridViews() } /** * GridTouchListener.ITouchCoordinator */ override fun onGridTouched(view: View) { if (view == gridbinderview_one) { if (chapter == GameHelper.Chapter.THREE) { setTouchHintShowing(touch_hint_right, false) } else { setTouchHintShowing(touch_hint_top, false) } } if (view == gridbinderview_two) { setTouchHintShowing(touch_hint_btm, false) } parentTouchCoordinator?.onGridTouched(view) } override fun allowGridTouch(view: View): Boolean { return parentTouchCoordinator?.allowGridTouch(view) ?: false } /** * SET DATA FOR A GIVEN CHAPTER */ fun chapterOne(playerGrid: Grid, gangerGrid: Grid) { chapter = GameHelper.Chapter.ONE gridOne = playerGrid gridTwo = Grid(1, 1) gangerOneGrid = gangerGrid gangerTwoGrid = Grid(1, 1) prepareGridViews() } fun chapterTwo(playerGridTop: Grid, playerGridBtm: Grid, gangerGrid: Grid) { chapter = GameHelper.Chapter.TWO gridOne = playerGridTop gridTwo = playerGridBtm gangerOneGrid = gangerGrid gangerTwoGrid = Grid(1, 1) prepareGridViews() } fun chapterThree(playerGrid: Grid, gangerGrid: Grid) { chapter = GameHelper.Chapter.THREE gridOne = playerGrid gridTwo = Grid(1, 1) gangerOneGrid = gangerGrid gangerTwoGrid = Grid(1, 1) prepareGridViews() } fun chapterFour(playerGridTop: Grid, playerGridBtm: Grid, gangerGridCenter: Grid, gangerGridLeft: Grid) { chapter = GameHelper.Chapter.FOUR gridOne = playerGridTop gridTwo = playerGridBtm gangerOneGrid = gangerGridCenter gangerTwoGrid = gangerGridLeft prepareGridViews() } /** * */ fun setAccentColor(color: Int) { touch_hint_top.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) touch_hint_btm.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) touch_hint_right.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) } fun findPositionInGridBinder(outerGrid: Grid, targetGrid: Grid, gridBinderView: GridBinderView): RectF? { return GridHelper.findInGrid(outerGrid, targetGrid)?.let { var vPadding = GridHelper.numEmptyRowsTopBtm(targetGrid) var hPadding = GridHelper.numEmptyColsLeftRight(targetGrid) var xOffset = it.left - hPadding.first var yOffset = it.top - vPadding.first gridBinderView.getSubGridPosition(targetGrid, xOffset, yOffset) } } fun genBoardsCollideAnim(combined: Grid): Animator { var animMoves = AnimatorSet() var coordinatorGrid = when (chapter) { GameHelper.Chapter.FOUR -> Grid(gangerOneGrid.width + gangerTwoGrid.width, gridOne.height + gridTwo.height + gangerOneGrid.height) GameHelper.Chapter.THREE -> Grid(gangerOneGrid.width + gridOne.width, gangerOneGrid.height) GameHelper.Chapter.TWO -> Grid(gridOne.width, gridOne.height + gridTwo.height + gangerOneGrid.height) GameHelper.Chapter.ONE -> Grid(gridOne.width, gridOne.height + gangerOneGrid.height) } GridHelper.addGrid(coordinatorGrid, combined, (coordinatorGrid.width - combined.width) / 2, (coordinatorGrid.height - combined.height) / 2) gridbinderview_animation_coordinator.grid = coordinatorGrid if (BuildConfig.IS_DEBUG_BUILD) { var combPrintStr = coordinatorGrid.getPrintString(" - ", { x -> when (x) { gridOne -> " 1 " gridTwo -> " 2 " gangerOneGrid -> " A " gangerTwoGrid -> " B " else -> " ? " } }) Timber.d("coordinatorGrid:\n" + combPrintStr) } var verticalAnimators = ArrayList<Animator>() var horizontalAnimators = ArrayList<Animator>() findPositionInGridBinder(coordinatorGrid, gridOne, gridbinderview_animation_coordinator)?.let { //it is now the coorinates for gridOne inside the coordinator var transX = gridbinderview_animation_coordinator.left + it.left - gridbinderview_one.left var transY = gridbinderview_animation_coordinator.top + it.top - gridbinderview_one.top if (transX != 0f) { horizontalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_one, "translationX", 0f, transX)) } if (transY != 0f) { verticalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_one, "translationY", 0f, transY)) } } findPositionInGridBinder(coordinatorGrid, gridTwo, gridbinderview_animation_coordinator)?.let { //it is now the coorinates for gridTwo inside the coordinator var transX = gridbinderview_animation_coordinator.left + it.left - gridbinderview_two.left var transY = gridbinderview_animation_coordinator.top + it.top - gridbinderview_two.top if (transX != 0f) { horizontalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_two, "translationX", 0f, transX)) } if (transY != 0f) { verticalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_two, "translationY", 0f, transY)) } } findPositionInGridBinder(coordinatorGrid, gangerOneGrid, gridbinderview_animation_coordinator)?.let { //it is now the coorinates for gangerOneGrid inside the coordinator var transX = gridbinderview_animation_coordinator.left + it.left - gridbinderview_blockelganger_one.left var transY = gridbinderview_animation_coordinator.top + it.top - gridbinderview_blockelganger_one.top if (transX != 0f) { horizontalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationX", 0f, transX)) } if (transY != 0f) { verticalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationY", 0f, transY)) } } findPositionInGridBinder(coordinatorGrid, gangerTwoGrid, gridbinderview_animation_coordinator)?.let { //it is now the coorinates for gangerTwoGrid inside the coordinator var transX = gridbinderview_animation_coordinator.left + it.left - gridbinderview_blockelganger_two.left var transY = gridbinderview_animation_coordinator.top + it.top - gridbinderview_blockelganger_two.top if (transX != 0f) { horizontalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_blockelganger_two, "translationX", 0f, transX)) } if (transY != 0f) { verticalAnimators.add(ObjectAnimator.ofFloat(gridbinderview_blockelganger_two, "translationY", 0f, transY)) } } var vertAnim = AnimatorSet() vertAnim.playTogether(verticalAnimators) var horizAnim = AnimatorSet() horizAnim.playTogether(horizontalAnimators) if (verticalAnimators.size > 0 && horizontalAnimators.size > 0) { animMoves.playSequentially(vertAnim, horizAnim) } else { animMoves.playTogether(vertAnim, horizAnim) } animMoves.setDuration(350L) animMoves.interpolator = AccelerateInterpolator() animMoves.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { gridbinderview_animation_coordinator.visibility = View.VISIBLE gridbinderview_one.visibility = View.INVISIBLE gridbinderview_two.visibility = View.INVISIBLE gridbinderview_blockelganger_one.visibility = View.INVISIBLE gridbinderview_blockelganger_two.visibility = View.INVISIBLE } }) return animMoves } fun genBoardsShrinkAnim(): Animator { var endGameScale = if (chapter == GameHelper.Chapter.THREE || chapter == GameHelper.Chapter.FOUR) 0.25f else 0.5f var gameScaleX = ObjectAnimator.ofFloat(grid_container, "scaleX", 1f, endGameScale) var gameScaleY = ObjectAnimator.ofFloat(grid_container, "scaleY", 1f, endGameScale) var scaleDownBoardsAnim = AnimatorSet() scaleDownBoardsAnim.playTogether(gameScaleX, gameScaleY) scaleDownBoardsAnim.interpolator = AccelerateInterpolator() scaleDownBoardsAnim.setDuration(450) return scaleDownBoardsAnim } fun genBoardsHideAnim(): Animator { var endScale = 0.2f var gridsZoomX = ObjectAnimator.ofFloat(grid_container, "scaleX", grid_container.scaleX, endScale) var gridsZoomY = ObjectAnimator.ofFloat(grid_container, "scaleY", grid_container.scaleY, endScale) var gridsAlpha = ObjectAnimator.ofFloat(grid_container, "alpha", grid_container.alpha, 0f) var animGridsOut = AnimatorSet() animGridsOut.playTogether(gridsZoomX, gridsZoomY, gridsAlpha) animGridsOut.interpolator = AccelerateInterpolator() animGridsOut.setDuration(450) return animGridsOut } fun genBoardsEnterAnim(chap: GameHelper.Chapter): Animator { var animReenter = AnimatorSet() var gangerReturn = when (chap) { GameHelper.Chapter.ONE -> { var anim = ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationY", height - gridbinderview_blockelganger_one.top.toFloat(), 0f) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_blockelganger_one.translationX = 0f } }) anim } GameHelper.Chapter.TWO -> { var anim = ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationX", width.toFloat(), 0f) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_blockelganger_one.translationY = 0f } }) anim } GameHelper.Chapter.THREE -> { var anim = ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationY", height.toFloat(), 0f) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_blockelganger_one.translationX = 0f } }) anim } GameHelper.Chapter.FOUR -> { var gangerOne = ObjectAnimator.ofFloat(gridbinderview_blockelganger_one, "translationX", width.toFloat(), 0f) var gangerTwo = ObjectAnimator.ofFloat(gridbinderview_blockelganger_two, "translationY", height.toFloat(), 0f) var anim = AnimatorSet() anim.playTogether(gangerOne, gangerTwo) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_blockelganger_one.translationY = 0f gridbinderview_blockelganger_two.translationX = 0f } }) anim } } var playablePieceReturn = when (chapter) { GameHelper.Chapter.ONE -> { var anim = ObjectAnimator.ofFloat(gridbinderview_one, "translationY", -gridbinderview_one.bottom.toFloat(), 0f) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_one.translationX = 0f } }) anim } GameHelper.Chapter.TWO -> { var topAnim = ObjectAnimator.ofFloat(gridbinderview_one, "translationY", -gridbinderview_one.bottom.toFloat(), 0f) var btmAnim = ObjectAnimator.ofFloat(gridbinderview_two, "translationY", height - gridbinderview_two.top.toFloat(), 0f) var anim = AnimatorSet() anim.playTogether(topAnim, btmAnim) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_one.translationX = 0f gridbinderview_two.translationX = 0f } }) anim } GameHelper.Chapter.THREE -> { var anim = ObjectAnimator.ofFloat(gridbinderview_one, "translationY", -height.toFloat(), 0f) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_one.translationX = 0f } }) anim } GameHelper.Chapter.FOUR -> { var topAnim = ObjectAnimator.ofFloat(gridbinderview_one, "translationY", -gridbinderview_one.bottom.toFloat(), 0f) var btmAnim = ObjectAnimator.ofFloat(gridbinderview_two, "translationY", height - gridbinderview_two.top.toFloat(), 0f) var anim = AnimatorSet() anim.playTogether(topAnim, btmAnim) anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { gridbinderview_one.translationX = 0f gridbinderview_two.translationX = 0f } }) anim } } animReenter.playTogether(playablePieceReturn, gangerReturn) animReenter.interpolator = DecelerateInterpolator() animReenter.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { grid_container.scaleX = 1f grid_container.scaleY = 1f grid_container.alpha = 1f prepareGridViews() } }) return animReenter } fun pauseAllTouchHintAnims() { for (anim in touchHintAnims.values) { anim.pause() } } fun resumePausedTouchHintAnims() { for (anim in touchHintAnims.values) { anim.resume() } } fun setTouchHintsShowing(showing: Boolean) { if (showing) { when (chapter) { GameHelper.Chapter.FOUR -> { setTouchHintShowing(touch_hint_top, true) setTouchHintShowing(touch_hint_btm, true) } GameHelper.Chapter.THREE -> { setTouchHintShowing(touch_hint_right, true) } GameHelper.Chapter.TWO -> { setTouchHintShowing(touch_hint_top, true) setTouchHintShowing(touch_hint_btm, true) } GameHelper.Chapter.ONE -> { setTouchHintShowing(touch_hint_top, true) } } } else { setTouchHintShowing(touch_hint_top, false) setTouchHintShowing(touch_hint_btm, false) setTouchHintShowing(touch_hint_right, false) } } private fun setTouchHintShowing(hintView: View, showing: Boolean, delay: Long = 0) { if (showing) { var wiggle = ObjectAnimator.ofFloat(hintView, "rotation", 0f, -5f, 0f, 5f, 0f) wiggle.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { hintView.visibility = View.VISIBLE } override fun onAnimationCancel(animation: Animator?) { hintView.visibility = View.INVISIBLE touchHintAnims.remove(hintView) } override fun onAnimationEnd(animation: Animator?) { if (touchHintAnims.containsKey(hintView)) { touchHintAnims.remove(hintView) setTouchHintShowing(hintView, true, 1000) } } }) wiggle.interpolator = OvershootInterpolator() wiggle.setDuration(650) wiggle.startDelay = delay touchHintAnims.put(hintView, wiggle) wiggle.start() } else { touchHintAnims.get(hintView)?.cancel() touchHintAnims.remove(hintView) hintView.visibility = View.INVISIBLE } } fun resetAnimationChanges() { var views = ArrayList<View>() views.add(grid_container) for (i in 0..grid_container.childCount - 1) { views.add(grid_container.getChildAt(i)) } for (v in views) { v.translationX = 0f v.translationY = 0f v.scaleX = 1f v.scaleY = 1f v.alpha = 1f } } fun prepareGridViews() { gridbinderview_animation_coordinator.visibility = View.INVISIBLE //var thirdHeight = usableHeight / 3f var fifthHeight = height / 5f var thirdWidth = width / 3f when (chapter) { GameHelper.Chapter.ONE -> { (gridbinderview_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = fifthHeight.toInt() it.width = ViewGroup.LayoutParams.MATCH_PARENT it.gravity = Gravity.TOP gridbinderview_one.layoutParams = it touch_hint_top.layoutParams = FrameLayout.LayoutParams(it) } (gridbinderview_blockelganger_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = fifthHeight.toInt() it.width = ViewGroup.LayoutParams.MATCH_PARENT it.gravity = Gravity.BOTTOM gridbinderview_blockelganger_one.layoutParams = it } gridbinderview_animation_coordinator.layoutParams?.let { it.height = fifthHeight.toInt() * 2 it.width = ViewGroup.LayoutParams.MATCH_PARENT gridbinderview_animation_coordinator.layoutParams = it } gridbinderview_one.visibility = View.VISIBLE gridbinderview_two.visibility = View.INVISIBLE gridbinderview_blockelganger_one.visibility = View.VISIBLE gridbinderview_blockelganger_two.visibility = View.INVISIBLE } GameHelper.Chapter.TWO -> { (gridbinderview_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = fifthHeight.toInt() it.width = ViewGroup.LayoutParams.MATCH_PARENT it.gravity = Gravity.TOP gridbinderview_one.layoutParams = it touch_hint_top.layoutParams = FrameLayout.LayoutParams(it) } (gridbinderview_two.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = fifthHeight.toInt() it.width = ViewGroup.LayoutParams.MATCH_PARENT it.gravity = Gravity.BOTTOM gridbinderview_two.layoutParams = it touch_hint_btm.layoutParams = FrameLayout.LayoutParams(it) } var gangerHeight = (gridbinderview_one.getSubGridPosition(Grid(1, 1), 0, 0).height() * gangerOneGrid.height).toInt() (gridbinderview_blockelganger_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = gangerHeight it.width = ViewGroup.LayoutParams.MATCH_PARENT it.gravity = Gravity.CENTER_VERTICAL gridbinderview_blockelganger_one.layoutParams = it } gridbinderview_animation_coordinator.layoutParams?.let { it.height = fifthHeight.toInt() * 2 + gangerHeight it.width = ViewGroup.LayoutParams.MATCH_PARENT gridbinderview_animation_coordinator.layoutParams = it } gridbinderview_one.visibility = View.VISIBLE gridbinderview_two.visibility = View.VISIBLE gridbinderview_blockelganger_one.visibility = View.VISIBLE gridbinderview_blockelganger_two.visibility = View.INVISIBLE } GameHelper.Chapter.THREE -> { (gridbinderview_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = ViewGroup.LayoutParams.MATCH_PARENT it.width = thirdWidth.toInt() it.gravity = Gravity.RIGHT gridbinderview_one.layoutParams = it touch_hint_right.layoutParams = FrameLayout.LayoutParams(it) } (gridbinderview_blockelganger_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = ViewGroup.LayoutParams.MATCH_PARENT it.width = thirdWidth.toInt() it.gravity = Gravity.LEFT gridbinderview_blockelganger_one.layoutParams = it } gridbinderview_animation_coordinator.layoutParams?.let { it.height = ViewGroup.LayoutParams.MATCH_PARENT it.width = thirdWidth.toInt() * 2 gridbinderview_animation_coordinator.layoutParams = it } gridbinderview_one.visibility = View.VISIBLE gridbinderview_two.visibility = View.INVISIBLE gridbinderview_blockelganger_one.visibility = View.VISIBLE gridbinderview_blockelganger_two.visibility = View.INVISIBLE } GameHelper.Chapter.FOUR -> { var totalBlocksW = gridOne.width + 2 + gangerTwoGrid.width var totalBlocksH = gridOne.height + 2 + gangerOneGrid.height + 2 + gridTwo.height var blockW = width / totalBlocksW.toFloat() var blockH = height / totalBlocksH.toFloat() (gridbinderview_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = (gridOne.height * blockH).toInt() it.width = (gridOne.width * blockW).toInt() it.gravity = Gravity.TOP or Gravity.RIGHT gridbinderview_one.layoutParams = it touch_hint_top.layoutParams = FrameLayout.LayoutParams(it) } (gridbinderview_two.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = (gridTwo.height * blockH).toInt() it.width = (gridTwo.width * blockW).toInt() it.gravity = Gravity.BOTTOM or Gravity.RIGHT gridbinderview_two.layoutParams = it touch_hint_btm.layoutParams = FrameLayout.LayoutParams(it) } (gridbinderview_blockelganger_one.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = (gangerOneGrid.height * blockH).toInt() it.width = (gangerOneGrid.width * blockW).toInt() it.gravity = Gravity.CENTER_VERTICAL or Gravity.RIGHT gridbinderview_blockelganger_one.layoutParams = it } (gridbinderview_blockelganger_two.layoutParams as? FrameLayout.LayoutParams)?.let { it.height = (gangerTwoGrid.height * blockH).toInt() it.width = (gangerTwoGrid.width * blockW).toInt() it.gravity = Gravity.CENTER_VERTICAL or Gravity.LEFT gridbinderview_blockelganger_two.layoutParams = it } //We set the layout to match the total of all of our gridviews, so it can fit all of them, and the grids should be the same measured size gridbinderview_animation_coordinator.layoutParams?.let { it.height = (gridOne.height + gridTwo.height + gangerOneGrid.height) * blockH.toInt() it.width = (gangerOneGrid.width + gangerTwoGrid.width) * blockW.toInt() gridbinderview_animation_coordinator.layoutParams = it } gridbinderview_one.visibility = View.VISIBLE gridbinderview_two.visibility = View.VISIBLE gridbinderview_blockelganger_one.visibility = View.VISIBLE gridbinderview_blockelganger_two.visibility = View.VISIBLE } } } fun combineGrids(): Grid { //We copy our grids and mask them so the cells point to the grids they represent var gridTop = GridHelper.maskGrid(gridOne, gridOne) var gridBtm = GridHelper.maskGrid(gridTwo, gridTwo) var gangCenter = GridHelper.maskGrid(gangerOneGrid, gangerOneGrid) var gangLeft = GridHelper.maskGrid(gangerTwoGrid, gangerTwoGrid) //Combine our grids var combined = when (chapter) { GameHelper.Chapter.ONE -> GameGridHelper.combineShapesVert(gridTop, gangCenter) GameHelper.Chapter.TWO -> { GameGridHelper.combineShapesVert(GameGridHelper.combineShapesVert(gridTop, gangCenter), gridBtm) } GameHelper.Chapter.THREE -> { GameGridHelper.combineShapesHoriz(gangCenter, gridTop) } GameHelper.Chapter.FOUR -> { //The left ganger's height is the center ganger's height + 2 var gangerVertPadding = GridHelper.numEmptyRowsTopBtm(gangCenter) var gangerAndTop = GameGridHelper.combineShapesVert(gridTop, gangCenter) var gangerAndTopAndBtm = GameGridHelper.combineShapesVert(gangerAndTop, gridBtm) //Calculate the offset of the left ganger relative to the combined shape var leftGangerTopOffset = gangerAndTop.height - (gangCenter.height - gangerVertPadding.first - gangerVertPadding.second) - 1 var gangerAndTopAndBtmAdjusted = Grid(gangerAndTopAndBtm.width, Math.max(gangerAndTopAndBtm.height, gangLeft.height) + Math.abs(leftGangerTopOffset)) var leftGangerAdjusted = Grid(gangLeft.width, gangerAndTopAndBtmAdjusted.height) if (leftGangerTopOffset > 0) { GridHelper.addGrid(gangerAndTopAndBtmAdjusted, gangerAndTopAndBtm, 0, 0) GridHelper.addGrid(leftGangerAdjusted, gangLeft, 0, leftGangerTopOffset) } else if (leftGangerTopOffset < 0) { GridHelper.addGrid(gangerAndTopAndBtmAdjusted, gangerAndTopAndBtm, 0, Math.abs(leftGangerTopOffset)) GridHelper.addGrid(leftGangerAdjusted, gangLeft, 0, 0) } else { GridHelper.addGrid(gangerAndTopAndBtmAdjusted, gangerAndTopAndBtm, 0, 0) GridHelper.addGrid(leftGangerAdjusted, gangLeft, 0, 0) } GameGridHelper.combineShapesHoriz(leftGangerAdjusted, gangerAndTopAndBtmAdjusted) } } combined = GridHelper.trim(combined) return combined } }
apache-2.0
a2c6d4537f5d22d574cf6111d90d29d4
44.483916
165
0.613469
5.305057
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/FileOptions.kt
1
6975
/* 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.options import com.eclipsesource.json.Json import com.eclipsesource.json.JsonArray import com.eclipsesource.json.JsonObject import com.eclipsesource.json.PrettyPrint import groovy.lang.Binding import uk.co.nickthecoder.paratask.Tool import uk.co.nickthecoder.paratask.gui.ScriptVariables import uk.co.nickthecoder.paratask.misc.FileListener import uk.co.nickthecoder.paratask.misc.FileTest import uk.co.nickthecoder.paratask.misc.FileWatcher import java.io.* import java.nio.file.Path class FileOptions(override val file: File) : FileListener, FileTest { val name = file.nameWithoutExtension val includes = mutableListOf<String>() var comments: String = "" var rowFilterScript: GroovyScript? = null var rowClassName: String = "" set(v) { field = v scriptVariables.add("row", v) } var toolClassName: String = Tool::class.java.name set(v) { field = v scriptVariables.add("tool", v) } private val optionsMap = mutableMapOf<String, Option>() private val primaryOptionsMap = mutableMapOf<String, Option>() private var saving: Boolean = false val scriptVariables = ScriptVariables() init { load() FileWatcher.instance.register(file, this) } fun listOptions(): Collection<Option> { return primaryOptionsMap.values } fun listIncludes(): Collection<String> { return includes } fun find(code: String): Option? { return optionsMap[code] } fun acceptRow(row: Any?): Boolean { if (rowFilterScript == null) { return true } if (row == null) { return false } val binding = Binding() binding.setVariable("row", row) return rowFilterScript?.run(binding) == true } fun renameOption(option: Option, newCode: String, newAliases: List<String>) { removeOption(option) option.code = newCode option.aliases = newAliases.toMutableList() addOption(option) } fun addOption(option: Option) { primaryOptionsMap.put(option.code, option) optionsMap.put(option.code, option) option.aliases.forEach { optionsMap.put(it, option) } } fun removeOption(option: Option) { primaryOptionsMap.values.remove(option) while (optionsMap.values.remove(option)) { } } fun update(option: Option) { removeOption(option) addOption(option) } override fun fileChanged(path: Path) { if (!saving) { load() } } /* Example JSON file : { "comments" : "Applies only to files (not directories)", "rowClassName" : "uk.co.nickthecoder.paratask.Foo", "toolClassName" : "uk.co.nickthecoder.paratask.Bar", "rowFilterScript" : "row.isFile()", "includes" : [ "foo", "bar" ], "options" : [ { "type" : "groovy", "script" : "println( 1 + 1 ) // Any groovy code!", "code" : "2", "label" : "Two", "isRow" : false, "isMultiple" : false, "newTab" : false, "prompt" : false, "refreshResults" : true }, { "type" : "task", "task" : "uk.co.nickthecoder.paratask.MyTask", "code" : "5", "label" : "Five", "script" : "", "isRow" : false, "isMultiple" : false, "newTab" : false, "prompt" : false, "refreshResults" : true, "parameters" : [ "parameter" : { "name" : "foo", value="Hello" }, "parameter" : { "name" : "bar", expression="1+1" } ] } ] } */ // https://github.com/ralfstx/minimal-json fun load() { includes.clear() optionsMap.clear() primaryOptionsMap.clear() val jroot: JsonObject try { jroot = Json.parse(InputStreamReader(file.inputStream())).asObject() } catch (e: Exception) { // We don't care if we can't read the file - it may not exist, and that's fine! //println("Failed to load options file ${resource}") return } comments = jroot.getString("comments", "") rowClassName = jroot.getString("rowClassName", "") toolClassName = jroot.getString("toolClassName", Tool::class.java.name) val rowFilterScriptSource = jroot.getString("rowFilterScript", "") rowFilterScript = if (rowFilterScriptSource == "") null else GroovyScript(rowFilterScriptSource) val jincludes = jroot.get("includes") jincludes?.let { jincludes.asArray().mapTo(includes) { it.asString() } } val joptions = jroot.get("options") joptions?.let { joptions.asArray().forEach { joption1 -> val joption = joption1.asObject() val option = Option.fromJson(joption) addOption(option) } } } fun save() { val jroot = JsonObject() if (comments.isNotBlank()) { jroot.add("comments", comments) } if (rowClassName.isNotBlank()) { jroot.add("rowClassName", rowClassName) } if (toolClassName.isNotBlank()) { jroot.add("toolClassName", toolClassName) } rowFilterScript?.let { jroot.add("rowFilterScript", it.source) } val jincludes = JsonArray() includes.forEach { include -> jincludes.add(include) } jroot.add("includes", jincludes) val joptions = JsonArray() listOptions().forEach { option -> joptions.add(option.toJson()) } jroot.add("options", joptions) saving = true try { BufferedWriter(OutputStreamWriter(FileOutputStream(file))).use { jroot.writeTo(it, PrettyPrint.indentWithSpaces(4)) } } finally { saving = false } } }
gpl-3.0
14928404fd798c085a61b4d67e16c004
28.1841
104
0.573333
4.541016
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/content/handler/MultiPartContentHandler.kt
1
11979
package com.fireflysource.net.http.server.impl.content.handler import com.fireflysource.common.concurrent.CompletableFutures import com.fireflysource.common.coroutine.clear import com.fireflysource.common.string.QuotedStringTokenizer import com.fireflysource.common.string.QuotedStringTokenizer.unquote import com.fireflysource.common.string.QuotedStringTokenizer.unquoteOnly import com.fireflysource.common.sys.Result import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.http.common.codec.MultiPartParser import com.fireflysource.net.http.common.exception.BadMessageException import com.fireflysource.net.http.common.model.HttpHeader import com.fireflysource.net.http.common.model.HttpStatus import com.fireflysource.net.http.server.HttpServerContentHandler import com.fireflysource.net.http.server.MultiPart import com.fireflysource.net.http.server.RoutingContext import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.future.asCompletableFuture import java.nio.ByteBuffer import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.concurrent.CompletableFuture class MultiPartContentHandler( private val maxUploadFileSize: Long = 200 * 1024 * 1024, private val maxRequestBodySize: Long = 200 * 1024 * 1024, private val uploadFileSizeThreshold: Int = 4 * 1024 * 1024, private val scope: CoroutineScope = CoroutineScope(CoroutineName("Firefly-file-content-provider")), private val path: Path = tempPath ) : HttpServerContentHandler { companion object { private val log = SystemLogger.create(MultiPartContentHandler::class.java) private val tempPath = Paths.get(System.getProperty("java.io.tmpdir")) } init { require(maxRequestBodySize >= maxUploadFileSize) { "The max request size must be greater than the max file size." } require(maxUploadFileSize >= uploadFileSizeThreshold) { "The max file size must be greater than the file size threshold." } } private val multiParts: LinkedList<AsyncMultiPart> = LinkedList() private val multiPartChannel: Channel<MultiPartHandlerMessage> = Channel(Channel.UNLIMITED) private var firstMessage = true private var requestSize: Long = 0 private var parser: MultiPartParser? = null private var byteBuffers: LinkedList<ByteBuffer> = LinkedList() private val multiPartHandler = MultiPartHandler() private var job: Job? = null private var part: AsyncMultiPart? = null private var parsingException: Throwable? = null private inner class MultiPartHandler : MultiPartParser.Handler { override fun startPart() { multiPartChannel.trySend(StartPart) } override fun parsedField(name: String, value: String) { multiPartChannel.trySend(PartField(name, value)) } override fun headerComplete(): Boolean { multiPartChannel.trySend(PartHeaderComplete) return false } override fun content(item: ByteBuffer, last: Boolean): Boolean { multiPartChannel.trySend(PartContent(item, last)) return false } override fun messageComplete(): Boolean { multiPartChannel.trySend(PartMessageComplete) return true } override fun earlyEOF() { multiPartChannel.trySend(PartEarlyEOF) } } private fun parsingJob() = scope.launch { parseLoop@ while (true) { try { when (val message = multiPartChannel.receive()) { is ParseMultiPartBoundary -> parseBoundaryAndCreateMultiPartParser(message) is ParseMultiPartContent -> parseContent(message) is EndMultiPartHandler -> endMultiPartHandler() is StartPart -> createMultiPart() is PartField -> addMultiPartField(message) is PartHeaderComplete -> handleHeaderComplete() is PartContent -> acceptContent(message) is PartMessageComplete -> { handleMessageComplete() break@parseLoop } is PartEarlyEOF -> handleEarlyEOF() } } catch (e: Throwable) { [email protected] = e break@parseLoop } } multiPartChannel.clear() val result = runCatching { closeAllFileHandlers() } log.debug { "close file handlers. result: ${result.isSuccess}" } } private fun createMultiPart() { val part = AsyncMultiPart( maxUploadFileSize, uploadFileSizeThreshold, Paths.get(path.toString(), UUID.randomUUID().toString()) ) multiParts.add(part) this.part = part log.debug { "Create multi-part. $part" } } private fun addMultiPartField(message: PartField) { part?.httpFields?.add(message.name, message.value) } private fun handleHeaderComplete() { val contentDisposition = part?.httpFields?.get("Content-Disposition") requireNotNull(contentDisposition) { "Missing Content-Disposition header" } val token = QuotedStringTokenizer(contentDisposition, ";", false, true) var formData = false var name: String? = null var fileName: String? = null while (token.hasMoreTokens()) { val tokenValue = token.nextToken().trim() val lowerCaseValue = tokenValue.lowercase(Locale.getDefault()) when { lowerCaseValue.startsWith("form-data") -> formData = true lowerCaseValue.startsWith("name=") -> name = value(tokenValue) lowerCaseValue.startsWith("filename=") -> fileName = fileNameValue(tokenValue) } } require(formData) { "Part not form-data" } requireNotNull(name) { "No name in part" } part?.name = name part?.fileName = fileName ?: "" log.debug { "Multi-part header complete. name: $name, fileName: $fileName, fields: ${part?.httpFields?.size()}" } } private fun acceptContent(message: PartContent) { log.debug { "Accept multi-part content. size: ${message.byteBuffer.remaining()}, last: ${message.last}" } part?.accept(message.byteBuffer, message.last) } private suspend fun handleMessageComplete() { val result = runCatching { closeAllFileHandlers() } log.debug { "Multi-part complete. part: $part. result: ${result.isSuccess}" } } private suspend fun handleEarlyEOF() { val result = runCatching { closeAllFileHandlers() } log.debug { "Early EOF. result: ${result.isSuccess}" } throw BadMessageException(HttpStatus.BAD_REQUEST_400) } private suspend fun closeAllFileHandlers() { var ex: Exception? = null multiParts.forEach { try { it.closeFileHandler() } catch (e: Exception) { ex = e } } val e = ex if (e != null) { throw e } } private fun parseBoundary(contentType: String?): String { if (contentType == null) return "" if (!contentType.startsWith("multipart/form-data")) return "" var contentTypeBoundary = "" val start: Int = contentType.indexOf("boundary=") if (start >= 0) { var end: Int = contentType.indexOf(";", start) end = if (end < 0) contentType.length else end contentTypeBoundary = unquote(value(contentType.substring(start, end)).trim()) } return contentTypeBoundary } private fun parseBoundaryAndCreateMultiPartParser(message: ParseMultiPartBoundary) { val boundary = parseBoundary(message.contentType) log.debug { "Parsed multi-part boundary: $boundary" } if (boundary.isNotBlank()) { parser = MultiPartParser(multiPartHandler, boundary) } else { throw BadMessageException(HttpStatus.BAD_REQUEST_400) } } private fun parseContent(message: ParseMultiPartContent) { byteBuffers.offer(message.byteBuffer) log.debug { "Parse multi part content. state: ${parser?.state}, size: ${message.byteBuffer.remaining()}" } if (byteBuffers.size > 1) { parser?.parse(byteBuffers.poll(), false) } } private fun endMultiPartHandler() { val buffer = byteBuffers.poll() requireNotNull(buffer) log.debug { "End multi-part handler. buffers: ${byteBuffers.size}, size: ${buffer.remaining()}" } parser?.parse(buffer, true) } private fun value(headerLine: String): String { val idx = headerLine.indexOf('=') val value = headerLine.substring(idx + 1).trim() return unquoteOnly(value) } private fun fileNameValue(headerLine: String): String { val idx = headerLine.indexOf('=') var value = headerLine.substring(idx + 1).trim() return if (value.matches(".??[a-z,A-Z]:\\\\[^\\\\].*".toRegex())) { // incorrectly escaped IE filenames that have the whole path // we just strip any leading & trailing quotes and leave it as is val first = value[0] if (first == '"' || first == '\'') value = value.substring(1) val last = value[value.length - 1] if (last == '"' || last == '\'') value = value.substring(0, value.length - 1) value } else unquoteOnly(value, true) // unquote the string, but allow any backslashes that don't // form a valid escape sequence to remain as many browsers // even on *nix systems will not escape a filename containing // backslashes } override fun accept(byteBuffer: ByteBuffer, ctx: RoutingContext) { requestSize += byteBuffer.remaining() if (requestSize > maxRequestBodySize) { throw BadMessageException(HttpStatus.PAYLOAD_TOO_LARGE_413) } if (firstMessage) { job = parsingJob() multiPartChannel.trySend(ParseMultiPartBoundary(ctx.httpFields[HttpHeader.CONTENT_TYPE])) firstMessage = false } multiPartChannel.trySend(ParseMultiPartContent(byteBuffer)) } override fun closeAsync(): CompletableFuture<Void> { val parsingJob = job return if (parsingJob != null) { if (parsingJob.isCompleted) complete() else scope.launch { closeAwait() }.asCompletableFuture().thenCompose { complete() } .thenAccept { scope.cancel() } } else Result.DONE } private fun complete(): CompletableFuture<Void> { val e = parsingException return if (e != null) CompletableFutures.failedFuture(e) else Result.DONE } private suspend fun closeAwait() { multiPartChannel.trySend(EndMultiPartHandler) job?.join() } override fun close() { closeAsync() } fun getPart(name: String): MultiPart? { return multiParts.find { it.name == name } } fun getParts(): List<MultiPart> = multiParts } sealed interface MultiPartHandlerMessage @JvmInline value class ParseMultiPartBoundary(val contentType: String?) : MultiPartHandlerMessage @JvmInline value class ParseMultiPartContent(val byteBuffer: ByteBuffer) : MultiPartHandlerMessage object StartPart : MultiPartHandlerMessage data class PartField(val name: String, val value: String) : MultiPartHandlerMessage object PartHeaderComplete : MultiPartHandlerMessage class PartContent(val byteBuffer: ByteBuffer, val last: Boolean) : MultiPartHandlerMessage object PartMessageComplete : MultiPartHandlerMessage object PartEarlyEOF : MultiPartHandlerMessage object EndMultiPartHandler : MultiPartHandlerMessage
apache-2.0
d13f208a8deffe0498bd58f873f206ab
37.031746
131
0.649219
4.921528
false
false
false
false
usbpc102/usbBot
src/main/kotlin/usbbot/modules/MiscCommands.kt
1
3979
package usbbot.modules import at.mukprojects.giphy4j.Giphy import at.mukprojects.giphy4j.exception.GiphyException import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.launch import usbbot.commands.DiscordCommands import usbbot.commands.core.Command import usbbot.main.UsbBot import org.slf4j.LoggerFactory import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.handle.obj.Permissions import sx.blah.discord.util.EmbedBuilder import sx.blah.discord.util.RequestBuffer import usbbot.util.MessageParsing import usbbot.util.MessageSending import usbbot.util.commands.AnnotationExtractor import usbbot.util.commands.DiscordCommand import util.* import java.awt.Color import java.util.concurrent.TimeUnit class MiscCommands : DiscordCommands { val giphy = Giphy(UsbBot.getProperty("giphy")) val logger = LoggerFactory.getLogger(MiscCommands::class.java) override fun getDiscordCommands(): MutableCollection<Command> = AnnotationExtractor.getCommandList(this) @DiscordCommand("getavatarlink") fun getavatarlink(msg: IMessage, vararg args: String) { if (args.size < 2) { msg.channel.sendSuccess(msg.author.avatarURL) } else if (msg.mentions.size == 1) { msg.channel.sendSuccess(msg.mentions.first().avatarURL) } else { msg.channel.sendError("Invalid syntax") } } @DiscordCommand("cat") fun cat(msg: IMessage, args: Array<String>) { val messageFuture = msg.channel.sendProcessing("Loading...") val embed = EmbedBuilder() .withImage(giphy.searchRandom("cute cat").data.imageOriginalUrl) .withColor(Color.GREEN) //.withTitle("A cute cat:") //.withAuthorName(msg.client.ourUser.getDisplayName(msg.guild)) //.withAuthorIcon(msg.client.ourUser.avatarURL) .withFooterText("Powered By GIPHY") val message = messageFuture.get() RequestBuffer.request { message.edit(embed.build()) } } @DiscordCommand("gif") fun giphy(msg: IMessage, args: Array<String>) { if (args.size < 2) { msg.channel.sendError("Please specify a search term...") return } val messageFuture = msg.channel.sendProcessing("Loading...") val builder = StringBuilder() args.drop(1).forEach { builder.append(it).append(" ") } try { val embed = EmbedBuilder() .withImage(giphy.searchRandom(builder.toString()).data.imageOriginalUrl) .withColor(Color.GREEN) //.withTitle("A cute cat:") //.withAuthorName(msg.client.ourUser.getDisplayName(msg.guild)) //.withAuthorIcon(msg.client.ourUser.avatarURL) .withFooterText("Powered By GIPHY") messageFuture.updateSuccess(embed.build()) } catch (ex: GiphyException) { messageFuture.updateError("Could not find a gif for `$builder`") } } @DiscordCommand("hug") fun hug(msg: IMessage, args: Array<String>) { if (msg.channel.checkOurPermissions(Permissions.MANAGE_MESSAGES)) { msg.bufferedDelete() } val userID = if (args.size > 1) { var tmp = MessageParsing.getUserID(args[1]) if (tmp == -1L) { msg.author.longID } else { tmp } } else { msg.author.longID } msg.channel.sendSuccess("*hugs <@$userID>*") } @DiscordCommand("spam") fun spam(msg: IMessage, args: Array<String>) = launch { var msgCount = args[1].toInt() while (msgCount-- > 0) { delay(1500) msg.channel.sendSuccess("""\W"i"ll this work? |yes! """.trimMargin()) MessageSending.sendMessage(msg.channel, msgCount.toString()).get() } } }
mit
4def323b2afdcec432eb8f8d4af08256
36.54717
108
0.625031
4.334423
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/view/CardInputWidget.kt
1
43444
package com.stripe.android.view import android.content.Context import android.os.Bundle import android.os.Parcelable import android.text.Editable import android.text.Layout import android.text.TextPaint import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.animation.Animation import android.view.animation.AnimationSet import android.view.animation.Transformation import android.view.inputmethod.EditorInfo import android.widget.FrameLayout import android.widget.LinearLayout import androidx.annotation.ColorInt import androidx.annotation.IdRes import androidx.annotation.IntRange import androidx.annotation.VisibleForTesting import androidx.core.content.withStyledAttributes import androidx.core.os.bundleOf import androidx.core.view.AccessibilityDelegateCompat import androidx.core.view.ViewCompat import androidx.core.view.accessibility.AccessibilityNodeInfoCompat import androidx.core.view.updateLayoutParams import androidx.core.widget.doAfterTextChanged import com.stripe.android.PaymentConfiguration import com.stripe.android.R import com.stripe.android.cards.CardNumber import com.stripe.android.cards.Cvc import com.stripe.android.databinding.CardInputWidgetBinding import com.stripe.android.model.Address import com.stripe.android.model.CardBrand import com.stripe.android.model.CardParams import com.stripe.android.model.ExpirationDate import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import kotlin.properties.Delegates /** * A single-line card input widget. * * To enable 19-digit card support, [PaymentConfiguration.init] must be called before * [CardInputWidget] is instantiated. * * The individual `EditText` views of this widget can be styled by defining a style * `Stripe.CardInputWidget.EditText` that extends `Stripe.Base.CardInputWidget.EditText`. * * The card number, cvc, and expiry date will always be left to right regardless of locale. Postal * code layout direction will be set according to the locale. */ class CardInputWidget @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr), CardWidget { private var customCvcLabel: String? = null private val viewBinding = CardInputWidgetBinding.inflate( LayoutInflater.from(context), this ) private val containerLayout = viewBinding.container @JvmSynthetic internal val cardBrandView = viewBinding.cardBrandView private val cardNumberTextInputLayout = viewBinding.cardNumberTextInputLayout private val expiryDateTextInputLayout = viewBinding.expiryDateTextInputLayout private val cvcNumberTextInputLayout = viewBinding.cvcTextInputLayout internal val postalCodeTextInputLayout = viewBinding.postalCodeTextInputLayout @JvmSynthetic internal val cardNumberEditText = viewBinding.cardNumberEditText @JvmSynthetic internal val expiryDateEditText = viewBinding.expiryDateEditText @JvmSynthetic internal val cvcEditText = viewBinding.cvcEditText @JvmSynthetic internal val postalCodeEditText = viewBinding.postalCodeEditText private var cardInputListener: CardInputListener? = null private var cardValidCallback: CardValidCallback? = null private val cardValidTextWatcher = object : StripeTextWatcher() { override fun afterTextChanged(s: Editable?) { super.afterTextChanged(s) cardValidCallback?.onInputChanged(invalidFields.isEmpty(), invalidFields) } } private val invalidFields: Set<CardValidCallback.Fields> get() { return listOfNotNull( CardValidCallback.Fields.Number.takeIf { cardNumberEditText.validatedCardNumber == null }, CardValidCallback.Fields.Expiry.takeIf { expiryDateEditText.validatedDate == null }, CardValidCallback.Fields.Cvc.takeIf { this.cvc == null }, CardValidCallback.Fields.Postal.takeIf { isPostalRequired() && postalCodeEditText.postalCode.isNullOrBlank() } ).toSet() } @VisibleForTesting internal var shouldShowErrorIcon = false private set(value) { cardBrandView.shouldShowErrorIcon = value field = value } /** * If `true`, the full card number is being shown. This is the initial view. * If `false`, the peek card number is being shown. */ @JvmSynthetic internal var isShowingFullCard = true private var isViewInitialized: Boolean = false @JvmSynthetic internal var layoutWidthCalculator: LayoutWidthCalculator = DefaultLayoutWidthCalculator() internal val placement = CardInputWidgetPlacement() private val postalCodeValue: String? get() { return if (postalCodeEnabled) { postalCodeEditText.postalCode } else { null } } private val cvc: Cvc.Validated? get() { return cvcEditText.cvc } /** * A [CardBrand] matching the current card number inputted by the user. */ val brand: CardBrand get() { return cardNumberEditText.cardBrand } @VisibleForTesting @JvmSynthetic internal val requiredFields: MutableSet<StripeEditText> private val allFields: Set<StripeEditText> /** * The [StripeEditText] fields that are currently enabled and active in the UI. */ @VisibleForTesting internal val currentFields: List<StripeEditText> @JvmSynthetic get() { return requiredFields .plus(postalCodeEditText.takeIf { postalCodeEnabled }) .filterNotNull() } /** * A [PaymentMethodCreateParams.Card] representing the card details if all fields are valid; * otherwise `null`. If a field is invalid focus will shift to the invalid field. */ override val paymentMethodCard: PaymentMethodCreateParams.Card? get() { return cardParams?.let { PaymentMethodCreateParams.Card( number = it.number, cvc = it.cvc, expiryMonth = it.expMonth, expiryYear = it.expYear, attribution = it.attribution ) } } private val billingDetails: PaymentMethod.BillingDetails? get() { return postalCodeValue?.let { PaymentMethod.BillingDetails( address = Address( postalCode = it ) ) } } /** * A [PaymentMethodCreateParams] representing the card details and postal code if all fields * are valid; otherwise `null`. If a field is invalid focus will shift to the invalid field */ override val paymentMethodCreateParams: PaymentMethodCreateParams? get() { return paymentMethodCard?.let { card -> PaymentMethodCreateParams.create(card, billingDetails) } } /** * A [CardParams] representing the card details and postal code if all fields are valid; * otherwise `null`. If a field is invalid focus will shift to the invalid field. */ override val cardParams: CardParams? get() { val cardNumber = cardNumberEditText.validatedCardNumber val expirationDate = expiryDateEditText.validatedDate val cvc = this.cvc cardNumberEditText.shouldShowError = cardNumber == null expiryDateEditText.shouldShowError = expirationDate == null cvcEditText.shouldShowError = cvc == null postalCodeEditText.shouldShowError = (postalCodeRequired || usZipCodeRequired) && postalCodeEditText.postalCode.isNullOrBlank() // Announce error messages for accessibility currentFields .filter { it.shouldShowError } .forEach { editText -> editText.errorMessage?.let { errorMessage -> editText.announceForAccessibility(errorMessage) } } when { cardNumber == null -> { cardNumberEditText.requestFocus() } expirationDate == null -> { expiryDateEditText.requestFocus() } cvc == null -> { cvcEditText.requestFocus() } postalCodeEditText.shouldShowError -> { postalCodeEditText.requestFocus() } else -> { shouldShowErrorIcon = false return CardParams( brand = brand, loggingTokens = setOf(LOGGING_TOKEN), number = cardNumber.value, expMonth = expirationDate.month, expYear = expirationDate.year, cvc = cvc.value, address = Address.Builder() .setPostalCode(postalCodeValue.takeUnless { it.isNullOrBlank() }) .build() ) } } shouldShowErrorIcon = true return null } private val frameWidth: Int get() = frameWidthSupplier() @JvmSynthetic internal var frameWidthSupplier: () -> Int /** * The postal code field is enabled by default. Disabling the postal code field may impact * auth success rates, so it is discouraged to disable it unless you are collecting the postal * code outside of this form. If the postal code is disabled it will not be shown in the view. */ var postalCodeEnabled: Boolean by Delegates.observable( CardWidget.DEFAULT_POSTAL_CODE_ENABLED ) { _, _, isEnabled -> if (isEnabled) { postalCodeEditText.isEnabled = true postalCodeTextInputLayout.visibility = View.VISIBLE cvcEditText.imeOptions = EditorInfo.IME_ACTION_NEXT // First remove if it's already added, to make sure it's not added multiple times. postalCodeEditText.removeTextChangedListener(cardValidTextWatcher) postalCodeEditText.addTextChangedListener(cardValidTextWatcher) } else { postalCodeEditText.isEnabled = false postalCodeTextInputLayout.visibility = View.GONE cvcEditText.imeOptions = EditorInfo.IME_ACTION_DONE postalCodeEditText.removeTextChangedListener(cardValidTextWatcher) } updatePostalRequired() } /** * If [postalCodeEnabled] is true and [postalCodeRequired] is true, then postal code is a * required field. * * If [postalCodeEnabled] is false, this value is ignored. * * Note that some countries do not have postal codes, so requiring postal code will prevent * those users from submitting this form successfully. */ var postalCodeRequired: Boolean by Delegates.observable( CardWidget.DEFAULT_POSTAL_CODE_REQUIRED ) { _, _, _ -> updatePostalRequired() } /** * If [postalCodeEnabled] is true and [usZipCodeRequired] is true, then postal code is a * required field and must be a 5-digit US zip code. * * If [postalCodeEnabled] is false, this value is ignored. */ var usZipCodeRequired: Boolean by Delegates.observable( CardWidget.DEFAULT_US_ZIP_CODE_REQUIRED ) { _, _, zipCodeRequired -> if (zipCodeRequired) { postalCodeEditText.config = PostalCodeEditText.Config.US } else { postalCodeEditText.config = PostalCodeEditText.Config.Global } updatePostalRequired() } private fun updatePostalRequired() { if (isPostalRequired()) { requiredFields.add(postalCodeEditText) } else { requiredFields.remove(postalCodeEditText) } } private fun isPostalRequired() = (postalCodeRequired || usZipCodeRequired) && postalCodeEnabled private val frameStart: Int get() { val isLtr = context.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR return if (isLtr) { containerLayout.left } else { containerLayout.right } } init { // This ensures that onRestoreInstanceState is called // during rotations. if (id == View.NO_ID) { id = DEFAULT_READER_ID } orientation = HORIZONTAL minimumWidth = resources.getDimensionPixelSize(R.dimen.stripe_card_widget_min_width) frameWidthSupplier = { containerLayout.width } requiredFields = mutableSetOf( cardNumberEditText, cvcEditText, expiryDateEditText ) allFields = requiredFields.plus(postalCodeEditText) initView(attrs) } override fun onFinishInflate() { super.onFinishInflate() postalCodeEditText.config = PostalCodeEditText.Config.Global } override fun setCardValidCallback(callback: CardValidCallback?) { this.cardValidCallback = callback requiredFields.forEach { it.removeTextChangedListener(cardValidTextWatcher) } // only add the TextWatcher if it will be used if (callback != null) { requiredFields.forEach { it.addTextChangedListener(cardValidTextWatcher) } } // call immediately after setting cardValidCallback?.onInputChanged(invalidFields.isEmpty(), invalidFields) } /** * Set a [CardInputListener] to be notified of card input events. * * @param listener the listener */ override fun setCardInputListener(listener: CardInputListener?) { cardInputListener = listener } /** * Set the card number. Method does not change text field focus. * * @param cardNumber card number to be set */ override fun setCardNumber(cardNumber: String?) { cardNumberEditText.setText(cardNumber) this.isShowingFullCard = !cardNumberEditText.isCardNumberValid } override fun setCardHint(cardHint: String) { cardNumberEditText.hint = cardHint } /** * Set the expiration date. Method invokes completion listener and changes focus * to the CVC field if a valid date is entered. * * Note that while a four-digit and two-digit year will both work, information * beyond the tens digit of a year will be truncated. Logic elsewhere in the SDK * makes assumptions about what century is implied by various two-digit years, and * will override any information provided here. * * @param month a month of the year, represented as a number between 1 and 12 * @param year a year number, either in two-digit form or four-digit form */ override fun setExpiryDate( @IntRange(from = 1, to = 12) month: Int, @IntRange(from = 0, to = 9999) year: Int ) { expiryDateEditText.setText( ExpirationDate.Unvalidated(month, year).getDisplayString() ) } /** * Set the CVC value for the card. Note that the maximum length is assumed to * be 3, unless the brand of the card has already been set (by setting the card number). * * @param cvcCode the CVC value to be set */ override fun setCvcCode(cvcCode: String?) { cvcEditText.setText(cvcCode) } @JvmSynthetic internal fun setPostalCode(postalCode: String?) { postalCodeEditText.setText(postalCode) } /** * Clear all text fields in the CardInputWidget. */ override fun clear() { if (currentFields.any { it.hasFocus() } || this.hasFocus()) { cardNumberEditText.requestFocus() } currentFields.forEach { it.setText("") } } /** * Enable or disable text fields * * @param isEnabled boolean indicating whether fields should be enabled */ override fun setEnabled(isEnabled: Boolean) { currentFields.forEach { it.isEnabled = isEnabled } } /** * Set a `TextWatcher` to receive card number changes. */ override fun setCardNumberTextWatcher(cardNumberTextWatcher: TextWatcher?) { cardNumberEditText.addTextChangedListener(cardNumberTextWatcher) } /** * Set a `TextWatcher` to receive expiration date changes. */ override fun setExpiryDateTextWatcher(expiryDateTextWatcher: TextWatcher?) { expiryDateEditText.addTextChangedListener(expiryDateTextWatcher) } /** * Set a `TextWatcher` to receive CVC value changes. */ override fun setCvcNumberTextWatcher(cvcNumberTextWatcher: TextWatcher?) { cvcEditText.addTextChangedListener(cvcNumberTextWatcher) } /** * Set a `TextWatcher` to receive postal code changes. */ override fun setPostalCodeTextWatcher(postalCodeTextWatcher: TextWatcher?) { postalCodeEditText.addTextChangedListener(postalCodeTextWatcher) } /** * Override of [View.isEnabled] that returns `true` only * if all three sub-controls are enabled. * * @return `true` if the card number field, expiry field, cvc field, and postal (if required) * are enabled, `false` otherwise */ override fun isEnabled(): Boolean { return requiredFields.all { it.isEnabled } } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { if (ev.action != MotionEvent.ACTION_DOWN) { return super.onInterceptTouchEvent(ev) } return getFocusField( ev.x.toInt(), frameStart )?.let { field -> when (field) { Field.Number -> cardNumberEditText Field.Expiry -> expiryDateEditText Field.Cvc -> cvcEditText Field.PostalCode -> postalCodeEditText }.requestFocus() true } ?: super.onInterceptTouchEvent(ev) } override fun onSaveInstanceState(): Parcelable { return bundleOf( STATE_SUPER_STATE to super.onSaveInstanceState(), STATE_CARD_VIEWED to isShowingFullCard, STATE_POSTAL_CODE_ENABLED to postalCodeEnabled ) } override fun onRestoreInstanceState(state: Parcelable) { if (state is Bundle) { postalCodeEnabled = state.getBoolean(STATE_POSTAL_CODE_ENABLED, true) isShowingFullCard = state.getBoolean(STATE_CARD_VIEWED, true) updateSpaceSizes(isShowingFullCard) placement.totalLengthInPixels = frameWidth val cardStartMargin: Int val dateStartMargin: Int val cvcStartMargin: Int val postalCodeStartMargin: Int if (isShowingFullCard) { cardStartMargin = 0 dateStartMargin = placement.getDateStartMargin(isFullCard = true) cvcStartMargin = placement.getCvcStartMargin(isFullCard = true) postalCodeStartMargin = placement.getPostalCodeStartMargin(isFullCard = true) } else { cardStartMargin = -1 * placement.hiddenCardWidth dateStartMargin = placement.getDateStartMargin(isFullCard = false) cvcStartMargin = placement.getCvcStartMargin(isFullCard = false) postalCodeStartMargin = if (postalCodeEnabled) { placement.getPostalCodeStartMargin(isFullCard = false) } else { placement.totalLengthInPixels } } updateFieldLayout( view = cardNumberTextInputLayout, newWidth = placement.cardWidth, newMarginStart = cardStartMargin ) updateFieldLayout( view = expiryDateTextInputLayout, newWidth = placement.dateWidth, newMarginStart = dateStartMargin ) updateFieldLayout( view = cvcNumberTextInputLayout, newWidth = placement.cvcWidth, newMarginStart = cvcStartMargin ) updateFieldLayout( view = postalCodeTextInputLayout, newWidth = placement.postalCodeWidth, newMarginStart = postalCodeStartMargin ) super.onRestoreInstanceState(state.getParcelable(STATE_SUPER_STATE)) } else { super.onRestoreInstanceState(state) } } private fun getFocusField( touchX: Int, frameStart: Int ) = placement.getFocusField( touchX, frameStart, isShowingFullCard, postalCodeEnabled ) @VisibleForTesting internal fun updateSpaceSizes( isShowingFullCard: Boolean, frameWidth: Int = this.frameWidth, frameStart: Int = this.frameStart ) { if (frameWidth == 0) { // This is an invalid view state. return } placement.cardWidth = getDesiredWidthInPixels( FULL_SIZING_CARD_TEXT, cardNumberEditText ) placement.dateWidth = getDesiredWidthInPixels( FULL_SIZING_DATE_TEXT, expiryDateEditText ) placement.hiddenCardWidth = getDesiredWidthInPixels( hiddenCardText, cardNumberEditText ) placement.cvcWidth = getDesiredWidthInPixels( cvcPlaceHolder, cvcEditText ) placement.postalCodeWidth = getDesiredWidthInPixels( FULL_SIZING_POSTAL_CODE_TEXT, postalCodeEditText ) placement.peekCardWidth = getDesiredWidthInPixels( peekCardText, cardNumberEditText ) placement.updateSpacing(isShowingFullCard, postalCodeEnabled, frameStart, frameWidth) } private fun updateFieldLayout( view: View, newWidth: Int, newMarginStart: Int ) { view.updateLayoutParams<FrameLayout.LayoutParams> { width = newWidth marginStart = newMarginStart } } private fun getDesiredWidthInPixels(text: String, editText: StripeEditText): Int { return layoutWidthCalculator.calculate(text, editText.paint) } private fun initView(attrs: AttributeSet?) { applyCardElementAttributes(attrs) ViewCompat.setAccessibilityDelegate( cardNumberEditText, object : AccessibilityDelegateCompat() { override fun onInitializeAccessibilityNodeInfo( host: View, info: AccessibilityNodeInfoCompat ) { super.onInitializeAccessibilityNodeInfo(host, info) // Avoid reading out "1234 1234 1234 1234" info.hintText = null } } ) isShowingFullCard = true @ColorInt var errorColorInt = cardNumberEditText.defaultErrorColorInt cardBrandView.tintColorInt = cardNumberEditText.hintTextColors.defaultColor var cardHintText: String? = null var shouldRequestFocus = true context.withStyledAttributes( attrs, R.styleable.CardInputView ) { cardBrandView.tintColorInt = getColor( R.styleable.CardInputView_cardTint, cardBrandView.tintColorInt ) errorColorInt = getColor( R.styleable.CardInputView_cardTextErrorColor, errorColorInt ) cardHintText = getString(R.styleable.CardInputView_cardHintText) shouldRequestFocus = getBoolean( R.styleable.CardInputView_android_focusedByDefault, true ) } cardHintText?.let { cardNumberEditText.hint = it } currentFields.forEach { it.setErrorColor(errorColorInt) } cardNumberEditText.internalFocusChangeListeners.add { _, hasFocus -> if (hasFocus) { scrollStart() cardInputListener?.onFocusChange(CardInputListener.FocusField.CardNumber) } } expiryDateEditText.internalFocusChangeListeners.add { _, hasFocus -> if (hasFocus) { scrollEnd() cardInputListener?.onFocusChange(CardInputListener.FocusField.ExpiryDate) } } postalCodeEditText.internalFocusChangeListeners.add { _, hasFocus -> if (hasFocus) { scrollEnd() cardInputListener?.onFocusChange(CardInputListener.FocusField.PostalCode) } } expiryDateEditText.setDeleteEmptyListener(BackUpFieldDeleteListener(cardNumberEditText)) cvcEditText.setDeleteEmptyListener(BackUpFieldDeleteListener(expiryDateEditText)) postalCodeEditText.setDeleteEmptyListener(BackUpFieldDeleteListener(cvcEditText)) cvcEditText.internalFocusChangeListeners.add { _, hasFocus -> cardBrandView.shouldShowCvc = hasFocus if (hasFocus) { scrollEnd() cardInputListener?.onFocusChange(CardInputListener.FocusField.Cvc) } } cvcEditText.setAfterTextChangedListener { text -> if (brand.isMaxCvc(text)) { cardInputListener?.onCvcComplete() } } postalCodeEditText.setAfterTextChangedListener { if (postalCodeEditText.isEnabled && postalCodeEditText.hasValidPostal()) { cardInputListener?.onPostalCodeComplete() } } cardNumberEditText.completionCallback = { scrollEnd() cardInputListener?.onCardComplete() } cardNumberEditText.brandChangeCallback = { brand -> cardBrandView.brand = brand hiddenCardText = createHiddenCardText(cardNumberEditText.panLength) updateCvc() } expiryDateEditText.completionCallback = { cvcEditText.requestFocus() cardInputListener?.onExpirationComplete() } cvcEditText.completionCallback = { if (postalCodeEnabled) { postalCodeEditText.requestFocus() } } allFields.forEach { field -> field.doAfterTextChanged { shouldShowErrorIcon = false } } if (shouldRequestFocus) { cardNumberEditText.requestFocus() } cardNumberEditText.isLoadingCallback = { cardBrandView.isLoading = it } } /** * Set an optional CVC field label to override defaults, or `null` to use defaults. */ fun setCvcLabel(cvcLabel: String?) { customCvcLabel = cvcLabel updateCvc() } private fun updateCvc() { cvcEditText.updateBrand( cardBrandView.brand, customCvcLabel ) } /** * @return a [String] that is the length of a full formatted PAN for the given PAN length, * without the last group of digits. This is used for measuring the rendered width of the * hidden portion (i.e. when the card number is "peeking") and does not have to be a valid * card number. * * e.g. if [panLength] is `16`, this will generate `"0000 0000 0000 "` (including the * trailing space). * * This should only be called when [brand] changes. */ @VisibleForTesting internal fun createHiddenCardText( panLength: Int ): String { val formattedNumber = CardNumber.Unvalidated( "0".repeat(panLength) ).getFormatted(panLength) return formattedNumber.take( formattedNumber.lastIndexOf(' ') + 1 ) } private fun applyCardElementAttributes(attrs: AttributeSet?) { context.withStyledAttributes( attrs, R.styleable.CardElement ) { postalCodeEnabled = getBoolean( R.styleable.CardElement_shouldShowPostalCode, postalCodeEnabled ) postalCodeRequired = getBoolean( R.styleable.CardElement_shouldRequirePostalCode, postalCodeRequired ) usZipCodeRequired = getBoolean( R.styleable.CardElement_shouldRequireUsZipCode, usZipCodeRequired ) } } // reveal the full card number field private fun scrollStart() { if (isShowingFullCard || !isViewInitialized) { return } val dateStartPosition = placement.getDateStartMargin(isFullCard = false) val cvcStartPosition = placement.getCvcStartMargin(isFullCard = false) val postalCodeStartPosition = placement.getPostalCodeStartMargin(isFullCard = false) updateSpaceSizes(isShowingFullCard = true) val slideCardStartAnimation = CardNumberSlideStartAnimation( view = cardNumberTextInputLayout ) val dateDestination = placement.getDateStartMargin(isFullCard = true) val slideDateStartAnimation = ExpiryDateSlideStartAnimation( view = expiryDateTextInputLayout, startPosition = dateStartPosition, destination = dateDestination ) val cvcDestination = cvcStartPosition + (dateDestination - dateStartPosition) val slideCvcStartAnimation = CvcSlideStartAnimation( view = cvcNumberTextInputLayout, startPosition = cvcStartPosition, destination = cvcDestination, newWidth = placement.cvcWidth ) val postalCodeDestination = postalCodeStartPosition + (cvcDestination - cvcStartPosition) val slidePostalCodeStartAnimation = if (postalCodeEnabled) { PostalCodeSlideStartAnimation( view = postalCodeTextInputLayout, startPosition = postalCodeStartPosition, destination = postalCodeDestination, newWidth = placement.postalCodeWidth ) } else { null } startSlideAnimation( listOfNotNull( slideCardStartAnimation, slideDateStartAnimation, slideCvcStartAnimation, slidePostalCodeStartAnimation ) ) isShowingFullCard = true } // reveal the secondary fields private fun scrollEnd() { if (!isShowingFullCard || !isViewInitialized) { return } val dateStartMargin = placement.getDateStartMargin(isFullCard = true) updateSpaceSizes(isShowingFullCard = false) val slideCardEndAnimation = CardNumberSlideEndAnimation( view = cardNumberTextInputLayout, hiddenCardWidth = placement.hiddenCardWidth, focusOnEndView = expiryDateEditText ) val dateDestination = placement.getDateStartMargin(isFullCard = false) val slideDateEndAnimation = ExpiryDateSlideEndAnimation( view = expiryDateTextInputLayout, startMargin = dateStartMargin, destination = dateDestination ) val cvcDestination = placement.getCvcStartMargin(isFullCard = false) val cvcStartMargin = cvcDestination + (dateStartMargin - dateDestination) val slideCvcEndAnimation = CvcSlideEndAnimation( view = cvcNumberTextInputLayout, startMargin = cvcStartMargin, destination = cvcDestination, newWidth = placement.cvcWidth ) val postalCodeDestination = placement.getPostalCodeStartMargin(isFullCard = false) val postalCodeStartMargin = postalCodeDestination + (cvcStartMargin - cvcDestination) val slidePostalCodeEndAnimation = if (postalCodeEnabled) { PostalCodeSlideEndAnimation( view = postalCodeTextInputLayout, startMargin = postalCodeStartMargin, destination = postalCodeDestination, newWidth = placement.postalCodeWidth ) } else { null } startSlideAnimation( listOfNotNull( slideCardEndAnimation, slideDateEndAnimation, slideCvcEndAnimation, slidePostalCodeEndAnimation ) ) isShowingFullCard = false } private fun startSlideAnimation(animations: List<Animation>) { val animationSet = AnimationSet(true).apply { animations.forEach { addAnimation(it) } } containerLayout.startAnimation(animationSet) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) if (!isViewInitialized && width != 0) { isViewInitialized = true placement.totalLengthInPixels = frameWidth updateSpaceSizes(isShowingFullCard) updateFieldLayout( view = cardNumberTextInputLayout, newWidth = placement.cardWidth, newMarginStart = if (isShowingFullCard) { 0 } else { -1 * placement.hiddenCardWidth } ) updateFieldLayout( view = expiryDateTextInputLayout, newWidth = placement.dateWidth, newMarginStart = placement.getDateStartMargin(isShowingFullCard) ) updateFieldLayout( view = cvcNumberTextInputLayout, newWidth = placement.cvcWidth, newMarginStart = placement.getCvcStartMargin(isShowingFullCard) ) updateFieldLayout( view = postalCodeTextInputLayout, newWidth = placement.postalCodeWidth, newMarginStart = placement.getPostalCodeStartMargin(isShowingFullCard) ) } } private var hiddenCardText: String = createHiddenCardText(cardNumberEditText.panLength) private val cvcPlaceHolder: String get() { return if (CardBrand.AmericanExpress == brand) { CVC_PLACEHOLDER_AMEX } else { CVC_PLACEHOLDER_COMMON } } private val peekCardText: String get() { return when (cardNumberEditText.panLength) { 19 -> 3 15 -> 5 14 -> 2 else -> 4 }.let { peekSize -> "0".repeat(peekSize) } } @SuppressWarnings("UnnecessaryAbstractClass") private abstract class CardFieldAnimation : Animation() { init { duration = ANIMATION_LENGTH } private companion object { private const val ANIMATION_LENGTH = 150L } } private class CardNumberSlideStartAnimation( private val view: View ) : CardFieldAnimation() { init { setAnimationListener( object : AnimationEndListener() { override fun onAnimationEnd(animation: Animation) { view.requestFocus() } } ) } override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { marginStart = (marginStart * (1 - interpolatedTime)).toInt() } } } private class ExpiryDateSlideStartAnimation( private val view: View, private val startPosition: Int, private val destination: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startPosition).toInt() } } } private class CvcSlideStartAnimation( private val view: View, private val startPosition: Int, private val destination: Int, private val newWidth: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { this.marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startPosition).toInt() this.marginEnd = 0 this.width = newWidth } } } private class PostalCodeSlideStartAnimation( private val view: View, private val startPosition: Int, private val destination: Int, private val newWidth: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation?) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { this.marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startPosition).toInt() this.marginEnd = 0 this.width = newWidth } } } private class CardNumberSlideEndAnimation( private val view: View, private val hiddenCardWidth: Int, private val focusOnEndView: View ) : CardFieldAnimation() { init { setAnimationListener( object : AnimationEndListener() { override fun onAnimationEnd(animation: Animation) { focusOnEndView.requestFocus() } } ) } override fun applyTransformation( interpolatedTime: Float, t: Transformation ) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { marginStart = (-1f * hiddenCardWidth.toFloat() * interpolatedTime).toInt() } } } private class ExpiryDateSlideEndAnimation( private val view: View, private val startMargin: Int, private val destination: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startMargin).toInt() } } } private class CvcSlideEndAnimation( private val view: View, private val startMargin: Int, private val destination: Int, private val newWidth: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startMargin).toInt() marginEnd = 0 width = newWidth } } } private class PostalCodeSlideEndAnimation( private val view: View, private val startMargin: Int, private val destination: Int, private val newWidth: Int ) : CardFieldAnimation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) view.updateLayoutParams<FrameLayout.LayoutParams> { this.marginStart = (interpolatedTime * destination + (1 - interpolatedTime) * startMargin).toInt() this.marginEnd = 0 this.width = newWidth } } } /** * A convenience class for when we only want to listen for when an animation ends. */ private abstract class AnimationEndListener : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { // Intentional No-op } override fun onAnimationRepeat(animation: Animation) { // Intentional No-op } } internal fun interface LayoutWidthCalculator { fun calculate(text: String, paint: TextPaint): Int } internal class DefaultLayoutWidthCalculator : LayoutWidthCalculator { override fun calculate(text: String, paint: TextPaint): Int { return Layout.getDesiredWidth(text, paint).toInt() } } internal enum class Field { Number, Expiry, Cvc, PostalCode } internal companion object { internal const val LOGGING_TOKEN = "CardInputView" private const val CVC_PLACEHOLDER_COMMON = "CVC" private const val CVC_PLACEHOLDER_AMEX = "2345" private const val FULL_SIZING_CARD_TEXT = "4242 4242 4242 4242 424" private const val FULL_SIZING_DATE_TEXT = "MM/MM" private const val FULL_SIZING_POSTAL_CODE_TEXT = "1234567890" private const val STATE_CARD_VIEWED = "state_card_viewed" private const val STATE_SUPER_STATE = "state_super_state" private const val STATE_POSTAL_CODE_ENABLED = "state_postal_code_enabled" // This value is used to ensure that onSaveInstanceState is called // in the event that the user doesn't give this control an ID. @IdRes private val DEFAULT_READER_ID = R.id.stripe_default_reader_id /** * Determines whether or not the icon should show the card brand instead of the * CVC helper icon. * * @param brand the [CardBrand] of the card number * @param cvcHasFocus `true` if the CVC entry field has focus, `false` otherwise * @param cvcText the current content of [cvcEditText] * * @return `true` if we should show the brand of the card, or `false` if we * should show the CVC helper icon instead */ @VisibleForTesting internal fun shouldIconShowBrand( brand: CardBrand, cvcHasFocus: Boolean, cvcText: String? ): Boolean { return !cvcHasFocus || brand.isMaxCvc(cvcText) } } }
mit
dbdf9662d6123db8214c3217d528b259
33.343083
101
0.615965
5.891511
false
false
false
false
clkim/demoKotlinAndroidDev2016
app/src/main/kotlin/net/gouline/dagger2demo/activity/AlbumSearchActivity.kt
1
7039
package net.gouline.dagger2demo.activity import android.app.SearchManager import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.util.Log import android.view.Menu import android.view.View import android.view.inputmethod.InputMethodManager import kotlinx.android.synthetic.main.activity_album_search.* import net.gouline.dagger2demo.DemoApplication import net.gouline.dagger2demo.R import net.gouline.dagger2demo.rest.ITunesService import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import javax.inject.Inject /** * Activity for search iTunes albums by artist name. * * * Created by mgouline on 23/04/15. * Converted by clkim to Kotlin from original java, * then substantially refactored, e.g. RecyclerView, * hiding soft keyboard, hiding prompt in textview when * album list is not empty, handling orientation change * e.g. caching what has been fetched, using Retrofit 2, * RxJava/RxAndroid and life-cycle handling, Picasso... * * Added basic unit tests for Activity, written in Java * AlbumSearchActivityTest * To run it, connect a device via USB to dev machine, * then in Android Studio > Run AlbumSearchActivityTest * * Acknowledgements: * Mike Gouline's blog on Dagger 2 * Sittiphol Phanvilai’s blog on Retrofit 2 * Dan Lew’s blogs “Grokking RxJava” and on RxAndroid 1.0 * Edwin Jose and NILANCHALA for RecyclerView examples */ class AlbumSearchActivity : AppCompatActivity(), SearchView.OnQueryTextListener { // iTunes api service (Retrofit2, injected in by Dagger2) @Inject lateinit var mITunesService: ITunesService // injected properties using Kotlin Android Extensions // from ids in the layout file activity_album_search.xml // recycler_view: RecyclerView // empty_view: TextView // adapter for recycler view private var mAlbumViewAdapter: AlbumViewAdapter? = null // composite subscription used to un-subscribe rx subscriptions private var mCompositeSubscription: CompositeSubscription? = null // object with "static" member property used by Log.x companion object { private val TAG = AlbumSearchActivity::class.simpleName } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_album_search) // Actual injection, performed via the component DemoApplication.from(this).component .inject(this) mAlbumViewAdapter = AlbumViewAdapter() // id of RecyclerView in layout, using Kotlin Android Extensions this.recycler_view.adapter = mAlbumViewAdapter this.recycler_view.layoutManager = LinearLayoutManager(this) // Reference - http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/ // we follow the pattern in above blog reference, although we have just one subscription in // this demo app and un-subscribing from the subscription directly seemed to work ok too mCompositeSubscription = CompositeSubscription() // if there is observable cached, use it to display album items from prior api call; // tried checking instead for empty sequence in cached observable using // DemoApplication.albumItemObservableCache.count().toBlocking().single() != 0 // but it is too slow on orientation change right after starting a search, since it seems // to block so as to count the items coming into the sequence from the new search; so we // live with the edge case that displays an empty view if cache is present but empty if (DemoApplication.albumItemObservableCache != null) { displayCachedResults(DemoApplication.albumItemObservableCache) // hide prompt-textview setPromptVisibility(View.GONE) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_album_search, menu) val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchView = menu.findItem(R.id.menu_item_search).actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) searchView.setOnQueryTextListener(this) return true } override fun onQueryTextSubmit(term: String): Boolean { if (term.isNotEmpty()) { fetchResults(term) // hide soft keyboard (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(this.recycler_view.applicationWindowToken, 0) } return true } override fun onQueryTextChange(s: String): Boolean { // show prompt-textview if search term is blanked out and no album items are displayed if (s.isNotEmpty()) setPromptVisibility(View.GONE) else if (s.isEmpty() && mAlbumViewAdapter?.itemCount == 0) setPromptVisibility(View.VISIBLE) return false } override fun onDestroy() { super.onDestroy() mCompositeSubscription?.unsubscribe() } private fun fetchResults(term: String) { // clear the items in recyclerview adapter mAlbumViewAdapter?.clear() // cache newly fetched observable DemoApplication.albumItemObservableCache = // using the injected Retrofit service mITunesService.search(term, "album") .flatMap { Observable.from(it.results) } .map { AlbumItem(it.collectionName, it.artworkUrl100) } .subscribeOn(Schedulers.io()) .cache() displayCachedResults(DemoApplication.albumItemObservableCache) } private fun displayCachedResults(cache: Observable<AlbumItem>) { // subscribe to the observable so as to display the album items val subscription: Subscription = cache .observeOn(AndroidSchedulers.mainThread()) .subscribe( { mAlbumViewAdapter?.addAlbumItem(it) mAlbumViewAdapter?.notifyItemInserted( mAlbumViewAdapter?.itemCount?.minus(1) ?: 0) }, { Log.w(TAG, "Retrieve albums failed\n" + it.message, it) }) // add the subscription to the CompositeSubscription // so we can do lifecycle un-subscribe mCompositeSubscription?.add(subscription) } private fun setPromptVisibility(visibility: Int) { // using id of TextView - Kotlin Android Extensions // this contains the prompt to search for artists' albums this.empty_view.visibility = visibility } }
mit
30b973ecd2da67ade7f90069f1f197b6
39.408046
99
0.691793
4.972419
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/MockServerFixture.kt
3
1200
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust import com.intellij.testFramework.fixtures.impl.BaseFixture import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import org.junit.Assert import org.rust.ide.utils.USER_AGENT typealias ResponseHandler = (RecordedRequest) -> MockResponse? class MockServerFixture : BaseFixture() { private var handler: ResponseHandler? = null private val mockWebServer = MockWebServer().apply { dispatcher = object : Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse { Assert.assertEquals(USER_AGENT, request.getHeader("User-Agent")) return handler?.invoke(request) ?: MockResponse().setResponseCode(404) } } } val baseUrl: String get() = mockWebServer.url("/").toString() fun withHandler(handler: ResponseHandler) { this.handler = handler } override fun tearDown() { mockWebServer.shutdown() super.tearDown() } }
mit
630bd1168cb83a753d018fc7497a0310
28.268293
86
0.7025
4.83871
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rustSlowTests/cargo/runconfig/RunConfigurationTestBase.kt
2
5744
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rustSlowTests.cargo.runconfig import com.intellij.execution.* import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.impl.RunManagerImpl import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl import com.intellij.execution.process.ProcessOutput import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.execution.runners.ProgramRunner import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiElement import org.rust.cargo.RsWithToolchainTestBase import org.rust.cargo.runconfig.CargoCommandRunner import org.rust.cargo.runconfig.buildtool.CargoBuildConfiguration import org.rust.cargo.runconfig.buildtool.CargoBuildManager import org.rust.cargo.runconfig.buildtool.CargoBuildResult import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.runconfig.command.CargoCommandConfigurationType import org.rust.cargo.runconfig.command.CargoExecutableRunConfigurationProducer import org.rust.cargo.runconfig.test.CargoTestRunConfigurationProducer abstract class RunConfigurationTestBase : RsWithToolchainTestBase() { override fun setUp() { super.setUp() val executionManager = ExecutionManagerImpl.getInstance(project) executionManager.forceCompilationInTests = true Disposer.register(testRootDisposable) { executionManager.forceCompilationInTests = false } } protected fun createConfiguration(command: String = "run"): CargoCommandConfiguration { val configurationType = CargoCommandConfigurationType.getInstance() val factory = configurationType.factory val configuration = factory.createTemplateConfiguration(myModule.project) as CargoCommandConfiguration configuration.command = command return configuration } protected fun createExecutableRunConfigurationFromContext( location: Location<PsiElement>? = null ): CargoCommandConfiguration = createRunConfigurationFromContext(CargoExecutableRunConfigurationProducer(), location) protected fun createTestRunConfigurationFromContext( location: Location<PsiElement>? = null ): CargoCommandConfiguration = createRunConfigurationFromContext(CargoTestRunConfigurationProducer(), location) private fun createRunConfigurationFromContext( producer: RunConfigurationProducer<CargoCommandConfiguration>, location: Location<PsiElement>? = null ): CargoCommandConfiguration = createRunnerAndConfigurationSettingsFromContext(producer, location) .configuration as? CargoCommandConfiguration ?: error("Can't create run configuration") protected fun createRunnerAndConfigurationSettingsFromContext( producer: RunConfigurationProducer<CargoCommandConfiguration>, location: Location<PsiElement>? = null ): RunnerAndConfigurationSettings { val context = if (location != null) { ConfigurationContext.createEmptyContextForLocation(location) } else { val dataContext = DataManager.getInstance().getDataContext(myFixture.editor.component) ConfigurationContext.getFromContext(dataContext, ActionPlaces.UNKNOWN) } return producer.createConfigurationFromContext(context) ?.configurationSettings ?: error("Can't create run configuration settings") } protected fun execute( configuration: RunConfiguration, customizeExecutionEnv: ExecutionEnvironmentBuilder.() -> ExecutionEnvironmentBuilder = { this } ): TestExecutionResult { val connection = project.messageBus.connect(testRootDisposable) val executionListener = TestExecutionListener(testRootDisposable, configuration) connection.subscribe(ExecutionManager.EXECUTION_TOPIC, executionListener) ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), configuration) .activeTarget() .customizeExecutionEnv() .buildAndExecute() return executionListener.waitFinished() ?: error("Process not finished") } protected fun executeAndGetOutput(configuration: RunConfiguration): ProcessOutput { val result = execute(configuration) return result.output ?: error("Process failed to start") } protected fun buildProject(command: String = "build"): CargoBuildResult { val buildConfiguration = createBuildConfiguration(command) return CargoBuildManager.build(buildConfiguration).get() } private fun createBuildConfiguration(command: String): CargoBuildConfiguration { val executor = ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID)!! val runner = ProgramRunner.findRunnerById(CargoCommandRunner.RUNNER_ID)!! val runManager = RunManager.getInstance(project) as RunManagerImpl val configuration = CargoBuildManager.getBuildConfiguration(createConfiguration(command))!! val settings = RunnerAndConfigurationSettingsImpl(runManager, configuration) val environment = ExecutionEnvironment(executor, runner, settings, project) return CargoBuildConfiguration(configuration, environment) } }
mit
761e1b7d58da77cb5dac88ac9ccf882f
48.094017
121
0.779422
6.110638
false
true
false
false
rarspace01/pirateboat
src/main/java/boat/multifileHoster/MultifileHosterService.kt
1
3667
package boat.multifileHoster import boat.torrent.HttpUser import boat.torrent.Torrent import boat.torrent.TorrentFile import boat.utilities.HttpHelper import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.util.function.Consumer import java.util.stream.Collectors @Service class MultifileHosterService @Autowired constructor(httpHelper: HttpHelper?) : HttpUser(httpHelper) { private val multifileHosterList: MutableList<MultifileHoster> = ArrayList() fun getCachedStateOfTorrents(returnResults: List<Torrent>): List<Torrent> { multifileHosterList.forEach(Consumer { multifileHoster: MultifileHoster -> multifileHoster.enrichCacheStateOfTorrents(returnResults) }) return returnResults } fun addTorrentToQueue(torrent: Torrent): String { val potentialCachedTorrentToDownload = getCachedStateOfTorrents(listOf(torrent)).stream().findFirst().orElse(torrent) return multifileHosterList.stream() .filter { multifileHoster: MultifileHoster -> multifileHoster.getName() == potentialCachedTorrentToDownload.cached.stream().findFirst().orElse("") } .min(Comparator.comparingInt { obj: MultifileHoster -> obj.getPrio() }) .orElse(multifileHosterList[0]) .addTorrentToQueue(torrent) } val remoteTorrents: List<Torrent> get() = multifileHosterList.stream() .flatMap { multifileHoster: MultifileHoster -> multifileHoster.getRemoteTorrents().stream() } .collect(Collectors.toList()) fun isSingleFileDownload(torrentToBeDownloaded: Torrent): Boolean { val tfList = getFilesFromTorrent(torrentToBeDownloaded) var sumFileSize = 0L var biggestFileYet = 0L for (tf in tfList) { if (tf.filesize > biggestFileYet) { biggestFileYet = tf.filesize } sumFileSize += tf.filesize } // if maxfilesize >90% sumSize --> Singlefile return biggestFileYet > 0.9 * sumFileSize } fun getFilesFromTorrent(torrentToBeDownloaded: Torrent): List<TorrentFile> { val hoster = multifileHosterList.stream().filter { multifileHoster: MultifileHoster -> multifileHoster.getName() == torrentToBeDownloaded.source }.findFirst() return if (hoster.isPresent) { hoster.get().getFilesFromTorrent(torrentToBeDownloaded) } else { ArrayList() } } fun getMainFileURLFromTorrent(torrentToBeDownloaded: Torrent): String? { val tfList = getFilesFromTorrent(torrentToBeDownloaded) var remoteURL: String? = null // iterate over and check for One File Torrent var biggestFileYet: Long = 0 for (tf in tfList) { if (tf.filesize > biggestFileYet) { biggestFileYet = tf.filesize remoteURL = tf.url } } return remoteURL } fun delete(torrent: Torrent) { val hoster = multifileHosterList.stream().filter { multifileHoster: MultifileHoster -> multifileHoster.getName() == torrent.source }.findFirst() if (hoster.isPresent) { hoster.get().delete(torrent) } else { log.error("Deletion of Torrent not possible: {}", torrent.toString()) } } companion object { private val log = LoggerFactory.getLogger(MultifileHosterService::class.java) } init { multifileHosterList.add(Premiumize(httpHelper)) //currently disabled multifileHosterList.add(new Alldebrid(httpHelper)); } }
apache-2.0
de1a314373eebc5353195b3732b28e88
40.213483
166
0.677938
5.194051
false
false
false
false
MegaShow/college-programming
Homework/Mobile Phone Application Development/Lab5 WebAPI/app/src/main/java/com/icytown/course/experimentfive/webapi/data/service/BilibiliApiService.kt
1
3351
package com.icytown.course.experimentfive.webapi.data.service import android.graphics.Bitmap import android.graphics.BitmapFactory import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.icytown.course.experimentfive.webapi.data.model.PVideo import com.icytown.course.experimentfive.webapi.data.model.Top import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.net.HttpURLConnection import java.net.URL import javax.net.ssl.HttpsURLConnection class BilibiliApiService { companion object { fun getTop(userId: Int): Observable<Top> { val observable: Observable<Top> = Observable.create { emitter -> val url = URL("https://space.bilibili.com/ajax/top/showTop?mid=$userId") val connection = url.openConnection() as HttpsURLConnection connection.requestMethod = "GET" connection.connectTimeout = 5000 connection.readTimeout = 5000 val inputStream = connection.inputStream val response = inputStream.bufferedReader().use { it.readText() } val top = try { Gson().fromJson(response, Top::class.java) } catch (e: JsonSyntaxException) { Top(false, null) } emitter.onNext(top) emitter.onComplete() } return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun getPVideo(aid: Int): Observable<PVideo> { val observable: Observable<PVideo> = Observable.create { emitter -> val url = URL("https://api.bilibili.com/pvideo?aid=$aid") val connection = url.openConnection() as HttpsURLConnection connection.requestMethod = "GET" connection.connectTimeout = 5000 connection.readTimeout = 5000 val inputStream = connection.inputStream val response = inputStream.bufferedReader().use { it.readText() } val pVideo = try { Gson().fromJson(response, PVideo::class.java) } catch (e: JsonSyntaxException) { PVideo() } emitter.onNext(pVideo) emitter.onComplete() } return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun getBitmap(urlstr: String): Observable<Bitmap> { val observable: Observable<Bitmap> = Observable.create { emitter -> val url = URL(urlstr) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 5000 connection.readTimeout = 5000 val inputStream = connection.inputStream emitter.onNext(BitmapFactory.decodeStream(inputStream)) emitter.onComplete() } return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } } }
mit
1f5cd05e80ab1eb07b974b5a74b6e1c8
40.8875
88
0.594449
5.439935
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/adventure/framework/AdventurePresentationProvider.kt
1
1437
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.adventure.framework import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.platform.adventure.AdventureConstants import com.demonwav.mcdev.util.get import com.demonwav.mcdev.util.manifest import com.intellij.openapi.roots.libraries.DummyLibraryProperties import com.intellij.openapi.roots.libraries.LibraryPresentationProvider import com.intellij.openapi.vfs.VirtualFile import java.util.jar.Attributes.Name.SPECIFICATION_TITLE import java.util.jar.Manifest class AdventurePresentationProvider : LibraryPresentationProvider<DummyLibraryProperties>(ADVENTURE_LIBRARY_KIND) { override fun getIcon(properties: DummyLibraryProperties?) = PlatformAssets.ADVENTURE_ICON override fun detect(classesRoots: MutableList<VirtualFile>): DummyLibraryProperties? { for (classesRoot in classesRoots) { val manifest = classesRoot.manifest ?: continue if (findUsingManifest(manifest)) { return DummyLibraryProperties.INSTANCE } } return null } private fun findUsingManifest(manifest: Manifest): Boolean = manifest[SPECIFICATION_TITLE] == AdventureConstants.API_SPECIFICATION_TITLE || manifest["Automatic-Module-Name"] == AdventureConstants.API_MODULE_ID }
mit
68cc946a0a6e83eeec88e2dd6ca97a92
34.04878
115
0.757829
4.711475
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt
3
2882
package info.nightscout.androidaps.plugins.general.smsCommunicator import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.smscommunicator_fragment.* import java.util.* import kotlin.math.max class SmsCommunicatorFragment : Fragment() { private val disposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.smscommunicator_fragment, container, false) } @Synchronized override fun onResume() { super.onResume() disposable.add(toObservable(EventSmsCommunicatorUpdateGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGui() }) { FabricPrivacy.logException(it) } ) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } fun updateGui() { class CustomComparator : Comparator<Sms> { override fun compare(object1: Sms, object2: Sms): Int { return (object1.date - object2.date).toInt() } } Collections.sort(SmsCommunicatorPlugin.messages, CustomComparator()) val messagesToShow = 40 val start = max(0, SmsCommunicatorPlugin.messages.size - messagesToShow) var logText = "" for (x in start until SmsCommunicatorPlugin.messages.size) { val sms = SmsCommunicatorPlugin.messages[x] when { sms.ignored -> { logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + "░ " + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } sms.received -> { logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } sms.sent -> { logText += DateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } } } smscommunicator_log?.text = HtmlHelper.fromHtml(logText) } }
agpl-3.0
442c219357f20a30de92ff84e4963f8e
40.042857
168
0.64032
4.438949
false
false
false
false
alangibson27/plus-f
plus-f/src/main/kotlin/com/socialthingy/plusf/sound/SoundSystem.kt
1
2226
package com.socialthingy.plusf.sound import com.jsyn.JSyn import com.jsyn.unitgen.* const val frameRate = 44100 class SoundSystem { private val synth = JSyn.createSynthesizer()!! private val lineOut = LineOut() private val masterMixer = FourWayFade() private val random = java.util.Random() private val beepSampler = createBeepSampler() private val toneChannels = createToneChannels() private var isEnabled = false val beeper = Beeper(beepSampler) val ayChip = AYChip(toneChannels) init { synth.add(lineOut) synth.add(masterMixer) masterMixer.output.connect(0, lineOut.input, 0) masterMixer.output.connect(0, lineOut.input, 1) } fun setEnabled(enabled: Boolean): Boolean { val wasEnabled = isEnabled isEnabled = enabled lineOut.isEnabled = enabled beeper.setEnabled(enabled) return wasEnabled } fun start() { synth.start(frameRate) lineOut.start() } fun stop() { synth.stop() lineOut.stop() } fun reset() { if (isEnabled) { setEnabled(false) setEnabled(true) } } private fun createBeepSampler(): VariableRateMonoReader { val s = VariableRateMonoReader() s.rate.set(frameRate.toDouble()) s.output.connect(0, masterMixer.input, 0) synth.add(s) return s } private fun createToneChannels(): List<ToneChannel> { val toneChannels = mutableListOf<ToneChannel>() for (i in 1..3) { val tone = SquareOscillator() val noise = FunctionOscillator() noise.function.set { if (noise.frequency.get() == 0.0) 0.0 else -1.0 + (random.nextDouble() * 2.0) } val internalMixer = Add() tone.output.connect(0, internalMixer.inputA, 0) noise.output.connect(0, internalMixer.inputB, 0) internalMixer.output.connect(0, masterMixer.input, i) synth.add(tone) synth.add(noise) synth.add(internalMixer) toneChannels.add(ToneChannel(tone, noise)) } return toneChannels } }
mit
f202fbcd399ecc6dd3463022b92fbd98
25.188235
93
0.59973
4.152985
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/remote/achievement/service/AchievementsService.kt
2
1006
package org.stepik.android.remote.achievement.service import io.reactivex.Single import org.stepik.android.remote.achievement.model.AchievementProgressesResponse import org.stepik.android.remote.achievement.model.AchievementsResponse import retrofit2.http.GET import retrofit2.http.Query interface AchievementsService { @GET("api/achievements") fun getAchievements( @Query("ids[]") ids: LongArray? = null, @Query("kind") kind: String? = null, @Query("page") page: Int? = null ): Single<AchievementsResponse> @GET("api/achievement-progresses") fun getAchievementProgresses( @Query("ids[]") ids: LongArray? = null, @Query("kind") kind: String? = null, @Query("achievement") achievement: Long? = null, @Query("user") user: Long? = null, @Query("is_obtained") isObtained: Boolean? = null, @Query("order") order: String? = null, @Query("page") page: Int? = null ): Single<AchievementProgressesResponse> }
apache-2.0
336acc0e571a8bd1df5213dee720da99
36.296296
80
0.678926
3.96063
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/classes/superConstructorCallWithComplexArg.kt
5
301
var log = "" open class Base(val s: String) class A(i: Int) : Base("O" + if (i == 23) { log += "logged" "K" } else { "fail" }) fun box(): String { val result = A(23).s if (result != "OK") return "fail: $result" if (log != "logged") return "fail log: $log" return "OK" }
apache-2.0
996aedf8a365a645ef8ad5a6d1cce939
14.894737
48
0.508306
2.6875
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/fragment/ProjectMembersFragment.kt
2
8059
package com.commit451.gitlab.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.activity.ProjectActivity import com.commit451.gitlab.adapter.ProjectMembersAdapter import com.commit451.gitlab.dialog.AccessDialog import com.commit451.gitlab.event.MemberAddedEvent import com.commit451.gitlab.event.ProjectReloadEvent import com.commit451.gitlab.extension.belongsToGroup import com.commit451.gitlab.extension.mapResponseSuccessWithPaginationData import com.commit451.gitlab.extension.with import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.model.api.User import com.commit451.gitlab.navigation.Navigator import com.commit451.gitlab.viewHolder.ProjectMemberViewHolder import com.google.android.material.snackbar.Snackbar import io.reactivex.rxjava3.core.Single import kotlinx.android.synthetic.main.fragment_members.* import org.greenrobot.eventbus.Subscribe import retrofit2.Response import timber.log.Timber class ProjectMembersFragment : BaseFragment() { companion object { fun newInstance(): ProjectMembersFragment { return ProjectMembersFragment() } } private lateinit var adapterProjectMembers: ProjectMembersAdapter private lateinit var layoutManagerMembers: GridLayoutManager private var project: Project? = null private var member: User? = null private var nextPageUrl: String? = null private var loading = false private val onScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val visibleItemCount = layoutManagerMembers.childCount val totalItemCount = layoutManagerMembers.itemCount val firstVisibleItem = layoutManagerMembers.findFirstVisibleItemPosition() if (firstVisibleItem + visibleItemCount >= totalItemCount && !loading && nextPageUrl != null) { loadMore() } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_members, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) App.bus().register(this) buttonAddUser.setOnClickListener { Navigator.navigateToAddProjectMember(baseActivty, buttonAddUser, project!!.id) } adapterProjectMembers = ProjectMembersAdapter(object : ProjectMembersAdapter.Listener { override fun onProjectMemberClicked(member: User, memberGroupViewHolder: ProjectMemberViewHolder) { Navigator.navigateToUser(baseActivty, memberGroupViewHolder.image, member) } override fun onRemoveMember(member: User) { [email protected] = member App.get().gitLab.removeProjectMember(project!!.id, member.id) .with(this@ProjectMembersFragment) .subscribe({ adapterProjectMembers.removeMember([email protected]!!) }, { Timber.e(it) Snackbar.make(root, R.string.failed_to_remove_member, Snackbar.LENGTH_SHORT) .show() }) } override fun onChangeAccess(member: User) { val accessDialog = AccessDialog(baseActivty, member, project!!.id) accessDialog.setOnAccessChangedListener(object : AccessDialog.OnAccessChangedListener { override fun onAccessChanged(member: User, accessLevel: String) { loadData() } }) accessDialog.show() } override fun onSeeGroupClicked() { Navigator.navigateToGroup(baseActivty, project!!.namespace!!.id) } }) layoutManagerMembers = GridLayoutManager(activity, 2) layoutManagerMembers.spanSizeLookup = adapterProjectMembers.spanSizeLookup listMembers.layoutManager = layoutManagerMembers listMembers.adapter = adapterProjectMembers listMembers.addOnScrollListener(onScrollListener) swipeRefreshLayout.setOnRefreshListener { loadData() } if (activity is ProjectActivity) { project = (activity as ProjectActivity).project setNamespace() loadData() } else { throw IllegalStateException("Incorrect parent activity") } } override fun onDestroyView() { App.bus().unregister(this) super.onDestroyView() } override fun loadData() { if (view == null) { return } if (project == null) { swipeRefreshLayout.isRefreshing = false return } swipeRefreshLayout.isRefreshing = true nextPageUrl = null loading = true load(App.get().gitLab.getProjectMembers(project!!.id)) } fun loadMore() { if (view == null) { return } if (nextPageUrl == null) { return } swipeRefreshLayout.isRefreshing = true loading = true Timber.d("loadMore called for ${nextPageUrl!!}") load(App.get().gitLab.getProjectMembers(nextPageUrl!!.toString())) } fun load(observable: Single<Response<List<User>>>) { observable .mapResponseSuccessWithPaginationData() .with(this) .subscribe({ loading = false swipeRefreshLayout.isRefreshing = false if (it.body.isNotEmpty()) { textMessage.visibility = View.GONE } else if (nextPageUrl == null) { Timber.d("No project members found") textMessage.setText(R.string.no_project_members) textMessage.visibility = View.VISIBLE } buttonAddUser.isVisible = true if (nextPageUrl == null) { adapterProjectMembers.setProjectMembers(it.body) } else { adapterProjectMembers.addProjectMembers(it.body) } nextPageUrl = it.paginationData.next Timber.d("Next page url " + nextPageUrl) }, { loading = false Timber.e(it) swipeRefreshLayout.isRefreshing = false textMessage.visibility = View.VISIBLE textMessage.setText(R.string.connection_error_users) buttonAddUser.isVisible = false adapterProjectMembers.setProjectMembers(null) nextPageUrl = null }) } private fun setNamespace() { if (project == null) { return } //If there is an owner, then there is no group if (project!!.belongsToGroup()) { adapterProjectMembers.setNamespace(project!!.namespace) } else { adapterProjectMembers.setNamespace(null) } } @Subscribe fun onProjectReload(event: ProjectReloadEvent) { project = event.project setNamespace() loadData() } @Subscribe fun onMemberAdded(event: MemberAddedEvent) { adapterProjectMembers.addMember(event.member) textMessage.visibility = View.GONE } }
apache-2.0
e8bd08997812d41982a96032cada0c98
35.139013
116
0.620921
5.569454
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/AppModule.kt
1
7206
package eu.kanade.tachiyomi import android.app.Application import android.os.Build import androidx.core.content.ContextCompat import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import com.squareup.sqldelight.android.AndroidSqliteDriver import com.squareup.sqldelight.db.SqlDriver import data.History import data.Mangas import eu.kanade.data.AndroidDatabaseHandler import eu.kanade.data.DatabaseHandler import eu.kanade.data.dateAdapter import eu.kanade.data.listOfStringsAdapter import eu.kanade.data.updateStrategyAdapter import eu.kanade.domain.backup.service.BackupPreferences import eu.kanade.domain.base.BasePreferences import eu.kanade.domain.download.service.DownloadPreferences import eu.kanade.domain.library.service.LibraryPreferences import eu.kanade.domain.source.service.SourcePreferences import eu.kanade.domain.track.service.TrackPreferences import eu.kanade.domain.ui.UiPreferences import eu.kanade.tachiyomi.core.preference.AndroidPreferenceStore import eu.kanade.tachiyomi.core.preference.PreferenceStore import eu.kanade.tachiyomi.core.provider.AndroidBackupFolderProvider import eu.kanade.tachiyomi.core.provider.AndroidDownloadFolderProvider import eu.kanade.tachiyomi.core.security.SecurityPreferences import eu.kanade.tachiyomi.data.cache.ChapterCache import eu.kanade.tachiyomi.data.cache.CoverCache import eu.kanade.tachiyomi.data.download.DownloadCache import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.download.DownloadProvider import eu.kanade.tachiyomi.data.saver.ImageSaver import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.job.DelayedTrackingStore import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.network.JavaScriptEngine import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.network.NetworkPreferences import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import eu.kanade.tachiyomi.util.system.isDevFlavor import io.requery.android.database.sqlite.RequerySQLiteOpenHelperFactory import kotlinx.serialization.json.Json import nl.adaptivity.xmlutil.serialization.UnknownChildHandler import nl.adaptivity.xmlutil.serialization.XML import uy.kohesive.injekt.api.InjektModule import uy.kohesive.injekt.api.InjektRegistrar import uy.kohesive.injekt.api.addSingleton import uy.kohesive.injekt.api.addSingletonFactory import uy.kohesive.injekt.api.get class AppModule(val app: Application) : InjektModule { override fun InjektRegistrar.registerInjectables() { addSingleton(app) addSingletonFactory<SqlDriver> { AndroidSqliteDriver( schema = Database.Schema, context = app, name = "tachiyomi.db", factory = if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // Support database inspector in Android Studio FrameworkSQLiteOpenHelperFactory() } else { RequerySQLiteOpenHelperFactory() }, callback = object : AndroidSqliteDriver.Callback(Database.Schema) { override fun onOpen(db: SupportSQLiteDatabase) { super.onOpen(db) setPragma(db, "foreign_keys = ON") setPragma(db, "journal_mode = WAL") setPragma(db, "synchronous = NORMAL") } private fun setPragma(db: SupportSQLiteDatabase, pragma: String) { val cursor = db.query("PRAGMA $pragma") cursor.moveToFirst() cursor.close() } }, ) } addSingletonFactory { Database( driver = get(), historyAdapter = History.Adapter( last_readAdapter = dateAdapter, ), mangasAdapter = Mangas.Adapter( genreAdapter = listOfStringsAdapter, update_strategyAdapter = updateStrategyAdapter, ), ) } addSingletonFactory<DatabaseHandler> { AndroidDatabaseHandler(get(), get()) } addSingletonFactory { Json { ignoreUnknownKeys = true explicitNulls = false } } addSingletonFactory { XML { unknownChildHandler = UnknownChildHandler { _, _, _, _, _ -> emptyList() } autoPolymorphic = true } } addSingletonFactory { ChapterCache(app) } addSingletonFactory { CoverCache(app) } addSingletonFactory { NetworkHelper(app) } addSingletonFactory { JavaScriptEngine(app) } addSingletonFactory { SourceManager(app, get(), get()) } addSingletonFactory { ExtensionManager(app) } addSingletonFactory { DownloadProvider(app) } addSingletonFactory { DownloadManager(app) } addSingletonFactory { DownloadCache(app) } addSingletonFactory { TrackManager(app) } addSingletonFactory { DelayedTrackingStore(app) } addSingletonFactory { ImageSaver(app) } // Asynchronously init expensive components for a faster cold start ContextCompat.getMainExecutor(app).execute { get<NetworkHelper>() get<SourceManager>() get<Database>() get<DownloadManager>() } } } class PreferenceModule(val application: Application) : InjektModule { override fun InjektRegistrar.registerInjectables() { addSingletonFactory<PreferenceStore> { AndroidPreferenceStore(application) } addSingletonFactory { NetworkPreferences( preferenceStore = get(), verboseLogging = isDevFlavor, ) } addSingletonFactory { SourcePreferences(get()) } addSingletonFactory { SecurityPreferences(get()) } addSingletonFactory { LibraryPreferences(get()) } addSingletonFactory { ReaderPreferences(get()) } addSingletonFactory { TrackPreferences(get()) } addSingletonFactory { AndroidDownloadFolderProvider(application) } addSingletonFactory { DownloadPreferences( folderProvider = get<AndroidDownloadFolderProvider>(), preferenceStore = get(), ) } addSingletonFactory { AndroidBackupFolderProvider(application) } addSingletonFactory { BackupPreferences( folderProvider = get<AndroidBackupFolderProvider>(), preferenceStore = get(), ) } addSingletonFactory { UiPreferences(get()) } addSingletonFactory { BasePreferences(application, get()) } } }
apache-2.0
670873f1e6856c859d63591e4cc59977
36.14433
100
0.654732
5.413974
false
false
false
false
da1z/intellij-community
plugins/java-decompiler/plugin/test/org/jetbrains/java/decompiler/IdeaDecompilerTest.kt
1
9108
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.java.decompiler import com.intellij.JavaTestUtil import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction import com.intellij.execution.filters.LineNumbersMapping import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.ide.structureView.impl.java.JavaAnonymousClassesNodeProvider import com.intellij.ide.structureView.newStructureView.StructureViewComponent import com.intellij.openapi.application.PluginPathManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.vfs.* import com.intellij.pom.Navigatable import com.intellij.psi.PsiManager import com.intellij.psi.impl.compiled.ClsFileImpl import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.intellij.util.io.URLUtil import com.intellij.util.ui.tree.TreeUtil class IdeaDecompilerTest : LightCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.testDataPath = "${PluginPathManager.getPluginHomePath("java-decompiler")}/plugin/testData" } override fun tearDown() { FileEditorManagerEx.getInstanceEx(project).closeAllFiles() for (file in EditorHistoryManager.getInstance(project).files) { EditorHistoryManager.getInstance(project).removeFile(file) } super.tearDown() } fun testSimple() { val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang/String.class") val decompiled = IdeaDecompiler().getText(file).toString() assertTrue(decompiled, decompiled.startsWith("${IdeaDecompiler.BANNER}package java.lang;\n")) assertTrue(decompiled, decompiled.contains("public final class String")) assertTrue(decompiled, decompiled.contains("@deprecated")) assertTrue(decompiled, decompiled.contains("private static class CaseInsensitiveComparator")) assertFalse(decompiled, decompiled.contains("/* compiled code */")) assertFalse(decompiled, decompiled.contains("synthetic")) } fun testStubCompatibility() { val visitor = MyFileVisitor(psiManager) Registry.get("decompiler.dump.original.lines").withValue(true) { VfsUtilCore.visitChildrenRecursively(getTestFile("${JavaTestUtil.getJavaTestDataPath()}/psi/cls/mirror"), visitor) VfsUtilCore.visitChildrenRecursively(getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang"), visitor) } } fun testNavigation() { myFixture.openFileInEditor(getTestFile("Navigation.class")) doTestNavigation(11, 14, 14, 10) // to "m2()" doTestNavigation(15, 21, 14, 17) // to "int i" doTestNavigation(16, 28, 15, 13) // to "int r" } private fun doTestNavigation(line: Int, column: Int, expectedLine: Int, expectedColumn: Int) { val target = GotoDeclarationAction.findTargetElement(project, myFixture.editor, offset(line, column)) as Navigatable target.navigate(true) val expected = offset(expectedLine, expectedColumn) assertEquals(expected, myFixture.caretOffset) } private fun offset(line: Int, column: Int): Int = myFixture.editor.document.getLineStartOffset(line - 1) + column - 1 fun testHighlighting() { myFixture.openFileInEditor(getTestFile("Navigation.class")) IdentifierHighlighterPassFactory.doWithHighlightingEnabled { myFixture.editor.caretModel.moveToOffset(offset(11, 14)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 10)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 17)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 21)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 13)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(16, 28)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(19, 24)) // throws: declaration, m4() call assertEquals(2, myFixture.doHighlighting().size) } } fun testLineNumberMapping() { Registry.get("decompiler.use.line.mapping").withValue(true) { val file = getTestFile("LineNumbers.class") assertNull(file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)) IdeaDecompiler().getText(file) val mapping = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)!! assertEquals(11, mapping.bytecodeToSource(3)) assertEquals(3, mapping.sourceToBytecode(11)) assertEquals(23, mapping.bytecodeToSource(13)) assertEquals(13, mapping.sourceToBytecode(23)) assertEquals(-1, mapping.bytecodeToSource(1000)) assertEquals(-1, mapping.sourceToBytecode(1000)) } } fun testPerformance() { val decompiler = IdeaDecompiler() val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/javax/swing/JTable.class") PlatformTestUtil.startPerformanceTest("decompiling JTable.class", 10000, { decompiler.getText(file) }).assertTiming() } fun testStructureView() { val file = getTestFile("StructureView.class") file.parent.children ; file.parent.refresh(false, true) // inner classes val editor = FileEditorManager.getInstance(project).openFile(file, false)[0] val builder = StructureViewBuilder.PROVIDER.getStructureViewBuilder(StdFileTypes.CLASS, file, project)!! val svc = builder.createStructureView(editor, project) as StructureViewComponent Disposer.register(myFixture.testRootDisposable, svc) svc.setActionActive(JavaAnonymousClassesNodeProvider.ID, true) TreeUtil.expandAll(svc.tree) PlatformTestUtil.assertTreeStructureEquals(svc.tree.model, """ StructureView.java StructureView B B() build(int): StructureView $1 class initializer StructureView() getData(): int setData(int): void data: int""".trimIndent()) } private fun getTestFile(name: String): VirtualFile { val path = if (FileUtil.isAbsolute(name)) name else "${myFixture.testDataPath}/${name}" val fs = if (path.contains(URLUtil.JAR_SEPARATOR)) StandardFileSystems.jar() else StandardFileSystems.local() return fs.refreshAndFindFileByPath(path)!! } private fun RegistryValue.withValue(testValue: Boolean, block: () -> Unit) { val currentValue = asBoolean() try { setValue(testValue) block() } finally { setValue(currentValue) } } private class MyFileVisitor(private val psiManager: PsiManager) : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { if (file.isDirectory) { println(file.path) } else if (file.fileType === StdFileTypes.CLASS && !file.name.contains('$')) { val clsFile = psiManager.findFile(file)!! val mirror = (clsFile as ClsFileImpl).mirror val decompiled = mirror.text assertTrue(file.path, decompiled.startsWith(IdeaDecompiler.BANNER) || file.name == "package-info.class") // check that no mapped line number is on an empty line val prefix = "// " decompiled.split("\n").dropLastWhile(String::isEmpty).toTypedArray().forEach { s -> val pos = s.indexOf(prefix) if (pos == 0 && prefix.length < s.length && Character.isDigit(s[prefix.length])) { fail("Incorrect line mapping in file " + file.path + " line: " + s) } } } else if (ArchiveFileType.INSTANCE == file.fileType) { val jarFile = JarFileSystem.getInstance().getRootByLocal(file) if (jarFile != null) { VfsUtilCore.visitChildrenRecursively(jarFile, this) } } return true } } }
apache-2.0
566dbef0e8568a7adde53d02338d188e
42.793269
121
0.731664
4.630402
false
true
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt
1
12167
package info.nightscout.androidaps.tile import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import androidx.wear.tiles.ActionBuilders import androidx.wear.tiles.ColorBuilders.argb import androidx.wear.tiles.DeviceParametersBuilders.DeviceParameters import androidx.wear.tiles.DeviceParametersBuilders.SCREEN_SHAPE_ROUND import androidx.wear.tiles.DimensionBuilders.SpProp import androidx.wear.tiles.DimensionBuilders.dp import androidx.wear.tiles.DimensionBuilders.sp import androidx.wear.tiles.LayoutElementBuilders.* import androidx.wear.tiles.ModifiersBuilders.Background import androidx.wear.tiles.ModifiersBuilders.Clickable import androidx.wear.tiles.ModifiersBuilders.Corner import androidx.wear.tiles.ModifiersBuilders.Modifiers import androidx.wear.tiles.ModifiersBuilders.Semantics import androidx.wear.tiles.RequestBuilders import androidx.wear.tiles.RequestBuilders.ResourcesRequest import androidx.wear.tiles.ResourceBuilders.AndroidImageResourceByResId import androidx.wear.tiles.ResourceBuilders.ImageResource import androidx.wear.tiles.ResourceBuilders.Resources import androidx.wear.tiles.TileBuilders.Tile import androidx.wear.tiles.TileService import androidx.wear.tiles.TimelineBuilders.Timeline import androidx.wear.tiles.TimelineBuilders.TimelineEntry import com.google.common.util.concurrent.ListenableFuture import dagger.android.AndroidInjection import info.nightscout.androidaps.R import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.weardata.EventData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.guava.future import javax.inject.Inject import kotlin.math.sqrt private const val SPACING_ACTIONS = 3f private const val ICON_SIZE_FRACTION = 0.4f // Percentage of button diameter private const val BUTTON_COLOR = R.color.gray_850 private const val LARGE_SCREEN_WIDTH_DP = 210 interface TileSource { fun getResourceReferences(resources: android.content.res.Resources): List<Int> fun getSelectedActions(): List<Action> fun getValidFor(): Long? } open class Action( val buttonText: String, val buttonTextSub: String? = null, val activityClass: String, @DrawableRes val iconRes: Int, val action: EventData? = null, val message: String? = null, ) enum class WearControl { NO_DATA, ENABLED, DISABLED } abstract class TileBase : TileService() { @Inject lateinit var sp: SP @Inject lateinit var aapsLogger: AAPSLogger abstract val resourceVersion: String abstract val source: TileSource private val serviceJob = Job() private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob) // Not derived from DaggerService, do injection here override fun onCreate() { AndroidInjection.inject(this) super.onCreate() } override fun onTileRequest( requestParams: RequestBuilders.TileRequest ): ListenableFuture<Tile> = serviceScope.future { val actionsSelected = getSelectedActions() val wearControl = getWearControl() val tile = Tile.Builder() .setResourcesVersion(resourceVersion) .setTimeline( Timeline.Builder().addTimelineEntry( TimelineEntry.Builder().setLayout( Layout.Builder().setRoot(layout(wearControl, actionsSelected, requestParams.deviceParameters!!)).build() ).build() ).build() ) val validFor = validFor() if (validFor != null) { tile.setFreshnessIntervalMillis(validFor) } tile.build() } private fun getSelectedActions(): List<Action> { // TODO check why thi scan not be don in scope of the coroutine return source.getSelectedActions() } private fun validFor(): Long? { return source.getValidFor() } @RequiresApi(Build.VERSION_CODES.N) override fun onResourcesRequest( requestParams: ResourcesRequest ): ListenableFuture<Resources> = serviceScope.future { Resources.Builder() .setVersion(resourceVersion) .apply { source.getResourceReferences(resources).forEach { resourceId -> addIdToImageMapping( resourceId.toString(), ImageResource.Builder() .setAndroidResourceByResId( AndroidImageResourceByResId.Builder() .setResourceId(resourceId) .build() ) .build() ) } } .build() } private fun layout(wearControl: WearControl, actions: List<Action>, deviceParameters: DeviceParameters): LayoutElement { if (wearControl == WearControl.DISABLED) { return Text.Builder() .setText(resources.getString(R.string.wear_control_not_enabled)) .build() } else if (wearControl == WearControl.NO_DATA) { return Text.Builder() .setText(resources.getString(R.string.wear_control_no_data)) .build() } if (actions.isNotEmpty()) { with(Column.Builder()) { if (actions.size == 1 || actions.size == 3) { addContent(addRowSingle(actions[0], deviceParameters)) } if (actions.size == 4 || actions.size == 2) { addContent(addRowDouble(actions[0], actions[1], deviceParameters)) } if (actions.size == 3) { addContent(addRowDouble(actions[1], actions[2], deviceParameters)) } if (actions.size == 4) { addContent(Spacer.Builder().setHeight(dp(SPACING_ACTIONS)).build()) addContent(addRowDouble(actions[2], actions[3], deviceParameters)) } return build() } } return Text.Builder() .setText(resources.getString(R.string.tile_no_config)) .build() } private fun addRowSingle(action: Action, deviceParameters: DeviceParameters): LayoutElement = Row.Builder() .addContent(action(action, deviceParameters)) .build() private fun addRowDouble(action1: Action, action2: Action, deviceParameters: DeviceParameters): LayoutElement = Row.Builder() .addContent(action(action1, deviceParameters)) .addContent(Spacer.Builder().setWidth(dp(SPACING_ACTIONS)).build()) .addContent(action(action2, deviceParameters)) .build() private fun doAction(action: Action): ActionBuilders.Action { val builder = ActionBuilders.AndroidActivity.Builder() .setClassName(action.activityClass) .setPackageName(this.packageName) if (action.action != null) { val actionString = ActionBuilders.AndroidStringExtra.Builder().setValue(action.action.serialize()).build() builder.addKeyToExtraMapping(DataLayerListenerServiceWear.KEY_ACTION, actionString) } if (action.message != null) { val message = ActionBuilders.AndroidStringExtra.Builder().setValue(action.message).build() builder.addKeyToExtraMapping(DataLayerListenerServiceWear.KEY_MESSAGE, message) } return ActionBuilders.LaunchAction.Builder() .setAndroidActivity(builder.build()) .build() } private fun action(action: Action, deviceParameters: DeviceParameters): LayoutElement { val circleDiameter = circleDiameter(deviceParameters) val text = action.buttonText val textSub = action.buttonTextSub return Box.Builder() .setWidth(dp(circleDiameter)) .setHeight(dp(circleDiameter)) .setModifiers( Modifiers.Builder() .setBackground( Background.Builder() .setColor(argb(ContextCompat.getColor(baseContext, BUTTON_COLOR))) .setCorner(Corner.Builder().setRadius(dp(circleDiameter / 2)).build()) .build() ) .setSemantics( Semantics.Builder() .setContentDescription("$text $textSub") .build() ) .setClickable( Clickable.Builder() .setOnClick(doAction(action)) .build() ) .build() ) .addContent(addTextContent(action, deviceParameters)) .build() } private fun addTextContent(action: Action, deviceParameters: DeviceParameters): LayoutElement { val circleDiameter = circleDiameter(deviceParameters) val iconSize = dp(circleDiameter * ICON_SIZE_FRACTION) val text = action.buttonText val textSub = action.buttonTextSub val col = Column.Builder() .addContent( Image.Builder() .setWidth(iconSize) .setHeight(iconSize) .setResourceId(action.iconRes.toString()) .build() ).addContent( Text.Builder() .setText(text) .setFontStyle( FontStyle.Builder() .setWeight(FONT_WEIGHT_BOLD) .setColor(argb(ContextCompat.getColor(baseContext, R.color.white))) .setSize(buttonTextSize(deviceParameters, text)) .build() ) .build() ) if (textSub != null) { col.addContent( Text.Builder() .setText(textSub) .setFontStyle( FontStyle.Builder() .setColor(argb(ContextCompat.getColor(baseContext, R.color.white))) .setSize(buttonTextSize(deviceParameters, textSub)) .build() ) .build() ) } return col.build() } private fun circleDiameter(deviceParameters: DeviceParameters) = when (deviceParameters.screenShape) { SCREEN_SHAPE_ROUND -> ((sqrt(2f) - 1) * deviceParameters.screenHeightDp) - (2 * SPACING_ACTIONS) else -> 0.5f * deviceParameters.screenHeightDp - SPACING_ACTIONS } private fun buttonTextSize(deviceParameters: DeviceParameters, text: String): SpProp { if (text.length > 6) { return sp(if (isLargeScreen(deviceParameters)) 14f else 12f) } return sp(if (isLargeScreen(deviceParameters)) 16f else 14f) } private fun isLargeScreen(deviceParameters: DeviceParameters): Boolean { return deviceParameters.screenWidthDp >= LARGE_SCREEN_WIDTH_DP } private fun getWearControl(): WearControl { if (!sp.contains(R.string.key_wear_control)) { return WearControl.NO_DATA } val wearControlPref = sp.getBoolean(R.string.key_wear_control, false) if (wearControlPref) { return WearControl.ENABLED } return WearControl.DISABLED } }
agpl-3.0
e5039ebca0e27627013523d9bce7a819
38.421927
128
0.597436
5.29
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/utils/MediaRetrieveHelper.kt
1
7283
package com.sjn.stamp.utils import android.Manifest import android.content.ContentUris import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.MediaStore import android.support.v4.media.MediaMetadataCompat import android.util.SparseArray import com.google.common.collect.Lists import java.util.* object MediaRetrieveHelper { private const val ALL_MUSIC_SELECTION = MediaStore.Audio.Media.IS_MUSIC + " != 0" private const val SORT_ORDER = MediaStore.Audio.Media.TITLE private val GENRE_PROJECTION = arrayOf(MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID) private val MEDIA_PROJECTION = arrayOf(MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TRACK, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATE_MODIFIED) val PERMISSIONS = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) interface PermissionRequiredCallback { fun onPermissionRequired() } fun allMediaMetadataCompat(context: Context, callback: PermissionRequiredCallback?): List<MediaMetadataCompat> = Lists.transform(retrieveAllMedia(context, callback)) { mediaCursorContainer -> mediaCursorContainer!!.buildMediaMetadataCompat() } fun createIterator(list: List<MediaCursorContainer>): Iterator<MediaMetadataCompat> = Lists.transform(list) { mediaCursorContainer -> mediaCursorContainer!!.buildMediaMetadataCompat() }.iterator() fun hasPermission(context: Context): Boolean = PermissionHelper.hasPermission(context, MediaRetrieveHelper.PERMISSIONS) fun findByMusicId(context: Context, musicId: Long?, callback: PermissionRequiredCallback?): MediaMetadataCompat? { musicId ?: return null if (!MediaRetrieveHelper.hasPermission(context) && callback != null) { callback.onPermissionRequired() return null } context.contentResolver.query(ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, musicId), MEDIA_PROJECTION, ALL_MUSIC_SELECTION, null, null).use { try { if (it?.moveToFirst() == true) { return parseCursor(it, null).buildMediaMetadataCompat() } } catch (e: java.lang.SecurityException) { e.printStackTrace() } } return null } fun findAlbumArtByArtist(context: Context, artist: String, callback: PermissionRequiredCallback?): String? { if (!MediaRetrieveHelper.hasPermission(context) && callback != null) { callback.onPermissionRequired() return null } context.contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART), MediaStore.Audio.Albums.ARTIST + "=?", arrayOf(artist), null).use { try { if (it?.moveToFirst() == true) { return makeAlbumArtUri(it.getLong(it.getColumnIndex(MediaStore.Audio.Albums._ID))).toString() } } catch (e: java.lang.SecurityException) { e.printStackTrace() } } return "" } fun retrieveAllMedia(context: Context, callback: PermissionRequiredCallback?): List<MediaCursorContainer> { val mediaList = ArrayList<MediaCursorContainer>() if (!MediaRetrieveHelper.hasPermission(context) && callback != null) { callback.onPermissionRequired() return mediaList } val genreMap = createGenreMap(context, callback) context.contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MEDIA_PROJECTION, ALL_MUSIC_SELECTION, null, SORT_ORDER).use { try { if (it?.moveToFirst() == true) { do { mediaList.add(parseCursor(it, genreMap)) } while (it.moveToNext()) } } catch (e: java.lang.SecurityException) { e.printStackTrace() } } return mediaList } private fun createGenreMap(context: Context, callback: PermissionRequiredCallback?): SparseArray<String>? { if (!MediaRetrieveHelper.hasPermission(context) && callback != null) { callback.onPermissionRequired() return null } val genreMap = SparseArray<String>() try { context.contentResolver.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, GENRE_PROJECTION, null, null, null).use { if (it?.moveToFirst() == true) { do { genreMap.put(it.getInt(it.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID)), it.getString(it.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME)) ) } while (it.moveToNext()) } } } catch (e: java.lang.SecurityException) { e.printStackTrace() } return genreMap } private fun parseCursor(cursor: Cursor, genreMap: SparseArray<String>?): MediaCursorContainer { val title = cursor.getString(0) val artist = cursor.getString(1) val album = cursor.getString(2) val duration = cursor.getLong(3) //String source = cursor.getString(4); val trackNumber = cursor.getInt(5) val totalTrackCount = cursor.getLong(6) val musicId = cursor.getString(7) val albumId = cursor.getLong(8) val dateAdded = TimeHelper.toRFC3339(cursor.getLong(10)) val source = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, java.lang.Long.valueOf(musicId)!!).toString() val genre = "" /* if (genreMap == null || genreMap.size() == 0) { genre = ""; } else { try { genre = genreMap.get(cursor.getInt(11)); } catch (Exception e) { e.printStackTrace(); } } */ return MediaCursorContainer(musicId, source, album, artist, duration, genre, makeAlbumArtUri(albumId).toString(), title, trackNumber, totalTrackCount, dateAdded) } internal fun makeAlbumArtUri(albumId: Long): Uri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId) class MediaCursorContainer(private var musicId: String, private var source: String, private var album: String, private var artist: String, private var duration: Long, private var genre: String, internal var albumArtUri: String, internal var title: String, private var trackNumber: Int, private var totalTrackCount: Long, private var dateAdded: String) { fun buildMediaMetadataCompat(): MediaMetadataCompat = MediaItemHelper.createMetadata(musicId, source, album, artist, genre, duration, albumArtUri, title, trackNumber.toLong(), totalTrackCount, dateAdded) } }
apache-2.0
f13be34f3027a95d3565e103f0448c24
45.987097
390
0.652204
4.920946
false
false
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/data/Category.kt
1
1882
package com.rolandvitezhu.todocloud.data import android.database.Cursor import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Entity(tableName = "category") @Parcelize data class Category ( @PrimaryKey(autoGenerate = true) var _id: Long?, @ColumnInfo(name = "category_online_id") @SerializedName("category_online_id") var categoryOnlineId: String?, @ColumnInfo(name = "user_online_id") @SerializedName("user_online_id") var userOnlineId: String?, @ColumnInfo(name = "title") @SerializedName("title") var title: String = "", @ColumnInfo(name = "row_version") @SerializedName("row_version") var rowVersion: Int = 0, @ColumnInfo(name = "deleted") @SerializedName("deleted") var deleted: Boolean? = false, @ColumnInfo(name = "dirty") var dirty: Boolean = false, @ColumnInfo(name = "position") @SerializedName("position") var position: Double = 5.0, @Ignore var isSelected: Boolean = false ) : Parcelable { constructor() : this("") constructor(title: String) : this( null, null, null, title, 0, false, false, 5.0 ) constructor(cursor: Cursor) : this( cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(4), cursor.getInt(5) != 0, cursor.getInt(6) != 0, if (cursor.getDouble(7) == 0.0) 5.0 else cursor.getDouble(7) ) override fun toString(): String { return title } }
mit
0cf4ef12fb2fa0a2c26f26c441c45e9f
27.969231
68
0.592986
4.248307
false
false
false
false
android/architecture-components-samples
GithubBrowserSample/app/src/main/java/com/android/example/github/ui/search/SearchViewModel.kt
1
5071
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.github.ui.search import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import com.android.example.github.repository.RepoRepository import com.android.example.github.testing.OpenForTesting import com.android.example.github.util.AbsentLiveData import com.android.example.github.vo.Repo import com.android.example.github.vo.Resource import com.android.example.github.vo.Status import java.util.Locale import javax.inject.Inject @OpenForTesting class SearchViewModel @Inject constructor(repoRepository: RepoRepository) : ViewModel() { private val _query = MutableLiveData<String>() private val nextPageHandler = NextPageHandler(repoRepository) val query : LiveData<String> = _query val results: LiveData<Resource<List<Repo>>> = _query.switchMap { search -> if (search.isBlank()) { AbsentLiveData.create() } else { repoRepository.search(search) } } val loadMoreStatus: LiveData<LoadMoreState> get() = nextPageHandler.loadMoreState fun setQuery(originalInput: String) { val input = originalInput.toLowerCase(Locale.getDefault()).trim() if (input == _query.value) { return } nextPageHandler.reset() _query.value = input } fun loadNextPage() { _query.value?.let { if (it.isNotBlank()) { nextPageHandler.queryNextPage(it) } } } fun refresh() { _query.value?.let { _query.value = it } } class LoadMoreState(val isRunning: Boolean, val errorMessage: String?) { private var handledError = false val errorMessageIfNotHandled: String? get() { if (handledError) { return null } handledError = true return errorMessage } } class NextPageHandler(private val repository: RepoRepository) : Observer<Resource<Boolean>> { private var nextPageLiveData: LiveData<Resource<Boolean>>? = null val loadMoreState = MutableLiveData<LoadMoreState>() private var query: String? = null private var _hasMore: Boolean = false val hasMore get() = _hasMore init { reset() } fun queryNextPage(query: String) { if (this.query == query) { return } unregister() this.query = query nextPageLiveData = repository.searchNextPage(query) loadMoreState.value = LoadMoreState( isRunning = true, errorMessage = null ) nextPageLiveData?.observeForever(this) } override fun onChanged(result: Resource<Boolean>?) { if (result == null) { reset() } else { when (result.status) { Status.SUCCESS -> { _hasMore = result.data == true unregister() loadMoreState.setValue( LoadMoreState( isRunning = false, errorMessage = null ) ) } Status.ERROR -> { _hasMore = true unregister() loadMoreState.setValue( LoadMoreState( isRunning = false, errorMessage = result.message ) ) } Status.LOADING -> { // ignore } } } } private fun unregister() { nextPageLiveData?.removeObserver(this) nextPageLiveData = null if (_hasMore) { query = null } } fun reset() { unregister() _hasMore = true loadMoreState.value = LoadMoreState( isRunning = false, errorMessage = null ) } } }
apache-2.0
15c2912199ae3969bbc7e6f929978aea
30.110429
97
0.540919
5.429336
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/ParserPatterns.kt
1
4831
package forpdateam.ru.forpda.model.data.remote object ParserPatterns { object Global { const val scope = "global" const val meta_tags = "meta_tags" } object Auth { const val scope = "auth"; const val captcha = "captcha"; const val check_login = "check_login"; const val errors_list = "errors_list"; } object DevDb { const val scope = "devdb"; const val main_root = "main_root"; const val main_breadcrumb = "main_breadcrumb"; const val main_specs = "main_specs"; const val main_search = "main_search"; const val brand_devices = "brand_devices"; const val brands_letters = "brands_letters"; const val brands_items_in_letter = "brands_items_in_letter"; const val device_head = "device_head"; const val device_images = "device_images"; const val device_specs_titled = "device_specs_titled"; const val device_reviews = "device_reviews"; const val device_discuss_and_firm = "device_discuss_and_firm"; const val device_discussions = "device_discussions"; const val device_firmwares = "device_firmwares"; const val device_comments = "device_comments"; } object EditPost { const val scope = "editpost"; const val form = "form"; const val poll_info = "poll_info"; const val poll_fucking_invalid_json = "poll_fucking_invalid_json"; const val attachments = "attachments"; } object Favorites { const val scope = "favorites"; const val main = "main"; const val check_action = "check_action"; } object Forum { const val scope = "forum"; const val rules_headers = "rules_headers"; const val rules_items = "rules_items"; const val announce = "announce"; const val forums_from_search = "forums_from_search"; const val forum_item_from_search = "forum_item_from_search"; } object Mentions { const val scope = "mentions"; const val main = "main"; } object Articles { const val scope = "articles"; const val list = "list"; const val detail = "detail"; const val detail_v2 = "detail_v2"; const val detail_detector = "detail_detector"; const val exclude_form_comment = "exclude_form_comment"; const val tags = "tags"; const val materials = "materials"; const val karma = "karma"; const val karmaSource = "karmaSource"; const val comment_id = "comment_id"; const val comment_user_id = "comment_user_id"; } object Profile { const val scope = "profile"; const val main = "main"; const val info = "info"; const val personal = "personal"; const val contacts = "contacts"; const val devices = "devices"; const val site_stats = "site_stats"; const val forum_stats = "forum_stats"; const val note = "note"; const val about = "about"; const val warnings = "warnings"; } object Qms { const val scope = "qms"; const val contacts_main = "contacts_main"; const val thread_main = "thread_main"; const val thread_nick = "thread_nick"; const val chat_info = "chat_info"; const val chat_pattern = "chat_pattern"; const val blacklist_main = "blacklist_main"; const val blacklist_msg = "blacklist_msg"; const val finduser = "finduser"; const val send_message_error = "send_message_error"; const val message_info = "message_info"; } object Reputation { const val scope = "reputation"; const val main = "main"; const val info = "info"; } object Search { const val scope = "search"; const val articles = "articles"; const val forum_topics = "forum_topics"; const val forum_posts = "forum_posts"; } object Topic { const val scope = "topic"; const val posts = "posts"; const val title = "title"; const val already_in_fav = "already_in_fav"; const val fav_id = "fav_id"; const val topic_id = "topic_id"; const val scroll_anchor = "scroll_anchor"; const val poll_main = "poll_main"; const val poll_questions = "poll_questions"; const val poll_question_item = "poll_question_item"; const val poll_buttons = "poll_buttons"; const val attached_images = "attached_images"; } object Topics { const val scope = "topics"; const val title = "title"; const val can_new_topic = "can_new_topic"; const val announce = "announce"; const val forum = "forum"; const val topics = "topics"; } }
gpl-3.0
1bdb33b1e92d2f26f047f324a111a1db
32.555556
74
0.584144
4.111489
false
false
false
false
NCBSinfo/NCBSinfo
app/src/main/java/com/rohitsuratekar/NCBSinfo/viewmodels/ManageTransportViewModel.kt
2
6156
package com.rohitsuratekar.NCBSinfo.viewmodels import android.os.AsyncTask import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.rohitsuratekar.NCBSinfo.database.CheckRoutes import com.rohitsuratekar.NCBSinfo.database.OnFinishRetrieving import com.rohitsuratekar.NCBSinfo.di.Repository import com.rohitsuratekar.NCBSinfo.models.Route class ManageTransportViewModel : ViewModel() { val routeList = MutableLiveData<List<Route>>() val routeDeleted = MutableLiveData<List<Route>>() val lastModified = MutableLiveData<String>() val favoriteChanged = MutableLiveData<Boolean>() fun getRouteList(repository: Repository) { GetData(repository, object : OnDataRetrieved { override fun lastModified(date: String) {} override fun resetRoutes() {} override fun routeDeleted(data: List<Route>) {} override fun updateRoutes(data: List<Route>) { routeList.postValue(data) } }).execute() } fun resetRoutes(repository: Repository) { ResetRoutes(repository, object : OnDataRetrieved { override fun lastModified(date: String) {} override fun updateRoutes(data: List<Route>) {} override fun routeDeleted(data: List<Route>) {} override fun resetRoutes() { remakeRoutes(repository) } }).execute() } fun getLastUpdate(repository: Repository) { LastUpdateFromData(repository, object : OnDataRetrieved { override fun updateRoutes(data: List<Route>) { } override fun routeDeleted(data: List<Route>) { } override fun lastModified(date: String) { lastModified.postValue(date) } override fun resetRoutes() { } }).execute() } private fun remakeRoutes(repository: Repository) { CheckRoutes( repository, object : OnFinishRetrieving { override fun returnRoutes(routeList: List<Route>) { routeDeleted.postValue(routeList) } override fun dataLoadFinished() {} override fun changeStatus(statusNote: String) {} }).execute() } fun deleteRoute(repository: Repository, route: Route) { DeleteRoute(repository, route, object : OnDataRetrieved { override fun resetRoutes() { remakeRoutes(repository) } override fun lastModified(date: String) {} override fun updateRoutes(data: List<Route>) {} override fun routeDeleted(data: List<Route>) { routeDeleted.postValue(data) } }).execute() } fun updateFavorite(repository: Repository, route: Route) { UpdateFavorite(repository, route, object : OnDataRetrieved { override fun updateRoutes(data: List<Route>) { } override fun routeDeleted(data: List<Route>) { } override fun lastModified(date: String) { favoriteChanged.postValue(true) } override fun resetRoutes() { } }).execute() } class UpdateFavorite( private val repository: Repository, private val route: Route, private val listener: OnDataRetrieved ) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { repository.data().changeFavoriteRoute(route.routeData) listener.lastModified("--:--") return null } } class LastUpdateFromData(private val repository: Repository, private val listener: OnDataRetrieved) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { listener.lastModified(repository.data().lastModifiedOn()) return null } } class GetData(private val repository: Repository, private val listener: OnDataRetrieved) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { val routeList = repository.data().getAllRoutes() val returnList = mutableListOf<Route>() for (r in routeList) { returnList.add(Route(r, repository.data().getTrips(r)).apply { isFavorite = r.favorite == "yes" }) } listener.updateRoutes(returnList) return null } } class ResetRoutes(private val repository: Repository, private val listener: OnDataRetrieved) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { repository.data().deleteAll() listener.resetRoutes() return null } } class DeleteRoute( private val repository: Repository, private val route: Route, private val listener: OnDataRetrieved ) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { repository.data().deleteRoute(route.routeData) val routeList = repository.data().getAllRoutes() if (routeList.isEmpty()) { listener.resetRoutes() } else { val returnList = mutableListOf<Route>() for (r in routeList) { returnList.add(Route(r, repository.data().getTrips(r))) } listener.routeDeleted(returnList) } return null } } interface OnDataRetrieved { fun updateRoutes(data: List<Route>) fun routeDeleted(data: List<Route>) fun lastModified(date: String) fun resetRoutes() } }
mit
7d32f7879304a7e8cb162b8d0dfbc1fb
29.10101
105
0.568551
5.521076
false
false
false
false
fengzhizi715/SAF-Kotlin-Utils
saf-kotlin-utils/src/main/java/com/safframework/utils/FileUtils.kt
1
1098
package com.safframework.utils import java.io.File import java.io.IOException /** * Created by Tony Shen on 2017/1/20. */ fun exists(file: File?) = file != null && file.exists() /** * 判断是否文件 * @param file * * @return */ fun isFile(file: File) = exists(file) && file.isFile /** * 判断是否目录 * @param file * * @return */ fun isDirectory(file: File) = exists(file) && file.isDirectory /** * 判断目录是否存在,不存在则判断是否创建成功 * * @param file 文件 * @return boolean */ fun createOrExistsDir(file: File?) = (file != null) && if (file.exists()) file.isDirectory else file.mkdirs() /** * 判断文件是否存在,不存在则判断是否创建成功 * * @param file 文件 * @return boolean */ fun createOrExistsFile(file: File?): Boolean { if (file == null || !createOrExistsDir(file.parentFile)) { return false } if (file.exists()) { return file.isFile } try { return file.createNewFile() } catch (e: IOException) { e.printStackTrace() return false } }
apache-2.0
dc8854afd5a2673af732100e5b642df9
16.854545
109
0.615071
3.262458
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/RequirePasswordDialog.kt
1
3587
/* * Copyright (c) 2013, Yubico AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.yubico.yubioath.ui import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import android.view.LayoutInflater import com.yubico.yubioath.R import kotlinx.android.synthetic.main.dialog_require_password.view.* class RequirePasswordDialog : DialogFragment() { companion object { private const val MISSING = "missing" internal fun newInstance(missing: Boolean, onNewPassword:(String, Boolean) -> Unit): RequirePasswordDialog { return RequirePasswordDialog().apply { arguments = Bundle().apply { putBoolean(MISSING, missing) } setOnNewPassword(onNewPassword) } } } private lateinit var onNewPassword: (String, Boolean) -> Unit private fun setOnNewPassword(handler:(String, Boolean) -> Unit) { onNewPassword = handler } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return arguments!!.let { val missing = it.getBoolean(MISSING) val view = LayoutInflater.from(context).inflate(R.layout.dialog_require_password, null) AlertDialog.Builder(activity).apply { setView(view) setTitle(if (missing) R.string.password_required else R.string.password_wrong) setPositiveButton(R.string.ok, null) // To be able to cancel dismissing the dialog we use the onClick listener set in the onShowListener... setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() } }.create().apply { setOnShowListener { getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val password = view.password.text.toString() val remember = view.rememberPassword.isChecked if (password.isNotEmpty()) { onNewPassword(password, remember) dismiss() } else { view.password_wrapper.error = getString(R.string.password_required) } } } } } } }
bsd-2-clause
59fb8d67d2ca7d08b4ced91232f697f1
41.702381
155
0.668525
4.927198
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddReturnToLastExpressionInFunctionFix.kt
1
2792
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class AddReturnToLastExpressionInFunctionFix(element: KtDeclarationWithBody) : KotlinQuickFixAction<KtDeclarationWithBody>(element) { private val available: Boolean init { val namedFunction = element as? KtNamedFunction val block = namedFunction?.bodyBlockExpression val last = block?.statements?.lastOrNull() available = last?.analyze(BodyResolveMode.PARTIAL)?.let { context -> last.getType(context)?.takeIf { !it.isError } }?.let { lastType -> val expectedType = namedFunction.resolveToDescriptorIfAny()?.returnType?.takeIf { !it.isError } ?: return@let false lastType.isSubtypeOf(expectedType) } ?: false } override fun getText() = KotlinBundle.message("fix.add.return.last.expression") override fun getFamilyName() = text override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = (element is KtNamedFunction) && available override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element as? KtNamedFunction ?: return val last = element.bodyBlockExpression?.statements?.lastOrNull() ?: return last.replace(KtPsiFactory(project).createExpression("return ${last.text}")) } companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val casted = Errors.NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY.cast(diagnostic) return AddReturnToLastExpressionInFunctionFix(casted.psiElement).takeIf(AddReturnToLastExpressionInFunctionFix::available) } } }
apache-2.0
62a3b5a6bf82edb80ece713067d80e04
47.982456
158
0.76361
4.83045
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/HistoryShort.kt
1
785
package org.snakeskin.utility.value class HistoryShort(initialValue: Short = Short.MIN_VALUE) { var last = initialValue @Synchronized get private set var current = initialValue @Synchronized get private set @Synchronized fun update(newValue: Short) { last = current current = newValue } /** * Returns true if the value changed from its previous value since the last call to "update" */ fun changed(): Boolean { return current != last } //Numeric operations /** * Returns the difference between the current value and the last value * Returns an Int, as short subtraction in Kotlin returns an Int */ fun delta(): Int { return current - last } }
gpl-3.0
853e902bafa8e32cda51025ca51a636d
22.117647
96
0.620382
4.968354
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/add/TargetValuePickerDialogController.kt
1
11387
package io.ipoli.android.challenge.add import android.annotation.SuppressLint import android.os.Bundle import android.support.v7.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import io.ipoli.android.Constants import io.ipoli.android.R import io.ipoli.android.challenge.add.TargetValuePickerViewState.StateType.* import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.Validator import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.ReduxDialogController import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.PetAvatar import kotlinx.android.synthetic.main.dialog_target_value_picker.view.* import kotlinx.android.synthetic.main.view_dialog_header.view.* import org.threeten.bp.LocalDate import java.util.* sealed class TargetValuePickerAction : Action { data class Load(val trackedValue: Challenge.TrackedValue.Target?) : TargetValuePickerAction() data class Select( val name: String, val targetValue: String, val units: String, val startValue: String, val accumulateValues: Boolean ) : TargetValuePickerAction() } object TargetValuePickerReducer : BaseViewStateReducer<TargetValuePickerViewState>() { override fun reduce( state: AppState, subState: TargetValuePickerViewState, action: Action ) = when (action) { is TargetValuePickerAction.Load -> { val trackedValueState = action.trackedValue?.let { subState.copy( id = it.id, name = it.name, targetValue = it.targetValue, units = it.units, startValue = it.startValue, isCumulative = it.isCumulative, allowChangeCumulative = false ) } ?: subState state.dataState.player?.let { trackedValueState.copy( type = DATA_LOADED, petAvatar = it.pet.avatar ) } ?: trackedValueState.copy( type = LOADING ) } is DataLoadedAction.PlayerChanged -> subState.copy( type = if (subState.type == LOADING) DATA_LOADED else PET_CHANGED, petAvatar = action.player.pet.avatar ) is TargetValuePickerAction.Select -> { val errors = Validator.validate(action).check<ValidationError> { "name" { given { name.isBlank() } addError ValidationError.EMPTY_NAME } "value format" { given { targetValue.toDoubleOrNull() == null || targetValue.toDouble() < 0 } addError ValidationError.INCORRECT_VALUE_FORMAT } "units" { given { units.isBlank() } addError ValidationError.EMPTY_UNITS } "starting value format" { given { startValue.toDoubleOrNull() == null || startValue.toDouble() < 0 } addError ValidationError.INCORRECT_START_VALUE_FORMAT } "accumulate value" { given { val startVal = startValue.toDoubleOrNull() val targetVal = targetValue.toDoubleOrNull() if (!accumulateValues || startVal == null || targetVal == null) { false } else { startVal >= targetVal } } addError ValidationError.ACCUMULATE_TARGET_BEFORE_START } } if (errors.isNotEmpty()) { subState.copy( type = VALIDATION_ERROR, errors = errors.toSet() ) } else { subState.copy( type = TRACKED_VALUE_CHOSEN, trackedValue = Challenge.TrackedValue.Target( id = subState.id ?: UUID.randomUUID().toString(), name = action.name, units = action.units, startValue = action.startValue.toDouble(), targetValue = action.targetValue.toDouble(), currentValue = 0.0, remainingValue = 0.0, isCumulative = if (subState.allowChangeCumulative) action.accumulateValues else subState.isCumulative, history = emptyMap<LocalDate, Challenge.TrackedValue.Log>().toSortedMap() ) ) } } else -> subState } override fun defaultState() = TargetValuePickerViewState( type = LOADING, petAvatar = null, id = null, name = null, targetValue = null, units = null, startValue = null, isCumulative = false, allowChangeCumulative = true, errors = emptySet(), trackedValue = null ) override val stateKey = key<TargetValuePickerViewState>() enum class ValidationError { EMPTY_NAME, INCORRECT_VALUE_FORMAT, EMPTY_UNITS, INCORRECT_START_VALUE_FORMAT, ACCUMULATE_TARGET_BEFORE_START } } data class TargetValuePickerViewState( val type: StateType, val petAvatar: PetAvatar?, val id: String?, val name: String?, val targetValue: Double?, val units: String?, val startValue: Double?, val isCumulative: Boolean, val allowChangeCumulative: Boolean, val errors: Set<TargetValuePickerReducer.ValidationError>, val trackedValue: Challenge.TrackedValue.Target? ) : BaseViewState() { enum class StateType { LOADING, DATA_LOADED, PET_CHANGED, VALIDATION_ERROR, TRACKED_VALUE_CHOSEN } } open class TextWatcherAdapter(private val afterTextChangedCallback: (Editable) -> Unit = {}) : TextWatcher { override fun afterTextChanged(s: Editable) { afterTextChangedCallback(s) } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } } class TargetValuePickerDialogController(args: Bundle? = null) : ReduxDialogController<TargetValuePickerAction, TargetValuePickerViewState, TargetValuePickerReducer>( args ) { private var trackedValueSelectedListener: (Challenge.TrackedValue.Target) -> Unit = {} private var cancelListener: () -> Unit = {} private var editTrackedValue: Challenge.TrackedValue.Target? = null override val reducer = TargetValuePickerReducer constructor( trackedValueSelectedListener: (Challenge.TrackedValue.Target) -> Unit, cancelListener: () -> Unit = {}, trackedValue: Challenge.TrackedValue.Target? = null ) : this() { this.trackedValueSelectedListener = trackedValueSelectedListener this.cancelListener = cancelListener this.editTrackedValue = trackedValue } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View = inflater.inflate(R.layout.dialog_target_value_picker, null) override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog = dialogBuilder .setPositiveButton(R.string.track_value, null) .setNegativeButton(R.string.cancel, null) .create() override fun onHeaderViewCreated(headerView: View) { headerView.dialogHeaderTitle.setText(R.string.dialog_target_value_picker_title) } override fun onCreateLoadAction() = TargetValuePickerAction.Load(editTrackedValue) override fun onDialogCreated(dialog: AlertDialog, contentView: View) { dialog.setOnShowListener { setPositiveButtonListener { dispatch( TargetValuePickerAction.Select( name = contentView.valueName.text.toString(), targetValue = contentView.valueReach.text.toString(), units = contentView.valueUnit.text.toString(), startValue = contentView.valueStart.text.toString(), accumulateValues = contentView.valueCumulativeSwitch.isChecked ) ) } setNeutralButtonListener { cancelListener() dismiss() } } } override fun render(state: TargetValuePickerViewState, view: View) { when (state.type) { DATA_LOADED -> { view.dialogContainer.requestFocus() state.petAvatar?.let { changeIcon(AndroidPetAvatar.valueOf(it.name).headImage) } state.name?.let { view.valueName.setText(it) view.valueReach.setText( Constants.DECIMAL_FORMATTER.format(state.targetValue!!) ) view.valueUnit.setText(state.units!!) view.valueStart.setText(Constants.DECIMAL_FORMATTER.format(state.startValue!!)) view.valueCumulativeSwitch.isChecked = state.isCumulative } view.valueCumulativeSwitch.isClickable = state.allowChangeCumulative } PET_CHANGED -> changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage) VALIDATION_ERROR -> state.errors.forEach { when (it) { TargetValuePickerReducer.ValidationError.EMPTY_NAME -> view.valueName.error = "Name is required" TargetValuePickerReducer.ValidationError.INCORRECT_VALUE_FORMAT -> view.valueReach.error = "Set target number" TargetValuePickerReducer.ValidationError.EMPTY_UNITS -> view.valueUnit.error = "Units are required" TargetValuePickerReducer.ValidationError.INCORRECT_START_VALUE_FORMAT -> view.valueStart.error = "Set start number" TargetValuePickerReducer.ValidationError.ACCUMULATE_TARGET_BEFORE_START -> view.valueReach.error = "Target value can't be smaller than start value" } } TRACKED_VALUE_CHOSEN -> { trackedValueSelectedListener(state.trackedValue!!) dismiss() } else -> { } } } }
gpl-3.0
fed87e0e0868a594da494505f69d03ad
35.383387
126
0.576183
5.707769
false
false
false
false
GunoH/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/quickfix/GradleVersionQuickFix.kt
2
7654
// 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.gradle.issue.quickfix import com.intellij.build.SyncViewManager import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.ide.actions.ShowLogAction import com.intellij.notification.NotificationGroupManager import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix.Companion.requestImport import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration.PROGRESS_LISTENER_KEY import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode.IN_BACKGROUND_ASYNC import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager import com.intellij.openapi.externalSystem.service.notification.NotificationCategory.WARNING import com.intellij.openapi.externalSystem.service.notification.NotificationData import com.intellij.openapi.externalSystem.service.notification.NotificationSource.PROJECT_SYNC import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemUtil.runTask import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.util.TimeoutUtil import com.intellij.util.io.createFile import com.intellij.util.io.inputStream import com.intellij.util.io.outputStream import org.gradle.internal.impldep.com.google.common.base.Charsets import org.gradle.internal.util.PropertiesUtils import org.gradle.util.GradleVersion import org.gradle.wrapper.WrapperExecutor import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.issue.quickfix.GradleWrapperSettingsOpenQuickFix.Companion.showWrapperPropertiesFile import org.jetbrains.plugins.gradle.service.task.GradleTaskManager import org.jetbrains.plugins.gradle.settings.DistributionType import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleBundle import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleUtil import java.nio.file.Paths import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture /** * @author Vladislav.Soroka */ @ApiStatus.Experimental class GradleVersionQuickFix(private val projectPath: String, private val gradleVersion: GradleVersion, private val requestImport: Boolean) : BuildIssueQuickFix { override val id: String = "fix_gradle_version_in_wrapper" override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { return updateOrCreateWrapper() .exceptionally { LOG.warn(it) val title = GradleBundle.message("gradle.version.quick.fix.error") val message = GradleBundle.message("gradle.version.quick.fix.error.description", ShowLogAction.getActionName()) val notification = NotificationData(title, message, WARNING, PROJECT_SYNC) .apply { isBalloonNotification = true balloonGroup = NotificationGroupManager.getInstance().getNotificationGroup("Gradle Wrapper Update") setListener("#open_log") { _, _ -> ShowLogAction.showLog() } } ExternalSystemNotificationManager.getInstance(project).showNotification(GradleConstants.SYSTEM_ID, notification) throw it } .thenApply { GradleSettings.getInstance(project).getLinkedProjectSettings(projectPath)!!.distributionType = DistributionType.DEFAULT_WRAPPED } .thenComposeAsync { runWrapperTask(project) } .thenApply { showWrapperPropertiesFile(project, projectPath, gradleVersion.version) } .thenComposeAsync { when { requestImport -> { TimeoutUtil.sleep(500) // todo remove when multiple-build view will be integrated into the BuildTreeConsoleView return@thenComposeAsync requestImport(project, projectPath, GradleConstants.SYSTEM_ID) } else -> return@thenComposeAsync completedFuture(null) } } } private fun updateOrCreateWrapper(): CompletableFuture<*> { return CompletableFuture.supplyAsync { val wrapperProperties: Properties var wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(projectPath) val distributionUrl = "https://services.gradle.org/distributions/gradle-${gradleVersion.version}-bin.zip" if (wrapperPropertiesFile == null) { val wrapperPropertiesPath = Paths.get(projectPath, "gradle", "wrapper", "gradle-wrapper.properties") wrapperPropertiesPath.createFile() wrapperPropertiesFile = wrapperPropertiesPath wrapperProperties = Properties() wrapperProperties[WrapperExecutor.DISTRIBUTION_URL_PROPERTY] = distributionUrl wrapperProperties[WrapperExecutor.DISTRIBUTION_BASE_PROPERTY] = "GRADLE_USER_HOME" wrapperProperties[WrapperExecutor.DISTRIBUTION_PATH_PROPERTY] = "wrapper/dists" wrapperProperties[WrapperExecutor.ZIP_STORE_BASE_PROPERTY] = "GRADLE_USER_HOME" wrapperProperties[WrapperExecutor.ZIP_STORE_PATH_PROPERTY] = "wrapper/dists" } else { wrapperProperties = wrapperPropertiesFile.inputStream().use { stream -> Properties().also { it.load(stream) } } wrapperProperties[WrapperExecutor.DISTRIBUTION_URL_PROPERTY] = distributionUrl } wrapperPropertiesFile?.outputStream().use { out -> PropertiesUtils.store(wrapperProperties, out, null as String?, Charsets.ISO_8859_1, "\n") } LocalFileSystem.getInstance().refreshNioFiles(listOf(wrapperPropertiesFile)) } } private fun runWrapperTask(project: Project): CompletableFuture<Nothing> { val userData = UserDataHolderBase() val initScript = "gradle.projectsEvaluated { g ->\n" + " def wrapper = g.rootProject.tasks.wrapper\n" + " if (wrapper == null) return \n" + " wrapper.gradleVersion = '" + gradleVersion.version + "'\n" + "}\n" userData.putUserData(GradleTaskManager.INIT_SCRIPT_KEY, initScript) userData.putUserData(PROGRESS_LISTENER_KEY, SyncViewManager::class.java) val gradleVmOptions = GradleSettings.getInstance(project).gradleVmOptions val settings = ExternalSystemTaskExecutionSettings() settings.executionName = GradleBundle.message("grable.execution.name.upgrade.wrapper") settings.externalProjectPath = projectPath settings.taskNames = listOf("wrapper") settings.vmOptions = gradleVmOptions settings.externalSystemIdString = GradleConstants.SYSTEM_ID.id val future = CompletableFuture<Nothing>() runTask(settings, DefaultRunExecutor.EXECUTOR_ID, project, GradleConstants.SYSTEM_ID, object : TaskCallback { override fun onSuccess() { future.complete(null) } override fun onFailure() { future.completeExceptionally(RuntimeException("Wrapper task failed")) } }, IN_BACKGROUND_ASYNC, false, userData) return future } companion object { private val LOG = logger<GradleVersionQuickFix>() } }
apache-2.0
866bf352cc17efbfb47754000065b20d
49.355263
135
0.753593
5.052145
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/learnIde/LearnIdeContentPanel.kt
1
8061
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.welcomeScreen.learnIde import com.intellij.icons.AllIcons.Ide.External_link_arrow import com.intellij.ide.IdeBundle import com.intellij.ide.actions.HelpTopicsAction import com.intellij.ide.actions.JetBrainsTvAction import com.intellij.ide.actions.OnlineDocAction import com.intellij.ide.actions.WhatsNewAction import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.wm.InteractiveCourseFactory import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeScreenUIManager import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.LearnIdeContentColorsAndFonts.HeaderColor import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.edutools.EduToolsInteractiveCoursePanel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Component import java.awt.Dimension import java.awt.Rectangle import javax.swing.* import javax.swing.plaf.ComponentUI class LearnIdeContentPanel(private val parentDisposable: Disposable) : JPanel() { //unscalable insets private val unscalable24px = 24 private val interactiveCoursesPanel: JPanel = JPanel() private val helpAndResourcesPanel: JPanel = JPanel() private val contentPanel: JPanel = JPanel() private val myScrollPane: JBScrollPane = JBScrollPane(contentPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER).apply { border = JBUI.Borders.empty() } private val interactiveCoursesHeader: JTextPane = HeightLimitedPane(IdeBundle.message("welcome.screen.learnIde.interactive.courses.text"), 5, HeaderColor, true) private val helpAndResourcesHeader: JTextPane = HeightLimitedPane(IdeBundle.message("welcome.screen.learnIde.help.and.resources.text"), 5, HeaderColor, true) init { layout = BorderLayout() isFocusable = false isOpaque = true background = WelcomeScreenUIManager.getProjectsBackground() contentPanel.apply { layout = BorderLayout() border = JBUI.Borders.empty(unscalable24px) background = WelcomeScreenUIManager.getProjectsBackground() } val interactiveCoursesExtensions = InteractiveCourseFactory.INTERACTIVE_COURSE_FACTORY_EP.extensions initInteractiveCoursesPanel(interactiveCoursesExtensions) initHelpAndResourcePanel() if (interactiveCoursesExtensions.isEmpty()) { contentPanel.add(helpAndResourcesPanel, BorderLayout.CENTER) } else { contentPanel.add(helpAndResourcesPanel, BorderLayout.SOUTH) } //set LearnPanel UI add(myScrollPane, BorderLayout.CENTER) contentPanel.bounds = Rectangle(contentPanel.location, contentPanel.preferredSize) revalidate() repaint() } private fun initHelpAndResourcePanel() { helpAndResourcesPanel.apply { layout = BoxLayout(this, BoxLayout.PAGE_AXIS) isOpaque = false add(helpAndResourcesHeader) add(rigid(0, 1)) addHelpActions() } } private fun initInteractiveCoursesPanel(interactiveCoursesExtensions: Array<InteractiveCourseFactory>) { updateInteractiveCoursesPanel(interactiveCoursesExtensions) InteractiveCourseFactory.INTERACTIVE_COURSE_FACTORY_EP.addExtensionPointListener( object : ExtensionPointListener<InteractiveCourseFactory> { override fun extensionAdded(extension: InteractiveCourseFactory, pluginDescriptor: PluginDescriptor) { updateInteractiveCoursesPanel(interactiveCoursesExtensions) } override fun extensionRemoved(extension: InteractiveCourseFactory, pluginDescriptor: PluginDescriptor) { updateInteractiveCoursesPanel(interactiveCoursesExtensions) } }, parentDisposable) } private fun updateInteractiveCoursesPanel(interactiveCoursesExtensions: Array<InteractiveCourseFactory>) { //clear before interactiveCoursesPanel.removeAll() contentPanel.remove(interactiveCoursesPanel) interactiveCoursesPanel.layout = BoxLayout(interactiveCoursesPanel, BoxLayout.LINE_AXIS) interactiveCoursesPanel.isOpaque = false val coursesList = interactiveCoursesExtensions.mapNotNull { it.getInteractiveCourseData() } if (coursesList.isNotEmpty()) { var actionButton: JButton? = null for (interactiveCourse in coursesList) { val interactiveCoursePanel = if (interactiveCourse.isEduTools()) { EduToolsInteractiveCoursePanel(interactiveCourse) } else { InteractiveCoursePanel(interactiveCourse) } interactiveCoursesPanel.add(interactiveCoursePanel) interactiveCoursesPanel.add((rigid(12, 6))) if (actionButton == null) actionButton = interactiveCoursePanel.startLearningButton } contentPanel.add(interactiveCoursesHeader, BorderLayout.NORTH) contentPanel.add(interactiveCoursesPanel, BorderLayout.CENTER) } revalidate() repaint() } private fun addHelpActions() { val whatsNewAction = WhatsNewAction() if (emptyWelcomeScreenEventFromAction(whatsNewAction).presentation.isEnabled) { helpAndResourcesPanel.add(linkLabelByAction(WhatsNewAction())) helpAndResourcesPanel.add(rigid(1, 16)) } val helpActions = ActionManager.getInstance().getAction(IdeActions.GROUP_WELCOME_SCREEN_LEARN_IDE) as ActionGroup val anActionEvent = emptyWelcomeScreenEventFromAction(helpActions) helpActions.getChildren(anActionEvent).forEach { if (setOf<String>(HelpTopicsAction::class.java.simpleName, OnlineDocAction::class.java.simpleName, JetBrainsTvAction::class.java.simpleName).any { simpleName -> simpleName == it.javaClass.simpleName }) { helpAndResourcesPanel.add(linkLabelByAction(it).wrapWithUrlPanel()) } else { helpAndResourcesPanel.add(linkLabelByAction(it)) } helpAndResourcesPanel.add(rigid(1, 6)) } } private fun LinkLabel<Any>.wrapWithUrlPanel(): JPanel { val jPanel = JPanel() jPanel.isOpaque = false jPanel.layout = BoxLayout(jPanel, BoxLayout.LINE_AXIS) jPanel.add(this, BorderLayout.CENTER) jPanel.add(JLabel(External_link_arrow), BorderLayout.EAST) jPanel.maximumSize = jPanel.preferredSize jPanel.alignmentX = LEFT_ALIGNMENT return jPanel } private fun emptyWelcomeScreenEventFromAction(action: AnAction) = AnActionEvent.createFromAnAction(action, null, ActionPlaces.WELCOME_SCREEN, DataContext.EMPTY_CONTEXT) private fun linkLabelByAction(it: AnAction): LinkLabel<Any> { return LinkLabel<Any>(it.templateText, null).apply { alignmentX = LEFT_ALIGNMENT setListener({ _, _ -> performActionOnWelcomeScreen(it) }, null) } } private fun rigid(_width: Int, _height: Int): Component { val d = Dimension(JBUI.scale(_width), JBUI.scale(_height)) return object: Box.Filler(d, d, d) { init { alignmentX = LEFT_ALIGNMENT } override fun updateUI() { super.updateUI() val newD = Dimension(JBUI.scale(_width), JBUI.scale(_height)) minimumSize = newD preferredSize = newD maximumSize = newD } override fun setUI(newUI: ComponentUI?) { super.setUI(newUI) } } } private fun performActionOnWelcomeScreen(action: AnAction) { val anActionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.WELCOME_SCREEN, DataContext.EMPTY_CONTEXT) ActionUtil.performActionDumbAwareWithCallbacks(action, anActionEvent) } }
apache-2.0
8fcdaf8b75e8a3fe1d6291fc0adfcc72
39.923858
143
0.740851
5.085804
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/CustomizeTabFactory.kt
2
12827
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen import com.intellij.ide.IdeBundle import com.intellij.ide.actions.QuickChangeLookAndFeel import com.intellij.ide.actions.ShowSettingsUtilImpl import com.intellij.ide.ui.* import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.PlatformEditorBundle import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl import com.intellij.openapi.help.HelpManager import com.intellij.openapi.keymap.KeyMapBundle import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.keymap.impl.KeymapManagerImpl import com.intellij.openapi.keymap.impl.keymapComparator import com.intellij.openapi.keymap.impl.ui.KeymapSchemeManager import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.wm.WelcomeTabFactory import com.intellij.openapi.wm.impl.welcomeScreen.TabbedWelcomeScreen.DefaultWelcomeScreenTab import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.UIBundle import com.intellij.ui.components.AnActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.* import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.Font import javax.swing.DefaultComboBoxModel import javax.swing.JComponent import javax.swing.plaf.FontUIResource import javax.swing.plaf.LabelUI private val settings get() = UISettings.getInstance() private val defaultProject get() = ProjectManager.getInstance().defaultProject private val laf get() = LafManager.getInstance() private val keymapManager get() = KeymapManager.getInstance() as KeymapManagerImpl private val editorColorsManager get() = EditorColorsManager.getInstance() as EditorColorsManagerImpl class CustomizeTabFactory : WelcomeTabFactory { override fun createWelcomeTab(parentDisposable: Disposable) = CustomizeTab(parentDisposable) } private fun getIdeFont() = if (settings.overrideLafFonts) settings.fontSize2D else JBFont.label().size2D class CustomizeTab(parentDisposable: Disposable) : DefaultWelcomeScreenTab(IdeBundle.message("welcome.screen.customize.title"), WelcomeScreenEventCollector.TabType.TabNavCustomize) { private val supportedColorBlindness = getColorBlindness() private val propertyGraph = PropertyGraph() private val lafProperty = propertyGraph.graphProperty { laf.lookAndFeelReference } private val syncThemeProperty = propertyGraph.graphProperty { laf.autodetect } private val ideFontProperty = propertyGraph.graphProperty { getIdeFont() } private val keymapProperty = propertyGraph.graphProperty { keymapManager.activeKeymap } private val colorBlindnessProperty = propertyGraph.graphProperty { settings.colorBlindness ?: supportedColorBlindness.firstOrNull() } private val adjustColorsProperty = propertyGraph.graphProperty { settings.colorBlindness != null } private var keymapComboBox: ComboBox<Keymap>? = null private var colorThemeComboBox: ComboBox<LafManager.LafReference>? = null init { lafProperty.afterChange({ val newLaf = laf.findLaf(it) if (laf.currentLookAndFeel == newLaf) return@afterChange ApplicationManager.getApplication().invokeLater { QuickChangeLookAndFeel.switchLafAndUpdateUI(laf, newLaf, true) WelcomeScreenEventCollector.logLafChanged(newLaf, laf.autodetect) } }, parentDisposable) syncThemeProperty.afterChange { if (laf.autodetect == it) return@afterChange laf.autodetect = it WelcomeScreenEventCollector.logLafChanged(laf.currentLookAndFeel, laf.autodetect) } ideFontProperty.afterChange({ if (settings.fontSize2D == it) return@afterChange settings.overrideLafFonts = true WelcomeScreenEventCollector.logIdeFontChanged(settings.fontSize2D, it) settings.fontSize2D = it updateFontSettingsLater() }, parentDisposable) keymapProperty.afterChange({ if (keymapManager.activeKeymap == it) return@afterChange WelcomeScreenEventCollector.logKeymapChanged(it) keymapManager.activeKeymap = it }, parentDisposable) adjustColorsProperty.afterChange({ if (adjustColorsProperty.get() == (settings.colorBlindness != null)) return@afterChange WelcomeScreenEventCollector.logColorBlindnessChanged(adjustColorsProperty.get()) updateColorBlindness() }, parentDisposable) colorBlindnessProperty.afterChange({ updateColorBlindness() }, parentDisposable) val busConnection = ApplicationManager.getApplication().messageBus.connect(parentDisposable) busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { updateProperty(ideFontProperty) { getIdeFont() } }) busConnection.subscribe(EditorColorsManager.TOPIC, EditorColorsListener { updateAccessibilityProperties() }) busConnection.subscribe(LafManagerListener.TOPIC, LafManagerListener { updateProperty(lafProperty) { laf.lookAndFeelReference } updateLafs() }) busConnection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener { override fun activeKeymapChanged(keymap: Keymap?) { updateProperty(keymapProperty) { keymapManager.activeKeymap } updateKeymaps() } override fun keymapAdded(keymap: Keymap) { updateKeymaps() } override fun keymapRemoved(keymap: Keymap) { updateKeymaps() } }) } private fun updateColorBlindness() { settings.colorBlindness = if (adjustColorsProperty.get()) colorBlindnessProperty.get() else null ApplicationManager.getApplication().invokeLater(Runnable { DefaultColorSchemesManager.getInstance().reload() editorColorsManager.schemeChangedOrSwitched(null) }) } private fun updateFontSettingsLater() { ApplicationManager.getApplication().invokeLater { laf.updateUI() settings.fireUISettingsChanged() } } private fun <T> updateProperty(property: GraphProperty<T>, settingGetter: () -> T) { val value = settingGetter() if (property.get() != value) { property.set(value) } } private fun updateAccessibilityProperties() { val adjustColorSetting = settings.colorBlindness != null updateProperty(adjustColorsProperty) { adjustColorSetting } if (adjustColorSetting) { updateProperty(colorBlindnessProperty) { settings.colorBlindness } } } override fun buildComponent(): JComponent { return panel { header(IdeBundle.message("welcome.screen.color.theme.header"), true) row { val themeBuilder = comboBox(laf.lafComboBoxModel, laf.lookAndFeelCellRenderer) .bindItem(lafProperty) .accessibleName(IdeBundle.message("welcome.screen.color.theme.header")) colorThemeComboBox = themeBuilder.component val syncCheckBox = checkBox(IdeBundle.message("preferred.theme.autodetect.selector")) .bindSelected(syncThemeProperty) .applyToComponent { isOpaque = false isVisible = laf.autodetectSupported } themeBuilder.enabledIf(syncCheckBox.selected.not()) cell(laf.settingsToolbar).visibleIf(syncCheckBox.selected) } header(IdeBundle.message("title.accessibility")) row(IdeBundle.message("welcome.screen.ide.font.size.label")) { fontComboBox(ideFontProperty) }.bottomGap(BottomGap.SMALL) createColorBlindnessSettingBlock() header(KeyMapBundle.message("keymap.display.name")) row { keymapComboBox = comboBox(DefaultComboBoxModel(getKeymaps().toTypedArray())) .bindItem(keymapProperty) .accessibleName(KeyMapBundle.message("keymap.display.name")) .component link(KeyMapBundle.message("welcome.screen.keymap.configure.link")) { ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject, KeyMapBundle.message("keymap.display.name")) } } row { cell(AnActionLink("WelcomeScreen.Configure.Import", ActionPlaces.WELCOME_SCREEN)) }.topGap(TopGap.MEDIUM) row { link(IdeBundle.message("welcome.screen.all.settings.link")) { ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject, *ShowSettingsUtilImpl.getConfigurableGroups(defaultProject, true)) } } }.withBorder(JBUI.Borders.empty(23, 30, 20, 20)) .withBackground(WelcomeScreenUIManager.getMainAssociatedComponentBackground()) } private fun updateKeymaps() { (keymapComboBox?.model as DefaultComboBoxModel?)?.apply { removeAllElements() addAll(getKeymaps()) selectedItem = keymapProperty.get() } } private fun updateLafs() { colorThemeComboBox?.apply { model = laf.lafComboBoxModel selectedItem = lafProperty.get() } } private fun Panel.createColorBlindnessSettingBlock() { if (supportedColorBlindness.isNotEmpty()) { row { if (supportedColorBlindness.size == 1) { checkBox(UIBundle.message("color.blindness.checkbox.text")) .bindSelected(adjustColorsProperty) .comment(UIBundle.message("color.blindness.checkbox.comment")) } else { val checkBox = checkBox(UIBundle.message("welcome.screen.color.blindness.combobox.text")) .bindSelected(adjustColorsProperty) .applyToComponent { isOpaque = false }.component comboBox(DefaultComboBoxModel(supportedColorBlindness.toTypedArray()), SimpleListCellRenderer.create("") { PlatformEditorBundle.message(it?.key ?: "") }) .bindItem(colorBlindnessProperty) .comment(UIBundle.message("color.blindness.combobox.comment")) .enabledIf(checkBox.selected) } link(UIBundle.message("color.blindness.link.to.help")) { HelpManager.getInstance().invokeHelp("Colorblind_Settings") } } } } private fun Panel.header(@Nls title: String, firstHeader: Boolean = false) { val row = row { cell(HeaderLabel(title)) }.bottomGap(BottomGap.SMALL) if (!firstHeader) { row.topGap(TopGap.MEDIUM) } } private class HeaderLabel(@Nls title: String) : JBLabel(title) { override fun setUI(ui: LabelUI?) { super.setUI(ui) if (font != null) { font = FontUIResource(font.deriveFont(font.size2D + JBUIScale.scale(3)).deriveFont(Font.BOLD)) } } } private fun Row.fontComboBox(fontProperty: GraphProperty<Float>): Cell<ComboBox<Float>> { val fontSizes = UIUtil.getStandardFontSizes().map { it.toFloat() }.toSortedSet() fontSizes.add(fontProperty.get()) val model = DefaultComboBoxModel(fontSizes.toTypedArray()) return comboBox(model) .bindItem(fontProperty) .applyToComponent { isEditable = true } } private fun getColorBlindness(): List<ColorBlindness> { return ColorBlindness.values().asList().filter { ColorBlindnessSupport.get(it) != null } } private fun getKeymaps(): List<Keymap> { return keymapManager.getKeymaps(KeymapSchemeManager.FILTER).sortedWith(keymapComparator) } }
apache-2.0
51a5bccb4c89fb28f627a010160ff319
42.931507
135
0.706167
5.10629
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis-api/analysis-api-utils/src/org/jetbrains/kotlin/idea/base/analysis/api/utils/KtSymbolFromIndexProvider.kt
2
5586
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.analysis.api.utils import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiMember import com.intellij.psi.search.PsiShortNamesCache import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.getSymbolOfTypeSafe import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.idea.base.psi.isExpectDeclaration import org.jetbrains.kotlin.platform.isCommon class KtSymbolFromIndexProvider(private val project: Project) { context(KtAnalysisSession) fun getKotlinClassesByName( name: Name, psiFilter: (KtClassOrObject) -> Boolean = { true }, ): Sequence<KtNamedClassOrObjectSymbol> { val scope = analysisScope val isCommon = useSiteModule.platform.isCommon() return KotlinClassShortNameIndex[name.asString(), project, scope] .asSequence() .filter { ktClass -> isCommon || !ktClass.isExpectDeclaration() } .filter (psiFilter) .mapNotNull { it.getNamedClassOrObjectSymbol() } } context(KtAnalysisSession) fun getKotlinClassesByNameFilter( nameFilter: (Name) -> Boolean, psiFilter: (KtClassOrObject) -> Boolean = { true }, ): Sequence<KtNamedClassOrObjectSymbol> { val scope = analysisScope val isCommon = useSiteModule.platform.isCommon() val index = KotlinFullClassNameIndex return index.getAllKeys(project).asSequence() .filter { fqName -> nameFilter(getShortName(fqName)) } .flatMap { fqName -> index[fqName, project, scope] } .filter { ktClass -> isCommon || !ktClass.isExpectDeclaration() } .filter (psiFilter) .mapNotNull { it.getNamedClassOrObjectSymbol() } } context(KtAnalysisSession) fun getJavaClassesByNameFilter( nameFilter: (Name) -> Boolean, psiFilter: (PsiClass) -> Boolean = { true } ): Sequence<KtNamedClassOrObjectSymbol> { val scope = analysisScope val names = buildSet<Name> { forEachNonKotlinCache { cache -> cache.processAllClassNames({ nameString -> if (!Name.isValidIdentifier(nameString)) return@processAllClassNames true val name = Name.identifier(nameString) if (nameFilter(name)) { add(name) } true }, scope, null) } } return sequence { names.forEach { name -> yieldAll(getJavaClassesByName(name, psiFilter)) } } } context(KtAnalysisSession) fun getJavaClassesByName( name: Name, psiFilter: (PsiClass) -> Boolean = { true } ): Sequence<KtNamedClassOrObjectSymbol> { val scope = analysisScope val nameString = name.asString() return sequence { forEachNonKotlinCache { cache -> yieldAll(cache.getClassesByName(nameString, scope).iterator()) } } .filter(psiFilter) .mapNotNull { it.getNamedClassSymbol() } } context(KtAnalysisSession) fun getKotlinCallableSymbolsByName( name: Name, psiFilter: (KtCallableDeclaration) -> Boolean = { true }, ): Sequence<KtCallableSymbol> { val scope = analysisScope val nameString = name.asString() return sequence { yieldAll(KotlinFunctionShortNameIndex[nameString, project, scope]) yieldAll(KotlinPropertyShortNameIndex[nameString, project, scope]) } .onEach { ProgressManager.checkCanceled() } .filter { it is KtCallableDeclaration && psiFilter(it) && !it.isExpectDeclaration()} .mapNotNull { it.getSymbolOfTypeSafe<KtCallableSymbol>() } } context(KtAnalysisSession) fun getJavaCallableSymbolsByName( name: Name, psiFilter: (PsiMember) -> Boolean = { true } ): Sequence<KtCallableSymbol> { val scope = analysisScope val nameString = name.asString() return sequence { forEachNonKotlinCache { cache -> yieldAll(cache.getMethodsByName(nameString, scope).iterator()) } forEachNonKotlinCache { cache -> yieldAll(cache.getFieldsByName(nameString, scope).iterator()) } } .filter(psiFilter) .mapNotNull { it.getCallableSymbol() } } private inline fun forEachNonKotlinCache(action: (cache: PsiShortNamesCache) -> Unit) { for (cache in PsiShortNamesCache.EP_NAME.getExtensions(project)) { if (cache::class.java.name == "org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache") continue action(cache) } } private fun getShortName(fqName: String) = Name.identifier(fqName.substringAfterLast('.')) }
apache-2.0
79dbd85c28e65457e5ef154bf06ccfab
39.485507
120
0.670426
5.279773
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt
6
1875
// 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.quickfix.createFromUsage.createCallable import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreateHasNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? { return diagnostic.psiElement.findParentOfType(strict = false) } override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo { val diagnosticWithParameters = DiagnosticFactory.cast(diagnostic, Errors.HAS_NEXT_MISSING, Errors.HAS_NEXT_FUNCTION_NONE_APPLICABLE) val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE) val returnType = TypeInfo(element.builtIns.booleanType, Variance.OUT_VARIANCE) return FunctionInfo( OperatorNameConventions.HAS_NEXT.asString(), ownerType, returnType, modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } }
apache-2.0
b9b23f3e19b0e268007be53bb798bf94
51.083333
120
0.798933
5.02681
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/test/kotlin/database/save/SequenceIdentifierConcurrencyTest.kt
1
17644
package database.save import com.onyx.exception.NoResultsException import com.onyx.persistence.IManagedEntity import database.base.DatabaseBaseTest import org.junit.FixMethodOrder import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.junit.runners.Parameterized import java.util.* import java.util.concurrent.Executors import java.util.concurrent.Future import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertTrue import entities.InheritedLongAttributeEntity @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(Parameterized::class) class SequenceIdentifierConcurrencyTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) { companion object { private val threadPool = Executors.newFixedThreadPool(10) } /** * Tests Batch inserting 10,000 record with a String identifier * last test took: 759(mac) */ @Test fun aConcurrencySequencePerformanceTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val before = System.currentTimeMillis() for (i in 0..10000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 500 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } val after = System.currentTimeMillis() assertTrue(after - before < 1500, "Should not take more than 1.5 seconds to complete") } /** * Runs 10 threads that insert 10k entities with a String identifier. * After insertion, this test validates the data integrity. * last test took: 698(win) 2231(mac) */ @Test fun concurrencySequenceSaveIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidate = ArrayList<InheritedLongAttributeEntity>() for (i in 0..5000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() tmpList.forEach { manager.saveEntity(it) } } } threads.forEach { it.get() } // Validate entities to ensure it was persisted correctly entitiesToValidate.parallelStream().forEach { var newEntity = InheritedLongAttributeEntity() newEntity.id = it.id newEntity = manager.find<IManagedEntity>(newEntity) as InheritedLongAttributeEntity assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}") assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}") } } @Test fun concurrencySequenceSaveIntegrityTestWithBatching() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidate = ArrayList<InheritedLongAttributeEntity>() for (i in 1..10000) { val entity = InheritedLongAttributeEntity() entity.id = i.toLong() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 1000 == 0) { val tmpList = ArrayList<InheritedLongAttributeEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } // Validate entities to ensure it was persisted correctly entitiesToValidate.parallelStream().forEach { var newEntity = InheritedLongAttributeEntity() newEntity.id = it.id newEntity = manager.find<IManagedEntity>(newEntity) as InheritedLongAttributeEntity assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}") assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}") } } @Test fun concurrencySequenceDeleteIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidate = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidateDeleted = ArrayList<InheritedLongAttributeEntity>() for (i in 0..10000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 2 == 0) { entitiesToValidateDeleted.add(entity) } else { entitiesToValidate.add(entity) } if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { tmpList.forEach { manager.saveEntity(it) } }) } } threads.forEach { it.get() } threads.clear() entities.clear() var deleteCount = 0 for (i in 0..10000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() val deletedIndex = deleteCount threads.add(async(threadPool) { tmpList.forEach { manager.saveEntity(it) } var t = deletedIndex while (t < deletedIndex + 5 && t < entitiesToValidateDeleted.size) { manager.deleteEntity(entitiesToValidateDeleted[t]) t++ } }) deleteCount += 5 } } threads.forEach { it.get() } entitiesToValidate.parallelStream().forEach { var newEntity = InheritedLongAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not persisted correctly") } entitiesToValidateDeleted.parallelStream().forEach { val newEntity = InheritedLongAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } assertTrue(pass, "Entity ${newEntity.id} was not deleted") } } @Test fun concurrencySequenceDeleteBatchIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidate = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidateDeleted = ArrayList<InheritedLongAttributeEntity>() val ignore = HashMap<Long, InheritedLongAttributeEntity>() for (i in 0..10000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 2 == 0) { entitiesToValidateDeleted.add(entity) ignore.put(entity.id, entity) } else { entitiesToValidate.add(entity) } if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } threads.clear() entities.clear() for (i in 0..10000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) for(k in 0 .. 6) { var entityToDelete: IManagedEntity? = null synchronized(entitiesToValidateDeleted) { if (entitiesToValidateDeleted.size > 0) { entityToDelete = entitiesToValidateDeleted.removeAt(0) } } if(entityToDelete != null) manager.deleteEntity(entityToDelete!!) } }) } } threads.forEach { it.get() } entitiesToValidate.parallelStream().forEach { var newEntity = InheritedLongAttributeEntity() newEntity.id = it.id if (!ignore.containsKey(newEntity.id)) { newEntity = manager.find(newEntity) assertEquals(it.longPrimitive, newEntity.longPrimitive, "Entity did not hydrate correctly") } } entitiesToValidateDeleted.parallelStream().forEach { val newEntity = InheritedLongAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } assertTrue(pass, "Entity ${newEntity.id} was not deleted") } } /** * Executes 10 threads that insert 30k entities with string id, then 10k are updated and 10k are deleted. * Then it validates the integrity of those actions */ @Test fun concurrencySequenceAllIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidate = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidateDeleted = ArrayList<InheritedLongAttributeEntity>() val entitiesToValidateUpdated = ArrayList<InheritedLongAttributeEntity>() val ignore = HashMap<Long, InheritedLongAttributeEntity>() for (i in 0..30000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) // Delete Even ones when { i % 2 == 0 -> { entitiesToValidateDeleted.add(entity) ignore.put(entity.id, entity) } i % 3 == 0 && i % 2 != 0 -> entitiesToValidateUpdated.add(entity) else -> entitiesToValidate.add(entity) } if (i % 1000 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } threads.clear() entities.clear() entitiesToValidateDeleted -= entitiesToValidateUpdated entitiesToValidateUpdated -= entitiesToValidateDeleted val entitiesToBeDeleted = ArrayList<InheritedLongAttributeEntity>(entitiesToValidateDeleted) entitiesToValidateUpdated.forEach { it.longPrimitive = 45645 } var updateCount = 0 for (i in 0..30000) { val entity = InheritedLongAttributeEntity() entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 20 == 0) { entitiesToValidate.add(entity) val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() val updatedIndex = updateCount threads.add(async(threadPool) { manager.saveEntities(tmpList) var t = updatedIndex while (t < updatedIndex + 13 && t < entitiesToValidateUpdated.size) { manager.saveEntity<IManagedEntity>(entitiesToValidateUpdated[t]) t++ } for (k in 0..31) { var entityToDelete: InheritedLongAttributeEntity? = null synchronized(entitiesToBeDeleted) { if (!entitiesToBeDeleted.isEmpty()) entityToDelete = entitiesToBeDeleted.removeAt(0) } if (entityToDelete != null) manager.deleteEntity(entityToDelete!!) } }) updateCount += 13 } } entitiesToValidateDeleted -= entitiesToValidateUpdated threads.forEach { it.get() } var failedEntities = 0 entitiesToValidate.parallelStream().forEach { val newEntity = InheritedLongAttributeEntity() newEntity.id = it.id if (!ignore.containsKey(newEntity.id)) { try { manager.find<IManagedEntity>(newEntity) } catch (e: Exception) { failedEntities++ } } } assertEquals(0, failedEntities, "There were several entities that failed to be found") entitiesToValidateDeleted.parallelStream().forEach { val newEntity = InheritedLongAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } if (!pass) { failedEntities++ } } assertEquals(0, failedEntities, "There were several entities that failed to be deleted") entitiesToValidateUpdated.parallelStream().forEach { var newEntity = InheritedLongAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(45645L, newEntity.longPrimitive, "Entity failed to update") } } }
agpl-3.0
c992ad7343b11f4b59c3ea8e4fbb86f4
33.596078
124
0.564101
5.869594
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/packaging/repository/PyRepositoryListItem.kt
1
4397
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.packaging.repository import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.ui.NamedConfigurable import com.intellij.openapi.util.NlsSafe import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.bindText import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBUI import com.jetbrains.python.PyBundle.message import org.jetbrains.annotations.ApiStatus import java.awt.BorderLayout import java.awt.Dimension import javax.swing.JComponent import javax.swing.JPanel @ApiStatus.Experimental class PyRepositoryListItem(val repository: PyPackageRepository) : NamedConfigurable<PyPackageRepository>(true, null) { @NlsSafe private var currentName = repository.name!! private var password = repository.getPassword() private val propertyGraph = PropertyGraph() private val urlProperty = propertyGraph.graphProperty { repository.repositoryUrl ?: "" } private val loginProperty = propertyGraph.graphProperty { repository.login ?: "" } private val passwordProperty = propertyGraph.graphProperty { repository.getPassword() ?: "" } private val authorizationTypeProperty = propertyGraph.graphProperty { repository.authorizationType } override fun getDisplayName(): String { return currentName } override fun isModified(): Boolean { return currentName != repository.name || repository.repositoryUrl != urlProperty.get() || repository.authorizationType != authorizationTypeProperty.get() || password != passwordProperty.get() } override fun apply() { if (currentName != repository.name) { repository.clearCredentials() } repository.name = currentName val newUrl = urlProperty.get().trim() repository.repositoryUrl = if (newUrl.endsWith("/")) newUrl else "$newUrl/" repository.authorizationType = authorizationTypeProperty.get() if (repository.authorizationType == PyPackageRepositoryAuthenticationType.HTTP) { repository.login = loginProperty.get() repository.setPassword(passwordProperty.get()) } else { repository.login = "" repository.clearCredentials() } } override fun setDisplayName(name: String) { currentName = name } override fun getEditableObject(): PyPackageRepository { return repository } @Suppress("DialogTitleCapitalization") override fun getBannerSlogan(): String { return displayName } override fun createOptionsPanel(): JComponent { val mainPanel = JPanel().apply { border = JBUI.Borders.empty(10) layout = BorderLayout() } val repositoryForm = panel { row(message("python.packaging.repository.form.url")) { cell(JBTextField(repository.repositoryUrl)) .align(AlignX.FILL) .bindText(urlProperty) } row(message("python.packaging.repository.form.authorization")) { segmentedButton(PyPackageRepositoryAuthenticationType.values().toList(), PyPackageRepositoryAuthenticationType::text) .bind(authorizationTypeProperty) } val row1 = row(message("python.packaging.repository.form.login")) { cell(JBTextField(repository.login)).apply { component.preferredSize = Dimension(250, component.preferredSize.height) } .bindText(loginProperty) }.visible(repository.authorizationType != PyPackageRepositoryAuthenticationType.NONE) val row2 = row(message("python.packaging.repository.form.password")) { passwordField().applyToComponent { text = repository.getPassword() } .apply { component.preferredSize = Dimension(250, component.preferredSize.height) } .bindText(passwordProperty) }.visible(repository.authorizationType != PyPackageRepositoryAuthenticationType.NONE) authorizationTypeProperty.afterChange { val state = authorizationTypeProperty.get() row1.visible(state != PyPackageRepositoryAuthenticationType.NONE) row2.visible(state != PyPackageRepositoryAuthenticationType.NONE) } } mainPanel.add(repositoryForm, BorderLayout.CENTER) return mainPanel } }
apache-2.0
906771c5274475b8dc6e7c56d9cd247d
38.267857
126
0.741642
5.065668
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/When.kt
2
4116
// WITH_STDLIB fun simpleRange(x: Int) = when { x > 10 -> 10 <warning descr="Condition 'x > 15' is always false">x > 15</warning> -> 15 else -> 0 } @OptIn(ExperimentalStdlibApi::class) fun inRange(obj : Int) { when (obj) { in 0..<10 -> {} 10 -> {} <warning descr="'when' branch is never reachable">9</warning> -> {} } when (obj) { in 0 until 10 -> {} 10 -> {} <warning descr="'when' branch is never reachable">9</warning> -> {} } when (obj) { in 0..<10 -> {} !in 0..9 -> {} <warning descr="'when' branch is never reachable">20</warning> -> {} else -> {} } when (obj) { in 0 until 10 -> {} !in 0..9 -> {} <warning descr="'when' branch is never reachable">20</warning> -> {} else -> {} } if (obj > 0) { when (obj) { 3 -> {} 2 -> {} 1 -> {} <warning descr="'when' branch is never reachable">0</warning> -> {} } } } fun whenIs(obj : Any?) { when(obj) { is X -> {} is Y -> {} else -> { if (<warning descr="Condition 'obj is X' is always false">obj is X</warning>) {} } } if (obj is X) { when(obj) { <warning descr="[USELESS_IS_CHECK] Check for instance is always 'false'">is Y</warning> -> {} } } } fun lastBranchTrue(obj : Boolean, obj2 : Any) { when(obj) { true -> {} false -> {} } when(obj2) { is String -> {} is Int -> {} else -> return } when(obj2) { is String -> {} is Int -> {} else -> return } } fun lastBranchTrue2(obj2 : Any) { when(obj2) { is String -> {} is Int -> {} else -> return } when(obj2) { is String -> {} is Int -> {} else -> return } } fun suppressSimilarTests1(a: Boolean) { when { a -> {} !a -> {} } } fun suppressSimilarTests2(a: Boolean, b: Boolean) { when { a && b -> {} a && !b -> {} !a && b -> {} else -> {} } } fun suppressSimilarTests3(a: Boolean, b: Boolean, c: Boolean) { when { a && b && c -> {} a && b && !c -> {} a && !b && c -> {} a && !b && !c -> {} } } fun unboxBoolean(obj : Boolean?) { when(obj) { true -> {} false -> {} null -> {} } } fun unboxAny(obj : Any) { when(obj) { 0 -> {} true -> {} } } fun returnFromWhen(x: Int): Unit { when { x > 10 -> return x < 0 -> return } if (<warning descr="Condition 'x == 11' is always false">x == 11</warning>) {} } fun throwBranch(x: Int) { when(x) { 0 -> {} 1 -> {} 2 -> return 3 -> {} } when(x) { 0 -> {} 1 -> {} <warning descr="'when' branch is never reachable">2</warning> -> throw Exception() 3 -> {} } when { x == 0 -> {} x == 1 -> {} <warning descr="Condition 'x == 2' is always false">x == 2</warning> -> throw Exception() x == 3 -> {} } } class X {} class Y {} fun test3(i: Int): Int { val r = when (i) { 0 -> "0" 1 -> "1" else -> error(0) } val l = when (i) { 0 -> "0" 1 -> "1" <warning descr="'when' branch is never reachable">2</warning> -> "2" else -> error(0) } val l1 = when (i) { 0 -> "0" 1, <warning descr="'when' branch is never reachable">2</warning> -> "1" <warning descr="'when' branch is never reachable">3</warning>, <warning descr="'when' branch is never reachable">4</warning>, <warning descr="'when' branch is never reachable">5</warning> -> "2" else -> error(0) } val l2 = when(1) { <warning descr="'when' branch is never reachable">0</warning> -> "0" 1 -> "1" <warning descr="'when' branch is never reachable">2</warning> -> "2" else -> "3" } return (r + l + l1 + l2).length }
apache-2.0
a55cedb6caa024cefcf8411ff069af4e
22.525714
202
0.433188
3.502979
false
false
false
false
ktorio/ktor
ktor-io/common/src/io/ktor/utils/io/ByteChannelSequential.kt
1
24232
package io.ktor.utils.io import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* import io.ktor.utils.io.internal.* import io.ktor.utils.io.pool.* import kotlinx.atomicfu.* import kotlinx.atomicfu.locks.* import kotlin.math.* private const val EXPECTED_CAPACITY: Long = 4088L /** * Sequential (non-concurrent) byte channel implementation */ @Suppress("OverridingDeprecatedMember", "DEPRECATION") public abstract class ByteChannelSequentialBase( initial: ChunkBuffer, override val autoFlush: Boolean, pool: ObjectPool<ChunkBuffer> = ChunkBuffer.Pool ) : ByteChannel, ByteReadChannel, ByteWriteChannel, SuspendableReadSession, HasReadSession, HasWriteSession { private val _lastReadView: AtomicRef<ChunkBuffer> = atomic(ChunkBuffer.Empty) private val _totalBytesRead = atomic(0L) private val _totalBytesWritten = atomic(0L) private val _availableForRead = atomic(0) private val channelSize = atomic(0) private val _closed = atomic<CloseElement?>(null) private val isCancelled: Boolean get() = _closed.value?.cause != null protected var closed: Boolean get() = _closed.value != null set(_) { error("Setting is not allowed for closed") } protected val writable: BytePacketBuilder = BytePacketBuilder(pool) protected val readable: ByteReadPacket = ByteReadPacket(initial, pool) private var lastReadAvailable: Int by atomic(0) private var lastReadView: ChunkBuffer by atomic(ChunkBuffer.Empty) private val slot = AwaitingSlot() override val availableForRead: Int get() = _availableForRead.value override val availableForWrite: Int get() = maxOf(0, EXPECTED_CAPACITY.toInt() - channelSize.value) override val isClosedForRead: Boolean get() = isCancelled || (closed && channelSize.value == 0) override val isClosedForWrite: Boolean get() = closed override val totalBytesRead: Long get() = _totalBytesRead.value override val totalBytesWritten: Long get() = _totalBytesWritten.value final override var closedCause: Throwable? get() = _closed.value?.cause set(_) { error("Closed cause shouldn't be changed directly") } private val flushMutex = SynchronizedObject() private val flushBuffer: BytePacketBuilder = BytePacketBuilder() init { val count = initial.remainingAll().toInt() afterWrite(count) _availableForRead.addAndGet(count) } internal suspend fun awaitAtLeastNBytesAvailableForWrite(count: Int) { while (availableForWrite < count && !closed) { if (!flushImpl()) { slot.sleep { availableForWrite < count && !closed } } } } internal suspend fun awaitAtLeastNBytesAvailableForRead(count: Int) { while (availableForRead < count && !isClosedForRead) { slot.sleep { availableForRead < count && !isClosedForRead } } } override fun flush() { flushImpl() } private fun flushImpl(): Boolean { if (writable.isEmpty) { slot.resume() return false } flushWrittenBytes() slot.resume() return true } /** * Send bytes to thread-safe storage. * * This method is writer-only safe. */ private fun flushWrittenBytes() { synchronized(flushMutex) { val size = writable.size val buffer = writable.stealAll()!! flushBuffer.writeChunkBuffer(buffer) _availableForRead.addAndGet(size) } } /** * Take flushed bytes before read. * * This method is reader-only safe. */ protected fun prepareFlushedBytes() { synchronized(flushMutex) { readable.unsafeAppend(flushBuffer) } } private fun ensureNotClosed() { if (closed) { throw closedCause ?: ClosedWriteChannelException("Channel $this is already closed") } } private fun ensureNotFailed() { closedCause?.let { throw it } } private fun ensureNotFailed(closeable: BytePacketBuilder) { closedCause?.let { cause -> closeable.release() throw cause } } override suspend fun writeByte(b: Byte) { awaitAtLeastNBytesAvailableForWrite(1) writable.writeByte(b) afterWrite(1) } override suspend fun writeShort(s: Short) { awaitAtLeastNBytesAvailableForWrite(2) writable.writeShort(s) afterWrite(2) } override suspend fun writeInt(i: Int) { awaitAtLeastNBytesAvailableForWrite(4) writable.writeInt(i) afterWrite(4) } override suspend fun writeLong(l: Long) { awaitAtLeastNBytesAvailableForWrite(8) writable.writeLong(l) afterWrite(8) } override suspend fun writeFloat(f: Float) { awaitAtLeastNBytesAvailableForWrite(4) writable.writeFloat(f) afterWrite(4) } override suspend fun writeDouble(d: Double) { awaitAtLeastNBytesAvailableForWrite(8) writable.writeDouble(d) afterWrite(8) } override suspend fun writePacket(packet: ByteReadPacket) { awaitAtLeastNBytesAvailableForWrite(1) val size = packet.remaining.toInt() writable.writePacket(packet) afterWrite(size) } override suspend fun writeFully(src: Buffer) { awaitAtLeastNBytesAvailableForWrite(1) val count = src.readRemaining writable.writeFully(src) afterWrite(count) } override suspend fun writeFully(src: ByteArray, offset: Int, length: Int) { var currentIndex = offset val endIndex = offset + length while (currentIndex < endIndex) { awaitAtLeastNBytesAvailableForWrite(1) val bytesCount = min(availableForWrite, endIndex - currentIndex) writable.writeFully(src, currentIndex, bytesCount) currentIndex += bytesCount afterWrite(bytesCount) } } override suspend fun writeFully(memory: Memory, startIndex: Int, endIndex: Int) { var currentIndex = startIndex while (currentIndex < endIndex) { awaitAtLeastNBytesAvailableForWrite(1) val bytesCount = min(availableForWrite, endIndex - currentIndex) writable.writeFully(memory, currentIndex, bytesCount) currentIndex += bytesCount afterWrite(bytesCount) } } override suspend fun writeAvailable(src: ChunkBuffer): Int { val srcRemaining = src.readRemaining if (srcRemaining == 0) return 0 val size = minOf(srcRemaining, availableForWrite) return if (size == 0) writeAvailableSuspend(src) else { writable.writeFully(src, size) afterWrite(size) size } } override suspend fun writeAvailable(src: ByteArray, offset: Int, length: Int): Int { if (length == 0) return 0 val size = minOf(length, availableForWrite) return if (size == 0) writeAvailableSuspend(src, offset, length) else { writable.writeFully(src, offset, size) afterWrite(size) size } } @Suppress("DEPRECATION") @Deprecated("Use write { } instead.") override suspend fun writeSuspendSession(visitor: suspend WriterSuspendSession.() -> Unit) { val session = beginWriteSession() visitor(session) } @Suppress("DEPRECATION") override fun beginWriteSession(): WriterSuspendSession { return object : WriterSuspendSession { override fun request(min: Int): ChunkBuffer? { if (availableForWrite == 0) return null return writable.prepareWriteHead(min) } override fun written(n: Int) { writable.afterHeadWrite() afterWrite(n) } override fun flush() { [email protected]() } override suspend fun tryAwait(n: Int) { if (availableForWrite < n) { awaitAtLeastNBytesAvailableForWrite(n) } } } } override fun endWriteSession(written: Int) { writable.afterHeadWrite() afterWrite(written) } override suspend fun readByte(): Byte { return if (readable.isNotEmpty) { readable.readByte().also { afterRead(1) } } else { readByteSlow() } } private fun checkClosed(remaining: Int, closeable: BytePacketBuilder? = null) { closedCause?.let { closeable?.close() throw it } if (closed && availableForRead < remaining) { closeable?.close() throw EOFException("$remaining bytes required but EOF reached") } } private suspend fun readByteSlow(): Byte { do { awaitSuspend(1) if (readable.isNotEmpty) return readable.readByte().also { afterRead(1) } checkClosed(1) } while (true) } override suspend fun readShort(): Short { return if (readable.hasBytes(2)) { readable.readShort().also { afterRead(2) } } else { readShortSlow() } } private suspend fun readShortSlow(): Short { awaitSuspend(2) val result = readable.readShort() afterRead(2) return result } protected fun afterRead(count: Int) { addBytesRead(count) slot.resume() } override suspend fun readInt(): Int { return if (readable.hasBytes(4)) { readable.readInt().also { afterRead(4) } } else { readIntSlow() } } private suspend fun readIntSlow(): Int { awaitSuspend(4) val result = readable.readInt() afterRead(4) return result } override suspend fun readLong(): Long { return if (readable.hasBytes(8)) { readable.readLong().also { afterRead(8) } } else { readLongSlow() } } private suspend fun readLongSlow(): Long { awaitSuspend(8) val result = readable.readLong() afterRead(8) return result } override suspend fun readFloat(): Float = if (readable.hasBytes(4)) { readable.readFloat().also { afterRead(4) } } else { readFloatSlow() } private suspend fun readFloatSlow(): Float { awaitSuspend(4) val result = readable.readFloat() afterRead(4) return result } override suspend fun readDouble(): Double = if (readable.hasBytes(8)) { readable.readDouble().also { afterRead(8) } } else { readDoubleSlow() } private suspend fun readDoubleSlow(): Double { awaitSuspend(8) val result = readable.readDouble() afterRead(8) return result } override suspend fun readRemaining(limit: Long): ByteReadPacket { ensureNotFailed() val builder = BytePacketBuilder() val size = minOf(limit, readable.remaining) builder.writePacket(readable, size) afterRead(size.toInt()) val newLimit = limit - builder.size return if (newLimit == 0L || isClosedForRead) { ensureNotFailed(builder) builder.build() } else { readRemainingSuspend(builder, limit) } } private suspend fun readRemainingSuspend(builder: BytePacketBuilder, limit: Long): ByteReadPacket { while (builder.size < limit) { val partLimit = minOf(limit - builder.size, readable.remaining) builder.writePacket(readable, partLimit) afterRead(partLimit.toInt()) ensureNotFailed(builder) if (isClosedForRead || builder.size == limit.toInt()) { break } awaitSuspend(1) } ensureNotFailed(builder) return builder.build() } override suspend fun readPacket(size: Int): ByteReadPacket { checkClosed(size) val builder = BytePacketBuilder() var remaining = size val partSize = minOf(remaining.toLong(), readable.remaining).toInt() remaining -= partSize builder.writePacket(readable, partSize) afterRead(partSize) checkClosed(remaining, builder) return if (remaining > 0) readPacketSuspend(builder, remaining) else builder.build() } private suspend fun readPacketSuspend(builder: BytePacketBuilder, size: Int): ByteReadPacket { var remaining = size while (remaining > 0) { val partSize = minOf(remaining.toLong(), readable.remaining).toInt() remaining -= partSize builder.writePacket(readable, partSize) afterRead(partSize) checkClosed(remaining, builder) if (remaining > 0) { awaitSuspend(1) } } checkClosed(remaining, builder) return builder.build() } protected fun readAvailableClosed(): Int { closedCause?.let { throw it } if (availableForRead > 0) { prepareFlushedBytes() } return -1 } override suspend fun readAvailable(dst: ChunkBuffer): Int = readAvailable(dst as Buffer) internal suspend fun readAvailable(dst: Buffer): Int { closedCause?.let { throw it } if (closed && availableForRead == 0) return -1 if (dst.writeRemaining == 0) return 0 if (availableForRead == 0) { awaitSuspend(1) } if (!readable.canRead()) { prepareFlushedBytes() } val size = minOf(dst.writeRemaining.toLong(), readable.remaining).toInt() readable.readFully(dst, size) afterRead(size) return size } override suspend fun readFully(dst: ChunkBuffer, n: Int) { readFully(dst as Buffer, n) } private suspend fun readFully(dst: Buffer, n: Int) { require(n <= dst.writeRemaining) { "Not enough space in the destination buffer to write $n bytes" } require(n >= 0) { "n shouldn't be negative" } return when { closedCause != null -> throw closedCause!! readable.remaining >= n -> readable.readFully(dst, n).also { afterRead(n) } closed -> throw EOFException( "Channel is closed and not enough bytes available: required $n but $availableForRead available" ) else -> readFullySuspend(dst, n) } } private suspend fun readFullySuspend(dst: Buffer, n: Int) { awaitSuspend(n) return readFully(dst, n) } override suspend fun readAvailable(dst: ByteArray, offset: Int, length: Int): Int { closedCause?.let { throw it } if (closed && availableForRead == 0) return -1 if (length == 0) return 0 if (availableForRead == 0) { awaitSuspend(1) } if (!readable.canRead()) { prepareFlushedBytes() } val size = minOf(length.toLong(), readable.remaining).toInt() readable.readFully(dst, offset, size) afterRead(size) return size } override suspend fun readFully(dst: ByteArray, offset: Int, length: Int) { val rc = readAvailable(dst, offset, length) if (rc == length) return if (rc == -1) throw EOFException("Unexpected end of stream") return readFullySuspend(dst, offset + rc, length - rc) } private suspend fun readFullySuspend(dst: ByteArray, offset: Int, length: Int) { var written = 0 while (written < length) { val rc = readAvailable(dst, offset + written, length - written) if (rc == -1) throw EOFException("Unexpected end of stream") written += rc } } override suspend fun readBoolean(): Boolean { return if (readable.canRead()) (readable.readByte() == 1.toByte()).also { afterRead(1) } else readBooleanSlow() } private suspend fun readBooleanSlow(): Boolean { awaitSuspend(1) checkClosed(1) return readBoolean() } private fun completeReading() { val remaining = lastReadView.readRemaining val delta = lastReadAvailable - remaining if (lastReadView !== Buffer.Empty) { readable.completeReadHead(lastReadView) } if (delta > 0) { afterRead(delta) } lastReadAvailable = 0 lastReadView = ChunkBuffer.Empty } override suspend fun await(atLeast: Int): Boolean { require(atLeast >= 0) { "atLeast parameter shouldn't be negative: $atLeast" } require(atLeast <= EXPECTED_CAPACITY) { "atLeast parameter shouldn't be larger than max buffer size of $EXPECTED_CAPACITY: $atLeast" } completeReading() if (atLeast == 0) return !isClosedForRead if (readable.remaining >= atLeast) return true return awaitSuspend(atLeast) } internal suspend fun awaitInternalAtLeast1(): Boolean = if (readable.isNotEmpty) { true } else { awaitSuspend(1) } protected suspend fun awaitSuspend(atLeast: Int): Boolean { require(atLeast >= 0) awaitAtLeastNBytesAvailableForRead(atLeast) prepareFlushedBytes() closedCause?.let { throw it } return !isClosedForRead && availableForRead >= atLeast } override fun discard(n: Int): Int { closedCause?.let { throw it } if (n == 0) { return 0 } return readable.discard(n).also { afterRead(n) requestNextView(1) } } override fun request(atLeast: Int): ChunkBuffer? { closedCause?.let { throw it } completeReading() return requestNextView(atLeast) } private fun requestNextView(atLeast: Int): ChunkBuffer? { if (readable.isEmpty) { prepareFlushedBytes() } val view = readable.prepareReadHead(atLeast) if (view == null) { lastReadView = ChunkBuffer.Empty lastReadAvailable = 0 } else { lastReadView = view lastReadAvailable = view.readRemaining } return view } override suspend fun discard(max: Long): Long { val discarded = readable.discard(max) afterRead(discarded.toInt()) return if (discarded == max || isClosedForRead) { ensureNotFailed() return discarded } else { discardSuspend(max, discarded) } } private suspend fun discardSuspend(max: Long, discarded0: Long): Long { var discarded = discarded0 do { if (!await(1)) break val count = readable.discard(max - discarded) afterRead(count.toInt()) discarded += count } while (discarded < max && !isClosedForRead) ensureNotFailed() return discarded } @Suppress("DEPRECATION") @Deprecated("Use read instead.") override fun readSession(consumer: ReadSession.() -> Unit) { try { consumer(this) } finally { completeReading() } } override fun startReadSession(): SuspendableReadSession = this override fun endReadSession() { completeReading() } @Suppress("DEPRECATION") @Deprecated("Use read instead.") override suspend fun readSuspendableSession(consumer: suspend SuspendableReadSession.() -> Unit) { try { consumer(this) } finally { completeReading() } } override suspend fun <A : Appendable> readUTF8LineTo(out: A, limit: Int): Boolean { if (isClosedForRead) { val cause = closedCause if (cause != null) { throw cause } return false } return decodeUTF8LineLoopSuspend(out, limit, { size -> if (await(size)) readable else null }) { afterRead(it) } } override suspend fun readUTF8Line(limit: Int): String? { val builder = StringBuilder() if (!readUTF8LineTo(builder, limit)) { return null } return builder.toString() } override fun cancel(cause: Throwable?): Boolean { if (closedCause != null || closed) { return false } return close(cause ?: io.ktor.utils.io.CancellationException("Channel cancelled")) } override fun close(cause: Throwable?): Boolean { val closeElement = if (cause == null) CLOSED_SUCCESS else CloseElement(cause) if (!_closed.compareAndSet(null, closeElement)) return false if (cause != null) { readable.release() writable.release() flushBuffer.release() } else { flush() } slot.cancel(cause) return true } internal fun transferTo(dst: ByteChannelSequentialBase, limit: Long): Long { val size = readable.remaining return if (size <= limit) { dst.writable.writePacket(readable) dst.afterWrite(size.toInt()) afterRead(size.toInt()) size } else { 0 } } @Suppress("DEPRECATION") private suspend fun writeAvailableSuspend(src: ChunkBuffer): Int { awaitAtLeastNBytesAvailableForWrite(1) return writeAvailable(src) } private suspend fun writeAvailableSuspend(src: ByteArray, offset: Int, length: Int): Int { awaitAtLeastNBytesAvailableForWrite(1) return writeAvailable(src, offset, length) } protected fun afterWrite(count: Int) { addBytesWritten(count) if (closed) { writable.release() ensureNotClosed() } if (autoFlush || availableForWrite == 0) { flush() } } override suspend fun awaitFreeSpace() { flush() awaitAtLeastNBytesAvailableForWrite(1) ensureNotClosed() } /** * Suspend until the channel has bytes to read or gets closed. Throws exception if the channel was closed with an error. */ override suspend fun awaitContent() { await(1) } final override suspend fun peekTo( destination: Memory, destinationOffset: Long, offset: Long, min: Long, max: Long ): Long { var bytesCopied = 0L @Suppress("DEPRECATION") readSuspendableSession { val desiredSize = (min + offset).coerceAtMost(EXPECTED_CAPACITY).toInt() await(desiredSize) val buffer = request(1) ?: ChunkBuffer.Empty if (buffer.readRemaining > offset) { bytesCopied = minOf(buffer.readRemaining.toLong() - offset, max, destination.size - destinationOffset) buffer.memory.copyTo(destination, offset, bytesCopied, destinationOffset) } } return bytesCopied } private fun addBytesRead(count: Int) { require(count >= 0) { "Can't read negative amount of bytes: $count" } channelSize.minusAssign(count) _totalBytesRead.addAndGet(count.toLong()) _availableForRead.minusAssign(count) check(channelSize.value >= 0) { "Readable bytes count is negative: $availableForRead, $count in $this" } check(availableForRead >= 0) { "Readable bytes count is negative: $availableForRead, $count in $this" } } private fun addBytesWritten(count: Int) { require(count >= 0) { "Can't write negative amount of bytes: $count" } channelSize.plusAssign(count) _totalBytesWritten.addAndGet(count.toLong()) check(channelSize.value >= 0) { "Readable bytes count is negative: ${channelSize.value}, $count in $this" } } }
apache-2.0
d13ff58af45cfe031b61a6641e6b0a97
27.676923
124
0.597103
5.039933
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/data/api/handler/TargetHandler.kt
1
1783
/* * Copyright (C) 2012 dvbviewer-controller 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 org.dvbviewer.controller.data.api.handler import android.sax.RootElement import android.util.Xml import org.dvbviewer.controller.data.entities.DVBTarget import org.xml.sax.SAXException import org.xml.sax.helpers.DefaultHandler import java.io.IOException import java.io.InputStream import java.util.* /** * Handler to parse the Remote Targets from the DVBViewer Recording Service (Since 1.30.1.0) * * @author RayBa * @date 11.01.2015 */ class TargetHandler : DefaultHandler() { private val targets = ArrayList<DVBTarget>() /** * Parses the xml String targets * * @param xml the xml * @return the list© * @author RayBa * @date 11.01.2015 */ @Throws(SAXException::class, IOException::class) fun parse(xml: InputStream): MutableList<DVBTarget> { val root = RootElement("targets") val targetElement = root.getChild("target") targetElement.setEndTextElementListener { body -> val target = DVBTarget() target.name = body targets.add(target) } Xml.parse(xml, Xml.Encoding.UTF_8, root.contentHandler) return targets } }
apache-2.0
7f9c1b484c090534c332369146db7aae
28.7
92
0.69697
4.077803
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt
2
1165
package eu.kanade.tachiyomi.util.lang import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext fun launchUI(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT, block) fun launchIO(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.IO, CoroutineStart.DEFAULT, block) fun launchNow(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED, block) fun CoroutineScope.launchUI(block: suspend CoroutineScope.() -> Unit): Job = launch(Dispatchers.Main, block = block) fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit): Job = launch(Dispatchers.IO, block = block) suspend fun <T> withUIContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.Main, block) suspend fun <T> withIOContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.IO, block)
apache-2.0
6de70d39e1b3807f1f67352b76ab9791
40.607143
107
0.781974
4.429658
false
false
false
false
zhclwr/YunWeatherKotlin
app/src/main/java/com/victor/yunweatherkotlin/activity/EditCitysActivity.kt
1
3982
package com.victor.yunweatherkotlin.activity import android.content.Intent import android.graphics.Canvas import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback import com.chad.library.adapter.base.listener.OnItemSwipeListener import com.victor.yunweatherkotlin.R import com.victor.yunweatherkotlin.adapter.QuickAdapter import com.victor.yunweatherkotlin.db.County import kotlinx.android.synthetic.main.activity_edit_citys.* import org.jetbrains.anko.defaultSharedPreferences import org.litepal.crud.DataSupport class EditCitysActivity : BaseActivity() { private lateinit var mRecyclerView: RecyclerView private lateinit var mData: MutableList<County> private lateinit var mAdapter: QuickAdapter private lateinit var mItemTouchHelper: ItemTouchHelper private lateinit var mItemDragAndSwipeCallback: ItemDragAndSwipeCallback override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_citys) initView() setListener() swipeAble() } /** * 为recyclerview设置adapter和滑动删除 * */ private fun swipeAble() { mData = DataSupport.findAll(County::class.java) mRecyclerView.layoutManager = LinearLayoutManager(this) val onItemSwipeListener = object : OnItemSwipeListener { override fun onItemSwipeStart(viewHolder: RecyclerView.ViewHolder, pos: Int) { } override fun clearView(viewHolder: RecyclerView.ViewHolder, pos: Int) { } override fun onItemSwiped(viewHolder: RecyclerView.ViewHolder, pos: Int) { var temp = DataSupport.findAll(County::class.java) temp.removeAt(pos) DataSupport.deleteAll(County::class.java) for ((name, weaInfo, cityCode) in temp){ County(name, weaInfo, cityCode).save() } } override fun onItemSwipeMoving(canvas: Canvas, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, isCurrentlyActive: Boolean) { canvas.drawColor(ContextCompat.getColor(this@EditCitysActivity, R.color.color_light_blue)) // canvas.drawText("Just some text", 0, 40, paint); } } mAdapter = QuickAdapter(mData) mItemDragAndSwipeCallback = ItemDragAndSwipeCallback(mAdapter) mItemTouchHelper = ItemTouchHelper(mItemDragAndSwipeCallback) mItemTouchHelper.attachToRecyclerView(mRecyclerView) mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START or ItemTouchHelper.END) mAdapter.enableSwipeItem() mAdapter.setOnItemSwipeListener(onItemSwipeListener) mAdapter.setOnItemClickListener { a, v, i -> val county= mData[i] val cityCode = county.cityCode val edit = defaultSharedPreferences.edit() edit.putString("cityCode", cityCode) edit.putString("cityName",county.name) edit.apply() val i =Intent(applicationContext, WeatherActivity::class.java) i.putExtra("update",true) startActivity(i) finish() } mRecyclerView.adapter = mAdapter } private fun initView(){ mRecyclerView = recycler } private fun setListener() { iv_back_edit.setOnClickListener { finish() } iv_add.setOnClickListener { startActivity(Intent(this, AddCityActivity::class.java)) } } companion object { private val TAG = "EditCityActivity" } }
apache-2.0
56f3271ed786de81f73eaea1ab072c65
36.882353
147
0.667927
4.988679
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OneEntityWithPersistentIdImpl.kt
2
6162
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.annotations.Open @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OneEntityWithPersistentIdImpl: OneEntityWithPersistentId, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _myName: String? = null override val myName: String get() = _myName!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: OneEntityWithPersistentIdData?): ModifiableWorkspaceEntityBase<OneEntityWithPersistentId>(), OneEntityWithPersistentId.Builder { constructor(): this(OneEntityWithPersistentIdData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OneEntityWithPersistentId is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isMyNameInitialized()) { error("Field OneEntityWithPersistentId#myName should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field OneEntityWithPersistentId#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var myName: String get() = getEntityData().myName set(value) { checkModificationAllowed() getEntityData().myName = value changedProperty.add("myName") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): OneEntityWithPersistentIdData = result ?: super.getEntityData() as OneEntityWithPersistentIdData override fun getEntityClass(): Class<OneEntityWithPersistentId> = OneEntityWithPersistentId::class.java } } class OneEntityWithPersistentIdData : WorkspaceEntityData.WithCalculablePersistentId<OneEntityWithPersistentId>() { lateinit var myName: String fun isMyNameInitialized(): Boolean = ::myName.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OneEntityWithPersistentId> { val modifiable = OneEntityWithPersistentIdImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): OneEntityWithPersistentId { val entity = OneEntityWithPersistentIdImpl() entity._myName = myName entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return OnePersistentId(myName) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OneEntityWithPersistentId::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OneEntityWithPersistentIdData if (this.myName != other.myName) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OneEntityWithPersistentIdData if (this.myName != other.myName) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + myName.hashCode() return result } }
apache-2.0
93203514a72d2a1e1d010f969134e979
35.040936
158
0.664395
6.294178
false
false
false
false
dahlstrom-g/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/utils/Utils.kt
10
771
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.utils import org.languagetool.rules.RuleMatch import java.util.* fun RuleMatch.toIntRange(offset: Int = 0) = IntRange(fromPos + offset, toPos + offset - 1) fun IntRange.withOffset(offset: Int) = IntRange(start + offset, endInclusive + offset) fun Boolean?.orTrue() = this ?: true fun Boolean?.orFalse() = this ?: false fun String.trimToNull(): String? = trim().takeIf(String::isNotBlank) fun <T> Collection<T>.toLinkedSet() = LinkedSet<T>(this) typealias LinkedSet<T> = LinkedHashSet<T> val IntRange.length get() = endInclusive - start + 1 fun <T> Enumeration<T>.toSet() = toList().toSet()
apache-2.0
358774bd48811766f7e95dcc27cc99ac
31.125
140
0.728923
3.504545
false
false
false
false
eman-1111/GoogleCodelabs
android-topeka-start/src/main/java/com/google/samples/apps/topeka/activity/CategorySelectionActivity.kt
1
4779
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.activity import android.annotation.SuppressLint import android.content.Intent import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.transition.TransitionInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import com.google.samples.apps.topeka.R import com.google.samples.apps.topeka.fragment.CategorySelectionFragment import com.google.samples.apps.topeka.helper.ActivityLaunchHelper import com.google.samples.apps.topeka.helper.ApiLevelHelper import com.google.samples.apps.topeka.helper.REQUEST_LOGIN import com.google.samples.apps.topeka.helper.REQUEST_SAVE import com.google.samples.apps.topeka.helper.database import com.google.samples.apps.topeka.helper.findFragmentById import com.google.samples.apps.topeka.helper.logout import com.google.samples.apps.topeka.helper.onSmartLockResult import com.google.samples.apps.topeka.helper.replaceFragment import com.google.samples.apps.topeka.helper.requestLogin import com.google.samples.apps.topeka.model.Player import com.google.samples.apps.topeka.widget.AvatarView class CategorySelectionActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_category_selection) initializePlayer() setUpToolbar() if (savedInstanceState == null) { attachCategoryGridFragment() } else { setProgressBarVisibility(View.GONE) } supportPostponeEnterTransition() } private fun updatePlayerViews(player: Player) { findViewById<TextView>(R.id.title).setText(player.toString()) player.avatar?.run { findViewById<AvatarView>(R.id.avatar).setAvatar(this) } } private fun initializePlayer() = requestLogin { updatePlayerViews(it) } private fun setUpToolbar() { setSupportActionBar(findViewById(R.id.toolbar_player)) supportActionBar?.setDisplayShowTitleEnabled(false) } private fun attachCategoryGridFragment() { replaceFragment(R.id.category_container, findFragmentById(R.id.category_container) ?: CategorySelectionFragment()) setProgressBarVisibility(View.GONE) } private fun setProgressBarVisibility(visibility: Int) { findViewById<View>(R.id.progress).visibility = visibility } override fun onResume() { super.onResume() (findViewById<TextView>(R.id.score)).text = getString(R.string.x_points, database().getScore()) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_category, menu) return true } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == CategorySelectionFragment.REQUEST_CATEGORY) { data?.let { findFragmentById(R.id.category_container)?.run { onActivityResult(requestCode, resultCode, data) } } } else if (requestCode == REQUEST_LOGIN || requestCode == REQUEST_SAVE) { onSmartLockResult( requestCode, resultCode, data, success = { }, failure = { requestLogin { updatePlayerViews(it) } }) } else { super.onActivityResult(requestCode, resultCode, data) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.sign_out) { handleSignOut() true } else super.onOptionsItemSelected(item) } @SuppressLint("NewApi") private fun handleSignOut() { if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) { window.exitTransition = TransitionInflater.from(this) .inflateTransition(R.transition.category_enter) } logout() ActivityLaunchHelper.launchSignIn(this, true) supportFinishAfterTransition() } }
apache-2.0
776e42b66c4d719cbfa089149e3f9bbd
35.761538
89
0.694497
4.626331
false
false
false
false
tommyli/nem12-manager
fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/domain/NmiMeterRegister.kt
1
4601
// Tommy Li ([email protected]), 2017-02-20 package co.firefire.fenergy.nem12.domain import co.firefire.fenergy.shared.domain.IntervalLength import co.firefire.fenergy.shared.domain.LoginNmi import co.firefire.fenergy.shared.domain.UnitOfMeasure import co.firefire.fenergy.shared.repository.IntervalLengthConverter import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.util.* import javax.persistence.CascadeType import javax.persistence.Convert import javax.persistence.Entity import javax.persistence.EnumType import javax.persistence.Enumerated import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.MapKey import javax.persistence.OneToMany import javax.persistence.OrderBy import org.hibernate.annotations.GenericGenerator as HbmGenericGenerator import org.hibernate.annotations.Parameter as HbmParameter @Entity data class NmiMeterRegister( @ManyToOne(optional = false) @JoinColumn(name = "login_nmi", referencedColumnName = "id", nullable = false) var loginNmi: LoginNmi = LoginNmi(), var meterSerial: String = "", var registerId: String = "", var nmiSuffix: String = "" ) : Comparable<NmiMeterRegister> { @Id @HbmGenericGenerator( name = "NmiMeterRegisterIdSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = arrayOf( HbmParameter(name = "sequence_name", value = "nmi_meter_register_id_seq"), HbmParameter(name = "initial_value", value = "1000"), HbmParameter(name = "increment_size", value = "1") ) ) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "NmiMeterRegisterIdSeq") var id: Long? = null var version: Int? = 0 var nmiConfig: String? = null var mdmDataStreamId: String? = null var nextScheduledReadDate: LocalDate? = null @Enumerated(EnumType.STRING) var uom: UnitOfMeasure = UnitOfMeasure.KWH @Convert(converter = IntervalLengthConverter::class) var intervalLength: IntervalLength = IntervalLength.IL_30 @OneToMany(mappedBy = "nmiMeterRegister", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true) @MapKey(name = "intervalDate") @OrderBy("intervalDate") var intervalDays: SortedMap<LocalDate, IntervalDay> = TreeMap() fun getDay(localDate: LocalDate): IntervalDay? { return intervalDays.get(localDate) } fun getVolumeType(): VolumeType { return when { nmiSuffix.startsWith("E") -> VolumeType.CONSUMPTION nmiSuffix.startsWith("B") -> VolumeType.GENERATION else -> VolumeType.OTHER } } fun intervalRange(): IntRange { return 1..(Duration.ofDays(1).toMinutes().toInt() / intervalLength.minute) } fun mergeIntervalDays(newIntervalDays: Collection<IntervalDay>) { newIntervalDays.forEach({ mergeIntervalDay(it) }) } fun mergeIntervalDay(newIntervalDay: IntervalDay) { intervalDays.merge(newIntervalDay.intervalDate, newIntervalDay, { existing: IntervalDay, new: IntervalDay -> if (existing.intervalQuality.quality == Quality.V || new.intervalQuality.quality == Quality.V) { existing.mergeNewIntervalValues(new.intervalValues, new.updateDateTime, new.msatsLoadDateTime) existing } else { val existingIntervalDayDateTime = existing.updateDateTime ?: existing.msatsLoadDateTime ?: LocalDateTime.now() val newIntervalDayDateTime = new.updateDateTime ?: new.msatsLoadDateTime ?: LocalDateTime.now() val existingQuality = TimestampedQuality(existing.intervalQuality.quality, existingIntervalDayDateTime) val newQuality = TimestampedQuality(new.intervalQuality.quality, newIntervalDayDateTime) if (newQuality >= existingQuality) { existing.replaceIntervalValues(new.intervalValues) existing } else { existing } } }) } override fun compareTo(other: NmiMeterRegister) = compareValuesBy(this, other, { it.loginNmi }, { it.meterSerial }, { it.registerId }, { it.nmiSuffix }) override fun toString() = "NmiMeterRegister(id=$id, loginNmi='$loginNmi', meterSerial='$meterSerial', registerId='$registerId', nmiSuffix='$nmiSuffix')" }
apache-2.0
5cbd67b3cce28577de56790d6d51903f
38.324786
156
0.692676
4.652174
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/notification/SingletonNotificationManager.kt
3
2087
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.notification import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager import java.util.concurrent.atomic.AtomicReference class SingletonNotificationManager(private val group: NotificationGroup, private val type: NotificationType, private val defaultListener: NotificationListener? = null) { private val notification = AtomicReference<Notification>() private val expiredListener = Runnable { val currentNotification = notification.get() if (currentNotification != null && currentNotification.isExpired) { notification.compareAndSet(currentNotification, null) } } fun notify(content: String, project: Project?): Boolean { return notify("", content, project) } @JvmOverloads fun notify(title: String = "", content: String, project: Project? = null, listener: NotificationListener? = defaultListener, action: AnAction? = null): Boolean { val oldNotification = notification.get() // !oldNotification.isExpired() is not enough - notification could be closed, but not expired if (oldNotification != null) { if (!oldNotification.isExpired && (oldNotification.balloon != null || project != null && group.displayType == NotificationDisplayType.TOOL_WINDOW && ToolWindowManager.getInstance(project).getToolWindowBalloon(group.toolWindowId) != null)) { return false } oldNotification.whenExpired(null) oldNotification.expire() } val newNotification = group.createNotification(title, content, type, listener) if (action != null) { newNotification.addAction(action) } newNotification.whenExpired(expiredListener) notification.set(newNotification) newNotification.notify(project) return true } fun clear() { notification.getAndSet(null)?.let { it.whenExpired(null) it.expire() } } }
apache-2.0
c5aebd3c90b60a986f2a7b969adf52f7
37.666667
169
0.731193
4.831019
false
false
false
false
paplorinc/intellij-community
plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.kt
2
11778
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.idea.svn.SvnPropertyKeys.MERGE_INFO import org.jetbrains.idea.svn.SvnUtil.createUrl import org.jetbrains.idea.svn.SvnUtil.parseUrl import org.jetbrains.idea.svn.api.Depth import org.jetbrains.idea.svn.api.Revision import org.jetbrains.idea.svn.api.Target import org.jetbrains.idea.svn.api.Url import org.jetbrains.idea.svn.dialogs.WCInfo import org.jetbrains.idea.svn.dialogs.WCInfoWithBranches import org.jetbrains.idea.svn.history.SvnChangeList import org.jetbrains.idea.svn.history.SvnRepositoryLocation import org.jetbrains.idea.svn.integrate.MergeContext import org.jetbrains.idea.svn.mergeinfo.BranchInfo import org.jetbrains.idea.svn.mergeinfo.MergeCheckResult import org.jetbrains.idea.svn.mergeinfo.OneShotMergeInfoHelper import org.junit.Assert.* import org.junit.Test import java.io.File private const val CONTENT1 = "123\n456\n123" private const val CONTENT2 = "123\n456\n123\n4" private fun assertRevisions(changeLists: List<SvnChangeList>, vararg expectedTopRevisions: Long) = assertArrayEquals(expectedTopRevisions, changeLists.take(expectedTopRevisions.size).map { it.number }.toLongArray()) private fun newFile(parent: File, name: String) = File(parent, name).also { it.createNewFile() } private fun newFolder(parent: String, name: String) = File(parent, name).also { it.mkdir() } private fun newFolder(parent: File, name: String) = File(parent, name).also { it.mkdir() } class SvnMergeInfoTest : SvnTestCase() { private lateinit var myBranchVcsRoot: File private lateinit var myOneShotMergeInfoHelper: OneShotMergeInfoHelper private lateinit var myMergeChecker: BranchInfo private lateinit var trunk: File private lateinit var folder: File private lateinit var f1: File private lateinit var f2: File private lateinit var myTrunkUrl: String private lateinit var myBranchUrl: String private val trunkChangeLists: List<SvnChangeList> get() { val provider = vcs.committedChangesProvider return provider.getCommittedChanges(provider.createDefaultSettings(), SvnRepositoryLocation(parseUrl(myTrunkUrl, false)), 0) } override fun setUp() { super.setUp() myTrunkUrl = "$myRepoUrl/trunk" myBranchUrl = "$myRepoUrl/branch" myBranchVcsRoot = File(myTempDirFixture.tempDirPath, "branch") myBranchVcsRoot.mkdir() vcsManager.setDirectoryMapping(myBranchVcsRoot.absolutePath, SvnVcs.VCS_NAME) val vcsRoot = LocalFileSystem.getInstance().findFileByIoFile(myBranchVcsRoot) val node = Node(vcsRoot!!, createUrl(myBranchUrl), myRepositoryUrl) val root = RootUrlInfo(node, WorkingCopyFormat.ONE_DOT_EIGHT, vcsRoot, null) val wcInfo = WCInfo(root, true, Depth.INFINITY) val mergeContext = MergeContext(vcs, parseUrl(myTrunkUrl, false), wcInfo, Url.tail(myTrunkUrl), vcsRoot) myOneShotMergeInfoHelper = OneShotMergeInfoHelper(mergeContext) vcs.svnConfiguration.isCheckNestedForQuickMerge = true enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE) val wcInfoWithBranches = WCInfoWithBranches(wcInfo, emptyList<WCInfoWithBranches.Branch>(), vcsRoot, WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("trunk", false))) myMergeChecker = BranchInfo(vcs, wcInfoWithBranches, WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("branch", false))) } @Test fun testSimpleNotMerged() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1) assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED) } @Test fun testSimpleMerged() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1) // rev 4: record as merged into branch recordMerge(myBranchVcsRoot, myTrunkUrl, "-c", "3") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) assertMergeInfo(myBranchVcsRoot, "/trunk:3") assertMergeResult(trunkChangeLists, MergeCheckResult.MERGED) } @Test fun testEmptyMergeinfoBlocks() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1) // rev 4: record as merged into branch merge(myBranchVcsRoot, myTrunkUrl, "-c", "3") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) // rev5: put blocking empty mergeinfo //runInAndVerifyIgnoreOutput("merge", "-c", "-3", myRepoUrl + "/trunk/folder", new File(myBranchVcsRoot, "folder").getAbsolutePath(), "--record-only")); merge(File(myBranchVcsRoot, "folder"), "$myTrunkUrl/folder", "-r", "3:2") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) assertMergeInfo(myBranchVcsRoot, "/trunk:3") assertMergeInfo(File(myBranchVcsRoot, "folder"), "") assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED) } @Test fun testNonInheritableMergeinfo() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1) // rev 4: record non inheritable merge setMergeInfo(myBranchVcsRoot, "/trunk:3*") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) assertMergeInfo(myBranchVcsRoot, "/trunk:3*") assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED) } @Test fun testOnlyImmediateInheritableMergeinfo() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1, CONTENT1) // rev4 editAndCommit(trunk, f1, CONTENT2) updateFile(myBranchVcsRoot) // rev 4: record non inheritable merge setMergeInfo(myBranchVcsRoot, "/trunk:3,4") setMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) assertMergeInfo(myBranchVcsRoot, "/trunk:3-4") assertMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3") val changeLists = trunkChangeLists assertRevisions(changeLists, 4, 3) assertMergeResult(changeLists, MergeCheckResult.NOT_MERGED, MergeCheckResult.MERGED) } @Test fun testTwoPaths() { createTwoFolderStructure(myBranchVcsRoot) // rev 3 editFile(f1) editFile(f2) commitFile(trunk) updateFile(myBranchVcsRoot) // rev 4: record non inheritable merge setMergeInfo(myBranchVcsRoot, "/trunk:3") // this makes not merged for f2 path setMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*") commitFile(myBranchVcsRoot) updateFile(myBranchVcsRoot) assertMergeInfo(myBranchVcsRoot, "/trunk:3") assertMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*") val changeListList = trunkChangeLists assertRevisions(changeListList, 3) assertMergeResult(changeListList, MergeCheckResult.NOT_MERGED) } @Test fun testWhenInfoInRepo() { val fullBranch = newFolder(myTempDirFixture.tempDirPath, "fullBranch") createTwoFolderStructure(fullBranch) // folder1 will be taken as branch wc root checkOutFile("$myBranchUrl/folder/folder1", myBranchVcsRoot) // rev 3 : f2 changed editAndCommit(trunk, f2) // rev 4: record as merged into branch using full branch WC recordMerge(fullBranch, myTrunkUrl, "-c", "3") commitFile(fullBranch) updateFile(myBranchVcsRoot) val changeListList = trunkChangeLists assertRevisions(changeListList, 3) assertMergeResult(changeListList[0], MergeCheckResult.MERGED) } @Test fun testMixedWorkingRevisions() { createOneFolderStructure() // rev 3 editAndCommit(trunk, f1) // rev 4: record non inheritable merge setMergeInfo(myBranchVcsRoot, "/trunk:3") commitFile(myBranchVcsRoot) // ! no update! assertMergeInfo(myBranchVcsRoot, "/trunk:3") val f1info = vcs.getInfo(File(myBranchVcsRoot, "folder/f1.txt")) assertEquals(2, f1info!!.revision.number) val changeList = trunkChangeLists[0] assertMergeResult(changeList, MergeCheckResult.NOT_MERGED) // and after update updateFile(myBranchVcsRoot) myMergeChecker.clear() assertMergeResult(changeList, MergeCheckResult.MERGED) } private fun createOneFolderStructure() { trunk = newFolder(myTempDirFixture.tempDirPath, "trunk") folder = newFolder(trunk, "folder") f1 = newFile(folder, "f1.txt") f2 = newFile(folder, "f2.txt") importAndCheckOut(trunk) } private fun createTwoFolderStructure(branchFolder: File) { trunk = newFolder(myTempDirFixture.tempDirPath, "trunk") folder = newFolder(trunk, "folder") f1 = newFile(folder, "f1.txt") val folder1 = newFolder(folder, "folder1") f2 = newFile(folder1, "f2.txt") importAndCheckOut(trunk, branchFolder) } private fun importAndCheckOut(trunk: File, branch: File = myBranchVcsRoot) { runInAndVerifyIgnoreOutput("import", "-m", "test", trunk.absolutePath, myTrunkUrl) runInAndVerifyIgnoreOutput("copy", "-m", "test", myTrunkUrl, myBranchUrl) FileUtil.delete(trunk) checkOutFile(myTrunkUrl, trunk) checkOutFile(myBranchUrl, branch) } private fun editAndCommit(trunk: File, file: File, content: String = CONTENT1) { val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) editAndCommit(trunk, vf!!, content) } private fun editAndCommit(trunk: File, file: VirtualFile, content: String) { editFileInCommand(file, content) commitFile(trunk) } private fun editFile(file: File) { val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) editFileInCommand(vf!!, CONTENT1) } private fun assertMergeInfo(file: File, expectedValue: String) { val propertyValue = vcs.getFactory(file).createPropertyClient().getProperty(Target.on(file), MERGE_INFO, false, Revision.WORKING) assertNotNull(propertyValue) assertEquals(expectedValue, propertyValue!!.toString()) } private fun assertMergeResult(changeLists: List<SvnChangeList>, vararg mergeResults: MergeCheckResult) { myOneShotMergeInfoHelper.prepare() for ((index, mergeResult) in mergeResults.withIndex()) { assertMergeResult(changeLists[index], mergeResult) assertMergeResultOneShot(changeLists[index], mergeResult) } } private fun assertMergeResult(changeList: SvnChangeList, mergeResult: MergeCheckResult) = assertEquals(mergeResult, myMergeChecker.checkList(changeList, myBranchVcsRoot.absolutePath)) private fun assertMergeResultOneShot(changeList: SvnChangeList, mergeResult: MergeCheckResult) = assertEquals(mergeResult, myOneShotMergeInfoHelper.checkList(changeList)) private fun commitFile(file: File) = runInAndVerifyIgnoreOutput("ci", "-m", "test", file.absolutePath) private fun updateFile(file: File) = runInAndVerifyIgnoreOutput("up", file.absolutePath) private fun checkOutFile(url: String, directory: File) = runInAndVerifyIgnoreOutput("co", url, directory.absolutePath) private fun setMergeInfo(file: File, value: String) = runInAndVerifyIgnoreOutput("propset", "svn:mergeinfo", value, file.absolutePath) private fun merge(file: File, url: String, vararg revisions: String) = merge(file, url, false, *revisions) private fun recordMerge(file: File, url: String, vararg revisions: String) = merge(file, url, true, *revisions) private fun merge(file: File, url: String, recordOnly: Boolean, vararg revisions: String) { val parameters = mutableListOf<String>("merge", *revisions, url, file.absolutePath) if (recordOnly) { parameters.add("--record-only") } runInAndVerifyIgnoreOutput(*parameters.toTypedArray()) } }
apache-2.0
1dc0f4c83245e1510955661f1ad9166f
34.908537
156
0.746052
4.485149
false
true
false
false
gen1nya/lfg_player-android
app/src/main/java/ru/ltcnt/lfg_player_android/presentation/navigation/MainNavigator.kt
1
3881
package ru.ltcnt.lfg_player_android.presentation.navigation import android.app.Fragment import android.support.v4.widget.DrawerLayout import android.util.Log import android.widget.Toast import com.mikepenz.materialdrawer.Drawer import com.pawegio.kandroid.runDelayed import ru.ltcnt.lfg_player_android.R import ru.ltcnt.lfg_player_android.app.App import ru.ltcnt.lfg_player_android.presentation.main.MainActivity import ru.ltcnt.lfg_player_android.presentation.player.PlayerFragment import ru.ltcnt.lfg_player_android.presentation.playlist.PlaylistFragment import ru.terrakok.cicerone.Navigator import ru.terrakok.cicerone.commands.* /** * Author aev * Since 21.10.2017. */ class MainNavigator( private val activity: MainActivity, private val drawer: Drawer ): Navigator { override fun applyCommand(command: Command?) { when (command){ is NavigateWithReplace -> navigateWithReplace(command) is Forward -> forward(command) is Replace -> replace(command) is BackTo -> backTo(command) is Back -> back() is OpenDrawer -> openDrawer() is LockDrawer -> lockDrawer(command) is SystemMessage -> Toast.makeText(App.appContext, command.message, Toast.LENGTH_SHORT).show() else -> Log.e("Cicerone", "Illegal command for this screen") } } private fun lockDrawer(command: LockDrawer) { if (command.drawerEnabled){ drawer.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) } else { drawer.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) } } private fun openDrawer() { drawer.openDrawer() } private var preexitState: Boolean = false private fun back() { if (activity.fragmentManager.backStackEntryCount > 0){ activity.fragmentManager.popBackStack() } else { if (preexitState){ activity.finish() } else { preexitState = true runDelayed(3000, {preexitState = false}) Toast.makeText(App.appContext, "Нажмите еще раз для выхода", Toast.LENGTH_SHORT).show() } } } private fun backTo(command: BackTo) { } private fun forward(command: Forward) { } private fun navigateWithReplace(command: NavigateWithReplace) { } private fun replace(command: Replace) { when (command.screenKey){ Screens.PLAYER -> { replaceFragment(PlayerFragment.newInstance(), false, false) } Screens.PLAYLIST -> { replaceFragment(PlaylistFragment.newInstance(), false, false) } } } private fun replaceFragment(fragment: Fragment, animate: Boolean = false, backStack: Boolean = false ) { val fragmentTransaction = activity.fragmentManager.beginTransaction() if (animate){ //fragmentTransaction.setCustomAnimations() } if (backStack) { fragmentTransaction.addToBackStack(null) } fragmentTransaction.replace(R.id.fragmentPlaceholder, fragment) fragmentTransaction.commit() } private fun addFragment(fragment: Fragment, animate: Boolean = false, backStack: Boolean = false) { val fragmentTransaction = activity.fragmentManager.beginTransaction() if (animate){ //fragmentTransaction.setCustomAnimations() } if (backStack) { fragmentTransaction.addToBackStack(null) } fragmentTransaction.add(R.id.fragmentPlaceholder, fragment, null) fragmentTransaction.commit() } }
apache-2.0
3d9dcc36fb6d1bff98d63b6322f739a8
32.859649
106
0.627624
4.92848
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentWithNullsImpl.kt
1
8308
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ParentWithNullsImpl(val dataSource: ParentWithNullsData) : ParentWithNulls, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNulls::class.java, ChildWithNulls::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } override val parentData: String get() = dataSource.parentData override val child: ChildWithNulls? get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ParentWithNullsData?) : ModifiableWorkspaceEntityBase<ParentWithNulls>(), ParentWithNulls.Builder { constructor() : this(ParentWithNullsData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentWithNulls is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isParentDataInitialized()) { error("Field ParentWithNulls#parentData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ParentWithNulls this.entitySource = dataSource.entitySource this.parentData = dataSource.parentData if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentData: String get() = getEntityData().parentData set(value) { checkModificationAllowed() getEntityData().parentData = value changedProperty.add("parentData") } override var child: ChildWithNulls? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityData(): ParentWithNullsData = result ?: super.getEntityData() as ParentWithNullsData override fun getEntityClass(): Class<ParentWithNulls> = ParentWithNulls::class.java } } class ParentWithNullsData : WorkspaceEntityData<ParentWithNulls>() { lateinit var parentData: String fun isParentDataInitialized(): Boolean = ::parentData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentWithNulls> { val modifiable = ParentWithNullsImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ParentWithNulls { return getCached(snapshot) { val entity = ParentWithNullsImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentWithNulls::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ParentWithNulls(parentData, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentWithNullsData if (this.entitySource != other.entitySource) return false if (this.parentData != other.parentData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentWithNullsData if (this.parentData != other.parentData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + parentData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
d8994c741d1cb126e60b743c704887a4
34.20339
135
0.701854
5.422977
false
false
false
false
google/intellij-community
plugins/kotlin/idea/tests/testData/multiModuleHighlighting/languageVersionsViaFacets/m2/m2.kt
3
747
package languageVersion1_0 public fun useJavaMap1_0(): java.util.HashMap<Int, Int> { val g = java.util.HashMap<Int, Int>() g.values.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: removeIf">removeIf</error> { <error descr="[UNRESOLVED_REFERENCE] Unresolved reference: it">it</error> <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved"><</error> 5 } return g } val use1_1 = languageVersion1_1.useJavaMap1_1().values.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: removeIf">removeIf</error> { <error descr="[UNRESOLVED_REFERENCE] Unresolved reference: it">it</error> <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved"><</error> 5 }
apache-2.0
f7db3ee640a9be3e1dcee2200e8caec9
73.7
321
0.741633
3.931579
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClientPreferences.kt
1
2439
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Opcodes.GETFIELD import org.objectweb.asm.Type.BOOLEAN_TYPE import org.objectweb.asm.Type.INT_TYPE class ClientPreferences : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceFields.count { it.type == LinkedHashMap::class.type } == 1 } class windowMode : InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE } } class parameters : InstanceField() { override val predicate = predicateOf<Field2> { it.type == LinkedHashMap::class.type } } @MethodParameters() @DependsOn(Packet::class) class toBuffer : InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<Packet>() } } @DependsOn(toBuffer::class) class roofsHidden : OrderMapper.InMethod.Field(toBuffer::class, 0, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == BOOLEAN_TYPE && it.fieldOwner == type<ClientPreferences>() } } @DependsOn(toBuffer::class) class titleMusicDisabled : OrderMapper.InMethod.Field(toBuffer::class, 1, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == BOOLEAN_TYPE && it.fieldOwner == type<ClientPreferences>() } } @DependsOn(toBuffer::class) class hideUsername : OrderMapper.InMethod.Field(toBuffer::class, 2, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == BOOLEAN_TYPE && it.fieldOwner == type<ClientPreferences>() } } class rememberedUsername : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == String::class.type } } }
mit
5c48dd6e6dd3eef961a58e4671026809
44.185185
162
0.731037
4.147959
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/toolboks/Toolboks.kt
2
637
package io.github.chrislo27.toolboks import com.badlogic.gdx.Input import io.github.chrislo27.toolboks.logging.Logger /** * Holds constants and some info about Toolboks. */ object Toolboks { // val TOOLBOKS_VERSION: Version = Version(1, 0, 0) const val TOOLBOKS_ASSET_PREFIX: String = "toolboks_" @Volatile lateinit var LOGGER: Logger const val DEBUG_KEY: Int = Input.Keys.F8 val DEBUG_KEY_NAME: String = Input.Keys.toString(DEBUG_KEY) var debugMode: Boolean = false var stageOutlines: StageOutlineMode = StageOutlineMode.NONE enum class StageOutlineMode { NONE, ALL, ONLY_VISIBLE } }
gpl-3.0
c569f1630130beb4050a7a02c51939cd
23.538462
63
0.714286
3.619318
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/PersistentMap.kt
1
681
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.util.Date @Parcelize class PersistentMap(var id: String? = null, var name: String? = null, var url: String? = null, var rawMapUrl: String? = null, var expireAt: Date? = null) : Parcelable{ //milliseconds //30 secs of margin val isExpired: Boolean get() { val difference = expireAt?.time?:Long.MAX_VALUE - System.currentTimeMillis() return difference < 30 * 1000 } }
mit
018d75ff6f9ff3a0c5e0019130cc999f
25.192308
88
0.591777
4.25625
false
false
false
false
allotria/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleTasksUtil.kt
2
4981
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.util import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.task.TaskData import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap import com.intellij.openapi.project.Project import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil import org.jetbrains.plugins.gradle.settings.GradleSettings /** * @return `external module path (path to the directory) -> {gradle module path -> {[tasks of this module]}}` */ @ApiStatus.Experimental fun getGradleTasksMap(project: Project): Map<String, MultiMap<String, TaskData>> { return getGradleTaskNodesMap(project).mapValues { (_, moduleTasks) -> val transformed = MultiMap.create<String, TaskData>() for ((gradleModulePath, moduleTaskNodes) in moduleTasks.entrySet()) { transformed.putValues(gradleModulePath, moduleTaskNodes.map { it.data }) } transformed } } /** * @return `external module path (path to the directory) -> {gradle module path -> {[task nodes of this module]}}` */ @ApiStatus.Experimental fun getGradleTaskNodesMap(project: Project): Map<String, MultiMap<String, DataNode<TaskData>>> { val tasks = LinkedHashMap<String, MultiMap<String, DataNode<TaskData>>>() for (projectTaskData in findGradleTasks(project)) { val projectTasks = MultiMap.createOrderedSet<String, DataNode<TaskData>>() val modulePaths = PathPrefixTreeMap<String>(":", removeTrailingSeparator = false) for (moduleTaskData in projectTaskData.modulesTaskData) { modulePaths[moduleTaskData.gradlePath] = moduleTaskData.externalModulePath projectTasks.putValues(moduleTaskData.gradlePath, moduleTaskData.tasks) } for ((gradlePath, externalModulePath) in modulePaths) { val moduleTasks = MultiMap.createOrderedSet<String, DataNode<TaskData>>() val childrenModulesPaths = modulePaths.getAllDescendantKeys(gradlePath) for (childModulePath in childrenModulesPaths) { moduleTasks.putValues(childModulePath, projectTasks.get(childModulePath)) } tasks[externalModulePath] = moduleTasks } } return tasks } @ApiStatus.Experimental fun getGradleFqnTaskName(gradleModulePath: String, taskData: TaskData): String { val taskPath = gradleModulePath.removeSuffix(":") val taskName = taskData.name.removePrefix(gradleModulePath).removePrefix(":") return "$taskPath:$taskName" } private data class ProjectTaskData(val externalProjectPath: String, val modulesTaskData: List<ModuleTaskData>) private data class ModuleTaskData(val externalModulePath: String, val gradlePath: String, val tasks: List<DataNode<TaskData>>) private fun findGradleTasks(project: Project): List<ProjectTaskData> { val projectDataManager = ProjectDataManager.getInstance() val projects = MultiMap.createOrderedSet<String, DataNode<ModuleData>>() for (settings in GradleSettings.getInstance(project).linkedProjectsSettings) { val projectInfo = projectDataManager.getExternalProjectData(project, GradleConstants.SYSTEM_ID, settings.externalProjectPath) val compositeParticipants = settings.compositeBuild?.compositeParticipants ?: emptyList() val compositeProjects = compositeParticipants.flatMap { it.projects.map { module -> module to it.rootPath } }.toMap() val projectNode = projectInfo?.externalProjectStructure ?: continue val moduleNodes = ExternalSystemApiUtil.getChildren(projectNode, ProjectKeys.MODULE) for (moduleNode in moduleNodes) { val externalModulePath = moduleNode.data.linkedExternalProjectPath val projectPath = compositeProjects[externalModulePath] ?: settings.externalProjectPath projects.putValue(projectPath, moduleNode) } } val projectTasksData = ArrayList<ProjectTaskData>() for ((externalProjectPath, modulesNodes) in projects.entrySet()) { val modulesTaskData = modulesNodes.map(::getModuleTasks) projectTasksData.add(ProjectTaskData(externalProjectPath, modulesTaskData)) } return projectTasksData } private fun getModuleTasks(moduleNode: DataNode<ModuleData>): ModuleTaskData { val moduleData = moduleNode.data val externalModulePath = moduleData.linkedExternalProjectPath val gradlePath = GradleProjectResolverUtil.getGradlePath(moduleData) .removeSuffix(":") val tasks = ExternalSystemApiUtil.getChildren(moduleNode, ProjectKeys.TASK) .filter { it.data.name.isNotEmpty() } return ModuleTaskData(externalModulePath, gradlePath, tasks) }
apache-2.0
ecea2f647e72caf0416f2a9b4251aa33
49.836735
140
0.788396
4.817215
false
false
false
false
xranby/modern-jogl-examples
src/main/kotlin/main/tut04/orthoCube.kt
1
5907
package main.tut04 import buffer.BufferUtils import buffer.destroy import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import com.jogamp.opengl.util.glsl.ShaderProgram import extensions.intBufferBig import extensions.toFloatBuffer import glsl.programOf import glsl.shaderCodeOf import main.L import main.SIZE import main.framework.Framework import main.framework.Semantic import vec._4.Vec4 /** * Created by GBarbieri on 22.02.2017. */ fun main(args: Array<String>) { OrthoCube_() } class OrthoCube_ : Framework("Tutorial 04 - Ortho Cube") { var theProgram = 0 var offsetUniform = 0 val vertexBufferObject = intBufferBig(1) val vao = intBufferBig(1) override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArrays(1, vao) glBindVertexArray(vao[0]) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, this::class.java, "tut04", "ortho-with-offset.vert", "standard-colors.frag") offsetUniform = gl.glGetUniformLocation(theProgram, "offset") } fun initializeVertexBuffer(gl: GL3) = with(gl) { val vertexBuffer = vertexData.toFloatBuffer() glGenBuffers(1, vertexBufferObject) glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[0]) glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) vertexBuffer.destroy() } override fun display(gl: GL3) = with(gl) { glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 0f)) glUseProgram(theProgram) glUniform2f(offsetUniform, 0.5f, 0.25f) val colorData = vertexData.size * java.lang.Float.BYTES / 2 glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[0]) glEnableVertexAttribArray(Semantic.Attr.POSITION) glEnableVertexAttribArray(Semantic.Attr.COLOR) glVertexAttribPointer(Semantic.Attr.POSITION, 4, GL_FLOAT, false, Vec4.SIZE, 0) glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, colorData.L) glDrawArrays(GL_TRIANGLES, 0, 36) glDisableVertexAttribArray(Semantic.Attr.POSITION) glDisableVertexAttribArray(Semantic.Attr.COLOR) glUseProgram(0) } override fun reshape(gl: GL3, w: Int, h: Int) { gl.glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(1, vertexBufferObject) glDeleteVertexArrays(1, vao) vao.destroy() vertexBufferObject.destroy() } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } } val vertexData = floatArrayOf( +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f) }
mit
1865a20c2f3549cbb753ebaf2e227cb4
26.867925
111
0.512781
2.477768
false
false
false
false
bekwam/todomvcFX
examples/tornadofx/src/main/kotlin/todomvcfx/tornadofx/app/Styles.kt
1
1384
package todomvcfx.tornadofx.app import tornadofx.* /** * CSS Styles for the TodoItem app * * Created by carl on 10/16/16. */ class Styles : Stylesheet() { companion object { val strikethrough by cssclass() val item_root by cssclass() val content_box by cssclass() val close_icon by cssclass() val content_label by cssclass() val check_box by cssclass() val title by cssid() val add_item_root by cssclass() val main_check_box by cssclass() } init { strikethrough { text { strikethrough = true } } close_icon { fill = c("#cc9a9a") and(hover) { fill = c("#af5b5e") } } item_root { padding = box(0.5.em) } content_box { button { backgroundColor += c("transparent") } } check_box { padding = box(0.0.em, 1.0.em, 0.0.em, 0.0.em) } content_label { fontSize = 1.2.em } title { fontSize = 3.em textFill = c(175,47,47,0.5) } add_item_root { padding = box(1.em) } main_check_box { padding = box(0.1.em, 1.em, 0.1.em, 0.1.em) } } }
mit
5f5695395a16e80b3da679a787942e32
18.785714
57
0.450145
3.898592
false
false
false
false
spring-projects/spring-framework
spring-jdbc/src/main/kotlin/org/springframework/jdbc/core/JdbcOperationsExtensions.kt
1
4270
/* * Copyright 2002-2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.core import java.sql.ResultSet /** * Extension for [JdbcOperations.queryForObject] providing a `queryForObject<Foo>("...")` variant. * * @author Mario Arias * @since 5.0 */ inline fun <reified T> JdbcOperations.queryForObject(sql: String): T = queryForObject(sql, T::class.java) as T /** * Extensions for [JdbcOperations.queryForObject] providing a RowMapper-like function * variant: `queryForObject("...", arg1, argN){ rs, i -> }`. * * @author Mario Arias * @since 5.0 */ inline fun <reified T> JdbcOperations.queryForObject(sql: String, vararg args: Any, crossinline function: (ResultSet, Int) -> T): T = queryForObject(sql, RowMapper { resultSet, i -> function(resultSet, i) }, *args) as T /** * Extension for [JdbcOperations.queryForObject] providing a * `queryForObject<Foo>("...", arrayOf(arg1, argN), intArray(type1, typeN))` variant. * * @author Mario Arias * @since 5.0 */ inline fun <reified T> JdbcOperations.queryForObject(sql: String, args: Array<out Any>, argTypes: IntArray): T? = queryForObject(sql, args, argTypes, T::class.java) as T /** * Extension for [JdbcOperations.queryForObject] providing a * `queryForObject<Foo>("...", arrayOf(arg1, argN))` variant. * * @author Mario Arias * @since 5.0 */ @Suppress("DEPRECATION") // TODO Replace by the vararg variant in Spring Framework 6 inline fun <reified T> JdbcOperations.queryForObject(sql: String, args: Array<out Any>): T? = queryForObject(sql, args, T::class.java) as T /** * Extension for [JdbcOperations.queryForList] providing a `queryForList<Foo>("...")` variant. * * @author Mario Arias * @since 5.0 */ @Suppress("EXTENSION_SHADOWED_BY_MEMBER") inline fun <reified T> JdbcOperations.queryForList(sql: String): List<T> = queryForList(sql, T::class.java) /** * Extension for [JdbcOperations.queryForList] providing a * `queryForList<Foo>("...", arrayOf(arg1, argN), intArray(type1, typeN))` variant. * * @author Mario Arias * @since 5.0 */ @Suppress("EXTENSION_SHADOWED_BY_MEMBER") inline fun <reified T> JdbcOperations.queryForList(sql: String, args: Array<out Any>, argTypes: IntArray): List<T> = queryForList(sql, args, argTypes, T::class.java) /** * Extension for [JdbcOperations.queryForList] providing a * `queryForList<Foo>("...", arrayOf(arg1, argN))` variant. * * @author Mario Arias * @since 5.0 */ @Suppress("DEPRECATION") // TODO Replace by the vararg variant in Spring Framework 6 inline fun <reified T> JdbcOperations.queryForList(sql: String, args: Array<out Any>): List<T> = queryForList(sql, args, T::class.java) /** * Extension for [JdbcOperations.query] providing a ResultSetExtractor-like function * variant: `query<Foo>("...", arg1, argN){ rs -> }`. * * @author Mario Arias * @since 5.0 */ inline fun <reified T> JdbcOperations.query(sql: String, vararg args: Any, crossinline function: (ResultSet) -> T): T = query(sql, ResultSetExtractor { function(it) }, *args) as T /** * Extension for [JdbcOperations.query] providing a RowCallbackHandler-like function * variant: `query("...", arg1, argN){ rs -> }`. * * @author Mario Arias * @since 5.0 */ fun JdbcOperations.query(sql: String, vararg args: Any, function: (ResultSet) -> Unit): Unit = query(sql, RowCallbackHandler { function(it) }, *args) /** * Extensions for [JdbcOperations.query] providing a RowMapper-like function variant: * `query("...", arg1, argN){ rs, i -> }`. * * @author Mario Arias * @since 5.0 */ fun <T> JdbcOperations.query(sql: String, vararg args: Any, function: (ResultSet, Int) -> T): List<T> = query(sql, RowMapper { rs, i -> function(rs, i) }, *args)
apache-2.0
a177de03722dcbca5dc03645dd8d1a58
32.888889
133
0.698361
3.662093
false
false
false
false
leafclick/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/RecentProjectManagerTest.kt
1
6822
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide import com.intellij.configurationStore.deserializeInto import com.intellij.openapi.util.JDOMUtil import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.assertions.Assertions.assertThat import org.junit.ClassRule import org.junit.Test class RecentProjectManagerTest { companion object { @ClassRule @JvmField val appRule = ApplicationRule() } @Test fun `migrate open paths - no additional info`() { val manager = RecentProjectsManagerBase() val element = JDOMUtil.load(""" <application> <component name="RecentProjectsManager"> <option name="openPaths"> <list> <option value="/IdeaProjects/untitled" /> </list> </option> </component> </application> """.trimIndent()) val state = RecentProjectManagerState() element.getChild("component")!!.deserializeInto(state) manager.loadState(state) assertThat(manager.state.additionalInfo.keys.joinToString("\n")).isEqualTo("/IdeaProjects/untitled") @Suppress("DEPRECATION") assertThat(manager.state.recentPaths.joinToString("\n")).isEqualTo("/IdeaProjects/untitled") } @Test fun `migrate open paths - 1 additional info`() { val manager = RecentProjectsManagerBase() val element = JDOMUtil.load(""" <application> <component name="RecentProjectsManager"> <option name="openPaths"> <list> <option value="/IdeaProjects/untitled" /> </list> </option> <option name="additionalInfo"> <map> <entry key="/IdeaProjects/untitled"> <value> <RecentProjectMetaInfo> </RecentProjectMetaInfo> </value> </entry> </map> </option> </component> </application> """.trimIndent()) val state = RecentProjectManagerState() element.getChild("component")!!.deserializeInto(state) manager.loadState(state) assertThat(manager.state.additionalInfo.keys.joinToString("\n")).isEqualTo("/IdeaProjects/untitled") @Suppress("DEPRECATION") assertThat(manager.state.recentPaths.joinToString("\n")).isEqualTo("/IdeaProjects/untitled") } @Test fun `migrate open paths - 2 additional info`() { val manager = RecentProjectsManagerBase() val element = JDOMUtil.load(""" <application> <component name="RecentProjectsManager"> <option name="openPaths"> <list> <option value="/IdeaProjects/untitled" /> </list> </option> <option name="additionalInfo"> <map> <entry key="/IdeaProjects/untitled"> <value> <RecentProjectMetaInfo> </RecentProjectMetaInfo> </value> </entry> <entry key="/IdeaProjects/untitled2"> <value> <RecentProjectMetaInfo> </RecentProjectMetaInfo> </value> </entry> </map> </option> </component> </application> """.trimIndent()) val state = RecentProjectManagerState() element.getChild("component")!!.deserializeInto(state) manager.loadState(state) assertThat(manager.state.additionalInfo.keys.joinToString("\n")).isEqualTo(""" /IdeaProjects/untitled2 /IdeaProjects/untitled """.trimIndent()) @Suppress("DEPRECATION") assertThat(manager.state.recentPaths.joinToString("\n")).isEqualTo(""" /IdeaProjects/untitled /IdeaProjects/untitled2 """.trimIndent()) } @Test fun `ignore projects in additionalInfo if not in recentPaths`() { val manager = RecentProjectsManagerBase() val element = JDOMUtil.load(""" <application> <component name="RecentDirectoryProjectsManager"> <option name="recentPaths"> <list> <option value="/home/WebstormProjects/untitled" /> <option value="/home/WebstormProjects/conference-data" /> </list> </option> <option name="pid" value="" /> <option name="additionalInfo"> <map> <entry key="/home/WebstormProjects/conference-data"> <value> <RecentProjectMetaInfo> <option name="build" value="WS-191.8026.39" /> <option name="productionCode" value="WS" /> <option name="projectOpenTimestamp" value="1572355647642" /> <option name="buildTimestamp" value="1564385774770" /> </RecentProjectMetaInfo> </value> </entry> <entry key="/home/WebstormProjects/new-react-app-for-testing"> <value> <RecentProjectMetaInfo> <option name="build" value="WS-191.8026.39" /> <option name="productionCode" value="WS" /> <option name="projectOpenTimestamp" value="1571662310725" /> <option name="buildTimestamp" value="1564385807237" /> </RecentProjectMetaInfo> </value> </entry> <entry key="/home/WebstormProjects/untitled"> <value> <RecentProjectMetaInfo> <option name="build" value="WS-191.8026.39" /> <option name="productionCode" value="WS" /> <option name="projectOpenTimestamp" value="1574357146611" /> <option name="buildTimestamp" value="1564385803063" /> </RecentProjectMetaInfo> </value> </entry> <entry key="/home/WebstormProjects/untitled2"> <value> <RecentProjectMetaInfo> <option name="build" value="WS-191.8026.39" /> <option name="productionCode" value="WS" /> <option name="projectOpenTimestamp" value="1574416340298" /> <option name="buildTimestamp" value="1564385805606" /> </RecentProjectMetaInfo> </value> </entry> </map> </option> </component> </application> """.trimIndent()) val state = RecentProjectManagerState() element.getChild("component")!!.deserializeInto(state) manager.loadState(state) assertThat(manager.state.additionalInfo.keys.joinToString("\n")).isEqualTo(""" /home/WebstormProjects/conference-data /home/WebstormProjects/untitled """.trimIndent()) @Suppress("DEPRECATION") assertThat(manager.state.recentPaths.joinToString("\n")).isEqualTo(""" /home/WebstormProjects/untitled /home/WebstormProjects/conference-data """.trimIndent()) } }
apache-2.0
64adf14279e0b394d62172b0745aed90
34.352332
140
0.602316
5.079672
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/ArraysTest/copyOf.kt
2
2376
import kotlin.test.* fun <T> assertArrayNotSameButEquals(expected: Array<out T>, actual: Array<out T>, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: IntArray, actual: IntArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: LongArray, actual: LongArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: ShortArray, actual: ShortArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: ByteArray, actual: ByteArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: DoubleArray, actual: DoubleArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: FloatArray, actual: FloatArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: CharArray, actual: CharArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: BooleanArray, actual: BooleanArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun box() { booleanArrayOf(true, false, true).let { assertArrayNotSameButEquals(it, it.copyOf()) } byteArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } shortArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } intArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } longArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } floatArrayOf(0F, 1F, 2F, 3F).let { assertArrayNotSameButEquals(it, it.copyOf()) } doubleArrayOf(0.0, 1.0, 2.0, 3.0, 4.0, 5.0).let { assertArrayNotSameButEquals(it, it.copyOf()) } charArrayOf('0', '1', '2', '3', '4', '5').let { assertArrayNotSameButEquals(it, it.copyOf()) } }
apache-2.0
d3031e84ea0aa6e200f47047d7afa5a7
48.5
105
0.719276
4.335766
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/handleException.kt
2
1910
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { var exception: Throwable? = null val postponedActions = ArrayList<() -> Unit>() suspend fun suspendWithValue(v: String): String = suspendCoroutineOrReturn { x -> postponedActions.add { x.resume(v) } COROUTINE_SUSPENDED } suspend fun suspendWithException(e: Exception): String = suspendCoroutineOrReturn { x -> postponedActions.add { x.resumeWithException(e) } COROUTINE_SUSPENDED } fun run(c: suspend Controller.() -> Unit) { c.startCoroutine(this, handleExceptionContinuation { exception = it }) while (postponedActions.isNotEmpty()) { postponedActions[0]() postponedActions.removeAt(0) } } } fun builder(c: suspend Controller.() -> Unit) { val controller = Controller() controller.run(c) if (controller.exception?.message != "OK") { throw RuntimeException("Unexpected result: ${controller.exception?.message}") } } fun commonThrow(t: Throwable) { throw t } fun box(): String { builder { throw RuntimeException("OK") } builder { commonThrow(RuntimeException("OK")) } builder { suspendWithException(RuntimeException("OK")) } builder { try { suspendWithException(RuntimeException("fail 1")) } catch (e: RuntimeException) { suspendWithException(RuntimeException("OK")) } } builder { try { suspendWithException(Exception("OK")) } catch (e: RuntimeException) { suspendWithException(RuntimeException("fail 3")) throw RuntimeException("fail 4") } } return "OK" }
apache-2.0
e6a14d17c26a2f21a326b69c01794f38
22.292683
92
0.601047
5
false
false
false
false
smmribeiro/intellij-community
platform/configuration-store-impl/src/TrackingPathMacroSubstitutorImpl.kt
5
2568
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.TrackingPathMacroSubstitutor import org.jetbrains.annotations.ApiStatus internal fun PathMacroManager?.createTrackingSubstitutor(): TrackingPathMacroSubstitutorImpl? = if (this == null) null else TrackingPathMacroSubstitutorImpl(this) @ApiStatus.Internal class TrackingPathMacroSubstitutorImpl(internal val macroManager: PathMacroManager) : PathMacroSubstitutor by macroManager, TrackingPathMacroSubstitutor { private val lock = Object() private val macroToComponentNames = HashMap<String, MutableSet<String>>() private val componentNameToMacros = HashMap<String, MutableSet<String>>() override fun reset() { synchronized(lock) { macroToComponentNames.clear() componentNameToMacros.clear() } } override fun hashCode() = macroManager.expandMacroMap.hashCode() override fun invalidateUnknownMacros(macros: Set<String>) { synchronized(lock) { for (macro in macros) { val componentNames = macroToComponentNames.remove(macro) ?: continue for (component in componentNames) { componentNameToMacros.remove(component) } } } } override fun getComponents(macros: Collection<String>): Set<String> { synchronized(lock) { val result = HashSet<String>() for (macro in macros) { result.addAll(macroToComponentNames.get(macro) ?: continue) } return result } } override fun getUnknownMacros(componentName: String?): Set<String> { return synchronized(lock) { @Suppress("UNCHECKED_CAST") if (componentName == null) { macroToComponentNames.keys } else { componentNameToMacros.get(componentName) ?: emptySet() } } } override fun addUnknownMacros(componentName: String, unknownMacros: Collection<String>) { if (unknownMacros.isEmpty()) { return } LOG.info("Registering unknown macros ${unknownMacros.joinToString(", ")} in component $componentName") synchronized(lock) { for (unknownMacro in unknownMacros) { macroToComponentNames.computeIfAbsent(unknownMacro, { HashSet() }).add(componentName) } componentNameToMacros.computeIfAbsent(componentName, { HashSet() }).addAll(unknownMacros) } } }
apache-2.0
99463e796ec10b6e8221131be4307014
32.789474
162
0.722741
5.187879
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSwitchExpression.kt
2
4240
// 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.uast.kotlin import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds class KotlinUSwitchExpression( override val sourcePsi: KtWhenExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), USwitchExpression, KotlinUElementWithType { override val expression by lz { KotlinConverter.convertOrNull(sourcePsi.subjectExpression, this) } override val body: UExpressionList by lz { object : KotlinUExpressionList(sourcePsi, KotlinSpecialExpressionKinds.WHEN, this@KotlinUSwitchExpression) { override fun asRenderString() = expressions.joinToString("\n") { it.asRenderString().withMargin } }.apply { expressions = [email protected] { KotlinUSwitchEntry(it, this) } } } override fun asRenderString() = buildString { val expr = expression?.let { "(" + it.asRenderString() + ") " } ?: "" appendLine("switch $expr {") appendLine(body.asRenderString()) appendLine("}") } override val switchIdentifier: UIdentifier get() = KotlinUIdentifier(null, this) } class KotlinUSwitchEntry( override val sourcePsi: KtWhenEntry, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), USwitchClauseExpressionWithBody { override val caseValues by lz { sourcePsi.conditions.map { KotlinConverter.convertWhenCondition(it, this, DEFAULT_EXPRESSION_TYPES_LIST) ?: UastEmptyExpression(null) } } override val body: UExpressionList by lz { object : KotlinUExpressionList(sourcePsi, KotlinSpecialExpressionKinds.WHEN_ENTRY, this@KotlinUSwitchEntry) { override fun asRenderString() = buildString { appendLine("{") expressions.forEach { appendLine(it.asRenderString().withMargin) } appendLine("}") } }.apply KotlinUExpressionList@{ val exprPsi = [email protected] val userExpressions = when (exprPsi) { is KtBlockExpression -> exprPsi.statements.map { KotlinConverter.convertOrEmpty(it, this) } else -> listOf(KotlinConverter.convertOrEmpty(exprPsi, this)) } expressions = if (userExpressions.isNotEmpty()) userExpressions.subList(0, userExpressions.lastIndex) + object : UYieldExpression { override val javaPsi: PsiElement? = null override val sourcePsi: PsiElement? = null override val psi: PsiElement? get() = null override val label: String? get() = null override val uastParent: UElement? get() = this@KotlinUExpressionList override val uAnnotations: List<UAnnotation> get() = emptyList() override val expression: UExpression? get() = userExpressions.lastOrNull()?.sourcePsi?.let { it.safeAs<KtExpression>() ?: it.parent.safeAs() } ?.let { KotlinConverter.convertExpression(it, this, DEFAULT_EXPRESSION_TYPES_LIST) } } else emptyList() } } override fun convertParent(): UElement? { val result = KotlinConverter.unwrapElements(sourcePsi.parent)?.let { parentUnwrapped -> KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null) } return (result as? KotlinUSwitchExpression)?.body ?: result } }
apache-2.0
3235ff3bb9638b1d6e156a825b628b5b
47.181818
158
0.648113
5.593668
false
false
false
false
smmribeiro/intellij-community
platform/object-serializer/src/xml/KotlinAwareBeanBinding.kt
10
2709
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serialization.xml import com.intellij.openapi.components.BaseState import com.intellij.openapi.diagnostic.logger import com.intellij.serialization.BaseBeanBinding import com.intellij.serialization.PropertyAccessor import com.intellij.util.ObjectUtils import com.intellij.util.xmlb.BeanBinding import com.intellij.util.xmlb.SerializationFilter import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.ints.IntList import org.jdom.Element internal class KotlinAwareBeanBinding(beanClass: Class<*>) : BeanBinding(beanClass) { private val beanBinding = BaseBeanBinding(beanClass) // only for accessor, not field private fun findBindingIndex(name: String): Int { // accessors sorted by name val index = ObjectUtils.binarySearch(0, bindings.size) { index -> bindings[index].accessor.name.compareTo(name) } if (index >= 0) { return index } for ((i, binding) in bindings.withIndex()) { val accessor = binding.accessor if (accessor is PropertyAccessor && accessor.getterName == name) { return i } } return -1 } override fun serializeInto(o: Any, element: Element?, filter: SerializationFilter?): Element? { return when (o) { is BaseState -> serializeBaseStateInto(o, element, filter) else -> super.serializeInto(o, element, filter) } } fun serializeBaseStateInto(o: BaseState, _element: Element?, filter: SerializationFilter?, excludedPropertyNames: Collection<String>? = null): Element? { var element = _element // order of bindings must be used, not order of properties var bindingIndices: IntList? = null for (property in o.__getProperties()) { val propertyName = property.name!! if (property.isEqualToDefault() || (excludedPropertyNames != null && excludedPropertyNames.contains(propertyName))) { continue } val propertyBindingIndex = findBindingIndex(propertyName) if (propertyBindingIndex < 0) { logger<BaseState>().debug("cannot find binding for property ${propertyName}") continue } if (bindingIndices == null) { bindingIndices = IntArrayList() } bindingIndices.add(propertyBindingIndex) } if (bindingIndices != null) { bindingIndices.sort() for (i in 0 until bindingIndices.size) { element = serializePropertyInto(bindings[bindingIndices.getInt(i)], o, element, filter, false) } } return element } override fun newInstance(): Any { return beanBinding.newInstance() } }
apache-2.0
d8a95aead202c703e5d47a0d198e89a7
33.74359
155
0.706903
4.515
false
false
false
false
smmribeiro/intellij-community
build/launch/src/com/intellij/tools/launch/LauncherOptions.kt
12
1074
package com.intellij.tools.launch import java.net.InetAddress interface LauncherOptions { val platformPrefix: String? val xmx: Int get() = 800 val debugPort: Int get() = -1 val debugSuspendOnStart: Boolean get() = false val javaArguments: List<String> get() = listOf() val ideaArguments: List<String> get() = listOf() val environment: Map<String, String> get() = mapOf() val beforeProcessStart: (ProcessBuilder) -> Unit get() = { } val redirectOutputIntoParentProcess: Boolean get() = false val runInDocker: Boolean get() = false } data class DockerNetwork( val name: String, val IPv4Address: String, val defaultGatewayIPv4Address: String?) { companion object { val AUTO = DockerNetwork("AUTO", "AUTO", "AUTO") } } interface DockerLauncherOptions : LauncherOptions { val exposedPorts: List<Int> get() = listOf(debugPort) val runBashBeforeJava: String? get() = null val address: InetAddress get() = InetAddress.getLoopbackAddress() val network: DockerNetwork get() = DockerNetwork.AUTO val containerName: String? get() = null }
apache-2.0
a25470ed1ab153c91761b7cfaa819e2e
31.575758
67
0.723464
3.977778
false
false
false
false
smmribeiro/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/WorkspaceModel.kt
3
3177
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder /** * Provides access to the storage which holds workspace model entities. */ interface WorkspaceModel { val entityStorage: VersionedEntityStorage @Deprecated("Use [WorkspaceModelCache.getInstance()] directly if you really need it") val cache: WorkspaceModelCache? /** * Modifies the current model by calling [updater] and applying it to the storage. Requires write action. */ fun <R> updateProjectModel(updater: (WorkspaceEntityStorageBuilder) -> R): R /** * Update project model without the notification to message bus and without resetting accumulated changes. * * This method doesn't require write action. */ fun <R> updateProjectModelSilent(updater: (WorkspaceEntityStorageBuilder) -> R): R /** * Get builder that can be updated in background and applied later and a project model. * * @see [WorkspaceModel.replaceProjectModel] */ fun getBuilderSnapshot(): BuilderSnapshot /** * Replace current project model with the new version from storage snapshot. * * This operation required write lock. * The snapshot replacement is performed using positive lock. If the project model was updated since [getCurrentBuilder], snapshot * won't be applied and this method will return false. In this case client should get a newer version of snapshot builder, apply changes * and try to call [replaceProjectModel]. * Keep in mind that you may not need to start the full builder update process (e.g. gradle sync) and the newer version of the builder * can be updated using [WorkspaceEntityStorageBuilder.addDiff] or [WorkspaceEntityStorageBuilder.replaceBySource], but you have be * sure that the changes will be applied to the new builder correctly. * * The calculation of changes will be performed during [BuilderSnapshot.getStorageReplacement]. This method only replaces the project model * and sends corresponding events. * * Example: * ``` * val builderSnapshot = projectModel.getBuilderSnapshot() * * update(builderSnapshot) * * val storageSnapshot = builderSnapshot.getStorageReplacement() * val updated = writeLock { projectModel.replaceProjectModel(storageSnapshot) } * * if (!updated) error("Project model updates too fast") * ``` * * Future plans: add some kind of ordering for async updates of the project model * * @see [WorkspaceModel.getBuilderSnapshot] */ fun replaceProjectModel(replacement: StorageReplacement): Boolean companion object { val enabledForArtifacts: Boolean get() = Registry.`is`("ide.new.project.model.artifacts") @JvmStatic fun getInstance(project: Project): WorkspaceModel = project.service() } }
apache-2.0
0d368de3d7426ff7a70dc8b8c5844626
40.25974
141
0.746616
4.872699
false
false
false
false
smmribeiro/intellij-community
platform/execution/src/com/intellij/execution/target/value/TargetEnvironmentFunctions.kt
1
8945
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("TargetEnvironmentFunctions") package com.intellij.execution.target.value import com.intellij.execution.target.* import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.FileUtil import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.Paths import java.util.function.Function import kotlin.io.path.name /** * The function that is expected to be resolved with provided * [TargetEnvironment]. * * Such functions could be used during the construction of a command line and * play the role of deferred values of, for example: * - the path to an executable; * - the working directory; * - the command-line parameters; * - the values of environment variables. * * It is recommended to subclass the default implementation [TraceableTargetEnvironmentFunction], see its documentation for rationale. */ typealias TargetEnvironmentFunction<R> = Function<TargetEnvironment, R> /** * Implementation of TraceableTargetEnvironmentFunction that holds the stack trace of its creation. * * Unless it's intended to create hundreds of such objects a second, prefer using this class as a base for [TargetEnvironmentFunction] * to ease debugging in case of raised exceptions. */ @ApiStatus.Experimental abstract class TraceableTargetEnvironmentFunction<R> : TargetEnvironmentFunction<R> { private val creationStack: Throwable = Throwable("Creation stack") final override fun apply(t: TargetEnvironment): R = try { applyInner(t) } catch (err: Throwable) { err.addSuppressed(creationStack) throw err } abstract fun applyInner(t: TargetEnvironment): R override fun <V> andThen(after: Function<in R, out V>): TraceableTargetEnvironmentFunction<V> = TraceableTargetEnvironmentFunction { targetEnvironment -> after.apply(apply(targetEnvironment)) } companion object { @JvmStatic inline operator fun <R> invoke( crossinline delegate: (targetEnvironment: TargetEnvironment) -> R, ): TraceableTargetEnvironmentFunction<R> = object : TraceableTargetEnvironmentFunction<R>() { override fun applyInner(t: TargetEnvironment): R = delegate(t) } } } /** * This function is preferable to use over function literals in Kotlin * (i.e. `TargetEnvironmentFunction { value }`) and lambdas in Java * (i.e. `ignored -> value`) because it is has more explicit [toString] which * results in clear variable descriptions during debugging and better logging * abilities. */ fun <T> constant(value: T): TargetEnvironmentFunction<T> = Constant(value) private class Constant<T>(private val value: T): TraceableTargetEnvironmentFunction<T>() { override fun toString(): String = "${javaClass.simpleName}($value)" override fun applyInner(t: TargetEnvironment): T = value } fun <T> Iterable<TargetEnvironmentFunction<T>>.joinToStringFunction(separator: CharSequence): TargetEnvironmentFunction<String> = JoinedStringTargetEnvironmentFunction(iterable = this, separator = separator) fun TargetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath: String): TargetEnvironmentFunction<String> { if (this is LocalTargetEnvironmentRequest) return constant(localPath) return TraceableTargetEnvironmentFunction { targetEnvironment -> if (targetEnvironment is ExternallySynchronized) { val pathForSynchronizedVolume = targetEnvironment.tryMapToSynchronizedVolume(localPath) if (pathForSynchronizedVolume != null) return@TraceableTargetEnvironmentFunction pathForSynchronizedVolume } val (uploadRoot, relativePath) = getUploadRootForLocalPath(localPath) ?: throw IllegalArgumentException( "Local path \"$localPath\" is not registered within uploads in the request") val volume = targetEnvironment.uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" is expected to be created in the target environment") joinPaths(volume.targetRoot, relativePath, targetEnvironment.targetPlatform) } } private fun ExternallySynchronized.tryMapToSynchronizedVolume(localPath: String): String? { // TODO [targets] Does not look nice this as TargetEnvironment val targetFileSeparator = targetPlatform.platform.fileSeparator val (volume, relativePath) = synchronizedVolumes.firstNotNullOfOrNull { volume -> getRelativePathIfAncestor(ancestor = volume.localPath, file = localPath)?.let { relativePath -> volume to if (File.separatorChar != targetFileSeparator) { relativePath.replace(File.separatorChar, targetFileSeparator) } else { relativePath } } } ?: return null return joinPaths(volume.targetPath, relativePath, targetPlatform) } fun TargetEnvironmentRequest.getUploadRootForLocalPath(localPath: String): Pair<TargetEnvironment.UploadRoot, String>? { val targetFileSeparator = targetPlatform.platform.fileSeparator return uploadVolumes.mapNotNull { uploadRoot -> getRelativePathIfAncestor(ancestor = uploadRoot.localRootPath, file = localPath)?.let { relativePath -> uploadRoot to if (File.separatorChar != targetFileSeparator) { relativePath.replace(File.separatorChar, targetFileSeparator) } else { relativePath } } }.firstOrNull() } private fun getRelativePathIfAncestor(ancestor: Path, file: String): String? = try { ancestor.relativize(Paths.get(file)).takeIf { !it.startsWith("..") }?.toString() } catch (ignored: InvalidPathException) { null } catch (ignored: IllegalArgumentException) { // It should not happen, but some tests use relative paths, and they fail trying to call `Paths.get("\\").relativize(Paths.get("."))` null } private fun joinPaths(basePath: String, relativePath: String, targetPlatform: TargetPlatform): String { val fileSeparator = targetPlatform.platform.fileSeparator.toString() return FileUtil.toSystemIndependentName("${basePath.removeSuffix(fileSeparator)}$fileSeparator$relativePath") } fun TargetEnvironment.UploadRoot.getTargetUploadPath(): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val uploadRoot = this@getTargetUploadPath val uploadableVolume = targetEnvironment.uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" cannot be found") uploadableVolume.targetRoot } fun TargetEnvironmentFunction<String>.getRelativeTargetPath(targetRelativePath: String): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val targetBasePath = [email protected](targetEnvironment) joinPaths(targetBasePath, targetRelativePath, targetEnvironment.targetPlatform) } fun TargetEnvironment.DownloadRoot.getTargetDownloadPath(): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val downloadRoot = this@getTargetDownloadPath val downloadableVolume = targetEnvironment.downloadVolumes[downloadRoot] ?: throw IllegalStateException("Download root \"$downloadRoot\" cannot be found") downloadableVolume.targetRoot } fun TargetEnvironment.LocalPortBinding.getTargetEnvironmentValue(): TargetEnvironmentFunction<HostPort> = TraceableTargetEnvironmentFunction { targetEnvironment -> val localPortBinding = this@getTargetEnvironmentValue val resolvedPortBinding = (targetEnvironment.localPortBindings[localPortBinding] ?: throw IllegalStateException("Local port binding \"$localPortBinding\" cannot be found")) resolvedPortBinding.targetEndpoint } @Throws(IOException::class) fun TargetEnvironment.downloadFromTarget(localPath: Path, progressIndicator: ProgressIndicator) { val localFileDir = localPath.parent val downloadVolumes = downloadVolumes.values val downloadVolume = downloadVolumes.find { it.localRoot == localFileDir } ?: error("Volume with local root $localFileDir not found") downloadVolume.download(localPath.name, progressIndicator) } private class JoinedStringTargetEnvironmentFunction<T>(private val iterable: Iterable<TargetEnvironmentFunction<T>>, private val separator: CharSequence) : TraceableTargetEnvironmentFunction<String>() { override fun applyInner(t: TargetEnvironment): String = iterable.map { it.apply(t) }.joinToString(separator = separator) override fun toString(): String { return "JoinedStringTargetEnvironmentValue(iterable=$iterable, separator=$separator)" } }
apache-2.0
4d0dbbf10939bc760656db7e52d52323
44.406091
140
0.762437
5.408102
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt
2
19941
// 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.plugins.github import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.impl.isTrusted import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.BrowserLink import com.intellij.ui.components.JBLabel import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.mapSmartSet import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.VcsFileUtil import git4idea.DialogManager import git4idea.GitUtil import git4idea.actions.GitInit import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.util.GitFileUtils import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.data.request.Type import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.ui.GithubShareDialog import org.jetbrains.plugins.github.util.* import java.awt.BorderLayout import java.awt.Component import java.awt.Container import java.io.IOException import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class GithubShareAction : DumbAwareAction(GithubBundle.messagePointer("share.action"), GithubBundle.messagePointer("share.action.description"), AllIcons.Vcs.Vendors.Github) { override fun update(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) e.presentation.isEnabledAndVisible = project != null && !project.isDefault && project.isTrusted() } // get gitRepository // check for existing git repo // check available repos and privateRepo access (net) // Show dialog (window) // create GitHub repo (net) // create local git repo (if not exist) // add GitHub as a remote host // make first commit // push everything (net) override fun actionPerformed(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) val file = e.getData(CommonDataKeys.VIRTUAL_FILE) if (project == null || project.isDisposed) { return } shareProjectOnGithub(project, file) } companion object { private val LOG = GithubUtil.LOG @JvmStatic fun shareProjectOnGithub(project: Project, file: VirtualFile?) { FileDocumentManager.getInstance().saveAllDocuments() val gitRepository = GithubGitHelper.findGitRepository(project, file) val possibleRemotes = gitRepository ?.let(project.service<GHProjectRepositoriesManager>()::findKnownRepositories) ?.map { it.gitRemoteUrlCoordinates.url }.orEmpty() if (possibleRemotes.isNotEmpty()) { val existingRemotesDialog = GithubExistingRemotesDialog(project, possibleRemotes) DialogManager.show(existingRemotesDialog) if (!existingRemotesDialog.isOK) { return } } val authManager = service<GithubAuthenticationManager>() val progressManager = service<ProgressManager>() val requestExecutorManager = service<GithubApiRequestExecutorManager>() val accountInformationProvider = service<GithubAccountInformationProvider>() val gitHelper = service<GithubGitHelper>() val git = service<Git>() val accountInformationLoader = object : (GithubAccount, Component) -> Pair<Boolean, Set<String>> { private val loadedInfo = mutableMapOf<GithubAccount, Pair<Boolean, Set<String>>>() @Throws(IOException::class) override fun invoke(account: GithubAccount, parentComponent: Component) = loadedInfo.getOrPut(account) { val requestExecutor = requestExecutorManager.getExecutor(account, parentComponent) ?: throw ProcessCanceledException() progressManager.runProcessWithProgressSynchronously(ThrowableComputable<Pair<Boolean, Set<String>>, IOException> { val user = requestExecutor.execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(account.server)) val names = GithubApiPagesLoader .loadAll(requestExecutor, progressManager.progressIndicator, GithubApiRequests.CurrentUser.Repos.pages(account.server, Type.OWNER)) .mapSmartSet { it.name } user.canCreatePrivateRepo() to names }, GithubBundle.message("share.process.loading.account.info", account), true, project) } } val shareDialog = GithubShareDialog(project, authManager.getAccounts(), authManager.getDefaultAccount(project), gitRepository?.remotes?.map { it.name }?.toSet() ?: emptySet(), accountInformationLoader) DialogManager.show(shareDialog) if (!shareDialog.isOK) { return } val name: String = shareDialog.getRepositoryName() val isPrivate: Boolean = shareDialog.isPrivate() val remoteName: String = shareDialog.getRemoteName() val description: String = shareDialog.getDescription() val account: GithubAccount = shareDialog.getAccount()!! val requestExecutor = requestExecutorManager.getExecutor(account, project) ?: return object : Task.Backgroundable(project, GithubBundle.message("share.process")) { private lateinit var url: String override fun run(indicator: ProgressIndicator) { // create GitHub repo (network) LOG.info("Creating GitHub repository") indicator.text = GithubBundle.message("share.process.creating.repository") url = requestExecutor .execute(indicator, GithubApiRequests.CurrentUser.Repos.create(account.server, name, description, isPrivate)).htmlUrl LOG.info("Successfully created GitHub repository") val root = gitRepository?.root ?: project.baseDir // creating empty git repo if git is not initialized LOG.info("Binding local project with GitHub") if (gitRepository == null) { LOG.info("No git detected, creating empty git repo") indicator.text = GithubBundle.message("share.process.creating.git.repository") if (!createEmptyGitRepository(project, root)) { return } } val repositoryManager = GitUtil.getRepositoryManager(project) val repository = repositoryManager.getRepositoryForRoot(root) if (repository == null) { GithubNotifications.showError(project, GithubNotificationIdsHolder.SHARE_CANNOT_FIND_GIT_REPO, GithubBundle.message("share.error.failed.to.create.repo"), GithubBundle.message("cannot.find.git.repo")) return } indicator.text = GithubBundle.message("share.process.retrieving.username") val username = accountInformationProvider.getInformation(requestExecutor, indicator, account).login val remoteUrl = gitHelper.getRemoteUrl(account.server, username, name) //git remote add origin [email protected]:login/name.git LOG.info("Adding GitHub as a remote host") indicator.text = GithubBundle.message("share.process.adding.gh.as.remote.host") git.addRemote(repository, remoteName, remoteUrl).throwOnError() repository.update() // create sample commit for binding project if (!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) { return } //git push origin master LOG.info("Pushing to github master") indicator.text = GithubBundle.message("share.process.pushing.to.github.master") if (!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) { return } GithubNotifications.showInfoURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_SUCCESSFULLY_SHARED, GithubBundle.message("share.process.successfully.shared"), name, url) } private fun createEmptyGitRepository(project: Project, root: VirtualFile): Boolean { val result = Git.getInstance().init(project, root) if (!result.success()) { VcsNotifier.getInstance(project).notifyError(GithubNotificationIdsHolder.GIT_REPO_INIT_REPO, GitBundle.message("initializing.title"), result.errorOutputAsHtmlString) LOG.info("Failed to create empty git repo: " + result.errorOutputAsJoinedString) return false } GitInit.refreshAndConfigureVcsMappings(project, root, root.path) GitUtil.generateGitignoreFileIfNeeded(project, root) return true } private fun performFirstCommitIfRequired(project: Project, root: VirtualFile, repository: GitRepository, indicator: ProgressIndicator, name: @NlsSafe String, url: String): Boolean { // check if there is no commits if (!repository.isFresh) { return true } LOG.info("Trying to commit") try { LOG.info("Adding files for commit") indicator.text = GithubBundle.message("share.process.adding.files") // ask for files to add val trackedFiles = ChangeListManager.getInstance(project).affectedFiles val untrackedFiles = filterOutIgnored(project, repository.untrackedFilesHolder.retrieveUntrackedFilePaths().mapNotNull(FilePath::getVirtualFile)) trackedFiles.removeAll(untrackedFiles) // fix IDEA-119855 val allFiles = ArrayList<VirtualFile>() allFiles.addAll(trackedFiles) allFiles.addAll(untrackedFiles) val dialog = invokeAndWaitIfNeeded(indicator.modalityState) { GithubUntrackedFilesDialog(project, allFiles).apply { if (!trackedFiles.isEmpty()) { selectedFiles = trackedFiles } DialogManager.show(this) } } val files2commit = dialog.selectedFiles if (!dialog.isOK || files2commit.isEmpty()) { GithubNotifications.showInfoURL(project, GithubNotificationIdsHolder.SHARE_EMPTY_REPO_CREATED, GithubBundle.message("share.process.empty.project.created"), name, url) return false } val files2add = ContainerUtil.intersection(untrackedFiles, files2commit) val files2rm = ContainerUtil.subtract(trackedFiles, files2commit) val modified = HashSet(trackedFiles) modified.addAll(files2commit) GitFileUtils.addFiles(project, root, files2add) GitFileUtils.deleteFilesFromCache(project, root, files2rm) // commit LOG.info("Performing commit") indicator.text = GithubBundle.message("share.process.performing.commit") val handler = GitLineHandler(project, root, GitCommand.COMMIT) handler.setStdoutSuppressed(false) handler.addParameters("-m", dialog.commitMessage) handler.endOptions() Git.getInstance().runCommand(handler).throwOnError() VcsFileUtil.markFilesDirty(project, modified) } catch (e: VcsException) { LOG.warn(e) GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_COMMIT_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.init.commit.failed") + GithubUtil.getErrorTextFromException( e), url) return false } LOG.info("Successfully created initial commit") return true } private fun filterOutIgnored(project: Project, files: Collection<VirtualFile>): Collection<VirtualFile> { val changeListManager = ChangeListManager.getInstance(project) val vcsManager = ProjectLevelVcsManager.getInstance(project) return ContainerUtil.filter(files) { file -> !changeListManager.isIgnoredFile(file) && !vcsManager.isIgnored(file) } } private fun pushCurrentBranch(project: Project, repository: GitRepository, remoteName: String, remoteUrl: String, name: String, url: String): Boolean { val currentBranch = repository.currentBranch if (currentBranch == null) { GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.push.no.current.branch"), url) return false } val result = git.push(repository, remoteName, remoteUrl, currentBranch.name, true) if (!result.success()) { GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.push.failed", result.errorOutputAsHtmlString), url) return false } return true } override fun onThrowable(error: Throwable) { GithubNotifications.showError(project, GithubNotificationIdsHolder.SHARE_CANNOT_CREATE_REPO, GithubBundle.message("share.error.failed.to.create.repo"), error) } }.queue() } } @TestOnly class GithubExistingRemotesDialog(project: Project, private val remotes: List<String>) : DialogWrapper(project) { init { title = GithubBundle.message("share.error.project.is.on.github") setOKButtonText(GithubBundle.message("share.anyway.button")) init() } override fun createCenterPanel(): JComponent? { val mainText = JBLabel(if (remotes.size == 1) GithubBundle.message("share.action.remote.is.on.github") else GithubBundle.message("share.action.remotes.are.on.github")) val remotesPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) } for (remote in remotes) { remotesPanel.add(BrowserLink(remote, remote)) } val messagesPanel = JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToTop(mainText) .addToCenter(remotesPanel) val iconContainer = Container().apply { layout = BorderLayout() add(JLabel(Messages.getQuestionIcon()), BorderLayout.NORTH) } return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToCenter(messagesPanel) .addToLeft(iconContainer) .apply { border = JBUI.Borders.emptyBottom(UIUtil.LARGE_VGAP) } } } @TestOnly class GithubUntrackedFilesDialog(private val myProject: Project, untrackedFiles: List<VirtualFile>) : SelectFilesDialog(myProject, untrackedFiles, null, null, true, false), DataProvider { private var myCommitMessagePanel: CommitMessage? = null val commitMessage: String get() = myCommitMessagePanel!!.comment init { title = GithubBundle.message("untracked.files.dialog.title") setOKButtonText(CommonBundle.getAddButtonText()) setCancelButtonText(CommonBundle.getCancelButtonText()) init() } override fun createNorthPanel(): JComponent? { return null } override fun createCenterPanel(): JComponent? { val tree = super.createCenterPanel() val commitMessage = CommitMessage(myProject) Disposer.register(disposable, commitMessage) commitMessage.setCommitMessage("Initial commit") myCommitMessagePanel = commitMessage val splitter = Splitter(true) splitter.setHonorComponentsMinimumSize(true) splitter.firstComponent = tree splitter.secondComponent = myCommitMessagePanel splitter.proportion = 0.7f return splitter } override fun getData(@NonNls dataId: String): Any? { return if (VcsDataKeys.COMMIT_MESSAGE_CONTROL.`is`(dataId)) { myCommitMessagePanel } else null } override fun getDimensionServiceKey(): String? { return "Github.UntrackedFilesDialog" } } }
apache-2.0
76fcc7a7f6439ea844089a1b398cd569
44.52968
158
0.638484
5.623519
false
false
false
false
smmribeiro/intellij-community
platform/util-ex/src/com/intellij/util/Plow.kt
1
3846
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util import com.intellij.openapi.progress.ProgressManager import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus /** * A Processor + Flow, or the Poor man's Flow: a reactive-stream-like wrapper around [Processor]. * * Instead of creating the [Processor] manually - create a [Plow] and work with the Processor inside a lambda. * If your method accepts the processor it is the good idea to return a [Plow] instead to avoid the "return value in parameter" semantic * * Itself [Plow] is stateless and ["Cold"](https://projectreactor.io/docs/core/3.3.9.RELEASE/reference/index.html#reactor.hotCold), * meaning that the same instance of [Plow] could be reused several times (by reevaluating the sources), * but depending on the idempotence of the [producingFunction] this contract could be violated, * so to be careful, and it is better to obtain the new [Plow] instance each time. */ class Plow<T> private constructor(private val producingFunction: (Processor<T>) -> Boolean) { @Suppress("UNCHECKED_CAST") fun processWith(processor: Processor<in T>): Boolean = producingFunction(processor as Processor<T>) fun <P : Processor<T>> processTo(processor: P): P = processor.apply { producingFunction(this) } fun findAny(): T? = processTo(CommonProcessors.FindFirstProcessor()).foundValue fun find(test: (T) -> Boolean): T? = processTo(object : CommonProcessors.FindFirstProcessor<T>() { override fun accept(t: T): Boolean = test(t) }).foundValue fun <C : MutableCollection<T>> collectTo(coll: C): C = coll.apply { processTo(CommonProcessors.CollectProcessor(this)) } fun toList(): List<T> = ContainerUtil.unmodifiableOrEmptyList(collectTo(SmartList())) fun toSet(): Set<T> = ContainerUtil.unmodifiableOrEmptySet(collectTo(HashSet())) fun toArray(array: Array<T>): Array<T> = processTo(CommonProcessors.CollectProcessor()).toArray(array) fun <R> transform(transformation: (Processor<R>) -> (Processor<T>)): Plow<R> = Plow { pr -> producingFunction(transformation(pr)) } fun <R> map(mapping: (T) -> R): Plow<R> = transform { pr -> Processor { v -> pr.process(mapping(v)) } } fun <R> mapNotNull(mapping: (T) -> R?): Plow<R> = transform { pr -> Processor { v -> mapping(v)?.let { pr.process(it) } ?: true } } fun filter(test: (T) -> Boolean): Plow<T> = transform { pr -> Processor { v -> !test(v) || pr.process(v) } } fun <R> mapToProcessor(mapping: (T, Processor<R>) -> Boolean): Plow<R> = Plow { rProcessor -> producingFunction(Processor { t -> mapping(t, rProcessor) }) } fun <R> flatMap(mapping: (T) -> Plow<R>): Plow<R> = mapToProcessor { t, processor -> mapping(t).processWith(processor) } fun cancellable(): Plow<T> = transform { pr -> Processor { v -> ProgressManager.checkCanceled();pr.process(v) } } fun limit(n: Int): Plow<T> { var processedCount = 0 return transform { pr -> Processor { processedCount++ processedCount <= n && pr.process(it) } } } companion object { @JvmStatic fun <T> empty(): Plow<T> = of { true } @JvmStatic fun <T> of(processorCall: (Processor<T>) -> Boolean): Plow<T> = Plow(processorCall) @JvmStatic @JvmName("ofArray") fun <T> Array<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic @JvmName("ofIterable") fun <T> Iterable<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic @JvmName("ofSequence") fun <T> Sequence<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic fun <T> concat(vararg plows: Plow<T>): Plow<T> = of { pr -> plows.all { it.processWith(pr) } } } }
apache-2.0
04b5eca5ed6c9269b4f17daaf5c80c34
41.744444
140
0.674207
3.655894
false
false
false
false