repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
coffeemakr/OST
app/src/main/java/ch/unstable/ost/views/lists/connection/ConnectionViewHolder.kt
1
1128
package ch.unstable.ost.views.lists.connection import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import ch.unstable.ost.R import ch.unstable.ost.views.ConnectionLineView import com.google.common.base.Preconditions.checkNotNull import com.google.common.base.Verify.verifyNotNull /** * View holder for connection items */ open class ConnectionViewHolder(itemView: View) : RecyclerView.ViewHolder(checkNotNull(itemView)) { val startTime: TextView = verifyNotNull(itemView.findViewById(R.id.startTime)) val endTime: TextView = verifyNotNull(itemView.findViewById(R.id.endTime)) val firstEndDestination: TextView = verifyNotNull(itemView.findViewById(R.id.firstSectionEndDestination)) val connectionLineView: ConnectionLineView = verifyNotNull(itemView.findViewById(R.id.connectionLineView)) val firstTransportName: TextView = verifyNotNull(itemView.findViewById(R.id.firstTransportName)) val duration: TextView = verifyNotNull(itemView.findViewById(R.id.duration)) val platform: TextView = verifyNotNull(itemView.findViewById(R.id.platform)) }
gpl-3.0
4be311fa86cb1181d9762cd66d7620a5
42.384615
110
0.81117
4.193309
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/bungeecord/BungeeCordModule.kt
1
4560
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.insight.generation.GenerationData import com.demonwav.mcdev.platform.AbstractModule import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bukkit.BukkitModule import com.demonwav.mcdev.platform.bukkit.BukkitModuleType import com.demonwav.mcdev.platform.bukkit.PaperModuleType import com.demonwav.mcdev.platform.bukkit.SpigotModuleType import com.demonwav.mcdev.platform.bungeecord.generation.BungeeCordGenerationData import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.SourceType import com.demonwav.mcdev.util.addImplements import com.demonwav.mcdev.util.extendsOrImplements import com.demonwav.mcdev.util.nullable import com.intellij.lang.jvm.JvmModifier import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import org.jetbrains.uast.UClass import org.jetbrains.uast.UIdentifier import org.jetbrains.uast.toUElementOfType class BungeeCordModule<out T : AbstractModuleType<*>>(facet: MinecraftFacet, type: T) : AbstractModule(facet) { var pluginYml by nullable { val file = facet.findFile("bungee.yml", SourceType.RESOURCE) if (file != null) { return@nullable file } if (facet.isOfType(BukkitModuleType) || facet.isOfType(SpigotModuleType) || facet.isOfType(PaperModuleType)) { // If this module is _both_ a bungeecord and a bukkit module, then `plugin.yml` defaults to that platform // So we don't check return@nullable null } return@nullable facet.findFile("plugin.yml", SourceType.RESOURCE) } private set override val type: PlatformType = type.platformType override val moduleType: T = type override fun isEventClassValid(eventClass: PsiClass, method: PsiMethod?) = BungeeCordConstants.EVENT_CLASS == eventClass.qualifiedName override fun writeErrorMessageForEventParameter(eventClass: PsiClass, method: PsiMethod) = "Parameter is not a subclass of net.md_5.bungee.api.plugin.Event\n" + "Compiling and running this listener may result in a runtime exception" override fun doPreEventGenerate(psiClass: PsiClass, data: GenerationData?) { val bungeeCordListenerClass = BungeeCordConstants.LISTENER_CLASS if (!psiClass.extendsOrImplements(bungeeCordListenerClass)) { psiClass.addImplements(bungeeCordListenerClass) } } override fun generateEventListenerMethod( containingClass: PsiClass, chosenClass: PsiClass, chosenName: String, data: GenerationData? ): PsiMethod? { val method = BukkitModule.generateBukkitStyleEventListenerMethod( chosenClass, chosenName, project, BungeeCordConstants.HANDLER_ANNOTATION, false ) ?: return null val generationData = data as BungeeCordGenerationData? ?: return method val modifierList = method.modifierList val annotation = modifierList.findAnnotation(BungeeCordConstants.HANDLER_ANNOTATION) ?: return method if (generationData.eventPriority == "NORMAL") { return method } val value = JavaPsiFacade.getElementFactory(project) .createExpressionFromText( BungeeCordConstants.EVENT_PRIORITY_CLASS + "." + generationData.eventPriority, annotation ) annotation.setDeclaredAttributeValue("priority", value) return method } override fun shouldShowPluginIcon(element: PsiElement?): Boolean { val identifier = element?.toUElementOfType<UIdentifier>() ?: return false val psiClass = (identifier.uastParent as? UClass)?.javaPsi ?: return false val pluginInterface = JavaPsiFacade.getInstance(element.project) .findClass(BungeeCordConstants.PLUGIN, module.getModuleWithDependenciesAndLibrariesScope(false)) ?: return false return !psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.isInheritor(pluginInterface, true) } override fun dispose() { super.dispose() pluginYml = null } }
mit
87db85a4f9cce48d920bf78448c45a13
35.48
118
0.716886
4.851064
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/db/dao/PageDao.kt
1
3039
package at.ac.tuwien.caa.docscan.db.dao import androidx.annotation.Keep import androidx.room.* import at.ac.tuwien.caa.docscan.db.model.Page import at.ac.tuwien.caa.docscan.db.model.Upload import at.ac.tuwien.caa.docscan.db.model.state.ExportState import at.ac.tuwien.caa.docscan.db.model.state.PostProcessingState import at.ac.tuwien.caa.docscan.db.model.state.UploadState import java.util.* @Keep @Dao interface PageDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertPage(page: Page) @Delete fun deletePage(page: Page) @Delete fun deletePages(page: List<Page>) @Query("SELECT * FROM ${Page.TABLE_NAME_PAGES} WHERE ${Page.KEY_ID} = :id") suspend fun getPageById(id: UUID): Page? @Query("SELECT * FROM ${Page.TABLE_NAME_PAGES} WHERE ${Page.KEY_ID} = :id") fun getPageByIdNonSuspendable(id: UUID): Page? @Query("SELECT * FROM ${Page.TABLE_NAME_PAGES} WHERE ${Page.KEY_LEGACY_ABSOLUTE_FILE_PATH} = :legacyFilePath AND ${Page.KEY_DOC_ID} = :docId") suspend fun getPageByLegacyFilePath(docId: UUID, legacyFilePath: String): List<Page> @Query("SELECT * FROM ${Page.TABLE_NAME_PAGES} WHERE ${Page.KEY_DOC_ID} = :docId") suspend fun getPagesByDoc(docId: UUID): List<Page> @Query("SELECT DISTINCT ${Page.KEY_DOC_ID} FROM ${Page.TABLE_NAME_PAGES} WHERE ${Page.KEY_UPLOAD_PREFIX}${Upload.KEY_UPLOAD_STATE} = :state OR ${Page.KEY_UPLOAD_PREFIX}${Upload.KEY_UPLOAD_STATE} = :stateTwo") suspend fun getAllDocIdsWithPendingUploadState(state: UploadState = UploadState.SCHEDULED, stateTwo: UploadState = UploadState.UPLOAD_IN_PROGRESS): List<UUID> @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_POST_PROCESSING_STATE}= :state WHERE ${Page.KEY_ID} = :pageId ") fun updatePageProcessingState(pageId: UUID, state: PostProcessingState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_POST_PROCESSING_STATE}= :state WHERE ${Page.KEY_DOC_ID} = :docId ") fun updatePageProcessingStateForDocument(docId: UUID, state: PostProcessingState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_EXPORT_STATE}= :state WHERE ${Page.KEY_DOC_ID} = :docId ") fun updatePageExportStateForDocument(docId: UUID, state: ExportState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_UPLOAD_PREFIX}${Upload.KEY_UPLOAD_STATE} = :state WHERE ${Page.KEY_ID} = :pageId ") fun updateUploadState(pageId: UUID, state: UploadState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_EXPORT_STATE} = :state WHERE ${Page.KEY_ID} = :pageId") fun updateExportState(pageId: UUID, state: ExportState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_UPLOAD_PREFIX}${Upload.KEY_UPLOAD_STATE} = :state WHERE ${Page.KEY_DOC_ID} = :docId ") fun updateUploadStateForDocument(docId: UUID, state: UploadState) @Query("UPDATE ${Page.TABLE_NAME_PAGES} SET ${Page.KEY_UPLOAD_PREFIX}${Upload.KEY_UPLOAD_FILE_NAME} = null WHERE ${Page.KEY_DOC_ID} = :docId ") suspend fun clearDocumentPagesUploadFileNames(docId: UUID) }
lgpl-3.0
95e794b330e7de73ba90fc790818b7d3
50.508475
212
0.721619
3.350606
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/util/FileUtil.kt
1
2557
package org.jetbrains.haskell.util import java.io.File import java.io.BufferedReader import java.io.Reader import java.io.FileReader import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream public fun joinPath(first: String, vararg more: String): String { var result = first for (str in more) { result += File.separator + str } return result } public fun deleteRecursive(path: File) { val files = path.listFiles(); if (files != null) { for (file in files) { if (file.isDirectory()) { deleteRecursive(file); file.delete(); } else { file.delete(); } } } path.delete(); } public fun copyFile(iStream: InputStream, destination: File) { val oStream = FileOutputStream(destination); try { val buffer = ByteArray(1024 * 16); var length: Int; while (true ) { length = iStream.read(buffer) if (length <= 0) { break } oStream.write(buffer, 0, length); } } finally { iStream.close(); oStream.close(); } } public fun getRelativePath(base: String, path: String): String { val bpath = File(base).getCanonicalPath() val fpath = File(path).getCanonicalPath() if (fpath.startsWith(bpath)) { return fpath.substring(bpath.length() + 1) } else { throw RuntimeException("Base path " + base + "is wrong to " + path); } } fun readLines(file: File): Iterable<String> { return object : Iterable<String> { override fun iterator(): Iterator<String> { val br = BufferedReader(FileReader(file)); return object : Iterator<String> { var reader: BufferedReader? = br var line: String? = null; fun fetch(): String? { if (line == null) { line = reader?.readLine(); } if (line == null && reader != null) { reader?.close() reader == null } return line; } override fun next(): String { val result = fetch() line = null; return result!! } override fun hasNext(): Boolean { return fetch() != null } } } } }
apache-2.0
1e98360bf3e86436fdd6b11ee3d5a5dd
25.371134
76
0.499022
4.700368
false
false
false
false
eboudrant/net.ebt.muzei.miyazaki
app/src/main/java/net/ebt/muzei/miyazaki/RedirectActivity.kt
1
3416
package net.ebt.muzei.miyazaki import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.StringRes import com.google.android.apps.muzei.api.MuzeiContract.Sources.createChooseProviderIntent import com.google.android.apps.muzei.api.MuzeiContract.Sources.isProviderSelected import net.ebt.muzei.miyazaki.common.BuildConfig /** * This activity's sole purpose is to redirect users to Muzei, which is where they should * activate Muzei and then select the Earth View source. * * You'll note the usage of the `enable_launcher` boolean resource value to only enable * this on API 29+ devices as it is on API 29+ that a launcher icon becomes mandatory for * every app. */ class RedirectActivity : ComponentActivity() { companion object { private const val MUZEI_PACKAGE_NAME = "net.nurik.roman.muzei" private const val PLAY_STORE_LINK = "https://play.google.com/store/apps/details?id=$MUZEI_PACKAGE_NAME" } private val redirectLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult()) { // It doesn't matter what the result is, the important part is that the // user hit the back button to return to this activity. Since this activity // has no UI of its own, we can simply finish the activity. finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // First check whether Ghibli is already selected val launchIntent = packageManager.getLaunchIntentForPackage(MUZEI_PACKAGE_NAME) if (isProviderSelected(this, BuildConfig.GHIBLI_AUTHORITY) && launchIntent != null) { // Already selected so just open Muzei redirectLauncher.launch(launchIntent) return } // Ghibli isn't selected, so try to deep link into Muzei's Sources screen val deepLinkIntent = createChooseProviderIntent(BuildConfig.GHIBLI_AUTHORITY) if (tryStartIntent(deepLinkIntent, R.string.toast_enable)) { return } // createChooseProviderIntent didn't work, so try to just launch Muzei if (launchIntent != null && tryStartIntent(launchIntent, R.string.toast_enable_source)) { return } // Muzei isn't installed, so try to open the Play Store so that // users can install Muzei val playStoreIntent = Intent(Intent.ACTION_VIEW).setData(Uri.parse(PLAY_STORE_LINK)) if (tryStartIntent(playStoreIntent, R.string.toast_muzei_missing_error)) { return } // Only if all Intents failed do we show a 'everything failed' Toast Toast.makeText(this, R.string.toast_play_store_missing_error, Toast.LENGTH_LONG).show() finish() } private fun tryStartIntent(intent: Intent, @StringRes toastResId: Int): Boolean { return try { // Use startActivityForResult() so that we get a callback to // onActivityResult() if the user hits the system back button redirectLauncher.launch(intent) Toast.makeText(this, toastResId, Toast.LENGTH_LONG).show() true } catch (e: Exception) { false } } }
apache-2.0
5d8d32ecc370b835fb5f153a6c5c6904
42.794872
111
0.691745
4.518519
false
false
false
false
rhdunn/xquery-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/xpath/codeInspection/ijvs/IJVS0003.kt
1
4283
/* * Copyright (C) 2016-2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.codeInspection.ijvs import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiFile import com.intellij.util.SmartList import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection import uk.co.reecedunn.intellij.plugin.core.lexer.EntityReferenceType import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.intellij.lang.Specification import uk.co.reecedunn.intellij.plugin.intellij.lang.XQuerySpec import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryPredefinedEntityRef class IJVS0003 : Inspection("ijvs/IJVS0003.md", IJVS0003::class.java.classLoader) { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (file !is XQueryModule) return null val version: Specification = file.XQueryVersion.getVersionOrDefault(file.getProject()) val descriptors = SmartList<ProblemDescriptor>() file.walkTree().filterIsInstance<XQueryPredefinedEntityRef>().forEach { element -> val ref = element.entityRef when (ref.type) { EntityReferenceType.XmlEntityReference -> { } EntityReferenceType.Html4EntityReference -> { if (version !== XQuerySpec.MARKLOGIC_0_9 && version !== XQuerySpec.MARKLOGIC_1_0) { val description = XQueryPluginBundle.message("annotator.string-literal.html4-entity", ref.name) descriptors.add( manager.createProblemDescriptor( element, description, null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly ) ) } } EntityReferenceType.Html5EntityReference -> { if (version !== XQuerySpec.MARKLOGIC_0_9 && version !== XQuerySpec.MARKLOGIC_1_0) { val description = XQueryPluginBundle.message("annotator.string-literal.html5-entity", ref.name) descriptors.add( manager.createProblemDescriptor( element, description, null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly ) ) } } else -> { val description = XQueryPluginBundle.message("annotator.string-literal.unknown-xml-entity", ref.name) descriptors.add( manager.createProblemDescriptor( element, description, null as LocalQuickFix?, ProblemHighlightType.ERROR, isOnTheFly ) ) } } } return descriptors.toTypedArray() } }
apache-2.0
5893ba1ec5cc2bc32b2b089cc88ed7b8
46.588889
119
0.590007
5.51933
false
false
false
false
kohesive/klutter
binder-kodein/src/main/kotlin/uy/klutter/binder/kodein/Construction.kt
2
1597
package uy.klutter.binder.kodein import com.github.salomonbrys.kodein.Kodein import uy.klutter.binder.EitherType import uy.klutter.binder.NamedValueProvider import uy.klutter.binder.ProvidedValue import uy.klutter.binder.ValueProviderTargetScope import kotlin.reflect.KType import kotlin.reflect.jvm.javaType class KodeinValueProvider(private val kodein: Kodein, private val delegate: NamedValueProvider) : NamedValueProvider by delegate { override fun valueByName(name: String, targetType: EitherType, scope: ValueProviderTargetScope): ProvidedValue<Any?> { val maybe = delegate.valueByName(name, targetType, scope) return when (maybe) { is ProvidedValue.Present -> maybe is ProvidedValue.NestedNamedValueProvider -> maybe // TODO: should we return this, or check if we have a full object first? is ProvidedValue.NestedOrderedValueProvider -> maybe // TODO: should we return this, or check if we have a full object first? is ProvidedValue.Absent -> kodein.container.providerOrNull(Kodein.Bind(targetType.asJava, null))?.invoke() ?.let { ProvidedValue.of(it) } ?: ProvidedValue.absent() } } override fun equals(other: Any?): Boolean { return other != null && this.javaClass == other.javaClass && other is KodeinValueProvider && other.kodein === this.kodein && // identity compare other.delegate == this.delegate } override fun hashCode(): Int { return kodein.hashCode() * delegate.hashCode() } }
mit
f7516d29fb06380cee43b7d3610f449c
44.628571
137
0.691296
4.839394
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/object/fields1.kt
1
380
class B(val a:Int, b:Int) { constructor(pos:Int):this(1, pos) {} val pos = b + 1 } fun primaryConstructorCall(a:Int, b:Int) = B(a, b).pos fun secondaryConstructorCall(a:Int) = B(a).pos fun main(args:Array<String>) { if (primaryConstructorCall(0xdeadbeef.toInt(), 41) != 42) throw Error() if (secondaryConstructorCall(41) != 42) throw Error() }
apache-2.0
b40d8104dd46747b37acf91f5fe4d598
28.307692
75
0.631579
3.04
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/img/Img.kt
1
3029
package nl.shadowlink.tools.shadowlib.img import nl.shadowlink.tools.io.ReadFunctions import nl.shadowlink.tools.io.WriteFunctions import nl.shadowlink.tools.shadowlib.utils.Utils import nl.shadowlink.tools.shadowlib.utils.saving.Saveable import nl.shadowlink.tools.shadowlib.utils.saving.SaveableFile import java.nio.file.Path import kotlin.io.path.fileSize import kotlin.io.path.isReadable import kotlin.io.path.isRegularFile import kotlin.io.path.name /** * @author Shadow-Link */ class Img( val path: Path, val items: MutableList<ImgItem> = mutableListOf(), var isEncrypted: Boolean = false ) : Saveable by SaveableFile() { val fileName: String get() = path.name private constructor(path: Path) : this(path, items = mutableListOf()) { setSaveRequired() } fun toggleEncryption(enabled: Boolean) { if (isEncrypted != enabled) { isEncrypted = enabled setSaveRequired() } } val totalItemCount: Int get() = items.count() fun getItemsOfType(extension: String): List<ImgItem> { return items.filter { item -> item.name.endsWith(extension) } } fun getItemOfTypeCount(extension: String): Int { return items.count { item -> item.name.endsWith(extension) } } /** * Find the index of the item with the given [name]. * * @return the index of the item or `-1` when item could not be found */ fun findItemIndex(name: String): Int { return items.indexOfFirst { item -> item.name == name } } /** * Find the item with the given name * * @return the item or `null` if item can not be found */ fun findItem(name: String): ImgItem? { return items.firstOrNull { item -> item.name == name } } /** * Adds the [path] to the IMG */ fun addItem(path: Path) { if (path.isRegularFile() && path.isReadable()) { val rf = ReadFunctions(path) val wf = WriteFunctions(path) val newFile: ByteArray = rf.readArray(path.fileSize().toInt()) val tempItem = ImgItem(path.name) tempItem.type = Utils.getResourceType(path.name) tempItem.offset = wf.fileSize tempItem.size = path.fileSize().toInt() if (tempItem.isResource) { rf.seek(0x8) tempItem.flags = rf.readInt() } items.add(tempItem) wf.gotoEnd() wf.write(newFile) if (wf.closeFile()) { println("Closed file") } else { println("Unable to close the file") } setSaveRequired() rf.closeFile() } } fun removeItem(imgItem: ImgItem) { items.remove(imgItem) setSaveRequired() } fun save() { TODO("IMG Saving is not implemented") } companion object { fun createNewImg(path: Path): Img { return Img(path) } } }
gpl-2.0
2cb6b9526144782a9c946bf7f4cf0c8e
26.788991
75
0.591284
4.093243
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/model/api/User.kt
2
2794
package com.commit451.gitlab.model.api import android.os.Parcelable import androidx.annotation.StringDef import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize import java.util.Date @Parcelize data class User( @Json(name = "created_at") var createdAt: Date? = null, @Json(name = "is_admin") var isAdmin: Boolean = false, @Json(name = "bio") var bio: String? = null, @Json(name = "skype") var skype: String? = null, @Json(name = "linkedin") var linkedin: String? = null, @Json(name = "twitter") var twitter: String? = null, @Json(name = "website_url") var websiteUrl: String? = null, @Json(name = "email") var email: String? = null, @Json(name = "theme_id") var themeId: Int? = 0, @Json(name = "color_scheme_id") var colorSchemeId: Int = 0, @Json(name = "projects_limit") var projectsLimit: Int = 0, @Json(name = "current_sign_in_at") var currentSignInAt: Date? = null, @Json(name = "identities") var identities: List<Identity>? = null, @Json(name = "can_create_group") var canCreateGroup: Boolean = false, @Json(name = "can_create_project") var canCreateProject: Boolean = false, @Json(name = "two_factor_enabled") var isTwoFactorEnabled: Boolean = false, @Json(name = "id") var id: Long = 0, @Json(name = "state") @State @get:State var state: String? = null, @Json(name = "avatar_url") var avatarUrl: String? = null, @Json(name = "web_url") var webUrl: String? = null, @Json(name = "name") var name: String? = null, @Json(name = "username") var username: String? = null, @Json(name = "private_token") var privateToken: String? = null, @Json(name = "access_level") var accessLevel: Int = 0 ) : Parcelable { companion object { const val STATE_ACTIVE = "active" const val STATE_BLOCKED = "blocked" fun getAccessLevel(accessLevel: String): Int { when (accessLevel.toLowerCase()) { "guest" -> return 10 "reporter" -> return 20 "developer" -> return 30 "master" -> return 40 "owner" -> return 50 } throw IllegalStateException("No known code for this access level") } fun getAccessLevel(accessLevel: Int): String { when (accessLevel) { 10 -> return "Guest" 20 -> return "Reporter" 30 -> return "Developer" 40 -> return "Master" 50 -> return "Owner" } return "Unknown" } } @StringDef(STATE_ACTIVE, STATE_BLOCKED) @Retention(AnnotationRetention.SOURCE) annotation class State }
apache-2.0
995b3ede3c885ca360a8ae8de8e0f497
28.410526
78
0.577666
3.801361
false
false
false
false
koral--/android-gradle-jenkins-plugin
plugin/src/main/kotlin/pl/droidsonroids/gradle/ci/MonkeyOutputReceiver.kt
1
635
package pl.droidsonroids.gradle.ci import com.android.ddmlib.MultiLineReceiver import java.io.File import java.io.PrintWriter class MonkeyOutputReceiver(outputFile: File) : MultiLineReceiver() { private val printWriter: PrintWriter = PrintWriter(outputFile.bufferedWriter(bufferSize = 16 shl 10)) private var isCancelled: Boolean = false override fun processNewLines(lines: Array<String>) = lines.forEach { printWriter.println(it) } override fun done() = with(printWriter) { flush() close() } override fun isCancelled() = isCancelled fun cancel() { isCancelled = true } }
mit
8c00d27eba03e8bcdf9cd22ab3ff70f6
25.458333
105
0.711811
4.440559
false
false
false
false
exponentjs/exponent
packages/expo-updates/android/src/main/java/expo/modules/updates/errorrecovery/ErrorRecoveryHandler.kt
2
4731
package expo.modules.updates.errorrecovery import android.os.Handler import android.os.Looper import android.os.Message import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.launcher.Launcher import java.lang.RuntimeException internal class ErrorRecoveryHandler( looper: Looper, private val delegate: ErrorRecoveryDelegate ) : Handler(looper) { private val pipeline = arrayListOf( Task.WAIT_FOR_REMOTE_UPDATE, Task.LAUNCH_NEW_UPDATE, Task.LAUNCH_CACHED_UPDATE, Task.CRASH ) private var isPipelineRunning = false private var isWaitingForRemoteUpdate = false private var hasContentAppeared = false private val encounteredErrors = ArrayList<Exception>() object MessageType { const val EXCEPTION_ENCOUNTERED = 0 const val CONTENT_APPEARED = 1 const val REMOTE_LOAD_STATUS_CHANGED = 2 } private enum class Task { WAIT_FOR_REMOTE_UPDATE, LAUNCH_NEW_UPDATE, LAUNCH_CACHED_UPDATE, CRASH } override fun handleMessage(msg: Message) { when (msg.what) { MessageType.EXCEPTION_ENCOUNTERED -> maybeStartPipeline(msg.obj as Exception) MessageType.CONTENT_APPEARED -> handleContentAppeared() MessageType.REMOTE_LOAD_STATUS_CHANGED -> handleRemoteLoadStatusChanged(msg.obj as ErrorRecoveryDelegate.RemoteLoadStatus) else -> throw RuntimeException("ErrorRecoveryHandler cannot handle message " + msg.what) } } private fun handleContentAppeared() { hasContentAppeared = true // the launch now counts as "successful" so we don't want to roll back; // remove any extraneous tasks from the pipeline as such pipeline.retainAll(setOf(Task.WAIT_FOR_REMOTE_UPDATE, Task.CRASH)) delegate.markSuccessfulLaunchForLaunchedUpdate() } private fun handleRemoteLoadStatusChanged(newStatus: ErrorRecoveryDelegate.RemoteLoadStatus) { if (!isWaitingForRemoteUpdate) { return } isWaitingForRemoteUpdate = false if (newStatus != ErrorRecoveryDelegate.RemoteLoadStatus.NEW_UPDATE_LOADED) { pipeline.remove(Task.LAUNCH_NEW_UPDATE) } runNextTask() } private fun runNextTask() { when (val nextTask = pipeline.removeAt(0)) { Task.WAIT_FOR_REMOTE_UPDATE -> waitForRemoteUpdate() Task.LAUNCH_NEW_UPDATE -> tryRelaunchFromCache() // only called after a new update is downloaded and added to the cache, so the implementation is equivalent Task.LAUNCH_CACHED_UPDATE -> tryRelaunchFromCache() Task.CRASH -> crash() else -> throw RuntimeException("ErrorRecoveryHandler cannot perform task $nextTask") } } private fun maybeStartPipeline(exception: Exception) { encounteredErrors.add(exception) if (delegate.getLaunchedUpdateSuccessfulLaunchCount() > 0) { pipeline.remove(Task.LAUNCH_CACHED_UPDATE) } else if (!hasContentAppeared) { delegate.markFailedLaunchForLaunchedUpdate() } if (!isPipelineRunning) { isPipelineRunning = true runNextTask() } } private fun waitForRemoteUpdate() { val remoteLoadStatus = delegate.getRemoteLoadStatus() if (remoteLoadStatus == ErrorRecoveryDelegate.RemoteLoadStatus.NEW_UPDATE_LOADED) { runNextTask() } else if (remoteLoadStatus == ErrorRecoveryDelegate.RemoteLoadStatus.NEW_UPDATE_LOADING || delegate.getCheckAutomaticallyConfiguration() != UpdatesConfiguration.CheckAutomaticallyConfiguration.NEVER ) { isWaitingForRemoteUpdate = true if (delegate.getRemoteLoadStatus() != ErrorRecoveryDelegate.RemoteLoadStatus.NEW_UPDATE_LOADING) { delegate.loadRemoteUpdate() } postDelayed({ handleRemoteLoadStatusChanged(ErrorRecoveryDelegate.RemoteLoadStatus.IDLE) }, REMOTE_LOAD_TIMEOUT_MS) } else { // there's no remote update, so move to the next step in the pipeline pipeline.remove(Task.LAUNCH_NEW_UPDATE) runNextTask() } } private fun tryRelaunchFromCache() { delegate.relaunch(object : Launcher.LauncherCallback { override fun onFailure(e: Exception) { // post to our looper, in case we're on a different thread now post { encounteredErrors.add(e) pipeline.removeAll(setOf(Task.LAUNCH_NEW_UPDATE, Task.LAUNCH_CACHED_UPDATE)) runNextTask() } } override fun onSuccess() { // post to our looper, in case we're on a different thread now post { isPipelineRunning = false } } }) } private fun crash() { // throw the initial exception to preserve its stacktrace // rather than creating a new (aggregate) one delegate.throwException(encounteredErrors[0]) } companion object { const val REMOTE_LOAD_TIMEOUT_MS = 5000L } }
bsd-3-clause
4c6efe53123ac0ba9781ac6bf29367d6
33.282609
162
0.717396
4.421495
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/logging/BuildMessagesImpl.kt
1
7425
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl.logging import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.util.containers.Stack import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.io.BufferedWriter import java.io.PrintWriter import java.io.StringWriter import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.util.* import java.util.function.Consumer class BuildMessagesImpl private constructor(private val logger: BuildMessageLogger, private val debugLogger: DebugLogger, private val parentInstance: BuildMessagesImpl?) : BuildMessages { private val delayedMessages = ArrayList<LogMessage>() private val blockNames = Stack<String>() companion object { fun create(): BuildMessagesImpl { val underTeamCity = System.getenv("TEAMCITY_VERSION") != null val mainLoggerFactory = if (underTeamCity) TeamCityBuildMessageLogger.FACTORY else ConsoleBuildMessageLogger.FACTORY val debugLogger = DebugLogger() val loggerFactory: () -> BuildMessageLogger = { CompositeBuildMessageLogger(listOf(mainLoggerFactory(), debugLogger.createLogger())) } return BuildMessagesImpl(logger = loggerFactory(), debugLogger = debugLogger, parentInstance = null) } } override fun getName() = "" override fun isLoggable(level: System.Logger.Level) = level.severity > System.Logger.Level.TRACE.severity override fun log(level: System.Logger.Level, bundle: ResourceBundle?, message: String, thrown: Throwable?) { when (level) { System.Logger.Level.INFO -> info(message) System.Logger.Level.ERROR -> { if (thrown == null) { error(message) } else { error(message, thrown) } } System.Logger.Level.WARNING -> warning(message) else -> debug(message) } } override fun log(level: System.Logger.Level, bundle: ResourceBundle?, format: String, vararg params: Any?) { log(level = level, message = format, bundle = bundle, thrown = null) } override fun info(message: String) { processMessage(LogMessage(LogMessage.Kind.INFO, message)) } override fun warning(message: String) { processMessage(LogMessage(LogMessage.Kind.WARNING, message)) } override fun debug(message: String) { processMessage(LogMessage(LogMessage.Kind.DEBUG, message)) } fun setDebugLogPath(path: Path) { debugLogger.setOutputFile(path) } val debugLogFile: Path? get() = debugLogger.getOutputFile() override fun error(message: String) { try { TraceManager.finish() } catch (e: Throwable) { System.err.println("Cannot finish tracing: $e") } throw BuildScriptsLoggedError(message) } override fun error(message: String, cause: Throwable) { val writer = StringWriter() PrintWriter(writer).use(cause::printStackTrace) processMessage(LogMessage(kind = LogMessage.Kind.ERROR, text = """ $message $writer """.trimIndent())) throw BuildScriptsLoggedError(message, cause) } override fun compilationError(compilerName: String, message: String) { compilationErrors(compilerName, listOf(message)) } override fun compilationErrors(compilerName: String, messages: List<String>) { processMessage(CompilationErrorsLogMessage(compilerName, messages)) } override fun progress(message: String) { if (parentInstance != null) { //progress messages should be shown immediately, there are no problems with that since they aren't organized into groups parentInstance.progress(message) } else { logger.processMessage(LogMessage(LogMessage.Kind.PROGRESS, message)) } } override fun buildStatus(message: String) { processMessage(LogMessage(LogMessage.Kind.BUILD_STATUS, message)) } override fun setParameter(parameterName: String, value: String) { processMessage(LogMessage(LogMessage.Kind.SET_PARAMETER, "$parameterName=$value")) } override fun <V> block(blockName: String, task: () -> V): V { spanBuilder(blockName.lowercase(Locale.getDefault())).useWithScope { try { blockNames.push(blockName) processMessage(LogMessage(LogMessage.Kind.BLOCK_STARTED, blockName)) return task() } catch (e: Throwable) { // print all pending spans TracerProviderManager.flush() throw e } finally { blockNames.pop() processMessage(LogMessage(LogMessage.Kind.BLOCK_FINISHED, blockName)) } } } override fun artifactBuilt(relativeArtifactPath: String) { logger.processMessage(LogMessage(LogMessage.Kind.ARTIFACT_BUILT, relativeArtifactPath)) } override fun reportStatisticValue(key: String, value: String) { processMessage(LogMessage(LogMessage.Kind.STATISTICS, "$key=$value")) } private fun processMessage(message: LogMessage) { if (parentInstance == null) { logger.processMessage(message) } else { //It appears that TeamCity currently cannot properly handle log messages from parallel tasks (https://youtrack.jetbrains.com/issue/TW-46515) //Until it is fixed we need to delay delivering of messages from the tasks running in parallel until all tasks have been finished. delayedMessages.add(message) } } } /** * Used to print debug-level log message to a file in the build output. It firstly prints messages to a temp file and copies it to the real * file after the build process cleans up the output directory. */ private class DebugLogger { private val tempFile: Path = Files.createTempFile("intellij-build", ".log") private var output: BufferedWriter private var outputFile: Path? = null private val loggers = ArrayList<PrintWriterBuildMessageLogger>() init { Files.createDirectories(tempFile.parent) output = Files.newBufferedWriter(tempFile) } @Synchronized fun setOutputFile(outputFile: Path) { this.outputFile = outputFile output.close() Files.createDirectories(outputFile.parent) if (Files.exists(tempFile)) { Files.move(tempFile, outputFile, StandardCopyOption.REPLACE_EXISTING) } output = Files.newBufferedWriter(outputFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND) for (logger in loggers) { logger.setOutput(output) } } @Synchronized fun getOutputFile() = outputFile @Synchronized fun createLogger(): BuildMessageLogger { val logger = PrintWriterBuildMessageLogger(output = output, disposer = loggers::remove) loggers.add(logger) return logger } } private class PrintWriterBuildMessageLogger( private var output: BufferedWriter, private val disposer: Consumer<PrintWriterBuildMessageLogger>, ) : BuildMessageLoggerBase() { @Synchronized fun setOutput(output: BufferedWriter) { this.output = output } @Override @Synchronized override fun printLine(line: String) { output.write(line) output.write("\n") output.flush() } override fun dispose() { disposer.accept(this) } }
apache-2.0
95b70f42c0c9240bfb692f6531ac7746
31.858407
146
0.703569
4.532967
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/KotlinFirCompletionContributor.kt
3
5417
// 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.completion import com.intellij.codeInsight.completion.* import com.intellij.openapi.components.service import com.intellij.patterns.PlatformPatterns import com.intellij.patterns.PsiJavaPatterns import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.low.level.api.fir.util.originalKtFile import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirPositionCompletionContextDetector import org.jetbrains.kotlin.idea.completion.context.FirRawPositionCompletionContext import org.jetbrains.kotlin.idea.completion.contributors.FirCompletionContributorFactory import org.jetbrains.kotlin.idea.completion.weighers.Weighers import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile class KotlinFirCompletionContributor : CompletionContributor() { init { extend(CompletionType.BASIC, PlatformPatterns.psiElement(), KotlinFirCompletionProvider) } override fun beforeCompletion(context: CompletionInitializationContext) { val psiFile = context.file if (psiFile !is KtFile) return val identifierProviderService = service<CompletionDummyIdentifierProviderService>() correctPositionAndDummyIdentifier(identifierProviderService, context) } private fun correctPositionAndDummyIdentifier( identifierProviderService: CompletionDummyIdentifierProviderService, context: CompletionInitializationContext ) { val dummyIdentifierCorrected = identifierProviderService.correctPositionForStringTemplateEntry(context) if (dummyIdentifierCorrected) { return } context.dummyIdentifier = identifierProviderService.provideDummyIdentifier(context) } } private object KotlinFirCompletionProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { @Suppress("NAME_SHADOWING") val parameters = KotlinFirCompletionParametersProvider.provide(parameters) if (shouldSuppressCompletion(parameters.ijParameters, result.prefixMatcher)) return val resultSet = createResultSet(parameters, result) val basicContext = FirBasicCompletionContext.createFromParameters(parameters, resultSet) ?: return recordOriginalFile(basicContext) val positionContext = FirPositionCompletionContextDetector.detect(basicContext) FirPositionCompletionContextDetector.analyzeInContext(basicContext, positionContext) { complete(basicContext, positionContext) } } private fun KtAnalysisSession.complete( basicContext: FirBasicCompletionContext, positionContext: FirRawPositionCompletionContext, ) { val factory = FirCompletionContributorFactory(basicContext) with(Completions) { complete(factory, positionContext) } } private fun recordOriginalFile(basicCompletionContext: FirBasicCompletionContext) { val originalFile = basicCompletionContext.originalKtFile val fakeFile = basicCompletionContext.fakeKtFile fakeFile.originalKtFile = originalFile } private fun createResultSet(parameters: KotlinFirCompletionParameters, result: CompletionResultSet): CompletionResultSet { @Suppress("NAME_SHADOWING") var result = result.withRelevanceSorter(createSorter(parameters.ijParameters, result)) if (parameters is KotlinFirCompletionParameters.Corrected) { val replaced = parameters.ijParameters @Suppress("DEPRECATION") val originalPrefix = CompletionData.findPrefixStatic(replaced.position, replaced.offset) result = result.withPrefixMatcher(originalPrefix) } return result } private fun createSorter(parameters: CompletionParameters, result: CompletionResultSet): CompletionSorter = CompletionSorter.defaultSorter(parameters, result.prefixMatcher) .let(Weighers::addWeighersToCompletionSorter) private val AFTER_NUMBER_LITERAL = PsiJavaPatterns.psiElement().afterLeafSkipping( PsiJavaPatterns.psiElement().withText(""), PsiJavaPatterns.psiElement().withElementType(PsiJavaPatterns.elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)) ) private val AFTER_INTEGER_LITERAL_AND_DOT = PsiJavaPatterns.psiElement().afterLeafSkipping( PsiJavaPatterns.psiElement().withText("."), PsiJavaPatterns.psiElement().withElementType(PsiJavaPatterns.elementType().oneOf(KtTokens.INTEGER_LITERAL)) ) private fun shouldSuppressCompletion(parameters: CompletionParameters, prefixMatcher: PrefixMatcher): Boolean { val position = parameters.position val invocationCount = parameters.invocationCount // no completion inside number literals if (AFTER_NUMBER_LITERAL.accepts(position)) return true // no completion auto-popup after integer and dot if (invocationCount == 0 && prefixMatcher.prefix.isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return true return false } }
apache-2.0
7b01d6608f5da2695cffcf8b2bd0f720
44.521008
139
0.767953
5.505081
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveRedundantSpreadOperatorInspection.kt
1
5004
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.isArrayOfFunction import org.jetbrains.kotlin.idea.refactoring.replaceWithCopyWithResolveCheck import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RemoveRedundantSpreadOperatorInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return valueArgumentVisitor(fun(argument) { val spreadElement = argument.getSpreadElement() ?: return if (argument.isNamed()) return val argumentExpression = argument.getArgumentExpression() ?: return val argumentOffset = argument.startOffset val startOffset = spreadElement.startOffset - argumentOffset val endOffset = when (argumentExpression) { is KtCallExpression -> { if (!argumentExpression.isArrayOfFunction()) return val call = argument.getStrictParentOfType<KtCallExpression>() ?: return val bindingContext = call.analyze(BodyResolveMode.PARTIAL) val argumentIndex = call.valueArguments.indexOfFirst { it == argument } if (call.replaceWithCopyWithResolveCheck( resolveStrategy = { expr, context -> expr.getResolvedCall(context)?.resultingDescriptor }, context = bindingContext, preHook = { val anchor = valueArgumentList?.arguments?.getOrNull(argumentIndex) argumentExpression.valueArguments.reversed().forEach { valueArgumentList?.addArgumentAfter(it, anchor) } valueArgumentList?.removeArgument(argumentIndex) } ) == null ) return argumentExpression.calleeExpression!!.endOffset - argumentOffset } is KtCollectionLiteralExpression -> startOffset + 1 else -> return } val problemDescriptor = holder.manager.createProblemDescriptor( argument, TextRange(startOffset, endOffset), KotlinBundle.message("remove.redundant.spread.operator.quickfix.text"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, isOnTheFly, RemoveRedundantSpreadOperatorQuickfix() ) holder.registerProblem(problemDescriptor) }) } } class RemoveRedundantSpreadOperatorQuickfix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.spread.operator.quickfix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { // Argument & expression under * val spreadValueArgument = descriptor.psiElement as? KtValueArgument ?: return val spreadArgumentExpression = spreadValueArgument.getArgumentExpression() ?: return val outerArgumentList = spreadValueArgument.getStrictParentOfType<KtValueArgumentList>() ?: return // Arguments under arrayOf or [] val innerArgumentExpressions = when (spreadArgumentExpression) { is KtCallExpression -> spreadArgumentExpression.valueArgumentList?.arguments?.map { it.getArgumentExpression() to it.isSpread } is KtCollectionLiteralExpression -> spreadArgumentExpression.getInnerExpressions().map { it to false } else -> null } ?: return val factory = KtPsiFactory(project) innerArgumentExpressions.reversed().forEach { (expression, isSpread) -> outerArgumentList.addArgumentAfter(factory.createArgument(expression, isSpread = isSpread), spreadValueArgument) } outerArgumentList.removeArgument(spreadValueArgument) } }
apache-2.0
435023e8a3d04d8a8c72aded9edb8acb
51.135417
124
0.655476
6.302267
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/services/discover/ReaderDiscoverServiceStarter.kt
1
2373
package org.wordpress.android.ui.reader.services.discover import android.app.job.JobInfo import android.app.job.JobInfo.Builder import android.app.job.JobScheduler import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.PersistableBundle import org.wordpress.android.JobServiceId import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverLogic.DiscoverTasks import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.READER /* * This class provides a way to decide which kind of Service to start, depending on the platform we're running on. * */ object ReaderDiscoverServiceStarter { const val ARG_DISCOVER_TASK = "discover_task" fun startService(context: Context, task: DiscoverTasks): Boolean { if (VERSION.SDK_INT < VERSION_CODES.O) { val intent = Intent(context, ReaderDiscoverService::class.java) intent.putExtra(ARG_DISCOVER_TASK, task) context.startService(intent) } else { // schedule the JobService here for API >= 26. The JobScheduler is available since API 21, but // it's preferable to use it only since enforcement in API 26 to not break any old behavior val componentName = ComponentName(context, ReaderDiscoverJobService::class.java) val extras = PersistableBundle() extras.putInt(ARG_DISCOVER_TASK, task.ordinal) val jobInfo = Builder(JobServiceId.JOB_READER_DISCOVER_SERVICE_ID, componentName) .setRequiresCharging(false) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setOverrideDeadline(0) // if possible, try to run right away .setExtras(extras) .build() val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler val resultCode = jobScheduler.schedule(jobInfo) if (resultCode == JobScheduler.RESULT_SUCCESS) { AppLog.i(READER, "reader discover service > job scheduled") } else { AppLog.e(READER, "reader discover service > job could not be scheduled") return false } } return true } }
gpl-2.0
fee167a3d488085774114889f6f6b0f8
44.634615
113
0.684787
4.616732
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/Constraint.kt
6
1944
// 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.nj2k.inference.common enum class ConstraintPriority { /* order of entries here used when solving system of constraints */ SUPER_DECLARATION, INITIALIZER, RETURN, ASSIGNMENT, PARAMETER, RECEIVER_PARAMETER, COMPARE_WITH_NULL, USE_AS_RECEIVER, } sealed class Constraint { abstract val priority: ConstraintPriority } class SubtypeConstraint( var subtype: ConstraintBound, var supertype: ConstraintBound, override val priority: ConstraintPriority ) : Constraint() { operator fun component1() = subtype operator fun component2() = supertype } class EqualsConstraint( var left: ConstraintBound, var right: ConstraintBound, override val priority: ConstraintPriority ) : Constraint() { operator fun component1() = left operator fun component2() = right } fun Constraint.copy() = when (this) { is SubtypeConstraint -> SubtypeConstraint(subtype, supertype, priority) is EqualsConstraint -> EqualsConstraint(left, right, priority) } sealed class ConstraintBound class TypeVariableBound(val typeVariable: TypeVariable) : ConstraintBound() class LiteralBound private constructor(val state: State) : ConstraintBound() { companion object { val UPPER = LiteralBound(State.UPPER) val LOWER = LiteralBound(State.LOWER) val UNKNOWN = LiteralBound(State.UNKNOWN) } } fun State.constraintBound(): LiteralBound? = when (this) { State.LOWER -> LiteralBound.LOWER State.UPPER -> LiteralBound.UPPER State.UNKNOWN -> LiteralBound.UNKNOWN State.UNUSED -> null } val ConstraintBound.isUnused get() = when (this) { is TypeVariableBound -> typeVariable.state == State.UNUSED is LiteralBound -> state == State.UNUSED }
apache-2.0
bb55c49173afffd8860b08cd1572561e
28.907692
158
0.71965
4.388262
false
false
false
false
consp1racy/android-support-preference
gradle/plugins/publish/src/main/java/net/xpece/gradle/publish/PublishPlugin.kt
1
2311
package net.xpece.gradle.publish import com.android.build.gradle.AppExtension import com.android.build.gradle.BaseExtension import com.android.build.gradle.LibraryExtension import net.xpece.gradle.publish.PublishExtension.Companion.DEFAULT_COMPONENT_NAME import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.UnknownDomainObjectException import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.getByType class PublishPlugin : Plugin<Project> { override fun apply(target: Project) = target.run { val extension = extensions.create<PublishExtension>("xpecePublish") // Automatically apply publishing plugin. target.plugins.findPlugin("maven-publish") ?: target.apply(plugin = "maven-publish") // Wait after DSL is parsed. afterEvaluate { try { // Check if we're running Android build. target.android target.applyAndroid(extension) } catch (_: UnknownDomainObjectException) { target.applyJava(extension) } } } private val Project.android: BaseExtension get() = extensions.getByType() private fun Project.applyAndroid(extension: PublishExtension) { var componentName = extension.publishReleaseFromComponent ?: return if (componentName == DEFAULT_COMPONENT_NAME) { componentName = when (android) { is LibraryExtension -> "release" is AppExtension -> "release_apk" else -> throw IllegalStateException("Unsupported Android extension: $android") } } val pom = extension.pom val repositories = extension.repositories val publisher = AndroidPublisher(this, componentName, pom, repositories) publisher.publish() } private fun Project.applyJava(extension: PublishExtension) { var componentName = extension.publishReleaseFromComponent ?: return if (componentName == DEFAULT_COMPONENT_NAME) componentName = "java" val pom = extension.pom val repositories = extension.repositories val publisher = JavaPublisher(this, componentName, pom, repositories) publisher.publish() } }
apache-2.0
a554df24134753301402881470c61f44
36.274194
94
0.673302
4.980603
false
false
false
false
RMHSProgrammingClub/Bot-Game
kotlin/src/main/kotlin/com/n9mtq4/botclient/Game.kt
1
4100
package com.n9mtq4.botclient /** * An object for the currently running game. * * Created by will on 11/24/15 at 3:14 PM. * * @author Will "n9Mtq4" Bresnahan */ class Game() { /** * The version of the server this client is connected to. * * "ruby" or "kotlin API_LEVEL" * ex: "ruby", "kotlin 1", "kotlin 2" * */ val serverVersion: String /** * The connection to the server. * */ private val connection: ServerConnection /** * Your team number. * So far it is either 1 or 2 * */ val team: Int /** * The compliance level that this client is running at * */ val currentCompliance: String /** * Constructor for the Game * * Makes sure that the game should * be stated/created and sets your team number. * */ init { // get the socket port to connect to val port = System.getProperty(PropertyDictionary.SERVER_PORT)?.toInt() ?: SOCKET_PORT this.connection = ServerConnection(port) // send our compliance level this.currentCompliance = System.getProperty(PropertyDictionary.COMPLIANCE_LEVEL) ?: SERVER_VERSION if (currentCompliance != SERVER_VERSION) println("[WARNING]: Not using the client's compliance level, forcing the use of: \"$currentCompliance\"") connection.writeln(currentCompliance) val command = connection.readLine() // verify the integrity of the start command if (!command.contains("START")) throw ClientNetworkException("Command error", "START", command) // Version checking. Only works with BotServer-kt if (command.contains("API")) { // we now know that this is a kotlin server val version = command.substring("START API ".length).toInt() this.serverVersion = "kotlin $version" if (version < API_LEVEL) { System.err.println("[ERROR]: the server is running a newer version than the client. Please update this API to support the newer server.") System.exit(-1) }else if (version != API_LEVEL) { println("[WARNING]: the server and the client are running a different version.") } }else { // this is a ruby server this.serverVersion = "ruby" } // get our team information team = connection.readLine().toInt() println("Team Number: $team") } /** * Kotlin method. Allows getting the bot like: * ```kotlin * val game = Game() * val bot = game() * ``` * */ @Throws(ClientNetworkException::class, GameEnded::class) operator fun invoke() = waitForTurn() /** * Halts, waiting for input through the socket * when it receives the Start turn command, it * makes a bot for that turn and returns it * * @return That turns bot * */ @Throws(ClientNetworkException::class, GameEnded::class) fun waitForTurn(): ControllableBot { val command = connection.read() // TODO: deprecated - as of commit 55df0f6 (above v1.0.6-beta) this will not happen; only for backwards compatibility if ("LOOSE" in command || "WIN" in command || "DRAW" in command) throw GameEnded(command) // check if the game has ended if (command == "END") { val data = connection.read() if ("LOOSE" in data || "WIN" in data || "DRAW" in data) throw GameEnded(command) else throw ClientNetworkException("Error with game end", "LOOSE || WIN || DRAW", command) } // if it hasn't ended, then make sure that the turn has started if (command != "START_TURN") throw ClientNetworkException("Command Error", "START_TURN", command) return readAndMakeBot() } /** * Ends your turn and writes the actions that your bot * has done this turn to a file * */ infix fun endTurn(controllableBot: ControllableBot) { // write the turn log to the socket and flush it connection.writeWholeLog(controllableBot.turnLog) } /** * Prepares the data for building a bot * does some replacing and splits it. * * The actually parsing is done by * ControllableBot.buildBot * * @see ControllableBot.buildBot * @return A [ControllableBot] make from the next line in StdIn * */ private fun readAndMakeBot(): ControllableBot { val data = connection.read() return ControllableBot.buildBot(data) } }
mit
dff96eda28609e04f00f59219d751cf0
27.082192
148
0.679024
3.565217
false
false
false
false
Mystery00/JanYoShare
app/src/main/java/com/janyo/janyoshare/util/TransferFileNotification.kt
1
3172
package com.janyo.janyoshare.util import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.support.v4.app.NotificationCompat import android.support.v4.content.FileProvider import com.janyo.janyoshare.R import com.janyo.janyoshare.classes.TransferFile import java.io.File object TransferFileNotification { fun notify(context: Context, id: Int) { val index = FileTransferHelper.getInstance().currentFileIndex val transferFile = FileTransferHelper.getInstance().fileList[index] val title = context.getString(R.string.hint_transfer_file_notification_title, transferFile.fileName) val builder = NotificationCompat.Builder(context, context.getString(R.string.app_name)) .setSmallIcon(R.drawable.ic_send) .setContentTitle(title) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setProgress(100, transferFile.transferProgress, false) .setAutoCancel(true) notify(context, id, builder.build()) } fun done(context: Context, id: Int, transferFile: TransferFile) { val title = context.getString(R.string.hint_transfer_file_notification_done, transferFile.fileName) var path = "" when (FileTransferHelper.getInstance().tag) { 1 -> { path = transferFile.filePath!! } 2 -> { path = JYFileUtil.getSaveFilePath(transferFile.fileName!!, "JY Share") } } val uri: Uri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) FileProvider.getUriForFile(context, context.getString(R.string.authorities), File(path)) else Uri.fromFile(File(path)) val mimeType = context.contentResolver.getType(uri) val intent = Intent(Intent.ACTION_VIEW) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.setDataAndType(uri, mimeType) JYFileUtil.grantUriPermission(context, intent, uri) val builder = NotificationCompat.Builder(context, context.getString(R.string.app_name)) .setSmallIcon(R.drawable.ic_send) .setContentTitle(title) .setContentText(context.getString(R.string.hint_transfer_file_notification_message)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent( PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true) notify(context, id, builder.build()) } private fun notify(context: Context, id: Int, notification: Notification) { val index = FileTransferHelper.getInstance().currentFileIndex val transferFile = FileTransferHelper.getInstance().fileList[index] val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(transferFile.fileName, id, notification) } fun cancel(context: Context, id: Int) { val index = FileTransferHelper.getInstance().currentFileIndex val transferFile = FileTransferHelper.getInstance().fileList[index] val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(transferFile.fileName, id) } }
gpl-3.0
8eccf6820d13ef4ef59c9b0e65cca077
33.857143
102
0.768285
3.925743
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt
4
11534
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.replaceWith import com.intellij.openapi.diagnostic.ControlFlowException import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInliner.CodeToInline import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtUserType import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport import org.jetbrains.kotlin.resolve.scopes.* import org.jetbrains.kotlin.resolve.scopes.utils.chainImportingScopes import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices data class ReplaceWithData(val pattern: String, val imports: List<String>, val replaceInWholeProject: Boolean) @OptIn(FrontendInternals::class) object ReplaceWithAnnotationAnalyzer { fun analyzeCallableReplacement( replaceWith: ReplaceWithData, symbolDescriptor: CallableDescriptor, resolutionFacade: ResolutionFacade, reformat: Boolean ): CodeToInline? { val originalDescriptor = symbolDescriptor.unwrapIfFakeOverride().original return analyzeOriginal(replaceWith, originalDescriptor, resolutionFacade, reformat) } private fun analyzeOriginal( replaceWith: ReplaceWithData, symbolDescriptor: CallableDescriptor, resolutionFacade: ResolutionFacade, reformat: Boolean ): CodeToInline? { val psiFactory = KtPsiFactory(resolutionFacade.project) val expression = psiFactory.createExpressionIfPossible(replaceWith.pattern) ?: return null val module = resolutionFacade.moduleDescriptor val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null val expressionTypingServices = resolutionFacade.getFrontendService(module, ExpressionTypingServices::class.java) fun analyzeExpression(ignore: KtExpression) = expression.analyzeInContext( scope, expressionTypingServices = expressionTypingServices ) return CodeToInlineBuilder(symbolDescriptor, resolutionFacade, originalDeclaration = null).prepareCodeToInline( expression, emptyList(), ::analyzeExpression, reformat, ) } fun analyzeClassifierReplacement( replaceWith: ReplaceWithData, symbolDescriptor: ClassifierDescriptorWithTypeParameters, resolutionFacade: ResolutionFacade ): KtUserType? { val psiFactory = KtPsiFactory(resolutionFacade.project) val typeReference = try { psiFactory.createType(replaceWith.pattern) } catch (e: Exception) { if (e is ControlFlowException) throw e return null } if (typeReference.typeElement !is KtUserType) return null val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null val typeResolver = resolutionFacade.getFrontendService(TypeResolver::class.java) val bindingTrace = BindingTraceContext() typeResolver.resolvePossiblyBareType(TypeResolutionContext(scope, bindingTrace, false, true, false), typeReference) val typesToQualify = ArrayList<Pair<KtNameReferenceExpression, FqName>>() typeReference.forEachDescendantOfType<KtNameReferenceExpression> { expression -> val parentType = expression.parent as? KtUserType ?: return@forEachDescendantOfType if (parentType.qualifier != null) return@forEachDescendantOfType val targetClass = bindingTrace.bindingContext[BindingContext.REFERENCE_TARGET, expression] as? ClassDescriptor ?: return@forEachDescendantOfType val fqName = targetClass.fqNameUnsafe if (fqName.isSafe) { typesToQualify.add(expression to fqName.toSafe()) } } for ((nameExpression, fqName) in typesToQualify) { nameExpression.mainReference.bindToFqName(fqName, KtSimpleNameReference.ShorteningMode.NO_SHORTENING) } return typeReference.typeElement as KtUserType } private fun buildScope( resolutionFacade: ResolutionFacade, replaceWith: ReplaceWithData, symbolDescriptor: DeclarationDescriptor ): LexicalScope? { val module = resolutionFacade.moduleDescriptor val explicitImportsScope = buildExplicitImportsScope(importFqNames(replaceWith), resolutionFacade, module) val languageVersionSettings = resolutionFacade.languageVersionSettings val defaultImportsScopes = buildDefaultImportsScopes(resolutionFacade, module, languageVersionSettings) return getResolutionScope( symbolDescriptor, symbolDescriptor, listOf(explicitImportsScope), defaultImportsScopes, languageVersionSettings ) } private fun buildDefaultImportsScopes( resolutionFacade: ResolutionFacade, module: ModuleDescriptor, languageVersionSettings: LanguageVersionSettings ): List<ImportingScope> { val allDefaultImports = resolutionFacade.frontendService<TargetPlatform>().findAnalyzerServices(resolutionFacade.project) .getDefaultImports(languageVersionSettings, includeLowPriorityImports = true) val (allUnderImports, aliasImports) = allDefaultImports.partition { it.isAllUnder } // this solution doesn't support aliased default imports with a different alias // TODO: Create import directives from ImportPath, create ImportResolver, create LazyResolverScope, see FileScopeProviderImpl return listOf(buildExplicitImportsScope(aliasImports.map { it.fqName }, resolutionFacade, module)) + allUnderImports.map { module.getPackage(it.fqName).memberScope.memberScopeAsImportingScope() }.asReversed() } private fun buildExplicitImportsScope( importFqNames: List<FqName>, resolutionFacade: ResolutionFacade, module: ModuleDescriptor ): ExplicitImportsScope { val importedSymbols = importFqNames.flatMap { resolutionFacade.resolveImportReference(module, it) } return ExplicitImportsScope(importedSymbols) } private fun importFqNames(annotation: ReplaceWithData): List<FqName> { val result = ArrayList<FqName>() for (fqName in annotation.imports) { if (!FqNameUnsafe.isValid(fqName)) continue result += FqNameUnsafe(fqName).takeIf { it.isSafe }?.toSafe() ?: continue } return result } private fun getResolutionScope( descriptor: DeclarationDescriptor, ownerDescriptor: DeclarationDescriptor, explicitScopes: Collection<ExplicitImportsScope>, additionalScopes: Collection<ImportingScope>, languageVersionSettings: LanguageVersionSettings ): LexicalScope? { return when (descriptor) { is PackageFragmentDescriptor -> { val moduleDescriptor = descriptor.containingDeclaration getResolutionScope( moduleDescriptor.getPackage(descriptor.fqName), ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings ) } is PackageViewDescriptor -> { val memberAsImportingScope = descriptor.memberScope.memberScopeAsImportingScope() LexicalScope.Base( chainImportingScopes(explicitScopes + listOf(memberAsImportingScope) + additionalScopes)!!, ownerDescriptor ) } is ClassDescriptor -> { val outerScope = getResolutionScope( descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings ) ?: return null ClassResolutionScopesSupport( descriptor, LockBasedStorageManager.NO_LOCKS, languageVersionSettings ) { outerScope }.scopeForMemberDeclarationResolution() } is TypeAliasDescriptor -> { val outerScope = getResolutionScope( descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings ) ?: return null LexicalScopeImpl( outerScope, descriptor, false, null, emptyList(), LexicalScopeKind.TYPE_ALIAS_HEADER, LocalRedeclarationChecker.DO_NOTHING ) { for (typeParameter in descriptor.declaredTypeParameters) { addClassifierDescriptor(typeParameter) } } } is FunctionDescriptor -> { val outerScope = getResolutionScope( descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings ) ?: return null FunctionDescriptorUtil.getFunctionInnerScope(outerScope, descriptor, LocalRedeclarationChecker.DO_NOTHING) } is PropertyDescriptor -> { val outerScope = getResolutionScope( descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings ) ?: return null val propertyHeader = ScopeUtils.makeScopeForPropertyHeader(outerScope, descriptor) LexicalScopeImpl( propertyHeader, descriptor, false, descriptor.extensionReceiverParameter, descriptor.contextReceiverParameters, LexicalScopeKind.PROPERTY_ACCESSOR_BODY ) } else -> return null // something local, should not work with ReplaceWith } } }
apache-2.0
13390dde47f50a8ca97d708974f9b856
45.136
158
0.695422
6.39357
false
false
false
false
GunoH/intellij-community
plugins/kotlin/refactorings/rename.k2/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinRenameUsageSearcher.kt
2
2027
// 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.refactoring.rename import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.rename.api.RenameUsage import com.intellij.refactoring.rename.api.RenameUsageSearchParameters import com.intellij.refactoring.rename.api.RenameUsageSearcher import com.intellij.util.Query import com.intellij.util.mappingNotNull import org.jetbrains.kotlin.idea.base.util.codeUsageScope import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtParameter internal class KotlinRenameUsageSearcher : RenameUsageSearcher { override fun collectImmediateResults(parameters: RenameUsageSearchParameters): Collection<RenameUsage> { val renameTarget = parameters.target as? KotlinNamedDeclarationRenameUsage return listOfNotNull(renameTarget) } override fun collectSearchRequests(parameters: RenameUsageSearchParameters): List<Query<out RenameUsage>> { val renameTarget = parameters.target as? KotlinNamedDeclarationRenameUsage ?: return emptyList() val codeUsageScope = getCodeUsageScopeForDeclaration(renameTarget.element) val searchScope = codeUsageScope.intersectWith(parameters.searchScope) val kotlinQuery = ReferencesSearch.search(renameTarget.element, searchScope) .mappingNotNull { it.element as? KtNameReferenceExpression } .mapping { KotlinReferenceModifiableRenameUsage(it) } return listOf(kotlinQuery) } private fun getCodeUsageScopeForDeclaration(declaration: KtNamedDeclaration): SearchScope { val adjustedDeclaration = when (declaration) { is KtParameter -> declaration.ownerFunction ?: declaration else -> declaration } return adjustedDeclaration.codeUsageScope() } }
apache-2.0
3e11127e5aaa3604c5cb079d12e38d49
46.139535
120
0.785397
5.224227
false
false
false
false
NiciDieNase/chaosflix
common/src/main/java/de/nicidienase/chaosflix/common/viewmodel/PlayerViewModel.kt
1
1353
package de.nicidienase.chaosflix.common.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.nicidienase.chaosflix.common.ChaosflixDatabase import de.nicidienase.chaosflix.common.userdata.entities.progress.PlaybackProgress import java.util.Date import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class PlayerViewModel(val database: ChaosflixDatabase) : ViewModel() { fun getPlaybackProgressLiveData(guid: String): LiveData<PlaybackProgress?> = database.playbackProgressDao().getProgressForEvent(guid) suspend fun getPlaybackProgress(guid: String) = database.playbackProgressDao().getProgressForEventSync(guid) fun setPlaybackProgress(eventGuid: String, progress: Long) { if (progress < 5_000) { return } viewModelScope.launch(Dispatchers.IO) { database.playbackProgressDao().saveProgress( PlaybackProgress( progress = progress, eventGuid = eventGuid, watchDate = Date().time)) } } fun deletePlaybackProgress(eventId: String) { viewModelScope.launch(Dispatchers.IO) { database.playbackProgressDao().deleteItem(eventId) } } }
mit
f1026f22263fa032b510a0f500a8538e
35.567568
112
0.692535
5.125
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-core/common/src/io/ktor/client/statement/DefaultHttpResponse.kt
1
1014
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.statement import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.util.* import io.ktor.util.date.* import io.ktor.utils.io.* import kotlin.coroutines.* @InternalAPI public class DefaultHttpResponse( override val call: HttpClientCall, responseData: HttpResponseData ) : HttpResponse() { override val coroutineContext: CoroutineContext = responseData.callContext override val status: HttpStatusCode = responseData.statusCode override val version: HttpProtocolVersion = responseData.version override val requestTime: GMTDate = responseData.requestTime override val responseTime: GMTDate = responseData.responseTime override val content: ByteReadChannel = responseData.body as? ByteReadChannel ?: ByteReadChannel.Empty override val headers: Headers = responseData.headers }
apache-2.0
e635f1df1b1449df993304d6fe2789bc
28.823529
118
0.771203
4.651376
false
false
false
false
bozaro/git-lfs-java
gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/auth/CachedAuthProvider.kt
1
1878
package ru.bozaro.gitlfs.client.auth import ru.bozaro.gitlfs.common.data.Link import ru.bozaro.gitlfs.common.data.Operation import java.io.IOException import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap /** * Get authentication ru.bozaro.gitlfs.common.data from external application. * This AuthProvider is EXPERIMENTAL and it can only be used at your own risk. * * @author Artem V. Navrotskiy */ abstract class CachedAuthProvider : AuthProvider { private val authCache: ConcurrentMap<Operation?, Link?> private val locks: EnumMap<Operation, Any> = createLocks() @Throws(IOException::class) override fun getAuth(operation: Operation): Link { var auth = authCache[operation] if (auth == null) { synchronized(locks[operation]!!) { auth = authCache[operation] if (auth == null) { try { auth = getAuthUncached(operation) authCache[operation] = auth } catch (e: InterruptedException) { throw IOException(e) } } } } return auth!! } @Throws(IOException::class, InterruptedException::class) protected abstract fun getAuthUncached(operation: Operation): Link override fun invalidateAuth(operation: Operation, auth: Link) { authCache.remove(operation, auth) } companion object { private fun createLocks(): EnumMap<Operation, Any> { val result = EnumMap<Operation, Any>(Operation::class.java) for (value in Operation.values()) { result[value] = Any() } return result } } init { authCache = ConcurrentHashMap(Operation.values().size) } }
lgpl-3.0
10f5fa1ecd9d6bbe62ad55ef30d50d48
30.3
78
0.609159
4.778626
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/attribute/AttributeModifier.kt
1
3211
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.attribute import com.mcmoonlake.api.notNull import com.mcmoonlake.api.ofValuableNotNull import com.mcmoonlake.api.parseDouble import com.mcmoonlake.api.parseInt import com.mcmoonlake.api.util.ComparisonChain import org.bukkit.configuration.serialization.ConfigurationSerializable import java.util.* /** * ## AttributeModifier (属性修改器) * * * Add or remove this modifier from the attribute. * * 从属性中添加或移除此修改器. * * @see [Attribute] * @see [Attribute.addModifier] * @see [Attribute.removeModifier] * @see [ConfigurationSerializable] * @author lgou2w * @since 2.0 */ data class AttributeModifier( /** * * The name of this modifier. * * 此修改器的名字. */ val name: String, /** * * The operation mode of this modifier. * * 此修改器的运算模式. * * @see [Operation] */ val operation: Operation, /** * * The operation amount of this modifier. * * 此修改器的运算数量. */ val amount: Double, /** * * The unique id of this modifier. * * 此修改器的唯一 Id. */ val uuid: UUID = UUID.randomUUID() ) : ConfigurationSerializable, Comparable<AttributeModifier> { override fun compareTo(other: AttributeModifier): Int { return ComparisonChain.start() .compare(name, other.name) .compare(operation, other.operation) .compare(amount, other.amount) .compare(uuid, other.uuid) .result } override fun serialize(): MutableMap<String, Any> { val result = LinkedHashMap<String, Any>() result["name"] = name result["operation"] = operation.value() result["amount"] = amount result["uuid"] = uuid.toString() return result } /** static */ companion object { @JvmStatic @JvmName("deserialize") fun deserialize(args: Map<String, Any>): AttributeModifier { val name: String = args["name"]?.toString().notNull() val operation: Operation = ofValuableNotNull(args["operation"]?.parseInt()) val amount = args["amount"]?.parseDouble() ?: .0 val uuid = UUID.fromString(args["uuid"]?.toString()) return AttributeModifier(name, operation, amount, uuid) } } }
gpl-3.0
3784ed988ffce3475263491d98381dcf
30.11
87
0.626808
4.332869
false
false
false
false
fyookball/electrum
android/app/src/main/java/org/electroncash/electroncash3/Dialog.kt
1
12486
package org.electroncash.electroncash3 import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.view.inputmethod.EditorInfo import android.widget.PopupMenu import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.observe import com.chaquo.python.PyException import kotlinx.android.synthetic.main.password.* import kotlin.properties.Delegates.notNull abstract class AlertDialogFragment : DialogFragment() { class Model : ViewModel() { var started = false } private val model: Model by viewModels() var started = false var suppressView = false var focusOnStop = View.NO_ID override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog { val builder = AlertDialog.Builder(context!!) onBuildDialog(builder) return builder.create() } // Although AlertDialog creates its own view, it's helpful for that view also to be // returned by Fragment.getView, because: // * It allows Kotlin synthetic properties to be used directly on the fragment, rather // than prefixing them all with `dialog.`. // * It ensures cancelPendingInputEvents is called when the fragment is stopped (see // https://github.com/Electron-Cash/Electron-Cash/issues/1091#issuecomment-526951516 // and Fragment.initLifecycle. override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // This isn't really consistent with the fragment lifecycle, but it's the only way to // make AlertDialog create its views. dialog.show() // The top-level view structure isn't really documented, so make sure we are returning // the layout defined in // android/platform/frameworks/support/appcompat/res/layout/abc_alert_dialog_material.xml. val content = dialog.findViewById<ViewGroup>(android.R.id.content)!!.getChildAt(0) val contentClassName = content.javaClass.name if (contentClassName != "androidx.appcompat.widget.AlertDialogLayout") { throw IllegalStateException("Unexpected content view $contentClassName") } return content } // Since we've implemented onCreateView, DialogFragment.onActivityCreated will attempt to // add the view to the dialog, but AlertDialog has already done that. Stop this by // overriding getView temporarily. // // Previously we worked around this by removing the view from the dialog in onCreateView // and letting DialogFragment.onActivityCreated add it back, but that stops <requestFocus/> // tags from working. override fun onActivityCreated(savedInstanceState: Bundle?) { suppressView = true super.onActivityCreated(savedInstanceState) suppressView = false } override fun getView() = if (suppressView) null else super.getView() open fun onBuildDialog(builder: AlertDialog.Builder) {} // We used to trigger onShowDialog from Dialog.setOnShowListener, but we had crash reports // indicating that the fragment context was sometimes null in that listener (#1046, #1108). // So use one of the fragment lifecycle methods instead. override fun onStart() { super.onStart() focusOnStop = View.NO_ID if (!started) { started = true onShowDialog() } if (!model.started) { model.started = true onFirstShowDialog() } } override fun onStop() { focusOnStop = dialog.findViewById<View>(android.R.id.content)?.findFocus()?.id ?: View.NO_ID super.onStop() } // When changing orientation on targetSdkVersion >= 28, onStop is called before // onSaveInstanceState and the focused view is lost. // (https://issuetracker.google.com/issues/152131900), override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (focusOnStop != View.NO_ID) { val hierarchy = outState.getBundle("android:savedDialogState") ?.getBundle("android:dialogHierarchy") if (hierarchy != null && hierarchy.getInt("android:focusedViewId", View.NO_ID) == View.NO_ID) { hierarchy.putInt("android:focusedViewId", focusOnStop) } } } /** Can be used to do things like configure custom views, or attach listeners to buttons so * they don't always close the dialog. */ open fun onShowDialog() {} /** Unlike onShowDialog, this will only be called once, even if the dialog is recreated * after a rotation. This can be used to do things like setting the initial state of * editable views. */ open fun onFirstShowDialog() {} override fun getDialog(): AlertDialog { return super.getDialog() as AlertDialog } } class MessageDialog() : AlertDialogFragment() { constructor(title: String, message: String) : this() { arguments = Bundle().apply { putString("title", title) putString("message", message) } } override fun onBuildDialog(builder: AlertDialog.Builder) { builder.setTitle(arguments!!.getString("title")) .setMessage(arguments!!.getString("message")) .setPositiveButton(android.R.string.ok, null) } } abstract class MenuDialog : AlertDialogFragment() { override fun onBuildDialog(builder: AlertDialog.Builder) { val menu = PopupMenu(app, null).menu onBuildDialog(builder, menu) val items = ArrayList<CharSequence>() var checkedItem: Int? = null for (i in 0 until menu.size()) { val item = menu.getItem(i) items.add(item.title) if (item.isChecked) { if (checkedItem != null) { throw IllegalArgumentException("Menu has multiple checked items") } checkedItem = i } } val listener = DialogInterface.OnClickListener { _, index -> onMenuItemSelected(menu.getItem(index)) } if (checkedItem == null) { builder.setItems(items.toTypedArray(), listener) } else { builder.setSingleChoiceItems(items.toTypedArray(), checkedItem, listener) } } abstract fun onBuildDialog(builder: AlertDialog.Builder, menu: Menu) abstract fun onMenuItemSelected(item: MenuItem) } abstract class TaskDialog<Result> : DialogFragment() { class Model : ViewModel() { var state = Thread.State.NEW val result = MutableLiveData<Any?>() val exception = MutableLiveData<ToastException>() } private val model: Model by viewModels() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { model.result.observe(this, { onFinished { @Suppress("UNCHECKED_CAST") onPostExecute(it as Result) } }) model.exception.observe(this, { onFinished { it!!.show() } }) isCancelable = false @Suppress("DEPRECATION") return android.app.ProgressDialog(this.context).apply { setMessage(getString(R.string.please_wait)) } } override fun onStart() { super.onStart() if (model.state == Thread.State.NEW) { try { model.state = Thread.State.RUNNABLE onPreExecute() Thread { try { model.result.postValue(doInBackground()) } catch (e: ToastException) { model.exception.postValue(e) } }.start() } catch (e: ToastException) { model.exception.postValue(e) } } } private fun onFinished(body: () -> Unit) { if (model.state == Thread.State.RUNNABLE) { model.state = Thread.State.TERMINATED body() dismiss() } } /** This method is called on the UI thread. doInBackground will be called on the same * fragment instance after it returns. If this method throws a ToastException, it will be * displayed, and doInBackground will not be called. */ open fun onPreExecute() {} /** This method is called on a background thread. It should not access user interface * objects in any way, as they may be destroyed by rotation and other events. If this * method throws a ToastException, it will be displayed, and onPostExecute will not be * called. */ abstract fun doInBackground(): Result /** This method is called on the UI thread after doInBackground returns. Unlike * onPreExecute, it may be called on a different fragment instance. */ open fun onPostExecute(result: Result) {} } abstract class TaskLauncherDialog<Result> : AlertDialogFragment() { override fun onShowDialog() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { // It's possible for multiple button clicks to be queued before the listener runs, // but showDialog will ensure that the progress dialog (and therefore the task) is // only created once. showDialog(activity!!, LaunchedTaskDialog<Result>().apply { setTargetFragment(this@TaskLauncherDialog, 0) }) } } // See notes in TaskDialog. open fun onPreExecute() {} abstract fun doInBackground(): Result open fun onPostExecute(result: Result) {} } class LaunchedTaskDialog<Result> : TaskDialog<Result>() { @Suppress("UNCHECKED_CAST") val launcher by lazy { targetFragment as TaskLauncherDialog<Result> } override fun onPreExecute() = launcher.onPreExecute() override fun doInBackground() = launcher.doInBackground() override fun onPostExecute(result: Result) { launcher.onPostExecute(result) launcher.dismiss() } } abstract class PasswordDialog<Result> : TaskLauncherDialog<Result>() { var password: String by notNull() override fun onBuildDialog(builder: AlertDialog.Builder) { builder.setTitle(R.string.Enter_password) .setView(R.layout.password) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) } override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) return dialog } override fun onShowDialog() { super.onShowDialog() etPassword.setOnEditorActionListener { _, actionId: Int, event: KeyEvent? -> // See comments in ConsoleActivity.createInput. if (actionId == EditorInfo.IME_ACTION_DONE || event?.action == KeyEvent.ACTION_UP) { dialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick() } true } } override fun onPreExecute() { password = etPassword.text.toString() } override fun doInBackground(): Result { try { return onPassword(password) } catch (e: PyException) { throw if (e.message!!.startsWith("InvalidPassword")) ToastException(R.string.incorrect_password, Toast.LENGTH_SHORT) else e } } /** Attempt to perform the operation with the given password. If the operation fails, this * method should throw either a ToastException, or an InvalidPassword PyException (most * Python functions that take passwords will do this automatically). * * This method is called on a background thread. It should not access user interface * objects in any way, as they may be destroyed by rotation and other events. */ abstract fun onPassword(password: String): Result }
mit
f828e75da72da7b205dd66b9d780f63c
36.160714
98
0.650248
4.962639
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/trackedentity/search/QueryPageUserModeMatcher.kt
1
2174
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.search import org.hisp.dhis.android.core.common.AssignedUserMode import org.mockito.ArgumentMatcher internal class QueryPageUserModeMatcher( private val page: Int, private val pageSize: Int, private val assignedUserMode: AssignedUserMode ) : ArgumentMatcher<TrackedEntityInstanceQueryOnline> { override fun matches(query: TrackedEntityInstanceQueryOnline?): Boolean { return query?.let { it.page() == page && it.pageSize() == pageSize && it.assignedUserMode() == assignedUserMode } ?: false } }
bsd-3-clause
b27bd60a014f95798ed9fed414a41c67
48.409091
103
0.75851
4.596195
false
false
false
false
mdanielwork/intellij-community
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonUtilAutoTest.kt
1
27086
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.HeavyDiffTestCase import com.intellij.diff.fragments.DiffFragment import com.intellij.diff.fragments.LineFragment import com.intellij.diff.fragments.MergeLineFragment import com.intellij.diff.fragments.MergeWordFragment import com.intellij.diff.tools.util.base.HighlightPolicy import com.intellij.diff.tools.util.base.IgnorePolicy import com.intellij.diff.tools.util.text.LineOffsetsUtil import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Range import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.ex.createRanges class ComparisonUtilAutoTest : HeavyDiffTestCase() { val RUNS = 30 val MAX_LENGTH = 300 fun testChar() { doTestChar(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testWord() { doTestWord(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLine() { doTestLine(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineSquashed() { doTestLineSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineTrimSquashed() { doTestLineTrimSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testExplicitBlocks() { doTestExplicitBlocks(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testMerge() { doTestMerge(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testThreeWayDiff() { doTestThreeWayDiff(System.currentTimeMillis(), RUNS, MAX_LENGTH) } private fun doTestLine(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) val fragmentsPolicies = listOf(InnerFragmentsPolicy.WORDS, InnerFragmentsPolicy.CHARS) doTest(seed, runs, maxLength, ignorePolicies, fragmentsPolicies) { text1, text2, ignorePolicy, fragmentsPolicy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val lineOffsets1 = LineOffsetsUtil.create(sequence1) val lineOffsets2 = LineOffsetsUtil.create(sequence2) val fragments = MANAGER.compareLinesInner(sequence1, sequence2, lineOffsets1, lineOffsets2, ignorePolicy, fragmentsPolicy, INDICATOR) debugData.put("Fragments", fragments) checkResultLine(text1, text2, fragments, ignorePolicy, true) } } private fun doTestLineSquashed(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) val fragmentsPolicies = listOf(InnerFragmentsPolicy.WORDS, InnerFragmentsPolicy.CHARS) doTest(seed, runs, maxLength, ignorePolicies, fragmentsPolicies) { text1, text2, ignorePolicy, fragmentsPolicy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val lineOffsets1 = LineOffsetsUtil.create(sequence1) val lineOffsets2 = LineOffsetsUtil.create(sequence2) val fragments = MANAGER.compareLinesInner(sequence1, sequence2, lineOffsets1, lineOffsets2, ignorePolicy, fragmentsPolicy, INDICATOR) debugData.put("Fragments", fragments) val squashedFragments = MANAGER.squash(fragments) debugData.put("Squashed Fragments", squashedFragments) checkResultLine(text1, text2, squashedFragments, ignorePolicy, false) } } private fun doTestLineTrimSquashed(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) val fragmentsPolicies = listOf(InnerFragmentsPolicy.WORDS, InnerFragmentsPolicy.CHARS) doTest(seed, runs, maxLength, ignorePolicies, fragmentsPolicies) { text1, text2, ignorePolicy, fragmentsPolicy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val lineOffsets1 = LineOffsetsUtil.create(sequence1) val lineOffsets2 = LineOffsetsUtil.create(sequence2) val fragments = MANAGER.compareLinesInner(sequence1, sequence2, lineOffsets1, lineOffsets2, ignorePolicy, fragmentsPolicy, INDICATOR) debugData.put("Fragments", fragments) val processed = MANAGER.processBlocks(fragments, sequence1, sequence2, ignorePolicy, true, true) debugData.put("Processed Fragments", processed) checkResultLine(text1, text2, processed, ignorePolicy, false) } } private fun doTestChar(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, ignorePolicies) { text1, text2, ignorePolicy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareChars(sequence1, sequence2, ignorePolicy, INDICATOR) debugData.put("Fragments", fragments) checkResultChar(sequence1, sequence2, fragments, ignorePolicy) } } private fun doTestWord(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, ignorePolicies) { text1, text2, ignorePolicy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareWords(sequence1, sequence2, ignorePolicy, INDICATOR) debugData.put("Fragments", fragments) checkResultWord(sequence1, sequence2, fragments, ignorePolicy) } } private fun doTestExplicitBlocks(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(IgnorePolicy.DEFAULT, IgnorePolicy.TRIM_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES_CHUNKS) val highlightPolicies = listOf(HighlightPolicy.BY_LINE, HighlightPolicy.BY_WORD, HighlightPolicy.BY_WORD_SPLIT) doTest(seed, runs, maxLength) { text1, text2, debugData -> for (highlightPolicy in highlightPolicies) { for (ignorePolicy in ignorePolicies) { debugData.put("HighlightPolicy", highlightPolicy) debugData.put("IgnorePolicy", ignorePolicy) val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val ranges = createRanges(sequence2, sequence1).map { Range(it.vcsLine1, it.vcsLine2, it.line1, it.line2) } debugData.put("Ranges", ranges) val fragments = compareExplicitBlocks(sequence1, sequence2, ranges, highlightPolicy, ignorePolicy) debugData.put("Fragments", fragments) checkResultLine(text1, text2, fragments, ignorePolicy.comparisonPolicy, !highlightPolicy.isShouldSquash) } } } } private fun doTestThreeWayDiff(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val sequence3 = text3.charsSequence val fragments = MANAGER.compareLines(sequence1, sequence2, sequence3, policy, INDICATOR) val fineFragments = fragments.map { f -> val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR) Pair(f, wordFragments) } debugData.put("Fragments", fineFragments) checkResultMerge(text1, text2, text3, fineFragments, policy, false) } } private fun doTestMerge(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val sequence3 = text3.charsSequence val fragments = MANAGER.mergeLines(sequence1, sequence2, sequence3, policy, INDICATOR) val fineFragments = fragments.map { f -> val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR) Pair(f, wordFragments) } debugData.put("Fragments", fineFragments) checkResultMerge(text1, text2, text3, fineFragments, policy, policy != ComparisonPolicy.DEFAULT) } } private fun doTest(seed: Long, runs: Int, maxLength: Int, ignorePolicies: List<ComparisonPolicy>, fragmentsPolicies: List<InnerFragmentsPolicy>, test: (Document, Document, ComparisonPolicy, InnerFragmentsPolicy, DiffTestCase.DebugData) -> Unit) { doTest(seed, runs, maxLength, ignorePolicies) { text1, text2, ignorePolicy, debugData -> for (fragmentsPolicy in fragmentsPolicies) { debugData.put("Inner Policy", fragmentsPolicy) test(text1, text2, ignorePolicy, fragmentsPolicy, debugData) } } } private fun doTest(seed: Long, runs: Int, maxLength: Int, ignorePolicies: List<ComparisonPolicy>, test: (Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doTest(seed, runs, maxLength) { text1, text2, debugData -> for (ignorePolicy in ignorePolicies) { debugData.put("Ignore Policy", ignorePolicy) test(text1, text2, ignorePolicy, debugData) } } } private fun doTest(seed: Long, runs: Int, maxLength: Int, test: (Document, Document, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) test(text1, text2, debugData) } } private fun doTest3(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>, test: (Document, Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) val text3 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) debugData.put("Text3", textToReadableFormat(text3.charsSequence)) for (comparisonPolicy in policies) { debugData.put("Policy", comparisonPolicy) test(text1, text2, text2, comparisonPolicy, debugData) } } } private fun checkResultLine(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { checkLineConsistency(text1, text2, fragments, allowNonSquashed) for (fragment in fragments) { if (fragment.innerFragments != null) { val sequence1 = text1.subSequence(fragment.startOffset1, fragment.endOffset1) val sequence2 = text2.subSequence(fragment.startOffset2, fragment.endOffset2) checkResultWord(sequence1, sequence2, fragment.innerFragments!!, policy) } } checkValidRanges(text1.charsSequence, text2.charsSequence, fragments, policy, true) checkCantTrimLines(text1, text2, fragments, policy, allowNonSquashed) } private fun checkResultWord(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultChar(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultMerge(text1: Document, text2: Document, text3: Document, fragments: List<Pair<MergeLineFragment, List<MergeWordFragment>>>, policy: ComparisonPolicy, allowIgnoredBlocks: Boolean) { val lineFragments = fragments.map { it.first } checkLineConsistency3(text1, text2, text3, lineFragments, allowIgnoredBlocks) checkValidRanges3(text1, text2, text3, lineFragments, policy) if (!allowIgnoredBlocks) checkCantTrimLines3(text1, text2, text3, lineFragments, policy) for (pair in fragments) { val f = pair.first val innerFragments = pair.second val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) checkDiffConsistency3(innerFragments) checkValidRanges3(chunk1, chunk2, chunk3, innerFragments, policy) } } private fun checkLineConsistency(text1: Document, text2: Document, fragments: List<LineFragment>, allowNonSquashed: Boolean) { var last1 = -1 var last2 = -1 for (fragment in fragments) { val startOffset1 = fragment.startOffset1 val startOffset2 = fragment.startOffset2 val endOffset1 = fragment.endOffset1 val endOffset2 = fragment.endOffset2 val start1 = fragment.startLine1 val start2 = fragment.startLine2 val end1 = fragment.endLine1 val end2 = fragment.endLine2 assertTrue(startOffset1 >= 0) assertTrue(startOffset2 >= 0) assertTrue(endOffset1 <= text1.textLength) assertTrue(endOffset2 <= text2.textLength) assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(startOffset1 <= endOffset1) assertTrue(startOffset2 <= endOffset2) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(allowNonSquashed || start1 != last1 || start2 != last2) checkLineOffsets(fragment, text1, text2) last1 = end1 last2 = end2 } } private fun checkLineConsistency3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, allowNonSquashed: Boolean) { var last1 = -1 var last2 = -1 var last3 = -1 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val end1 = fragment.endLine1 val end2 = fragment.endLine2 val end3 = fragment.endLine3 assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(start3 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(end3 <= getLineCount(text3)) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(allowNonSquashed || start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkDiffConsistency(fragments: List<DiffFragment>) { var last1 = -1 var last2 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(start1 != last1 || start2 != last2) last1 = end1 last2 = end2 } } private fun checkDiffConsistency3(fragments: List<MergeWordFragment>) { var last1 = -1 var last2 = -1 var last3 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val start3 = diffFragment.startOffset3 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 val end3 = diffFragment.endOffset3 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkLineOffsets(fragment: LineFragment, before: Document, after: Document) { checkLineOffsets(before, fragment.startLine1, fragment.endLine1, fragment.startOffset1, fragment.endOffset1) checkLineOffsets(after, fragment.startLine2, fragment.endLine2, fragment.startOffset2, fragment.endOffset2) } private fun checkLineOffsets(document: Document, startLine: Int, endLine: Int, startOffset: Int, endOffset: Int) { if (startLine != endLine) { assertEquals(document.getLineStartOffset(startLine), startOffset) var offset = document.getLineEndOffset(endLine - 1) if (offset < document.textLength) offset++ assertEquals(offset, endOffset) } else { val offset = if (startLine == getLineCount(document)) document.textLength else document.getLineStartOffset(startLine) assertEquals(offset, startOffset) assertEquals(offset, endOffset) } } private fun checkValidRanges(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy, skipNewline: Boolean) { // TODO: better check for Trim spaces case ? val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val chunk1 = text1.subSequence(last1, start1) val chunk2 = text2.subSequence(last2, start2) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) if (!skipNewline) { assertNotEqualsCharSequences(chunkContent1, chunkContent2, ignoreSpacesChanged, skipNewline) } last1 = fragment.endOffset1 last2 = fragment.endOffset2 } val chunk1 = text1.subSequence(last1, text1.length) val chunk2 = text2.subSequence(last2, text2.length) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) } private fun checkValidRanges3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { val ignoreSpaces = policy != ComparisonPolicy.DEFAULT var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val content1 = DiffUtil.getLinesContent(text1, last1, start1) val content2 = DiffUtil.getLinesContent(text2, last2, start2) val content3 = DiffUtil.getLinesContent(text3, last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) last1 = fragment.endLine1 last2 = fragment.endLine2 last3 = fragment.endLine3 } val content1 = DiffUtil.getLinesContent(text1, last1, getLineCount(text1)) val content2 = DiffUtil.getLinesContent(text2, last2, getLineCount(text2)) val content3 = DiffUtil.getLinesContent(text3, last3, getLineCount(text3)) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) } private fun checkValidRanges3(text1: CharSequence, text2: CharSequence, text3: CharSequence, fragments: List<MergeWordFragment>, policy: ComparisonPolicy) { val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val start3 = fragment.startOffset3 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val end3 = fragment.endOffset3 val content1 = text1.subSequence(last1, start1) val content2 = text2.subSequence(last2, start2) val content3 = text3.subSequence(last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) val chunkContent3 = text3.subSequence(start3, end3) assertFalse(isEqualsCharSequences(chunkContent2, chunkContent1, ignoreSpacesChanged) && isEqualsCharSequences(chunkContent2, chunkContent3, ignoreSpacesChanged)) last1 = fragment.endOffset1 last2 = fragment.endOffset2 last3 = fragment.endOffset3 } val content1 = text1.subSequence(last1, text1.length) val content2 = text2.subSequence(last2, text2.length) val content3 = text3.subSequence(last3, text3.length) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) } private fun checkCantTrimLines(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) if (sequence1 == null || sequence2 == null) continue checkNonEqualsIfLongEnough(sequence1.first, sequence2.first, policy, allowNonSquashed) checkNonEqualsIfLongEnough(sequence1.second, sequence2.second, policy, allowNonSquashed) } } private fun checkCantTrimLines3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) val sequence3 = getFirstLastLines(text3, fragment.startLine3, fragment.endLine3) if (sequence1 == null || sequence2 == null || sequence3 == null) continue assertFalse(MANAGER.isEquals(sequence2.first, sequence1.first, policy) && MANAGER.isEquals(sequence2.first, sequence3.first, policy)) assertFalse(MANAGER.isEquals(sequence2.second, sequence1.second, policy) && MANAGER.isEquals(sequence2.second, sequence3.second, policy)) } } private fun checkNonEqualsIfLongEnough(line1: CharSequence, line2: CharSequence, policy: ComparisonPolicy, allowNonSquashed: Boolean) { // in non-squashed blocks non-trimmed elements are possible if (allowNonSquashed) { if (policy != ComparisonPolicy.IGNORE_WHITESPACES) return if (countNonWhitespaceCharacters(line1) <= ComparisonUtil.getUnimportantLineCharCount()) return if (countNonWhitespaceCharacters(line2) <= ComparisonUtil.getUnimportantLineCharCount()) return } assertFalse(MANAGER.isEquals(line1, line2, policy)) } private fun countNonWhitespaceCharacters(line: CharSequence): Int { return (0 until line.length).count { !StringUtil.isWhiteSpace(line[it]) } } private fun getFirstLastLines(text: Document, start: Int, end: Int): Couple<CharSequence>? { if (start == end) return null val firstLineRange = DiffUtil.getLinesRange(text, start, start + 1) val lastLineRange = DiffUtil.getLinesRange(text, end - 1, end) val firstLine = firstLineRange.subSequence(text.charsSequence) val lastLine = lastLineRange.subSequence(text.charsSequence) return Couple.of(firstLine, lastLine) } private fun Document.subSequence(start: Int, end: Int): CharSequence { return this.charsSequence.subSequence(start, end) } private val MergeLineFragment.startLine1: Int get() = this.getStartLine(ThreeSide.LEFT) private val MergeLineFragment.startLine2: Int get() = this.getStartLine(ThreeSide.BASE) private val MergeLineFragment.startLine3: Int get() = this.getStartLine(ThreeSide.RIGHT) private val MergeLineFragment.endLine1: Int get() = this.getEndLine(ThreeSide.LEFT) private val MergeLineFragment.endLine2: Int get() = this.getEndLine(ThreeSide.BASE) private val MergeLineFragment.endLine3: Int get() = this.getEndLine(ThreeSide.RIGHT) private val MergeWordFragment.startOffset1: Int get() = this.getStartOffset(ThreeSide.LEFT) private val MergeWordFragment.startOffset2: Int get() = this.getStartOffset(ThreeSide.BASE) private val MergeWordFragment.startOffset3: Int get() = this.getStartOffset(ThreeSide.RIGHT) private val MergeWordFragment.endOffset1: Int get() = this.getEndOffset(ThreeSide.LEFT) private val MergeWordFragment.endOffset2: Int get() = this.getEndOffset(ThreeSide.BASE) private val MergeWordFragment.endOffset3: Int get() = this.getEndOffset(ThreeSide.RIGHT) }
apache-2.0
bd772adcee3e9683e0a54b15258094d8
40.352672
158
0.72207
4.39922
false
true
false
false
Talentica/AndroidWithKotlin
audioplayer/src/main/java/com/talentica/androidkotlin/audioplayer/utils/SeekBarHandler.kt
1
1592
package com.talentica.androidkotlin.audioplayer.utils import android.media.MediaPlayer import android.os.AsyncTask import android.widget.SeekBar import android.widget.TextView /** * Created by suyashg on 29/05/17. */ class SeekBarHandler(val seekbar: SeekBar?, var mediaPlayer: MediaPlayer?, var isViewOn: Boolean,val timer:TextView): AsyncTask<Void, Void, Boolean>() { override fun onPreExecute() { super.onPreExecute() seekbar?.max = mediaPlayer?.duration!! } override fun onProgressUpdate(vararg values: Void?) { super.onProgressUpdate(*values) val time = mediaPlayer?.getCurrentPosition()!! seekbar?.setProgress(time); var seconds = (time / 1000) val minutes = time / (1000 * 60) % 60 seconds = seconds - minutes * 60 timer.setText(minutes.toString()+":"+seconds.toString()) } override fun onCancelled() { super.onCancelled() setViewOnOff(false) } fun setViewOnOff(isOn:Boolean) { isViewOn = isOn } fun refreshMediaPlayer(mediaPlayer: MediaPlayer?) { this.mediaPlayer = mediaPlayer } override fun doInBackground(vararg params: Void?): Boolean { while (mediaPlayer?.isPlaying() == true && isViewOn == true) { try { Thread.sleep(200) } catch (e: InterruptedException) { e.printStackTrace() } publishProgress() } return true } override fun onPostExecute(result: Boolean?) { super.onPostExecute(result) } }
apache-2.0
e525b542b66aedf307b42c147d296ebd
26
152
0.625
4.696165
false
false
false
false
mdanielwork/intellij-community
plugins/git4idea/src/git4idea/checkin/GitUnresolvedMergeCheckProvider.kt
5
4174
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.checkin import com.intellij.dvcs.repo.Repository import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.ui.SimpleChangesBrowser import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.checkin.UnresolvedMergeCheckProvider import com.intellij.util.containers.MultiMap import com.intellij.util.ui.JBUI import git4idea.GitVcs import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import javax.swing.JComponent import javax.swing.JLabel class GitUnresolvedMergeCheckProvider : UnresolvedMergeCheckProvider() { override fun checkUnresolvedConflicts(panel: CheckinProjectPanel, commitContext: CommitContext, executor: CommitExecutor?): CheckinHandler.ReturnResult? { if (executor != null) return null if (!panel.vcsIsAffected(GitVcs.NAME)) return null val project = panel.project val repositoryManager = GitRepositoryManager.getInstance(project) val changeListManager = ChangeListManager.getInstance(project) val selectedChanges = panel.selectedChanges.toSet() val repositories = selectedChanges.mapNotNull { repositoryManager.getRepositoryForFile(ChangesUtil.getFilePath(it)) }.toSet() val groupedChanges = MultiMap<GitRepository, Change>() for (change in changeListManager.allChanges) { val repo = repositoryManager.getRepositoryForFile(ChangesUtil.getFilePath(change)) if (repositories.contains(repo)) groupedChanges.putValue(repo, change) } val hasConflicts = groupedChanges.values().any { it.fileStatus === FileStatus.MERGED_WITH_CONFLICTS } if (hasConflicts) { Messages.showMessageDialog(panel.component, "Can't commit changes due to unresolved conflicts.", "Unresolved Conflicts", Messages.getWarningIcon()) return CheckinHandler.ReturnResult.CANCEL } // Duplicates dialog from GitCheckinEnvironment.mergeCommit, so is disabled for `git commit --only` mode if (Registry.`is`("git.force.commit.using.staging.area")) { val changesExcludedFromMerge = repositories.filter { it.state == Repository.State.MERGING } .flatMap { groupedChanges[it].subtract(selectedChanges) } if (changesExcludedFromMerge.isNotEmpty()) { val dialog = MyExcludedChangesDialog(project, changesExcludedFromMerge) if (!dialog.showAndGet()) return CheckinHandler.ReturnResult.CANCEL } } return CheckinHandler.ReturnResult.COMMIT } private class MyExcludedChangesDialog(project: Project, changes: List<Change>) : DialogWrapper(project) { val browser = SimpleChangesBrowser(project, changes) init { title = "Changes Excluded from Merge Commit" setOKButtonText("Commit Anyway") init() } override fun createNorthPanel(): JComponent? { val label = JLabel("Are you sure you want to exclude these changed files from merge commit?") label.border = JBUI.Borders.empty(5, 1) return label } override fun createCenterPanel(): JComponent? = browser override fun getPreferredFocusedComponent(): JComponent? = browser.preferredFocusedComponent } }
apache-2.0
4ed4bc6a56d0b02952876eb02b90172c
41.591837
129
0.734547
4.825434
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/ArrayConstructor.kt
1
5607
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.builder.self import com.github.jonathanxd.kores.common.Stack import com.github.jonathanxd.kores.literal.Literals import com.github.jonathanxd.kores.type import com.github.jonathanxd.kores.type.isArray import com.github.jonathanxd.kores.type.koresType import java.lang.reflect.Type /** * Constructs an array of type [arrayType] with dimensions [dimensions]. Example: * * `new ArrayConstructor(String[].class, listOf(Literals.INT(5)), emptyList()) = new String[5]` * `new ArrayConstructor(String[].class, listOf(Literals.INT(5), Literals.INT(9)), emptyList()) = new String[5][9]` * ``` * new ArrayConstructor( * String[].class, * listOf(Literals.INT(3)), * listOf(Literals.STRING("A"), Literals.STRING("B"), Literals.STRING("C")) * ) = new String[] {"A", "B", "C"} * ``` */ data class ArrayConstructor( val arrayType: Type, val dimensions: List<Instruction>, override val arguments: List<Instruction> ) : ArgumentsHolder, TypedInstruction { init { check(arrayType.isArray) { "arrayType is not an array type!" } check(dimensions.isNotEmpty()) { "dimensions cannot be empty" } } override val type: Type get() = this.arrayType override val array: Boolean get() = true override val types: List<Type> get() = ArrayList<Type>(this.arguments.size).apply { (0..arguments.size).forEach { add(arrayType.koresType.arrayComponent) } } /** * Array values */ val arrayValues: List<ArrayStore> get() { val arguments = this.arguments val arrayStores = mutableListOf<ArrayStore>() for (i in arguments.indices) { val argument = arguments[i] arrayStores.add( ArrayStore.Builder.builder() .arrayType([email protected]) //[email protected]([email protected]) .target(Stack) .index(Literals.INT(i)) .valueType(argument.type) .valueToStore(argument) .build() ) } return arrayStores } override fun builder(): Builder = Builder(this) class Builder() : ArgumentsHolder.Builder<ArrayConstructor, Builder>, Typed.Builder<ArrayConstructor, Builder> { lateinit var arrayType: Type var dimensions: List<Instruction> = emptyList() var arguments: List<Instruction> = emptyList() constructor(defaults: ArrayConstructor) : this() { this.arrayType = defaults.arrayType this.dimensions = defaults.dimensions this.arguments = defaults.arguments } override fun type(value: Type): Builder = this.arrayType(value) @Suppress("UNCHECKED_CAST") override fun array(value: Boolean): Builder = self() /** * See [ArrayConstructor.arrayType] */ fun arrayType(value: Type): Builder { this.arrayType = value return this } /** * See [ArrayConstructor.dimensions] */ fun dimensions(value: List<Instruction>): Builder { this.dimensions = value return this } /** * See [ArrayConstructor.dimensions] */ fun dimensions(vararg values: Instruction): Builder = dimensions(values.toList()) override fun arguments(value: List<Instruction>): Builder { this.arguments = value return this } override fun build(): ArrayConstructor = ArrayConstructor(this.arrayType, this.dimensions, this.arguments) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: ArrayConstructor): Builder = Builder(defaults) } } }
mit
ebc816e446f61af10211b857a8466f90
33.826087
148
0.626182
4.61102
false
false
false
false
intellij-solidity/intellij-solidity
src/test/kotlin/me/serce/solidity/ide/inspections/SolInspectionsTestBase.kt
1
1355
package me.serce.solidity.ide.inspections import com.intellij.codeInspection.LocalInspectionTool import me.serce.solidity.utils.SolTestBase import org.intellij.lang.annotations.Language abstract class SolInspectionsTestBase(private val inspection: LocalInspectionTool) : SolTestBase() { protected fun enableInspection() = myFixture.enableInspections(inspection.javaClass) protected fun checkByText( @Language("Solidity") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) { myFixture.configureByText("main.sol", prepare(text)) enableInspection() myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) } protected fun checkFixByText( fixName: String, before: String, after: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) { myFixture.configureByText("main.sol", before) enableInspection() myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) applyQuickFix(fixName) myFixture.checkResult(after) } protected fun applyQuickFix(name: String) { val action = myFixture.findSingleIntention(name) myFixture.launchAction(action) } private fun prepare(text: String): String { return text.replace("/*@", "<").replace("@*/", ">") } }
mit
41a750d78e99d676a6a79995ed497c2a
29.111111
100
0.733579
4.531773
false
true
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/platform/AttachProjectAction.kt
3
3908
// 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.platform import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.ide.actions.OpenProjectFileChooserDescriptor import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.project.isProjectDirectoryExistsUsingIo import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.projectImport.ProjectAttachProcessor import com.intellij.util.SystemProperties import java.io.File import java.nio.file.Path import java.nio.file.Paths /** * This action is enabled when confirmOpenNewProject option is set in settings to either OPEN_PROJECT_NEW_WINDOW or * OPEN_PROJECT_SAME_WINDOW, so there is no dialog shown on open directory action, which makes attaching a new project impossible. * This action provides a way to do that in this case. * * @author traff */ open class AttachProjectAction : AnAction(ActionsBundle.message("action.AttachProject.text")), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = ProjectAttachProcessor.canAttachToProject() && GeneralSettings.getInstance().confirmOpenNewProject != GeneralSettings.OPEN_PROJECT_ASK } override fun actionPerformed(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) ?: return chooseAndAttachToProject(project) } open fun validateDirectory(project: Project, directory: VirtualFile): Boolean { return true } fun chooseAndAttachToProject(project: Project) { val descriptor = OpenProjectFileChooserDescriptor(true) var preselectedDirectory = project.getUserData(TO_SELECT_KEY)?.let { project.putUserData(TO_SELECT_KEY, null) // reset the value LocalFileSystem.getInstance().findFileByNioFile(it) } if (preselectedDirectory == null) { preselectedDirectory = if (StringUtil.isNotEmpty(GeneralSettings.getInstance().defaultProjectDirectory)) VfsUtil.findFileByIoFile(File(GeneralSettings.getInstance().defaultProjectDirectory), true) else VfsUtil.findFileByIoFile(File(SystemProperties.getUserHome()), true) } FileChooser.chooseFiles(descriptor, project, preselectedDirectory) { val directory = it[0] if (validateDirectory(project, directory)) { attachProject(directory, project) } } } companion object { @JvmStatic val TO_SELECT_KEY = Key.create<Path>("attach_to_select_key") fun attachProject(virtualFile: VirtualFile, project: Project) { var baseDir: VirtualFile? = virtualFile if (!virtualFile.isDirectory) { baseDir = virtualFile.parent while (baseDir != null) { if (isProjectDirectoryExistsUsingIo(baseDir)) { break } baseDir = baseDir.parent } } if (baseDir == null) { Messages.showErrorDialog(IdeBundle.message("dialog.message.attach.project.not.found", virtualFile.path), IdeBundle.message("dialog.title.attach.project.error")) } else { PlatformProjectOpenProcessor.attachToProject(project, Paths.get(FileUtil.toSystemDependentName(baseDir.path)), null) } } } }
apache-2.0
0eef886f6b93167f8799c6441cc38f4c
39.28866
140
0.742323
4.657926
false
false
false
false
chromeos/video-decode-encode-demo
app/src/main/java/dev/hadrosaur/videodecodeencodedemo/Utils/GlUtils.kt
1
17125
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.hadrosaur.videodecodeencodedemo.Utils import android.opengl.* import java.nio.Buffer import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.* /** * Utility functions for using EGL. * * TODO: Make the relationship with GLManager clearer (or merge these two) */ object GlUtils { const val POSITION_ATTRIBUTE_NAME = "a_position" const val TEXCOORD_ATTRIBUTE_NAME = "a_texcoord" const val POS_MATRIX_UNIFORM_NAME = "u_pos_matrix" const val ST_MATRIX_UNIFORM_NAME = "u_surface_tex_transform_matrix" const val TEX_SAMPLER_NAME = "tex_sampler_0" private const val TEX_COORDINATE_NAME = "v_texcoord" const val NO_FBO = 0 /** * Vertex shader that renders a quad filling the viewport. * * Applies provided matrix transformations (needed for SurfaceTextures) */ private val BLIT_VERTEX_SHADER = String.format(Locale.US, "attribute vec4 %1${"$"}s;\n" + "attribute vec4 %2${"$"}s;\n" + "varying vec2 %3${"$"}s;\n" + "uniform mat4 %4${"$"}s;\n" + "uniform mat4 %5${"$"}s;\n" + "void main() {\n" + "gl_Position = %4${"$"}s * %1${"$"}s;\n" + "%3${"$"}s = ((%5${"$"}s) * %2${"$"}s).xy;\n" + "}\n" , POSITION_ATTRIBUTE_NAME, TEXCOORD_ATTRIBUTE_NAME, TEX_COORDINATE_NAME, POS_MATRIX_UNIFORM_NAME, ST_MATRIX_UNIFORM_NAME ) /** * Fragment shader that renders from an external shader to the current target. */ private val COPY_EXTERNAL_FRAGMENT_SHADER = String.format(Locale.US, "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "uniform samplerExternalOES %1${"$"}s;\n" + "varying vec2 %2${"$"}s;\n" + "void main() {\n" + " gl_FragColor = texture2D(%1${"$"}s, %2${"$"}s);\n" + "}\n" , TEX_SAMPLER_NAME, TEX_COORDINATE_NAME ) /** * Fragment shader that simply samples the textures with no modifications. */ private val PASSTHROUGH_FRAGMENT_SHADER = String.format(Locale.US, "precision mediump float;\n" + "uniform sampler2D %1${"$"}s;\n" + "varying vec2 %2${"$"}s;\n" + "void main() {\n" + " gl_FragColor = texture2D(%1${"$"}s, %2${"$"}s);\n" + "}\n" , TEX_SAMPLER_NAME, TEX_COORDINATE_NAME ) /** * Fragment shader that applies a simple Sepia filter. */ private val SEPIA_FRAGMENT_SHADER = String.format(Locale.US, "precision mediump float;\n" + "uniform sampler2D %1${"$"}s;\n" + "varying vec2 %2${"$"}s;\n" + "void main() {\n" + " vec4 sampleColor = texture2D(%1${"$"}s, %2${"$"}s);\n" + " gl_FragColor = vec4(sampleColor.r * 0.493 + sampleColor. g * 0.769 + sampleColor.b * 0.289, sampleColor.r * 0.449 + sampleColor.g * 0.686 + sampleColor.b * 0.268, sampleColor.r * 0.272 + sampleColor.g * 0.534 + sampleColor.b * 0.131, 1.0);\n" + "}\n" , TEX_SAMPLER_NAME, TEX_COORDINATE_NAME ) /** * Returns an initialized default display. */ fun createEglDisplay(): EGLDisplay { val eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) check(!(eglDisplay === EGL14.EGL_NO_DISPLAY)) { "no EGL display" } val major = IntArray(1) val minor = IntArray(1) check(EGL14.eglInitialize(eglDisplay, major, 0, minor, 0)) { "error in eglInitialize" } checkGlError() return eglDisplay } /** * Returns the texture identifier for a newly-allocated surface with the specified dimensions. * * @param width of the new texture in pixels * @param height of the new texture in pixels */ fun allocateTexture(width: Int, height: Int): Int { val texId = generateTexture() GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId) GLES20.glTexImage2D( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null ) checkGlError() return texId } /** * Returns a new framebuffer for the texture. * * @param texId of the texture to attach to the framebuffer */ fun getFboForTexture(texId: Int): Int { val fbo = generateFbo() GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbo) checkGlError() GLES20.glFramebufferTexture2D( GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, texId, 0 ) checkGlError() return fbo } /** * Makes the specified `surface` the render target, using a viewport of `width` by * `height` pixels. */ fun focusSurface( eglDisplay: EGLDisplay?, eglContext: EGLContext?, surface: EGLSurface?, fbo: Int, width: Int, height: Int ) { val fbos = IntArray(1) GLES20.glGetIntegerv(GLES20.GL_FRAMEBUFFER_BINDING, fbos, 0) if (fbos[0] != fbo) { GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbo) } EGL14.eglMakeCurrent(eglDisplay, surface, surface, eglContext) GLES20.glViewport(0, 0, width, height) } /** * Returns a new GL texture identifier. */ private fun generateTexture(): Int { val textures = IntArray(1) GLES20.glGenTextures(1, textures, 0) checkGlError() return textures[0] } /** * Returns a new framebuffer identifier. */ private fun generateFbo(): Int { val fbos = IntArray(1) GLES20.glGenFramebuffers(1, fbos, 0) checkGlError() return fbos[0] } /** * Deletes a GL texture. * * @param texId of the texture to delete */ fun deleteTexture(texId: Int) { val textures = intArrayOf(texId) GLES20.glDeleteTextures(1, textures, 0) } /** * Deletes a GL framebuffer. * * @param fboId of the texture to delete */ fun deleteFbo(fboId: Int) { val fbos = intArrayOf(fboId) GLES20.glDeleteFramebuffers(1, fbos, 0) } /** * Returns the [Attribute]s in the specified `program`. */ fun getAttributes(program: Int): Array<Attribute?> { val attributeCount = IntArray(1) GLES20.glGetProgramiv(program, GLES20.GL_ACTIVE_ATTRIBUTES, attributeCount, 0) check(attributeCount[0] == 2) { "expected two attributes" } val attributes = arrayOfNulls<Attribute>(attributeCount[0]) for (i in 0 until attributeCount[0]) { attributes[i] = Attribute(program, i) } return attributes } /** * Returns the [Uniform]s in the specified `program`. */ fun getUniforms(program: Int): Array<Uniform?> { val uniformCount = IntArray(3) GLES20.glGetProgramiv(program, GLES20.GL_ACTIVE_UNIFORMS, uniformCount, 0) val uniforms = arrayOfNulls<Uniform>(uniformCount[0]) for (i in 0 until uniformCount[0]) { uniforms[i] = Uniform(program, i) } return uniforms } /** * Returns a GL shader program identifier for a compiled program that copies from an external * texture. * * * It has two vertex attributes, [.POSITION_ATTRIBUTE_NAME] and * [.TEXCOORD_ATTRIBUTE_NAME] which should be set to the output position (vec4) and * texture coordinates (vec3) respectively of the output quad. */ val copyExternalShaderProgram: Int get() { val vertexShader = compileShader(GLES20.GL_VERTEX_SHADER, BLIT_VERTEX_SHADER) val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, COPY_EXTERNAL_FRAGMENT_SHADER) return linkProgram(vertexShader, fragmentShader) } /** * Returns a GL shader program identifier for a compiled program that composites two textures. * * * It has two vertex attributes, [.POSITION_ATTRIBUTE_NAME] and * [.TEXCOORD_ATTRIBUTE_NAME] which should be set to the output position (vec4) and * texture coordinates (vec3) respectively of the output quad. */ val passthroughShaderProgram: Int get() { val vertexShader = compileShader(GLES20.GL_VERTEX_SHADER, BLIT_VERTEX_SHADER) val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, PASSTHROUGH_FRAGMENT_SHADER) return linkProgram(vertexShader, fragmentShader) } val sepiaShaderProgram: Int get() { val vertexShader = compileShader(GLES20.GL_VERTEX_SHADER, BLIT_VERTEX_SHADER) val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, SEPIA_FRAGMENT_SHADER) return linkProgram(vertexShader, fragmentShader) } private fun compileShader(type: Int, source: String): Int { val shader = GLES20.glCreateShader(type) if (shader == 0) { throw RuntimeException("could not create shader: " + GLES20.glGetError()) } GLES20.glShaderSource(shader, source) GLES20.glCompileShader(shader) val compiled = IntArray(1) GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0) if (compiled[0] == 0) { val info = GLES20.glGetShaderInfoLog(shader) GLES20.glDeleteShader(shader) throw RuntimeException("could not compile shader $type:$info") } return shader } private fun linkProgram(vertexShader: Int, fragmentShader: Int): Int { val program = GLES20.glCreateProgram() if (program == 0) { throw RuntimeException("could not create shader program") } GLES20.glAttachShader(program, vertexShader) GLES20.glAttachShader(program, fragmentShader) GLES20.glLinkProgram(program) val linked = IntArray(1) GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0) if (linked[0] != GLES20.GL_TRUE) { val info = GLES20.glGetProgramInfoLog(program) GLES20.glDeleteProgram(program) throw RuntimeException("could not link shader $info") } return program } /** * Returns a [Buffer] containing the specified floats, suitable for passing to * [GLES20.glVertexAttribPointer]. */ private fun getVertexBuffer(values: FloatArray): Buffer { val FLOAT_SIZE = 4 return ByteBuffer.allocateDirect(values.size * FLOAT_SIZE) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(values) .position(0) } /** * Returns the length of the null-terminated string in `strVal`. */ private fun strlen(strVal: ByteArray): Int { for (i in strVal.indices) { if (strVal[i].toChar() == '\u0000') { return i } } return strVal.size } /** * Checks for a GL error using [GLES20.glGetError]. * * @throws RuntimeException if there is a GL error */ private fun checkGlError() { var errorCode: Int if (GLES20.glGetError().also { errorCode = it } != GLES20.GL_NO_ERROR) { throw RuntimeException("gl error: " + Integer.toHexString(errorCode)) } } class UnsupportedEglVersionException : Exception() /** * GL attribute, which can be attached to a buffer with * [Attribute.setBuffer]. */ class Attribute(program: Int, index: Int) { val name: String private val mIndex: Int private val mLocation: Int private var mBuffer: Buffer? = null private var mSize = 0 /** * Configures [.bind] to attach vertices in `buffer` (each of size * `size` elements) to this [Attribute]. * * @param buffer to bind to this attribute * @param size elements per vertex */ fun setBuffer(buffer: FloatArray?, size: Int) { requireNotNull(buffer) { "buffer must be non-null" } mBuffer = getVertexBuffer(buffer) mSize = size } /** * Sets the vertex attribute to whatever was attached via [.setBuffer]. * * * Should be called before each drawing call. */ fun bind() { checkNotNull(mBuffer) { "call setBuffer before bind" } GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0) GLES20.glVertexAttribPointer( mLocation, mSize, // count GLES20.GL_FLOAT, // type false, // normalize 0, // stride mBuffer ) GLES20.glEnableVertexAttribArray(mIndex) checkGlError() } init { val len = IntArray(1) GLES20.glGetProgramiv(program, GLES20.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, len, 0) val type = IntArray(1) val size = IntArray(1) val nameBytes = ByteArray(len[0]) val ignore = IntArray(1) GLES20.glGetActiveAttrib( program, index, len[0], ignore, 0, size, 0, type, 0, nameBytes, 0 ) name = String(nameBytes, 0, strlen(nameBytes)) mLocation = GLES20.glGetAttribLocation(program, name) mIndex = index } } /** * GL uniform, which can be attached to a sampler using * [Uniform.setSamplerTexId]. */ class Uniform(program: Int, index: Int) { val mName: String private val mLocation: Int private val mType: Int private var mTexId = 0 private var mUnit = 0 /** * Configures [.bind] to use the specified `texId` for this sampler uniform. * * @param texId from which to sample * @param unit for this texture */ fun setSamplerTexId(texId: Int, unit: Int) { mTexId = texId mUnit = unit } /** * Sets the uniform to whatever was attached via [.setSamplerTexId]. * * Should be called before each drawing call, for sampler uniforms only. */ fun bindToTextureSampler() { check(mTexId != 0) { "call setSamplerTexId before bind" } GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + mUnit) when (mType) { GLES11Ext.GL_SAMPLER_EXTERNAL_OES -> { GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTexId) } GLES20.GL_SAMPLER_2D -> { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTexId) } else -> { throw IllegalStateException("unexpected uniform type: $mType") } } GLES20.glUniform1i(mLocation, mUnit) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR ) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR ) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE ) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE ) checkGlError() } init { val len = IntArray(1) GLES20.glGetProgramiv(program, GLES20.GL_ACTIVE_UNIFORM_MAX_LENGTH, len, 0) val type = IntArray(1) val size = IntArray(1) val name = ByteArray(len[0]) val ignore = IntArray(1) GLES20.glGetActiveUniform( program, index, len[0], ignore, 0, size, 0, type, 0, name, 0 ) mName = String(name, 0, strlen(name)) mLocation = GLES20.glGetUniformLocation(program, mName) mType = type[0] } } }
apache-2.0
04490a7e92c6655d433a5b13eb632ed0
33.389558
259
0.570336
4.16971
false
false
false
false
openium/auvergne-webcams-droid
app/src/main/java/fr/openium/auvergnewebcams/ui/settings/FragmentSettings.kt
1
6536
package fr.openium.auvergnewebcams.ui.settings import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import androidx.core.content.pm.PackageInfoCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.base.AbstractFragment import fr.openium.auvergnewebcams.event.eventNewRefreshDelayValue import fr.openium.auvergnewebcams.event.eventRefreshDelayValueChanged import fr.openium.auvergnewebcams.ui.about.ActivitySettingsAbout import fr.openium.auvergnewebcams.utils.AnalyticsUtils import fr.openium.auvergnewebcams.utils.FirebaseUtils import fr.openium.kotlintools.ext.gone import fr.openium.kotlintools.ext.show import fr.openium.kotlintools.ext.snackbar import fr.openium.kotlintools.ext.startActivity import io.reactivex.rxkotlin.addTo import kotlinx.android.synthetic.main.fragment_settings.* import timber.log.Timber /** * Created by Openium on 19/02/2019. */ class FragmentSettings : AbstractFragment() { override val layoutId: Int = R.layout.fragment_settings // --- Life cycle // --------------------------------------------------- override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setListeners() initVersion() } // --- Methods // --------------------------------------------------- private fun setListeners() { // Auto refresh showDelayRefresh(prefUtils.isWebcamsDelayRefreshActive) switchSettingsRefreshDelay.isChecked = prefUtils.isWebcamsDelayRefreshActive switchSettingsRefreshDelay.setOnCheckedChangeListener { _, isChecked -> FirebaseUtils.setUserPropertiesRefreshPreferences(requireContext(), isChecked) prefUtils.isWebcamsDelayRefreshActive = isChecked showDelayRefresh(isChecked) } // Auto refresh delay linearLayoutSettingsDelayRefresh.setOnClickListener { val numberPickerDialog = RefreshDelayPickerDialog.newInstance(prefUtils.webcamsDelayRefreshValue) childFragmentManager.beginTransaction() .add(numberPickerDialog, "dialog_picker") .commitAllowingStateLoss() } textViewSettingsDelayValue.text = prefUtils.webcamsDelayRefreshValue.toString() eventNewRefreshDelayValue.subscribe { FirebaseUtils.setUserPropertiesRefreshIntervalPreferences(requireContext(), it) prefUtils.webcamsDelayRefreshValue = it textViewSettingsDelayValue.text = it.toString() eventRefreshDelayValueChanged.accept(Unit) }.addTo(disposables) // Webcams quality switchSettingsQualityWebcams.setOnCheckedChangeListener { _, isChecked -> FirebaseUtils.setUserPropertiesWebcamQualityPreferences(requireContext(), if (isChecked) "high" else "low") prefUtils.isWebcamsHighQuality = isChecked } switchSettingsQualityWebcams.isChecked = prefUtils.isWebcamsHighQuality // About screen textViewSettingsAbout.setOnClickListener { AnalyticsUtils.aboutClicked(requireContext()) startActivity<ActivitySettingsAbout>() } // Openium website textViewSettingsOpenium.setOnClickListener { AnalyticsUtils.websiteOpeniumClicked(requireContext()) startActivityForUrl(getString(R.string.url_openium)) } // Les pirates website textViewSettingsPirates.setOnClickListener { AnalyticsUtils.lesPiratesClicked(requireContext()) startActivityForUrl(getString(R.string.url_pirates)) } // Send new webcam textViewSettingsSendNewWebcam.setOnClickListener { MaterialAlertDialogBuilder(requireContext(), R.style.MaterialAlertDialogTheme) .setTitle(R.string.settings_send_new_webcam_title) .setMessage(R.string.settings_send_new_webcam_message) .setNeutralButton(R.string.generic_ok) { dialog, _ -> AnalyticsUtils.suggestWebcamClicked(requireContext()) sendEmail() dialog.dismiss() }.show() } // Rate app textViewSettingsNote.setOnClickListener { AnalyticsUtils.rateAppClicked(requireContext()) startActivityForUrl(getString(R.string.url_note_format, requireContext().packageName)) } } private fun sendEmail() { val intentEmail = Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("mailto:${getString(R.string.detail_signal_problem_email)}") putExtra(Intent.EXTRA_SUBJECT, getString(R.string.settings_send_new_webcam_email_title)) putExtra(Intent.EXTRA_TEXT, getString(R.string.settings_send_new_webcam_email_message)) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } val chooser = Intent.createChooser(intentEmail, getString(R.string.generic_chooser)) chooser.resolveActivity(requireContext().packageManager)?.also { startActivity(chooser) } ?: snackbar(R.string.generic_no_email_app, Snackbar.LENGTH_SHORT) } private fun showDelayRefresh(show: Boolean) { if (show) { linearLayoutSettingsDelayRefresh.show() } else { linearLayoutSettingsDelayRefresh.gone() } } private fun startActivityForUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } val chooser = Intent.createChooser(intent, getString(R.string.generic_chooser)) chooser.resolveActivity(requireContext().packageManager)?.also { startActivity(chooser) } ?: snackbar(R.string.generic_no_application_for_action, Snackbar.LENGTH_SHORT) } private fun initVersion() { try { requireContext().packageManager.getPackageInfo(requireContext().packageName, 0)?.also { val version = getString(R.string.settings_version_format, it.versionName, PackageInfoCompat.getLongVersionCode(it).toString()) textViewSettingsVersion.text = version } } catch (e: PackageManager.NameNotFoundException) { Timber.e(e) } } }
mit
d772349807f4b09e67d5fe64d881c77e
39.104294
132
0.680998
5.008429
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/arrows/EditArrowListFragment.kt
1
4627
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.arrows import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.databinding.DataBindingUtil import android.os.Bundle import androidx.annotation.CallSuper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import de.dreier.mytargets.R import de.dreier.mytargets.base.adapters.SimpleListAdapterBase import de.dreier.mytargets.base.fragments.EditableListFragmentBase import de.dreier.mytargets.base.fragments.ItemActionModeCallback import de.dreier.mytargets.base.viewmodel.ViewModelFactory import de.dreier.mytargets.databinding.FragmentArrowsBinding import de.dreier.mytargets.databinding.ItemImageDetailsBinding import de.dreier.mytargets.shared.models.db.Arrow import de.dreier.mytargets.utils.DividerItemDecoration import de.dreier.mytargets.utils.SlideInItemAnimator import de.dreier.mytargets.utils.multiselector.SelectableViewHolder class EditArrowListFragment : EditableListFragmentBase<Arrow, SimpleListAdapterBase<Arrow>>() { private lateinit var binding: FragmentArrowsBinding private lateinit var viewModel: ArrowListViewModel init { itemTypeDelRes = R.plurals.arrow_deleted actionModeCallback = ItemActionModeCallback(this, selector, R.plurals.arrow_selected) actionModeCallback?.setEditCallback({ this.onEdit(it) }) actionModeCallback?.setDeleteCallback({ this.onDelete(it) }) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.fab.setOnClickListener { navigationController.navigateToCreateArrow() .fromFab(binding.fab) .start() } } @CallSuper override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_arrows, container, false) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.addItemDecoration( DividerItemDecoration(context!!, R.drawable.full_divider) ) adapter = ArrowAdapter() binding.recyclerView.itemAnimator = SlideInItemAnimator() binding.recyclerView.adapter = adapter return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val factory = ViewModelFactory(activity!!.application!!) viewModel = ViewModelProviders.of(this, factory).get(ArrowListViewModel::class.java) viewModel.arrows.observe(this, Observer { arrows -> if (arrows != null) { adapter!!.setList(arrows) binding.emptyState.root.visibility = if (arrows.isEmpty()) View.VISIBLE else View.GONE } }) } private fun onEdit(itemId: Long) { navigationController.navigateToEditArrow(itemId) .start() } override fun onSelected(item: Arrow) { navigationController.navigateToEditArrow(item.id) .start() } override fun deleteItem(item: Arrow) = viewModel.deleteArrow(item) private inner class ArrowAdapter : SimpleListAdapterBase<Arrow>(compareBy(Arrow::name, Arrow::id)) { public override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.item_image_details, parent, false) return ViewHolder(itemView) } } internal inner class ViewHolder(itemView: View) : SelectableViewHolder<Arrow>( itemView, selector, this@EditArrowListFragment, this@EditArrowListFragment ) { private val binding = ItemImageDetailsBinding.bind(itemView) override fun bindItem(item: Arrow) { binding.name.text = item.name binding.image.setImageDrawable(item.thumbnail!!.roundDrawable) } } }
gpl-2.0
4805b1902a00b38ab65ccca1c93e0d9f
36.016
95
0.712557
4.948663
false
false
false
false
arnab/adventofcode
src/main/kotlin/aoc2021/day6/Lanternfish.kt
1
1318
package aoc2021.day6 object Lanternfish { data class Fish(val counter: Int = 8) { fun nextDay(): List<Fish> { return if (counter == 0) { listOf(Fish(6), Fish()) } else { listOf(Fish(counter - 1)) } } } fun parse(data: String) = data.split(",").map { Fish(it.toInt()) } fun calculateSchoolSize(initialPopulation: List<Fish>, days: Int): Int { val schoolAtTheEnd: List<Fish> = (1..days).fold(initialPopulation) { school, _ -> school.map { fish -> listOf(fish.nextDay()) }.flatten().flatten() } return schoolAtTheEnd.size } fun calculateSchoolSizeRecursiveWithMemory(school: List<Fish>, days: Int): Long = school.sumOf { fish -> spawnAndMemoize(fish, days) } private val memory = HashMap<Pair<Fish, Int>, Long>() private fun spawnAndMemoize(fish: Fish, days: Int): Long { return when { fish.counter == -1 -> spawnAndMemoize(Fish(6), days) + spawnAndMemoize(Fish(), days) days == 0 -> 1L else -> memory[Pair(fish, days)] ?: spawnAndMemoize( Fish(fish.counter - 1), days - 1 ).also { memory[Pair(fish, days)] = it } } } }
mit
18a8ee9f7d704ed858035d2eec405c94
29.651163
96
0.531108
3.981873
false
false
false
false
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/roots/AutomaticModuleUnloaderTest.kt
1
5908
// 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.roots import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.stateStore import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.module.impl.UnloadedModuleDescriptionImpl import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.ModuleTestCase import kotlinx.coroutines.runBlocking import java.io.File import java.util.* /** * @author nik */ class AutomaticModuleUnloaderTest : ModuleTestCase() { fun `test unload simple module`() = runBlocking { createModule("a") createModule("b") val moduleManager = ModuleManager.getInstance(project) moduleManager.setUnloadedModules(listOf("a")) createModule("c") val moduleFiles = createNewModuleFiles(listOf("d")) {} reloadProjectWithNewModules(moduleFiles) ModuleTestCase.assertSameElements(moduleManager.unloadedModuleDescriptions.map { it.name }, "a", "d") } fun `test unload modules with dependencies between them`() = runBlocking { createModule("a") createModule("b") doTest("a", listOf("c", "d"), { modules -> ModuleRootModificationUtil.updateModel(modules["c"]!!) { it.addModuleOrderEntry(modules["d"]!!) } },"a", "c", "d") } fun `test do not unload module if loaded module depends on it`() = runBlocking { createModule("a") val b = createModule("b") ModuleRootModificationUtil.updateModel(b) { it.addInvalidModuleEntry("d") } doTest("a", listOf("d"), {}, "a") } fun `test unload module if only unloaded module depends on it`() = runBlocking { val a = createModule("a") createModule("b") ModuleRootModificationUtil.updateModel(a) { it.addInvalidModuleEntry("d") } doTest("a", listOf("d"), {}, "a", "d") } fun `test do not unload modules if loaded module depends on them transitively`() = runBlocking { createModule("a") val b = createModule("b") ModuleRootModificationUtil.updateModel(b) { it.addInvalidModuleEntry("d") } doTest("a", listOf("c", "d"), { modules -> ModuleRootModificationUtil.updateModel(modules["d"]!!) { it.addModuleOrderEntry(modules["c"]!!) } }, "a") } fun `test unload module if loaded module transitively depends on it via previously unloaded module`() = runBlocking { val a = createModule("a") val b = createModule("b") ModuleRootModificationUtil.addDependency(a, b) ModuleRootModificationUtil.updateModel(b) { it.addInvalidModuleEntry("c") } doTest("b", listOf("c"), {}, "b", "c") } fun `test deleted iml file`() = runBlocking { createModule("a") createModule("b") val deletedIml = createModule("deleted") val moduleManager = ModuleManager.getInstance(project) moduleManager.setUnloadedModules(listOf("a")) createModule("c") val moduleFiles = createNewModuleFiles(listOf("d")) {} reloadProjectWithNewModules(moduleFiles) { File(deletedIml.moduleFilePath).delete() } ModuleTestCase.assertSameElements(moduleManager.unloadedModuleDescriptions.map { it.name }, "a", "d") } private suspend fun doTest(initiallyUnloaded: String, newModulesName: List<String>, setup: (Map<String, Module>) -> Unit, vararg expectedUnloadedModules: String) { val moduleManager = ModuleManager.getInstance(project) moduleManager.setUnloadedModules(listOf(initiallyUnloaded)) val moduleFiles = createNewModuleFiles(newModulesName, setup) reloadProjectWithNewModules(moduleFiles) ModuleTestCase.assertSameElements(moduleManager.unloadedModuleDescriptions.map { it.name }, *expectedUnloadedModules) } private suspend fun createNewModuleFiles(moduleNames: List<String>, setup: (Map<String, Module>) -> Unit): List<File> { val newModulesProjectDir = FileUtil.createTempDirectory("newModules", "") val moduleFiles = moduleNames.map { File(newModulesProjectDir, "$it.iml") } val projectManager = ProjectManagerEx.getInstanceEx() as ProjectManagerImpl val project = projectManager.createProject("newModules", newModulesProjectDir.absolutePath)!! try { val modules = runWriteAction { moduleFiles.map { ModuleManager.getInstance(project).newModule(it.absolutePath, StdModuleTypes.JAVA.id) } } setup(ModuleManager.getInstance(project).modules.associateBy { it.name }) modules.forEach { it.stateStore.save() } } finally { projectManager.forceCloseProject(project, true) runWriteAction { Disposer.dispose(project) } } return moduleFiles } private suspend fun reloadProjectWithNewModules(moduleFiles: List<File>, beforeReload: () -> Unit = {}) { val moduleManager = ModuleManagerImpl.getInstanceImpl(myProject) val modulePaths = LinkedHashSet<ModulePath>() moduleManager.modules.forEach { it.stateStore.save() } moduleManager.modules.mapTo(modulePaths) { ModulePath(it.moduleFilePath, null) } moduleManager.unloadedModuleDescriptions.mapTo(modulePaths) { (it as UnloadedModuleDescriptionImpl).modulePath } moduleFiles.mapTo(modulePaths) { ModulePath(FileUtil.toSystemIndependentName(it.absolutePath), null) } beforeReload() moduleManager.loadStateFromModulePaths(modulePaths) } }
apache-2.0
8a5d791173ca44910d66a062735ebd02
36.878205
140
0.718009
4.576297
false
true
false
false
google/intellij-community
platform/util/ui/src/com/intellij/ui/svg/SvgCacheManager.kt
5
5784
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package com.intellij.ui.svg import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.diagnostic.Logger import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.ImageLoader import org.jetbrains.annotations.ApiStatus import org.jetbrains.mvstore.MVMap import org.jetbrains.mvstore.MVStore import org.jetbrains.mvstore.type.FixedByteArrayDataType import org.jetbrains.xxh3.Xxh3 import sun.awt.image.SunWritableRaster import java.awt.Image import java.awt.Point import java.awt.image.* import java.nio.ByteBuffer import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.function.BiConsumer private const val IMAGE_KEY_SIZE = java.lang.Long.BYTES + 3 private fun getLogger() = Logger.getInstance(SvgCacheManager::class.java) @ApiStatus.Internal class SvgCacheManager(dbFile: Path) { private val store: MVStore private val scaleToMap: MutableMap<Float, MVMap<ByteArray, ImageValue>> = ConcurrentHashMap(2, 0.75f, 2) private val mapBuilder: MVMap.Builder<ByteArray, ImageValue> companion object { fun <K, V> getMap(scale: Float, isDark: Boolean, scaleToMap: MutableMap<Float, MVMap<K, V>>, store: MVStore, mapBuilder: MVMap.MapBuilder<MVMap<K, V>, K, V>): MVMap<K, V> { return scaleToMap.computeIfAbsent(scale + if (isDark) 10000 else 0) { store.openMap("icons@" + scale + if (isDark) "_d" else "", mapBuilder) } } fun readImage(value: ImageValue): Image { val dataBuffer = DataBufferInt(value.data, value.data.size) SunWritableRaster.makeTrackable(dataBuffer) return createImage(value.w, value.h, dataBuffer) } fun readImage(buffer: ByteBuffer, w: Int, h: Int): Image { val dataBuffer = DataBufferInt(w * h) buffer.asIntBuffer().get(SunWritableRaster.stealData(dataBuffer, 0)) SunWritableRaster.makeTrackable(dataBuffer) return createImage(w, h, dataBuffer) } } init { val storeErrorHandler = StoreErrorHandler() val storeBuilder = MVStore.Builder() .backgroundExceptionHandler(storeErrorHandler) .autoCommitDelay(60000) .compressionLevel(1) store = storeBuilder.openOrNewOnIoError(dbFile, true) { getLogger().debug("Cannot open icon cache database", it) } storeErrorHandler.isStoreOpened = true val mapBuilder = MVMap.Builder<ByteArray, ImageValue>() mapBuilder.keyType(FixedByteArrayDataType(IMAGE_KEY_SIZE)) mapBuilder.valueType(ImageValue.ImageValueSerializer()) this.mapBuilder = mapBuilder } private class StoreErrorHandler : BiConsumer<Throwable, MVStore> { var isStoreOpened = false override fun accept(e: Throwable, store: MVStore) { val logger = getLogger() if (isStoreOpened) { logger.error("Icon cache error (db=$store)") } else { logger.warn("Icon cache will be recreated or previous version of data reused, (db=$store)") } logger.debug(e) } } fun close() { store.close() } fun save() { store.triggerAutoSave() } fun loadFromCache(themeDigest: ByteArray, imageBytes: ByteArray, scale: Float, isDark: Boolean, docSize: ImageLoader.Dimension2DDouble?): Image? { val key = getCacheKey(themeDigest, imageBytes) val map = getMap(scale, isDark, scaleToMap, store, mapBuilder) try { val start = StartUpMeasurer.getCurrentTimeIfEnabled() val data = map.get(key) ?: return null val image = readImage(data) docSize?.setSize((data.w / scale).toDouble(), (data.h / scale).toDouble()) IconLoadMeasurer.svgCacheRead.end(start) return image } catch (e: Throwable) { getLogger().error(e) try { map.remove(key) } catch (e1: Exception) { getLogger().error("Cannot remove invalid entry", e1) } return null } } fun storeLoadedImage(themeDigest: ByteArray, imageBytes: ByteArray, scale: Float, image: BufferedImage) { val key = getCacheKey(themeDigest, imageBytes) getMap(scale, false, scaleToMap, store, mapBuilder).put(key, writeImage(image)) } } private val ZERO_POINT = Point(0, 0) private fun getCacheKey(themeDigest: ByteArray, imageBytes: ByteArray): ByteArray { val contentDigest = Xxh3.hashLongs(longArrayOf( Xxh3.hash(imageBytes), Xxh3.hash(themeDigest))) val buffer = ByteBuffer.allocate(IMAGE_KEY_SIZE) // add content size to key to reduce chance of hash collision (write as medium int) buffer.put((imageBytes.size ushr 16).toByte()) buffer.put((imageBytes.size ushr 8).toByte()) buffer.put(imageBytes.size.toByte()) buffer.putLong(contentDigest) return buffer.array() } private fun createImage(w: Int, h: Int, dataBuffer: DataBufferInt): BufferedImage { val colorModel = ColorModel.getRGBdefault() as DirectColorModel val raster = Raster.createPackedRaster(dataBuffer, w, h, w, colorModel.masks, ZERO_POINT) @Suppress("UndesirableClassUsage") return BufferedImage(colorModel, raster, false, null) } private fun writeImage(image: BufferedImage): ImageValue { val w = image.width val h = image.height @Suppress("UndesirableClassUsage") val convertedImage = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g = convertedImage.createGraphics() g.drawImage(image, 0, 0, null) g.dispose() val dataBufferInt = convertedImage.raster.dataBuffer as DataBufferInt return ImageValue(dataBufferInt.data, w, h) }
apache-2.0
29d3d5bc1b7fb737787e2f928cb3414c
34.709877
120
0.703492
3.887097
false
false
false
false
google/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autolink/UnlinkedProjectStartupActivity.kt
2
12217
// 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.externalSystem.autolink import com.intellij.openapi.Disposable import com.intellij.openapi.application.EDT import com.intellij.openapi.application.readAction import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker.Companion.LOG import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener.Companion.installAsyncVirtualFileListener import com.intellij.openapi.externalSystem.autolink.ExternalSystemUnlinkedProjectAware.Companion.EP_NAME import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.startup.ProjectPostStartupActivity 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.use import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isConfiguredByPlatformProcessor import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isNewProject import com.intellij.util.PathUtil import kotlinx.coroutines.* import org.jetbrains.annotations.VisibleForTesting @VisibleForTesting class UnlinkedProjectStartupActivity : ProjectPostStartupActivity { override suspend fun execute(project: Project) { val externalProjectPath = project.guessProjectDir()?.path ?: return showNotificationWhenNonEmptyProjectUnlinked(project) showNotificationWhenBuildToolPluginEnabled(project, externalProjectPath) showNotificationWhenNewBuildFileCreated(project, externalProjectPath) linkAndLoadProjectIfUnlinkedProjectsFound(project, externalProjectPath) } private fun isEnabledAutoLink(project: Project): Boolean { return ExternalSystemUnlinkedProjectSettings.getInstance(project).isEnabledAutoLink && !Registry.`is`("external.system.auto.import.disabled") } private fun isNewExternalProject(project: Project): Boolean { return ExternalSystemUtil.isNewProject(project) } private fun isNewPlatformProject(project: Project): Boolean { return project.isNewProject() } private fun isOpenedWithEmptyModel(project: Project): Boolean { return project.isConfiguredByPlatformProcessor() || isEmptyModel(project) } private fun isEmptyModel(project: Project): Boolean { val moduleManager = ModuleManager.getInstance(project) return moduleManager.modules.isEmpty() } private suspend fun linkAndLoadProjectIfUnlinkedProjectsFound(project: Project, externalProjectPath: String) { if (!isNewExternalProject(project)) { val isExpectedAutoLink = isEnabledAutoLink(project) && !isNewPlatformProject(project) && isOpenedWithEmptyModel(project) val projects = findUnlinkedProjectBuildFiles(project, externalProjectPath) val linkedProjects = projects.filter { it.key.isLinkedProject(project, externalProjectPath) } val unlinkedProjects = projects.filter { it.key !in linkedProjects && it.value.isNotEmpty() } if (isExpectedAutoLink && unlinkedProjects.size == 1 && linkedProjects.isEmpty()) { val unlinkedProjectAware = unlinkedProjects.keys.single() if (LOG.isDebugEnabled) { val projectId = unlinkedProjectAware.getProjectId(externalProjectPath) LOG.debug("Auto-linked ${projectId.debugName} project") } withContext(Dispatchers.EDT) { unlinkedProjectAware.linkAndLoadProjectWithLoadingConfirmation(project, externalProjectPath) } return } for ((unlinkedProjectAware, buildFiles) in unlinkedProjects) { showUnlinkedProjectsNotification(project, externalProjectPath, unlinkedProjectAware, buildFiles) } } } private suspend fun showNotificationIfUnlinkedProjectsFound(project: Project, externalProjectPath: String) { forEachExtensionSafe(EP_NAME) { unlinkedProjectAware -> showNotificationIfUnlinkedProjectsFound(project, externalProjectPath, unlinkedProjectAware) } } private suspend fun showNotificationIfUnlinkedProjectsFound( project: Project, externalProjectPath: String, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware ) { val buildFiles = findUnlinkedProjectBuildFiles(project, externalProjectPath, unlinkedProjectAware) showUnlinkedProjectsNotification(project, externalProjectPath, unlinkedProjectAware, buildFiles) } private suspend fun showUnlinkedProjectsNotification( project: Project, externalProjectPath: String, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware, buildFiles: Set<VirtualFile> ) { if (buildFiles.isNotEmpty()) { val notificationAware = UnlinkedProjectNotificationAware.getInstance(project) withContext(Dispatchers.EDT) { notificationAware.notify(unlinkedProjectAware, externalProjectPath) } } } private suspend fun findUnlinkedProjectBuildFiles( project: Project, externalProjectPath: String ): Map<ExternalSystemUnlinkedProjectAware, Set<VirtualFile>> { return EP_NAME.extensionList.associateWith { unlinkedProjectAware -> findUnlinkedProjectBuildFiles(project, externalProjectPath, unlinkedProjectAware) } } private suspend fun findUnlinkedProjectBuildFiles( project: Project, externalProjectPath: String, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware ): Set<VirtualFile> { if (unlinkedProjectAware.isLinkedProject(project, externalProjectPath)) { return emptySet() } val buildFiles = readAction(project, unlinkedProjectAware) { unlinkedProjectAware.getBuildFiles(project, externalProjectPath) } if (LOG.isDebugEnabled && buildFiles.isNotEmpty()) { val projectId = unlinkedProjectAware.getProjectId(externalProjectPath) LOG.debug("Found unlinked ${projectId.debugName} project; buildFiles=${buildFiles.map(VirtualFile::getPath)}") } return buildFiles } private fun showNotificationWhenNonEmptyProjectUnlinked(project: Project) { EP_NAME.forEachExtensionSafe { showNotificationWhenNonEmptyProjectUnlinked(project, it) } EP_NAME.addExtensionPointListener( object : ExtensionPointListener<ExternalSystemUnlinkedProjectAware> { override fun extensionAdded(extension: ExternalSystemUnlinkedProjectAware, pluginDescriptor: PluginDescriptor) { showNotificationWhenNonEmptyProjectUnlinked(project, extension) } }, project) } private fun showNotificationWhenNonEmptyProjectUnlinked(project: Project, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware) { val extensionDisposable = createExtensionDisposable(project, unlinkedProjectAware) unlinkedProjectAware.subscribe(project, object : ExternalSystemProjectLinkListener { override fun onProjectUnlinked(externalProjectPath: String) { project.coroutineScope.launch { coroutineScope(extensionDisposable) { showNotificationIfUnlinkedProjectsFound(project, externalProjectPath) } } } }, extensionDisposable) } private fun showNotificationWhenBuildToolPluginEnabled(project: Project, externalProjectPath: String) { EP_NAME.addExtensionPointListener( object : ExtensionPointListener<ExternalSystemUnlinkedProjectAware> { override fun extensionAdded(extension: ExternalSystemUnlinkedProjectAware, pluginDescriptor: PluginDescriptor) { val extensionDisposable = createExtensionDisposable(project, extension) project.coroutineScope.launch { coroutineScope(extensionDisposable) { showNotificationIfUnlinkedProjectsFound(project, externalProjectPath, extension) } } } }, project) } private fun showNotificationWhenNewBuildFileCreated(project: Project, externalProjectPath: String) { EP_NAME.forEachExtensionSafe { showNotificationWhenNewBuildFileCreated(project, externalProjectPath, it) } EP_NAME.addExtensionPointListener( object : ExtensionPointListener<ExternalSystemUnlinkedProjectAware> { override fun extensionAdded(extension: ExternalSystemUnlinkedProjectAware, pluginDescriptor: PluginDescriptor) { showNotificationWhenNewBuildFileCreated(project, externalProjectPath, extension) } }, project) } private fun showNotificationWhenNewBuildFileCreated( project: Project, externalProjectPath: String, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware ) { val extensionDisposable = createExtensionDisposable(project, unlinkedProjectAware) val listener = NewBuildFilesListener(project, externalProjectPath, unlinkedProjectAware, extensionDisposable) installAsyncVirtualFileListener(listener, extensionDisposable) } private fun ExternalSystemUnlinkedProjectAware.getBuildFiles(project: Project, externalProjectPath: String): Set<VirtualFile> { val localFilesSystem = LocalFileSystem.getInstance() val externalProjectDir = localFilesSystem.findFileByPath(externalProjectPath) ?: return emptySet() return externalProjectDir.children.filter { isBuildFile(project, it) }.toSet() } private inner class NewBuildFilesListener( private val project: Project, private val externalProjectPath: String, private val unlinkedProjectAware: ExternalSystemUnlinkedProjectAware, private val parentDisposable: Disposable ) : VirtualFileChangesListener { private lateinit var buildFiles: MutableSet<VirtualFile> override fun init() { buildFiles = HashSet() } override fun apply() { project.coroutineScope.launch { coroutineScope(parentDisposable) { showUnlinkedProjectsNotification(project, externalProjectPath, unlinkedProjectAware, buildFiles.toSet()) } } } override fun isRelevant(file: VirtualFile, event: VFileEvent): Boolean { return event is VFileCreateEvent && FileUtil.pathsEqual(PathUtil.getParentPath(file.path), externalProjectPath) && unlinkedProjectAware.isBuildFile(project, file) } override fun updateFile(file: VirtualFile, event: VFileEvent) { buildFiles.add(file) } } companion object { private suspend fun <R> readAction(project: Project, unlinkedProjectAware: ExternalSystemUnlinkedProjectAware, action: () -> R): R { return createExtensionDisposable(project, unlinkedProjectAware).use { disposable -> readAction(disposable) { action() } } } private suspend fun <R> readAction(parentDisposable: Disposable, action: () -> R): R { return coroutineScope(parentDisposable) { readAction { action() } } } private suspend fun <R> coroutineScope(parentDisposable: Disposable, action: suspend CoroutineScope.() -> R): R { return coroutineScope { Disposer.newDisposable(parentDisposable, "CoroutineScope").use { disposable -> val task = async(start = CoroutineStart.LAZY) { action() } Disposer.register(disposable, Disposable { task.cancel("disposed") }) task.start() task.await() } } } } private inline fun <T> forEachExtensionSafe(point: ExtensionPointName<T>, consumer: (T) -> Unit) { for (item in point.extensionList) { try { consumer(item) } catch (e: CancellationException) { throw e } catch (e: Exception) { LOG.error(e) } } } }
apache-2.0
1e64c93ae71cfbf8edda04bf99cb0c6f
41.423611
136
0.76058
5.316362
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/JavaResolveExtension.kt
1
7340
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("JavaResolutionUtils") package org.jetbrains.kotlin.idea.caches.resolve.util import com.intellij.openapi.application.runReadAction import com.intellij.psi.* import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.load.java.sources.JavaSourceElement import org.jetbrains.kotlin.load.java.structure.* import org.jetbrains.kotlin.load.java.structure.impl.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver import org.jetbrains.kotlin.resolve.scopes.MemberScope fun PsiMethod.getJavaMethodDescriptor(): FunctionDescriptor? = javaResolutionFacade()?.let { getJavaMethodDescriptor(it) } private fun PsiMethod.getJavaMethodDescriptor(resolutionFacade: ResolutionFacade): FunctionDescriptor? { val method = originalElement as? PsiMethod ?: return null if (method.containingClass == null || !Name.isValidIdentifier(method.name)) return null val resolver = method.getJavaDescriptorResolver(resolutionFacade) return when { method.isConstructor -> resolver?.resolveConstructor(JavaConstructorImpl(method)) else -> resolver?.resolveMethod(JavaMethodImpl(method)) } } fun PsiClass.getJavaClassDescriptor() = javaResolutionFacade()?.let { getJavaClassDescriptor(it) } fun PsiClass.getJavaClassDescriptor(resolutionFacade: ResolutionFacade): ClassDescriptor? { val psiClass = originalElement as? PsiClass ?: return null return psiClass.getJavaDescriptorResolver(resolutionFacade)?.resolveClass(JavaClassImpl(psiClass)) } private fun PsiField.getJavaFieldDescriptor(resolutionFacade: ResolutionFacade): PropertyDescriptor? { val field = originalElement as? PsiField ?: return null return field.getJavaDescriptorResolver(resolutionFacade)?.resolveField(JavaFieldImpl(field)) } fun PsiMember.getJavaMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? { return when (this) { is PsiClass -> getJavaClassDescriptor(resolutionFacade) is PsiMethod -> getJavaMethodDescriptor(resolutionFacade) is PsiField -> getJavaFieldDescriptor(resolutionFacade) else -> null } } fun PsiMember.getJavaMemberDescriptor(): DeclarationDescriptor? = javaResolutionFacade()?.let { getJavaMemberDescriptor(it) } fun PsiMember.getJavaOrKotlinMemberDescriptor(): DeclarationDescriptor? = javaResolutionFacade()?.let { getJavaOrKotlinMemberDescriptor(it) } fun PsiMember.getJavaOrKotlinMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? { return when (val callable = unwrapped) { is PsiMember -> getJavaMemberDescriptor(resolutionFacade) is KtDeclaration -> { val descriptor = resolutionFacade.resolveToDescriptor(callable) if (descriptor is ClassDescriptor && this is PsiMethod) descriptor.unsubstitutedPrimaryConstructor else descriptor } else -> null } } fun PsiParameter.getParameterDescriptor(): ValueParameterDescriptor? = javaResolutionFacade()?.let { getParameterDescriptor(it) } fun PsiParameter.getParameterDescriptor(resolutionFacade: ResolutionFacade): ValueParameterDescriptor? { val method = declarationScope as? PsiMethod ?: return null val methodDescriptor = method.getJavaMethodDescriptor(resolutionFacade) ?: return null return methodDescriptor.valueParameters[parameterIndex()] } fun PsiClass.resolveToDescriptor( resolutionFacade: ResolutionFacade, declarationTranslator: (KtClassOrObject) -> KtClassOrObject? = { it } ): ClassDescriptor? { return if (this is KtLightClass && this !is KtLightClassForDecompiledDeclaration) { val origin = this.kotlinOrigin ?: return null val declaration = declarationTranslator(origin) ?: return null resolutionFacade.resolveToDescriptor(declaration) } else { getJavaClassDescriptor(resolutionFacade) } as? ClassDescriptor } @OptIn(FrontendInternals::class) private fun PsiElement.getJavaDescriptorResolver(resolutionFacade: ResolutionFacade): JavaDescriptorResolver? { return resolutionFacade.tryGetFrontendService(this, JavaDescriptorResolver::class.java) } private fun JavaDescriptorResolver.resolveMethod(method: JavaMethod): FunctionDescriptor? { return getContainingScope(method)?.getContributedFunctions(method.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(method) } private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstructor): ConstructorDescriptor? { return resolveClass(constructor.containingClass)?.constructors?.findByJavaElement(constructor) } private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? { return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field) } private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? { val containingClass = resolveClass(member.containingClass) return if (member.isStatic) containingClass?.staticScope else containingClass?.defaultType?.memberScope } private fun <T : DeclarationDescriptorWithSource> Collection<T>.findByJavaElement(javaElement: JavaElement): T? { return firstOrNull { member -> val memberJavaElement = (member.original.source as? JavaSourceElement)?.javaElement when { memberJavaElement == javaElement -> true memberJavaElement is JavaElementImpl<*> && javaElement is JavaElementImpl<*> -> memberJavaElement.psi.isEquivalentTo(javaElement.psi) else -> false } } } fun PsiElement.hasJavaResolutionFacade(): Boolean = this.originalElement.containingFile != null fun PsiElement.javaResolutionFacade() = KotlinCacheService.getInstance(project).getResolutionFacadeByFile( this.originalElement.containingFile ?: reportCouldNotCreateJavaFacade(), JvmPlatforms.unspecifiedJvmPlatform ) private fun PsiElement.reportCouldNotCreateJavaFacade(): Nothing = runReadAction { error( "Could not get javaResolutionFacade for element:\n" + "same as originalElement = ${this === this.originalElement}" + "class = ${javaClass.name}, text = $text, containingFile = ${containingFile?.name}\n" + "originalElement.class = ${originalElement.javaClass.name}, originalElement.text = ${originalElement.text}), " + "originalElement.containingFile = ${originalElement.containingFile?.name}" ) }
apache-2.0
1943ae9ccc903a6773cdb35c22cd8fb7
46.051282
132
0.77139
5.510511
false
false
false
false
JetBrains/intellij-community
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/generation/model/HiddenStateCache.kt
1
3773
package org.jetbrains.completion.full.line.local.generation.model import io.kinference.ndarray.arrays.NDArray import io.kinference.ndarray.arrays.slice open class HiddenStateCache { private var cachedItem: Item? = null open fun onCacheHit(commonPrefixLength: Int) {} internal fun query(inputIds: IntArray): QueryResult { var commonPrefixLength = 0 val queryResult = cachedItem?.let { commonPrefixLength = inputIds.commonPrefixLengthWith(it.inputIds) if (commonPrefixLength < 5) { // It's probably a coincidence, we don't want to keep such a cache // TODO: prefer storing relatively long matching caches return@let null } else { if (inputIds.size == it.inputIds.size && inputIds.size == commonPrefixLength) { return@let QueryResult(inputIds, null, modelOutput = it.modelOutput, false) } val pastStatesInfo = processPastStates( inputIds, commonPrefixLength, it.inputIds, it.modelOutput.pastStates ) if (pastStatesInfo != null) { val (processedPastStates, processedContextLen, croppedPast) = pastStatesInfo val newInputIds = inputIds.slice(IntRange(processedContextLen, inputIds.size - 1)).toIntArray() return@let QueryResult(newInputIds, processedPastStates, null, !croppedPast) } return@let null } } ?: QueryResult(inputIds, null, null, true) if (queryResult.pastStates != null || queryResult.modelOutput != null) { onCacheHit(commonPrefixLength) } return queryResult } internal fun cache(inputIds: IntArray, modelOutput: ModelOutput) { cachedItem = Item(inputIds, modelOutput) } internal fun reset() { cachedItem = null } private fun processPastStates( inputIds: IntArray, commonPrefixLength: Int, cachedInputIds: IntArray, cachedPastStates: List<NDArray> ): Triple<List<NDArray>, Int, Boolean>? { // If cached input ids is longer than common prefix, we need to crop past states if (cachedInputIds.size > commonPrefixLength) { var croppedPastStatesLength = commonPrefixLength // If new inputIds is a full prefix of cached inputIds, there'll be no new input // and KInference doesn't work that way, so we need to do something about it if (inputIds.size == commonPrefixLength) { // We'll make inputIds smaller by 1 token and put this token into model context // for it not to be empty, but we can't use this trick if the context is shorter than 2 // In that case we'll say that there was no cache hit at all if (inputIds.size > 1) { croppedPastStatesLength-- } else { return null } } return Triple(cropPastStates(cachedPastStates, croppedPastStatesLength), croppedPastStatesLength, true) } else { return Triple(cachedPastStates, commonPrefixLength, false) } } private fun cropPastStates(pastStates: List<NDArray>, length: Int): List<NDArray> { return pastStates.map { if (it.shape[3] != length) { val newShape = it.shape.copyOf() newShape[3] = length it.slice(ends = newShape) } else { it } } } data class Item(val inputIds: IntArray, val modelOutput: ModelOutput) data class QueryResult( val newInputIds: IntArray, val pastStates: List<NDArray>?, val modelOutput: ModelOutput?, val cacheOutdated: Boolean ) private fun IntArray.commonPrefixLengthWith(another: IntArray): Int { var firstDifferentIndex = this.zip(another).indexOfFirst { (a, b) -> a != b } if (firstDifferentIndex == -1) { firstDifferentIndex = kotlin.math.min(this.size, another.size) } return firstDifferentIndex } }
apache-2.0
dab62b6318270a0f35eebed24b89f52e
34.933333
109
0.675855
4.141603
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt
1
7134
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.intellij.ui.NonFocusableCheckBox import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import javax.swing.JCheckBox class KotlinVariableInplaceIntroducer( addedVariable: KtProperty, originalExpression: KtExpression?, occurrencesToReplace: Array<KtExpression>, suggestedNames: Collection<String>, val isVar: Boolean, private val doNotChangeVar: Boolean, val expressionType: KotlinType?, private val noTypeInference: Boolean, project: Project, editor: Editor, private val postProcess: (KtDeclaration) -> Unit ) : AbstractKotlinInplaceIntroducer<KtProperty>( localVariable = addedVariable.takeIf { it.isLocal }, expression = originalExpression, occurrences = occurrencesToReplace, title = KotlinIntroduceVariableHandler.INTRODUCE_VARIABLE, project = project, editor = editor, ) { private val suggestedNames = suggestedNames.toTypedArray() private var expressionTypeCheckBox: JCheckBox? = null private val addedVariablePointer = addedVariable.createSmartPointer() private val addedVariable get() = addedVariablePointer.element init { initFormComponents { if (!doNotChangeVar) { val varCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.declare.with.var")) varCheckBox.isSelected = isVar varCheckBox.addActionListener { myProject.executeWriteCommand(commandName, commandName) { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.document) val psiFactory = KtPsiFactory(myProject) val keyword = if (varCheckBox.isSelected) psiFactory.createVarKeyword() else psiFactory.createValKeyword() addedVariable.valOrVarKeyword.replace(keyword) } } addComponent(varCheckBox) } if (expressionType != null && !noTypeInference) { val renderedType = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(expressionType) expressionTypeCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.specify.type.explicitly")).apply { isSelected = false addActionListener { runWriteCommandAndRestart { updateVariableName() if (isSelected) { addedVariable.typeReference = KtPsiFactory(myProject).createType(renderedType) } else { addedVariable.typeReference = null } } } addComponent(this) } } } } override fun getVariable() = addedVariable override fun suggestNames(replaceAll: Boolean, variable: KtProperty?) = suggestedNames override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>) = addedVariable override fun addAdditionalVariables(builder: TemplateBuilderImpl) { val variable = addedVariable ?: return variable.typeReference?.let { val expression = SpecifyTypeExplicitlyIntention.createTypeExpressionForTemplate(expressionType!!, variable) ?: return@let builder.replaceElement(it, "TypeReferenceVariable", expression, false) } } override fun buildTemplateAndStart( refs: Collection<PsiReference>, stringUsages: Collection<Pair<PsiElement, TextRange>>, scope: PsiElement, containingFile: PsiFile ): Boolean { myNameSuggestions = myNameSuggestions.mapTo(LinkedHashSet(), String::quoteIfNeeded) myEditor.caretModel.moveToOffset(nameIdentifier!!.startOffset) val result = super.buildTemplateAndStart(refs, stringUsages, scope, containingFile) val templateState = TemplateManagerImpl .getTemplateState(com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil.getTopLevelEditor(myEditor)) val variable = addedVariable if (templateState != null && variable?.typeReference != null) { templateState.addTemplateStateListener(SpecifyTypeExplicitlyIntention.createTypeReferencePostprocessor(variable)) } return result } override fun getInitialName() = super.getInitialName().quoteIfNeeded() override fun updateTitle(variable: KtProperty?, value: String?) { expressionTypeCheckBox?.isEnabled = value == null || value.isIdentifier() // No preview to update } override fun deleteTemplateField(psiField: KtProperty?) { // Do not delete introduced variable as it was created outside of in-place refactoring } override fun isReplaceAllOccurrences() = true override fun setReplaceAllOccurrences(allOccurrences: Boolean) { } override fun getComponent() = myWholePanel override fun performIntroduce() { val newName = inputName ?: return val replacement = KtPsiFactory(myProject).createExpression(newName) runWriteAction { addedVariable?.setName(newName) occurrences.forEach { if (it.isValid) { it.replace(replacement) } } } } override fun moveOffsetAfter(success: Boolean) { super.moveOffsetAfter(success) if (success) { addedVariable?.let { postProcess(it) } } } }
apache-2.0
5b01a7a2ef006b3c5a1543dd0259db6a
40.725146
158
0.689235
5.666402
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/GitNewProjectWizardStep.kt
1
2527
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.IdeBundle import com.intellij.ide.projectWizard.NewProjectWizardCollector import com.intellij.ide.wizard.NewProjectWizardStep.Companion.GIT_PROPERTY_NAME import com.intellij.openapi.GitRepositoryInitializer import com.intellij.openapi.observable.util.bindBooleanStorage import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.UIBundle import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindSelected import java.nio.file.Path class GitNewProjectWizardStep( parent: NewProjectWizardBaseStep ) : AbstractNewProjectWizardStep(parent), NewProjectWizardBaseData by parent, GitNewProjectWizardData { private val gitRepositoryInitializer = GitRepositoryInitializer.getInstance() private val gitProperty = propertyGraph.property(false) .bindBooleanStorage(GIT_PROPERTY_NAME) override val git get() = gitRepositoryInitializer != null && gitProperty.get() override fun setupUI(builder: Panel) { if (gitRepositoryInitializer != null) { with(builder) { row("") { checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox")) .bindSelected(gitProperty) }.bottomGap(BottomGap.SMALL) } } } override fun setupProject(project: Project) { setupProjectSafe(project, UIBundle.message("error.project.wizard.new.project.git")) { if (git) { val projectBaseDirectory = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(path, name)) if (projectBaseDirectory != null) { whenProjectCreated(project) { runBackgroundableTask(IdeBundle.message("progress.title.creating.git.repository"), project) { setupProjectSafe(project, UIBundle.message("error.project.wizard.new.project.git")) { gitRepositoryInitializer!!.initRepository(project, projectBaseDirectory, true) } } } } } NewProjectWizardCollector.logGitFinished(context, git) } } init { data.putUserData(GitNewProjectWizardData.KEY, this) gitProperty.afterChange { NewProjectWizardCollector.logGitChanged(context) } } }
apache-2.0
6a8f50c9cfb217cd460b2e7228f8283e
37.30303
158
0.741987
4.645221
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/storage/dao/UnitDaoImpl.kt
2
4242
package org.stepic.droid.storage.dao import android.content.ContentValues import android.database.Cursor import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.util.DbParseHelper import org.stepic.droid.util.getBoolean import org.stepic.droid.util.getDate import org.stepic.droid.util.getInt import org.stepic.droid.util.getLong import org.stepic.droid.util.getString import org.stepik.android.cache.unit.structure.DbStructureUnit import org.stepik.android.model.Unit import javax.inject.Inject class UnitDaoImpl @Inject constructor( databaseOperations: DatabaseOperations ) : DaoBase<Unit>(databaseOperations) { public override fun getDbName() = DbStructureUnit.TABLE_NAME public override fun getDefaultPrimaryColumn() = DbStructureUnit.Columns.ID public override fun getDefaultPrimaryValue(persistentObject: Unit): String = persistentObject.id.toString() public override fun parsePersistentObject(cursor: Cursor): Unit = Unit( id = cursor.getLong(DbStructureUnit.Columns.ID), section = cursor.getLong(DbStructureUnit.Columns.SECTION), lesson = cursor.getLong(DbStructureUnit.Columns.LESSON), assignments = DbParseHelper.parseStringToLongList(cursor.getString(DbStructureUnit.Columns.ASSIGNMENTS)), position = cursor.getInt(DbStructureUnit.Columns.POSITION), progress = cursor.getString(DbStructureUnit.Columns.PROGRESS), beginDate = cursor.getDate(DbStructureUnit.Columns.BEGIN_DATE), endDate = cursor.getDate(DbStructureUnit.Columns.END_DATE), softDeadline = cursor.getDate(DbStructureUnit.Columns.SOFT_DEADLINE), hardDeadline = cursor.getDate(DbStructureUnit.Columns.HARD_DEADLINE), gradingPolicy = cursor.getString(DbStructureUnit.Columns.GRADING_POLICY), beginDateSource = cursor.getString(DbStructureUnit.Columns.BEGIN_DATE_SOURCE), endDateSource = cursor.getString(DbStructureUnit.Columns.END_DATE_SOURCE), softDeadlineSource = cursor.getString(DbStructureUnit.Columns.SOFT_DEADLINE_SOURCE), hardDeadlineSource = cursor.getString(DbStructureUnit.Columns.HARD_DEADLINE_SOURCE), gradingPolicySource = cursor.getString(DbStructureUnit.Columns.GRADING_POLICY_SOURCE), isActive = cursor.getBoolean(DbStructureUnit.Columns.IS_ACTIVE), createDate = cursor.getDate(DbStructureUnit.Columns.CREATE_DATE), updateDate = cursor.getDate(DbStructureUnit.Columns.UPDATE_DATE) ) public override fun getContentValues(unit: Unit): ContentValues { val values = ContentValues() values.put(DbStructureUnit.Columns.ID, unit.id) values.put(DbStructureUnit.Columns.SECTION, unit.section) values.put(DbStructureUnit.Columns.LESSON, unit.lesson) values.put(DbStructureUnit.Columns.ASSIGNMENTS, DbParseHelper.parseLongListToString(unit.assignments)) values.put(DbStructureUnit.Columns.POSITION, unit.position) values.put(DbStructureUnit.Columns.PROGRESS, unit.progress) values.put(DbStructureUnit.Columns.BEGIN_DATE, unit.beginDate?.time ?: -1) values.put(DbStructureUnit.Columns.END_DATE, unit.endDate?.time ?: -1) values.put(DbStructureUnit.Columns.SOFT_DEADLINE, unit.softDeadline?.time ?: -1) values.put(DbStructureUnit.Columns.HARD_DEADLINE, unit.hardDeadline?.time ?: -1) values.put(DbStructureUnit.Columns.GRADING_POLICY, unit.gradingPolicy) values.put(DbStructureUnit.Columns.BEGIN_DATE_SOURCE, unit.beginDateSource) values.put(DbStructureUnit.Columns.END_DATE_SOURCE, unit.endDateSource) values.put(DbStructureUnit.Columns.SOFT_DEADLINE_SOURCE, unit.softDeadlineSource) values.put(DbStructureUnit.Columns.HARD_DEADLINE_SOURCE, unit.hardDeadlineSource) values.put(DbStructureUnit.Columns.GRADING_POLICY_SOURCE, unit.gradingPolicySource) values.put(DbStructureUnit.Columns.IS_ACTIVE, unit.isActive) values.put(DbStructureUnit.Columns.CREATE_DATE, unit.createDate?.time ?: -1) values.put(DbStructureUnit.Columns.UPDATE_DATE, unit.updateDate?.time ?: -1) return values } }
apache-2.0
c04e7af2da84b9e412db69fb2c561b8a
56.337838
117
0.747289
4.350769
false
false
false
false
allotria/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyProtocols.kt
2
2977
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL_EXT import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionHelper.resolveImplicitlyInvokedMethods import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.RatedResolveResult import com.jetbrains.python.psi.types.* fun isProtocol(classLikeType: PyClassLikeType, context: TypeEvalContext): Boolean = containsProtocol(classLikeType.getSuperClassTypes(context)) fun isProtocol(cls: PyClass, context: TypeEvalContext): Boolean = containsProtocol(cls.getSuperClassTypes(context)) fun matchingProtocolDefinitions(expected: PyType?, actual: PyType?, context: TypeEvalContext): Boolean = expected is PyClassLikeType && actual is PyClassLikeType && expected.isDefinition && actual.isDefinition && isProtocol(expected, context) && isProtocol(actual, context) typealias ProtocolAndSubclassElements = Pair<PyTypedElement, List<RatedResolveResult>?> fun inspectProtocolSubclass(protocol: PyClassType, subclass: PyClassType, context: TypeEvalContext): List<ProtocolAndSubclassElements> { val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val result = mutableListOf<Pair<PyTypedElement, List<RatedResolveResult>?>>() protocol.toInstance().visitMembers( { e -> if (e is PyTypedElement) { if (e is PyPossibleClassMember) { val cls = e.containingClass if (cls != null && !isProtocol(cls, context)) { return@visitMembers true } } val name = e.name ?: return@visitMembers true if (name == PyNames.CALL) { result.add(Pair(e, resolveImplicitlyInvokedMethods(subclass, null, resolveContext))) } else { result.add(Pair(e, subclass.resolveMember(name, null, AccessDirection.READ, resolveContext))) } } true }, true, context ) return result } private fun containsProtocol(types: List<PyClassLikeType?>) = types.any { type -> val classQName = type?.classQName PROTOCOL == classQName || PROTOCOL_EXT == classQName }
apache-2.0
8397570495d747d7d7fcaf83eead8898
45.515625
143
0.618072
5.543762
false
false
false
false
allotria/intellij-community
plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/Main.kt
2
7700
// 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 org.jetbrains.plugins.gradle.tooling.proxy import org.apache.log4j.ConsoleAppender import org.apache.log4j.Level import org.apache.log4j.Logger import org.apache.log4j.PatternLayout import org.gradle.internal.concurrent.DefaultExecutorFactory import org.gradle.internal.remote.internal.inet.InetAddressFactory import org.gradle.internal.remote.internal.inet.InetEndpoint import org.gradle.launcher.cli.action.BuildActionSerializer import org.gradle.launcher.daemon.protocol.BuildEvent import org.gradle.launcher.daemon.protocol.DaemonMessageSerializer import org.gradle.launcher.daemon.protocol.Failure import org.gradle.launcher.daemon.protocol.Success import org.gradle.tooling.* import org.gradle.tooling.internal.consumer.BlockingResultHandler import org.gradle.tooling.model.build.BuildEnvironment import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.InternalBuildIdentifier import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.InternalJavaEnvironment import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.build.InternalBuildEnvironment import org.slf4j.LoggerFactory import java.io.File import java.net.InetAddress object Main { const val LOCAL_BUILD_PROPERTY = "idea.gradle.target.local" private lateinit var LOG: org.slf4j.Logger private lateinit var serverConnector: TargetTcpServerConnector private lateinit var incomingConnectionHandler: TargetIncomingConnectionHandler @JvmStatic fun main(args: Array<String>) { initLogging(args) try { doMain() } finally { if (::serverConnector.isInitialized) { serverConnector.stop() } } } private fun doMain() { serverConnector = TargetTcpServerConnector(DaemonMessageSerializer.create(BuildActionSerializer.create())) incomingConnectionHandler = TargetIncomingConnectionHandler() val address = serverConnector.start(incomingConnectionHandler) { LOG.error("connection error") } as InetEndpoint println("Gradle target server hostName: ${address.candidates.first().hostName} port: ${address.port}") waitForIncomingConnection() waitForBuildParameters() val targetBuildParameters = incomingConnectionHandler.targetBuildParameters() LOG.debug("targetBuildParameters: $targetBuildParameters") val connector = GradleConnector.newConnector() val workingDirectory = File(".").canonicalFile LOG.debug("Working directory: ${workingDirectory.absolutePath}") connector.forProjectDirectory(workingDirectory.absoluteFile) val gradleHome = targetBuildParameters.gradleHome if (gradleHome != null) { connector.useInstallation(File(gradleHome)) } val resultHandler = BlockingResultHandler(Any::class.java) try { val result = connector.connect().use { runBuildAndGetResult(targetBuildParameters, it, resultHandler) } LOG.debug("operation result: $result") val adapted = maybeConvert(result) incomingConnectionHandler.dispatch(Success(adapted)) } catch (t: Throwable) { LOG.debug("GradleConnectionException: $t") incomingConnectionHandler.dispatch(Failure(t)) } finally { incomingConnectionHandler.receiveResultAck() } } private fun runBuildAndGetResult(targetBuildParameters: TargetBuildParameters, connection: ProjectConnection, resultHandler: BlockingResultHandler<Any>): Any? { val operation = when (targetBuildParameters) { is BuildLauncherParameters -> connection.newBuild().apply { targetBuildParameters.tasks.nullize()?.run { forTasks(*toTypedArray()) } } is TestLauncherParameters -> connection.newTestLauncher() is ModelBuilderParameters<*> -> connection.model(targetBuildParameters.modelType).apply { targetBuildParameters.tasks.nullize()?.run { forTasks(*toTypedArray()) } } is BuildActionParameters<*> -> connection.action(targetBuildParameters.buildAction).apply { targetBuildParameters.tasks.nullize()?.run { forTasks(*toTypedArray()) } } is PhasedBuildActionParameters<*> -> connection.action() .projectsLoaded(targetBuildParameters.projectsLoadedAction, IntermediateResultHandler { //resultHandler.onComplete(it) }) .buildFinished(targetBuildParameters.buildFinishedAction, IntermediateResultHandler { resultHandler.onComplete(it) }) .build().apply { targetBuildParameters.tasks.nullize()?.run { forTasks(*toTypedArray()) } } } val progressEventConverter = ProgressEventConverter() operation.apply { setStandardError(OutputWrapper { incomingConnectionHandler.dispatch(StandardError(it)) }) setStandardOutput(OutputWrapper { incomingConnectionHandler.dispatch(StandardOutput(it)) }) addProgressListener( { incomingConnectionHandler.dispatch(BuildEvent(progressEventConverter.convert(it))) }, targetBuildParameters.progressListenerOperationTypes ) addProgressListener(ProgressListener { val description = it.description if (description.isNotEmpty()) { incomingConnectionHandler.dispatch(BuildEvent(description)) } }) withArguments(targetBuildParameters.arguments) setJvmArguments(targetBuildParameters.jvmArguments) when (this) { is BuildLauncher -> run(resultHandler) is TestLauncher -> run(resultHandler) is ModelBuilder<*> -> get(resultHandler) is BuildActionExecuter<*> -> run(resultHandler) } } return resultHandler.result } private fun maybeConvert(result: Any?): Any? { if (result is BuildEnvironment) { return InternalBuildEnvironment({ InternalBuildIdentifier(result.buildIdentifier.rootDir) }, { result.java.run { InternalJavaEnvironment(javaHome, jvmArguments) } }, { result.gradle.gradleUserHome }, result.gradle.gradleVersion) } return result } private fun waitForIncomingConnection() { waitFor({ incomingConnectionHandler.isConnected() }, "Waiting for incoming connection....", "Incoming connection timeout") } private fun waitForBuildParameters() { waitFor({ incomingConnectionHandler.isBuildParametersReceived() }, "Waiting for target build parameters....", "Target build parameters were not received") } private fun waitFor(handler: () -> Boolean, waitingMessage: String, timeOutMessage: String) { val startTime = System.currentTimeMillis() while (!handler.invoke() && (System.currentTimeMillis() - startTime) < 5000) { LOG.debug(waitingMessage) val lock = Object() synchronized(lock) { try { lock.wait(100) } catch (ignore: InterruptedException) { } } } check(handler.invoke()) { timeOutMessage } } private fun initLogging(args: Array<String>) { val loggingArguments = listOf("--debug", "--info", "-warn", "--error", "--trace") val loggingLevel = args.find { it in loggingArguments }?.drop(2) ?: "error" Logger.getRootLogger().apply { addAppender(ConsoleAppender(PatternLayout("%d{dd/MM HH:mm:ss} %-5p %C{1}.%M - %m%n"))) level = Level.toLevel(loggingLevel, Level.ERROR) } LOG = LoggerFactory.getLogger(Main::class.java) } } private fun <T> List<T>?.nullize() = if (isNullOrEmpty()) null else this
apache-2.0
647bdc772233e6102c0e4cc4ff30fdab
41.081967
140
0.713506
4.758962
false
false
false
false
theunknownxy/mcdocs
src/main/kotlin/de/theunknownxy/mcdocs/docs/loader/xml/XMLParserHandler.kt
1
1140
package de.theunknownxy.mcdocs.docs.loader.xml import de.theunknownxy.mcdocs.docs.Content import org.xml.sax.Attributes import org.xml.sax.helpers.DefaultHandler import java.lang import java.util.Stack public class XMLParserHandler : DefaultHandler() { public class ParsedDocument { var title: String = "" var content: Content = Content() } var document: ParsedDocument = ParsedDocument() val xmlstate: Stack<State> = Stack() override fun startDocument() { xmlstate.push(StartState(this)) } override fun endDocument() { assert(xmlstate.pop() is StartState) } override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) { xmlstate.peek().startElement(uri, localName, qName, attributes) } override fun endElement(uri: String?, localName: String, qName: String) { xmlstate.peek().endElement(uri, localName, qName) } override fun characters(ch: CharArray?, start: Int, length: Int) { val str: String = lang.String(ch, start, length).toString() xmlstate.peek().characters(str) } }
mit
963438adef71fbc23c2d9f42338c3953
29.026316
102
0.685965
4.100719
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipActionProvider.kt
4
5783
// 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.codeInsight.daemon.impl import com.intellij.codeInsight.daemon.impl.tooltips.TooltipActionProvider import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction import com.intellij.codeInsight.intention.CustomizableIntentionAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.internal.statistic.service.fus.collectors.TooltipActionsLogger import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.TooltipAction import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.xml.util.XmlStringUtil import java.awt.event.InputEvent import java.util.* class DaemonTooltipActionProvider : TooltipActionProvider { override fun getTooltipAction(info: HighlightInfo, editor: Editor, psiFile: PsiFile): TooltipAction? { val intention = extractMostPriorityFixFromHighlightInfo(info, editor, psiFile) ?: return null return wrapIntentionToTooltipAction(intention, info, editor) } } /** * Tooltip link-action that proxies its execution to intention action with text [myActionText] * @param myFixText is a text to show in tooltip * @param myActionText is a text to search for in intentions' actions */ class DaemonTooltipAction(@NlsActions.ActionText private val myFixText: String, @NlsContexts.Command private val myActionText: String, private val myActualOffset: Int) : TooltipAction { override fun getText(): String { return myFixText } override fun execute(editor: Editor, inputEvent: InputEvent?) { val project = editor.project ?: return TooltipActionsLogger.logExecute(project, inputEvent) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return val intentions = ShowIntentionsPass.getAvailableFixes(editor, psiFile, -1, myActualOffset) for (descriptor in intentions) { val action = descriptor.action if (action.text == myActionText) { //unfortunately it is very common case when quick fixes/refactorings use caret position editor.caretModel.moveToOffset(myActualOffset) ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, action, myActionText) return } } } override fun showAllActions(editor: Editor) { editor.caretModel.moveToOffset(myActualOffset) val project = editor.project ?: return TooltipActionsLogger.showAllEvent.log(project) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return ShowIntentionActionsHandler().invoke(project, editor, psiFile) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val info = other as DaemonTooltipAction? return myActualOffset == info!!.myActualOffset && myFixText == info.myFixText } override fun hashCode(): Int { return Objects.hash(myFixText, myActualOffset) } } fun extractMostPriorityFixFromHighlightInfo(highlightInfo: HighlightInfo, editor: Editor, psiFile: PsiFile): IntentionAction? { ApplicationManager.getApplication().assertReadAccessAllowed() val fixes = mutableListOf<HighlightInfo.IntentionActionDescriptor>() val quickFixActionMarkers = highlightInfo.quickFixActionRanges if (quickFixActionMarkers == null || quickFixActionMarkers.isEmpty()) return null fixes.addAll(quickFixActionMarkers.map { it.first }.toList()) val intentionsInfo = ShowIntentionsPass.IntentionsInfo() ShowIntentionsPass.fillIntentionsInfoForHighlightInfo(highlightInfo, intentionsInfo, fixes) intentionsInfo.filterActions(psiFile) return getFirstAvailableAction(psiFile, editor, intentionsInfo) } fun getFirstAvailableAction(psiFile: PsiFile, editor: Editor, intentionsInfo: ShowIntentionsPass.IntentionsInfo): IntentionAction? { val project = psiFile.project //sort the actions val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFile, editor, intentionsInfo) val allActions = cachedIntentions.allActions if (allActions.isEmpty()) return null allActions.forEach { val action = IntentionActionDelegate.unwrap(it.action) if (action !is AbstractEmptyIntentionAction && action.isAvailable(project, editor, psiFile)) { val text = it.text //we cannot properly render html inside the fix button fixes with html text if (!XmlStringUtil.isWrappedInHtml(text)) { return action } } } return null } fun wrapIntentionToTooltipAction(intention: IntentionAction, info: HighlightInfo, editor: Editor): TooltipAction { val editorOffset = editor.caretModel.offset val text = (intention as? CustomizableIntentionAction)?.tooltipText ?: intention.text if ((info.actualStartOffset .. info.actualEndOffset).contains(editorOffset)) { //try to avoid caret movements return DaemonTooltipAction(text, intention.text, editorOffset) } val pair = info.quickFixActionMarkers?.find { it.first?.action == intention } val offset = if (pair?.second?.isValid == true) pair.second.startOffset else info.actualStartOffset return DaemonTooltipAction(text, intention.text, offset) }
apache-2.0
c9f4cac933111608a14a6b1c4e8cf70e
41.522059
185
0.768113
4.697807
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/application/options/RegistryManagerImpl.kt
1
1961
// 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.application.options import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.registry.Registry import com.intellij.util.ArrayUtilRt import org.jdom.Element import java.util.* @State(name = "Registry", storages = [Storage("ide.general.xml")]) private class RegistryManagerImpl : PersistentStateComponent<Element>, RegistryManager { override fun `is`(key: String): Boolean { return Registry.get(key).asBoolean() } override fun intValue(key: String) = Registry.get(key).asInteger() override fun intValue(key: String, defaultValue: Int): Int { return try { intValue(key) } catch (ignore: MissingResourceException) { defaultValue } } override fun get(key: String) = Registry.get(key) override fun getState() = Registry.getInstance().state override fun noStateLoaded() { Registry.getInstance().markAsLoaded() } override fun loadState(state: Element) { val registry = Registry.getInstance() registry.loadState(state) log(registry) } private fun log(registry: Registry) { val userProperties = registry.userProperties if (userProperties.size <= (if (userProperties.containsKey("ide.firstStartup")) 1 else 0)) { return } val keys = ArrayUtilRt.toStringArray(userProperties.keys) Arrays.sort(keys) val builder = StringBuilder("Registry values changed by user: ") for (key in keys) { if ("ide.firstStartup" == key) { continue } builder.append(key).append(" = ").append(userProperties[key]).append(", ") } logger<RegistryManager>().info(builder.substring(0, builder.length - 2)) } }
apache-2.0
cd781a9db017c5663d063d5cc2c30e1b
31.163934
140
0.718001
4.244589
false
false
false
false
allotria/intellij-community
platform/util-ex/src/com/intellij/diagnostic/startUpMeasurer.kt
1
998
// 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.diagnostic import org.jetbrains.annotations.NonNls inline fun <T> Activity?.runChild(name: String, task: () -> T): T { val activity = this?.startChild(name) val result = task() activity?.end() return result } inline fun <T> runMainActivity(name: String, task: () -> T): T = runActivity(name, ActivityCategory.MAIN, task) inline fun <T> runActivity(@NonNls name: String, category: ActivityCategory = ActivityCategory.APP_INIT, task: () -> T): T { val activity = createActivity(name, category) val result = task() activity.end() return result } @PublishedApi internal fun createActivity(name: String, category: ActivityCategory): Activity { return when (category) { ActivityCategory.MAIN -> StartUpMeasurer.startMainActivity(name) else -> StartUpMeasurer.startActivity(name, ActivityCategory.APP_INIT) } }
apache-2.0
f745f0b10ca301af72d24b5a13df0dd2
34.678571
140
0.734469
4.008032
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/ServiceMessageSourceImpl.kt
1
1373
package jetbrains.buildServer.agent.runner import jetbrains.buildServer.messages.serviceMessages.ServiceMessage import jetbrains.buildServer.messages.serviceMessages.ServiceMessageHandler import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTypes import jetbrains.buildServer.messages.serviceMessages.ServiceMessagesRegister import jetbrains.buildServer.rx.* class ServiceMessageSourceImpl( private val _serviceMessagesRegister: ServiceMessagesRegister) : ServiceMessageSource, ServiceMessageHandler { private val _subject: Subject<ServiceMessage> = subjectOf() private val _sharedSource: Observable<ServiceMessage> = _subject .track( { if (it) activate() }, { if (!it) deactivate() }) .share() override fun subscribe(observer: Observer<ServiceMessage>): Disposable = _sharedSource.subscribe(observer) override fun handle(serviceMessage: ServiceMessage) = _subject.onNext(serviceMessage) private fun activate() = serviceMessages.forEach { _serviceMessagesRegister.registerHandler(it, this) } private fun deactivate() = serviceMessages.forEach { _serviceMessagesRegister.removeHandler(it) } companion object { internal val serviceMessages = sequenceOf(ServiceMessageTypes.TEST_FAILED) } }
apache-2.0
fc950d4563216d372f09a2f31b7e6a0b
39.411765
90
0.732702
5.448413
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/viewmodel/content/TransferDetailContentViewModel.kt
1
2459
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.viewmodel.content import android.view.View import androidx.appcompat.widget.PopupMenu import com.genonbeta.android.framework.util.Files import org.monora.uprotocol.client.android.R import org.monora.uprotocol.client.android.database.model.TransferDetail import org.monora.uprotocol.client.android.protocol.isIncoming import kotlin.math.max class TransferDetailContentViewModel(detail: TransferDetail) { val clientNickname = detail.clientNickname val sizeText = Files.formatLength(detail.size, false) val isFinished = detail.itemsCount == detail.itemsDoneCount val isReceiving = detail.direction.isIncoming val count = detail.itemsCount val icon = if (isReceiving) { R.drawable.ic_arrow_down_white_24dp } else { R.drawable.ic_arrow_up_white_24dp } val finishedIcon = R.drawable.ic_done_white_24dp val needsApproval = !detail.accepted && isReceiving var onRemove: (() -> Unit)? = null private val percentage = with(detail) { if (sizeOfDone <= 0) 0 else ((sizeOfDone.toDouble() / size) * 100).toInt() } val progress = max(1, percentage) val percentageText = percentage.toString() val waitingApproval = !detail.accepted && !isReceiving fun showPopupMenu(view: View) { PopupMenu(view.context, view).apply { inflate(R.menu.transfer_details) setOnMenuItemClickListener { when (it.itemId) { R.id.remove -> onRemove?.invoke() else -> return@setOnMenuItemClickListener false } true } show() } } }
gpl-2.0
7ef57c084176e686aef4fa1c56a37c4b
31.773333
82
0.689992
4.28223
false
false
false
false
SmokSmog/smoksmog-android
app/src/main/kotlin/com/antyzero/smoksmog/ui/dialog/AboutDialog.kt
1
1827
package com.antyzero.smoksmog.ui.dialog import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import android.widget.TextView import com.antyzero.smoksmog.R import com.antyzero.smoksmog.SmokSmogApplication import com.antyzero.smoksmog.dsl.compatFromHtml import com.antyzero.smoksmog.dsl.tag import com.antyzero.smoksmog.user.User import smoksmog.logger.Logger import javax.inject.Inject class AboutDialog : InfoDialog() { @Inject lateinit var logger: Logger @Inject lateinit var user: User lateinit var textView: TextView lateinit var textViewVersionName: TextView lateinit var textViewUserId: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) SmokSmogApplication[activity] .appComponent .inject(this) } override fun getLayoutId(): Int = R.layout.dialog_info_about override fun initView(view: View) { super.initView(view) with(view) { textView = findViewById(R.id.textView) as TextView textViewUserId = findViewById(R.id.textViewUserId) as TextView textViewVersionName = findViewById(R.id.textViewVersionName) as TextView } textView.compatFromHtml(R.string.about) textView.movementMethod = LinkMovementMethod.getInstance() try { val packageInfo = activity.packageManager.getPackageInfo(activity.packageName, 0) textViewVersionName.text = getString(R.string.version_name_and_code, packageInfo.versionName, packageInfo.versionCode) } catch (e: Exception) { logger.i(tag(), "Problem with obtaining version", e) } textViewUserId.text = user.identifier } }
gpl-3.0
4a78c55897c618d55cedde04ab247cc5
31.625
93
0.695129
4.696658
false
false
false
false
AndroidX/androidx
fragment/fragment-ktx/src/main/java/androidx/fragment/app/FragmentTransaction.kt
3
3185
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app import android.os.Bundle import androidx.annotation.IdRes /** * Add a fragment to the associated [FragmentManager], inflating * the Fragment's view into the container view specified by * [containerViewId], to later retrieve via * [FragmentManager.findFragmentById]. * * The new fragment to be added will be created via the * [FragmentFactory] of the [FragmentManager]. * * @param containerViewId Identifier of the container this fragment is * to be placed in. * @param tag Optional tag name for the fragment, to later retrieve the * fragment with [FragmentManager.findFragmentByTag]. * @param args Optional arguments to be set on the fragment. * * @return Returns the same [FragmentTransaction] instance. */ public inline fun <reified F : Fragment> FragmentTransaction.add( @IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null ): FragmentTransaction = add(containerViewId, F::class.java, args, tag) /** * Add a fragment to the associated [FragmentManager] without * adding the Fragment to any container view. * * The new fragment to be added will be created via the * [FragmentFactory] of the [FragmentManager]. * * @param tag Tag name for the fragment, to later retrieve the * fragment with [FragmentManager.findFragmentByTag]. * @param args Optional arguments to be set on the fragment. * * @return Returns the same [FragmentTransaction] instance. */ public inline fun <reified F : Fragment> FragmentTransaction.add( tag: String, args: Bundle? = null ): FragmentTransaction = add(F::class.java, args, tag) /** * Replace an existing fragment that was added to a container. This is * essentially the same as calling [remove] for all * currently added fragments that were added with the same `containerViewId` * and then [add] with the same arguments given here. * * The new fragment to place in the container will be created via the * [FragmentFactory] of the [FragmentManager]. * * @param containerViewId Identifier of the container whose fragment(s) are * to be replaced. * @param tag Optional tag name for the fragment, to later retrieve the * fragment with [FragmentManager.findFragmentByTag]. * @param args Optional arguments to be set on the fragment. * * @return Returns the same [FragmentTransaction] instance. */ public inline fun <reified F : Fragment> FragmentTransaction.replace( @IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null ): FragmentTransaction = replace(containerViewId, F::class.java, args, tag)
apache-2.0
5b443d9d88fee9a7b7122ffdedeb36d5
36.916667
76
0.742229
4.333333
false
false
false
false
mglukhikh/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/SvnDiffSettingsHolder.kt
1
2784
// 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.idea.svn.difftool import com.intellij.diff.util.DiffPlaces import com.intellij.diff.util.DiffUtil import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.util.Key import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.XMap import java.util.* @State( name = "SvnDiffSettings", storages = arrayOf(Storage(value = DiffUtil.DIFF_CONFIG)) ) class SvnDiffSettingsHolder : PersistentStateComponent<SvnDiffSettingsHolder.State> { class SharedSettings( ) data class PlaceSettings( var SPLITTER_PROPORTION: Float = 0.9f, var HIDE_PROPERTIES: Boolean = false ) class SvnDiffSettings internal constructor(private val SHARED_SETTINGS: SharedSettings, private val PLACE_SETTINGS: PlaceSettings) { constructor() : this(SharedSettings(), PlaceSettings()) var isHideProperties: Boolean get() = PLACE_SETTINGS.HIDE_PROPERTIES set(value) { PLACE_SETTINGS.HIDE_PROPERTIES = value } var splitterProportion: Float get() = PLACE_SETTINGS.SPLITTER_PROPORTION set(value) { PLACE_SETTINGS.SPLITTER_PROPORTION = value } companion object { @JvmField val KEY: Key<SvnDiffSettings> = Key.create("SvnDiffSettings") @JvmStatic fun getSettings(): SvnDiffSettings = getSettings(null) @JvmStatic fun getSettings(place: String?): SvnDiffSettings = service<SvnDiffSettingsHolder>().getSettings(place) } } fun getSettings(place: String?): SvnDiffSettings { val placeKey = place ?: DiffPlaces.DEFAULT val placeSettings = myState.PLACES_MAP.getOrPut(placeKey, { defaultPlaceSettings(placeKey) }) return SvnDiffSettings(myState.SHARED_SETTINGS, placeSettings) } private fun copyStateWithoutDefaults(): State { val result = State() result.SHARED_SETTINGS = myState.SHARED_SETTINGS result.PLACES_MAP = DiffUtil.trimDefaultValues(myState.PLACES_MAP, { defaultPlaceSettings(it) }) return result } private fun defaultPlaceSettings(place: String): PlaceSettings { return PlaceSettings() } class State { @XMap @OptionTag @JvmField var PLACES_MAP: TreeMap<String, PlaceSettings> = TreeMap() @JvmField var SHARED_SETTINGS = SharedSettings() } private var myState: State = State() override fun getState(): State { return copyStateWithoutDefaults() } override fun loadState(state: State) { myState = state } }
apache-2.0
5bf6d84e50244b3f50b9d105c87d1473
31.372093
140
0.730603
4.461538
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/FAQOverviewFragment.kt
1
3982
package com.habitrpg.android.habitica.ui.fragments.support import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.os.bundleOf import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.FAQRepository import com.habitrpg.android.habitica.databinding.FragmentFaqOverviewBinding import com.habitrpg.android.habitica.databinding.SupportFaqItemBinding import com.habitrpg.android.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.setMarkdown import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import io.reactivex.functions.Consumer import javax.inject.Inject class FAQOverviewFragment : BaseMainFragment() { private lateinit var binding: FragmentFaqOverviewBinding @Inject lateinit var faqRepository: FAQRepository override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { hidesToolbar = true super.onCreateView(inflater, container, savedInstanceState) binding = FragmentFaqOverviewBinding.inflate(inflater, container, false) binding.healthSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfHeartLarge()) binding.experienceSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfExperienceReward()) binding.manaSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfMagicLarge()) binding.goldSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfGoldReward()) binding.gemsSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfGem()) binding.hourglassesSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfHourglassLarge()) binding.statsSection.findViewById<ImageView>(R.id.icon_view).setImageBitmap(HabiticaIconsHelper.imageOfStats()) binding.moreHelpTextView.setMarkdown(context?.getString(R.string.need_help_header_description, "[Habitica Help Guild](https://habitica.com/groups/guild/5481ccf3-5d2d-48a9-a871-70a7380cee5a)")) binding.moreHelpTextView.setOnClickListener { MainNavigationController.navigate(R.id.guildFragment, bundleOf("groupID" to "5481ccf3-5d2d-48a9-a871-70a7380cee5a")) } binding.moreHelpTextView.movementMethod = LinkMovementMethod.getInstance() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.loadArticles() } override fun onDestroy() { faqRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun loadArticles() { compositeSubscription.add(faqRepository.getArticles().subscribe(Consumer { val context = context ?: return@Consumer for (article in it) { val binding = SupportFaqItemBinding.inflate(context.layoutInflater, binding.faqLinearLayout, true) binding.textView.text = article.question binding.root.setOnClickListener { MainNavigationController.navigate(FAQOverviewFragmentDirections.openFAQDetail(article.position ?: 0)) } } }, RxErrorHandler.handleEmptyError())) } }
gpl-3.0
fe04df9d2e6550e4b522da679fced4da
49.051282
200
0.751632
4.786058
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetadataStubBuilder.kt
1
2091
// 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.klib import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.compiled.ClsStubBuilder import com.intellij.psi.impl.compiled.ClassFileStubBuilder import com.intellij.psi.stubs.PsiFileStub import com.intellij.util.indexing.FileContent import org.jetbrains.kotlin.idea.decompiler.stubBuilder.createIncompatibleAbiVersionFileStub import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import org.jetbrains.kotlin.serialization.js.DynamicTypeDeserializer open class KlibMetadataStubBuilder( private val version: Int, private val fileType: FileType, private val serializerProtocol: () -> SerializerExtensionProtocol, private val readFile: (VirtualFile) -> FileWithMetadata? ) : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + version override fun buildFileStub(content: FileContent): PsiFileStub<*>? { val virtualFile = content.file assert(virtualFile.fileType == fileType) { "Unexpected file type ${virtualFile.fileType}" } val file = readFile(virtualFile) ?: return null return when (file) { is FileWithMetadata.Incompatible -> createIncompatibleAbiVersionFileStub() is FileWithMetadata.Compatible -> { //todo: this part is implemented in our own way val renderer = DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() } val ktFileText = decompiledText( file, serializerProtocol(), DynamicTypeDeserializer, renderer ) createFileStub(content.project, ktFileText.text) } } } }
apache-2.0
4596b27a0befb6848adb9a8162310778
44.456522
158
0.728838
5.150246
false
false
false
false
JetBrains/xodus
benchmarks/src/jmh/kotlin/jetbrains/exodus/benchmark/query/InMemorySortBenchmarkBase.kt
1
3564
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.benchmark.query import jetbrains.exodus.entitystore.* import jetbrains.exodus.query.* import jetbrains.exodus.util.Random import org.junit.rules.TemporaryFolder import kotlin.math.abs open class InMemorySortBenchmarkBase { lateinit var store: PersistentEntityStoreImpl lateinit var temporaryFolder: TemporaryFolder private val comparator = compareBy<Entity> { it.getProperty("int") } private val valueGetter = ComparableGetter { it.getProperty("int") } private val valueComparator = Comparator<Comparable<Any>> { o1, o2 -> o1.compareTo(o2) } fun setup() { temporaryFolder = TemporaryFolder() temporaryFolder.create() store = PersistentEntityStores.newInstance(temporaryFolder.newFolder("data").absolutePath) val rnd = Random(5566) store.computeInTransaction { val txn = it as PersistentStoreTransaction repeat(50000) { val value = abs(rnd.nextInt()) txn.newEntity("Issue").setProperty("int", value) } } } fun close() { store.close() temporaryFolder.delete() } open fun testMergeSort(): Long { return testSort { InMemoryMergeSortIterable(it, comparator) } } open fun testMergeSortWithArrayList(): Long { return testSort { InMemoryMergeSortIterableWithArrayList(it, comparator) } } open fun testMergeSortWithValueGetter(): Long { return testSort { InMemoryMergeSortIterableWithValueGetter(it, valueGetter, valueComparator) } } open fun testTimSort(): Long { return testSort { InMemoryTimSortIterable(it, comparator) } } open fun testQuickSort(): Long { return testSort { InMemoryQuickSortIterable(it, comparator) } } open fun testHeapSort(): Long { return testSort { InMemoryHeapSortIterable(it, comparator) } } open fun testHeapSortWithValueGetter(): Long { return testSort { InMemoryHeapSortIterableWithValueGetter(it, valueGetter, valueComparator) } } open fun testKeapSort(): Long { return testSort { InMemoryKeapSortIterable(it, comparator) } } open fun testBoundedSort(): Long { return testSort { InMemoryBoundedHeapSortIterable(100, it, comparator) } } open fun testNoSort(): Long { return store.computeInTransaction { val sum = it.getAll("Issue").sumBy { it.getProperty("int") as Int } if (abs(sum) < 100) { throw IndexOutOfBoundsException() } it.getAll("Issue").take(100).map { it.id.localId }.sum() } } private fun testSort(sortFun: (it: Iterable<Entity>) -> Iterable<Entity>): Long { return store.computeInTransaction { val sorted = sortFun(it.getAll("Issue")) // sum of ids of least 100 entities sorted.take(100).map { it.id.localId }.sum() } } }
apache-2.0
9f661d5ab788cf69c2f232dbd3b3be06
32.942857
102
0.666105
4.540127
false
true
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/lang/references/MarkdownAnchorReferenceImpl.kt
1
2738
// 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.intellij.plugins.markdown.lang.references import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StubIndex import com.intellij.util.Processor import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.index.MarkdownHeadersIndex import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeaderImpl class MarkdownAnchorReferenceImpl internal constructor(private val myAnchor: String, private val myFileReference: PsiReference?, private val myPsiElement: PsiElement, private val myOffset: Int) : MarkdownAnchorReference, PsiPolyVariantReferenceBase<PsiElement>( myPsiElement), EmptyResolveMessageProvider { private val file: PsiFile? get() = if (myFileReference != null) myFileReference.resolve() as? PsiFile else myPsiElement.containingFile.originalFile override fun getElement(): PsiElement = myPsiElement override fun getRangeInElement(): TextRange = TextRange(myOffset, myOffset + myAnchor.length) override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { if (myAnchor.isEmpty()) return PsiElementResolveResult.createResults(myPsiElement) val project = myPsiElement.project return PsiElementResolveResult.createResults(MarkdownAnchorReference.getPsiHeaders(project, canonicalText, file)) } override fun getCanonicalText(): String = myAnchor override fun getVariants(): Array<Any> { val project = myPsiElement.project val list = ArrayList<String>() StubIndex.getInstance().getAllKeys(MarkdownHeadersIndex.KEY, project) .forEach { key -> StubIndex.getInstance().processElements(MarkdownHeadersIndex.KEY, key, project, file?.let { GlobalSearchScope.fileScope(it) }, MarkdownHeaderImpl::class.java, Processor { list.add(MarkdownAnchorReference.dashed(key)) } ) } return list.toTypedArray() } override fun getUnresolvedMessagePattern(): String = if (file == null) MarkdownBundle.message("markdown.cannot.resolve.anchor.error.message", myAnchor) else MarkdownBundle.message("markdown.cannot.resolve.anchor.in.file.error.message", myAnchor, (file as PsiFile).name) }
apache-2.0
eaacccf88de4a1f2b425ed9c0be4f4c3
47.892857
149
0.701972
5.079777
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.kt
1
24371
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.application.options.editor import com.intellij.application.options.editor.EditorCaretStopPolicyItem.* import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPass import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationBundle.message import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.actions.CaretStopBoundary import com.intellij.openapi.editor.actions.CaretStopOptionsTransposed import com.intellij.openapi.editor.actions.CaretStopOptionsTransposed.Companion.fromCaretStopOptions import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.ex.EditorSettingsExternalizable.TOOLTIPS_DELAY_RANGE import com.intellij.openapi.editor.richcopy.settings.RichCopySettings import com.intellij.openapi.extensions.BaseExtensionPointName import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.options.BoundCompositeConfigurable import com.intellij.openapi.options.Configurable.WithEpDependencies import com.intellij.openapi.options.Scheme import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.options.ex.ConfigurableWrapper import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.profile.codeInspection.ui.ErrorOptionsProvider import com.intellij.profile.codeInspection.ui.ErrorOptionsProviderEP import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.layout.* import org.jetbrains.annotations.Contract import javax.swing.DefaultComboBoxModel import javax.swing.JCheckBox // @formatter:off private val codeInsightSettings get() = CodeInsightSettings.getInstance() private val editorSettings get() = EditorSettingsExternalizable.getInstance() private val stripTrailingSpacesProxy get() = StripTrailingSpacesProxy() private val uiSettings get() = UISettings.instance private val richCopySettings get() = RichCopySettings.getInstance() private val codeAnalyzerSettings get() = DaemonCodeAnalyzerSettings.getInstance() @Contract(pure = true) private fun String.capitalizeWords(): String = StringUtil.capitalizeWords(this, true) private val enableWheelFontChange get() = CheckboxDescriptor(if (SystemInfo.isMac) message("checkbox.enable.ctrl.mousewheel.changes.font.size.macos") else message("checkbox.enable.ctrl.mousewheel.changes.font.size"), PropertyBinding(editorSettings::isWheelFontChangeEnabled, editorSettings::setWheelFontChangeEnabled)) private val enableDnD get() = CheckboxDescriptor(message("checkbox.enable.drag.n.drop.functionality.in.editor"), PropertyBinding(editorSettings::isDndEnabled, editorSettings::setDndEnabled)) private val virtualSpace get() = CheckboxDescriptor(message("checkbox.allow.placement.of.caret.after.end.of.line"), PropertyBinding(editorSettings::isVirtualSpace, editorSettings::setVirtualSpace), groupName = message("checkbox.allow.placement.of.caret.label").capitalizeWords()) private val caretInsideTabs get() = CheckboxDescriptor(message("checkbox.allow.placement.of.caret.inside.tabs"), PropertyBinding(editorSettings::isCaretInsideTabs, editorSettings::setCaretInsideTabs), groupName = message("checkbox.allow.placement.of.caret.label").capitalizeWords()) private val virtualPageAtBottom get() = CheckboxDescriptor(message("checkbox.show.virtual.space.at.file.bottom"), PropertyBinding(editorSettings::isAdditionalPageAtBottom, editorSettings::setAdditionalPageAtBottom)) private val highlightBraces get() = CheckboxDescriptor(message("checkbox.highlight.matched.brace"), codeInsightSettings::HIGHLIGHT_BRACES, groupName = message("group.brace.highlighting")) private val highlightScope get() = CheckboxDescriptor(message("checkbox.highlight.current.scope"), codeInsightSettings::HIGHLIGHT_SCOPE, groupName = message("group.brace.highlighting")) private val highlightIdentifierUnderCaret get() = CheckboxDescriptor(message("checkbox.highlight.usages.of.element.at.caret"), codeInsightSettings::HIGHLIGHT_IDENTIFIER_UNDER_CARET, groupName = message("group.brace.highlighting")) private val renameLocalVariablesInplace get() = CheckboxDescriptor(message("radiobutton.rename.local.variables.inplace"), PropertyBinding(editorSettings::isVariableInplaceRenameEnabled, editorSettings::setVariableInplaceRenameEnabled), groupName = message("radiogroup.rename.local.variables").capitalizeWords()) private val preselectCheckBox get() = CheckboxDescriptor(message("checkbox.rename.local.variables.preselect"), PropertyBinding(editorSettings::isPreselectRename, editorSettings::setPreselectRename), groupName = message("group.refactorings")) private val showInlineDialogForCheckBox get() = CheckboxDescriptor(message("checkbox.show.inline.dialog.on.local.variable.references"), PropertyBinding(editorSettings::isShowInlineLocalDialog, editorSettings::setShowInlineLocalDialog)) private val cdSmoothScrolling get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), PropertyBinding(editorSettings::isSmoothScrolling, editorSettings::setSmoothScrolling)) private val cdUseSoftWrapsAtEditor get() = CheckboxDescriptor(message("checkbox.use.soft.wraps.at.editor"), PropertyBinding(editorSettings::isUseSoftWraps, editorSettings::setUseSoftWraps)) private val cdUseCustomSoftWrapIndent get() = CheckboxDescriptor(message("checkbox.use.custom.soft.wraps.indent"), PropertyBinding(editorSettings::isUseCustomSoftWrapIndent, editorSettings::setUseCustomSoftWrapIndent)) private val cdShowSoftWrapsOnlyOnCaretLine get() = CheckboxDescriptor(message("checkbox.show.softwraps.only.for.caret.line"), PropertyBinding({ !editorSettings.isAllSoftWrapsShown }, { editorSettings.setAllSoftwrapsShown(!it) })) private val cdRemoveTrailingBlankLines get() = CheckboxDescriptor(message("editor.options.remove.trailing.blank.lines"), PropertyBinding(editorSettings::isRemoveTrailingBlankLines, editorSettings::setRemoveTrailingBlankLines)) private val cdEnsureBlankLineBeforeCheckBox get() = CheckboxDescriptor(message("editor.options.line.feed"), PropertyBinding(editorSettings::isEnsureNewLineAtEOF, editorSettings::setEnsureNewLineAtEOF)) private val cdShowQuickDocOnMouseMove get() = CheckboxDescriptor(message("editor.options.quick.doc.on.mouse.hover"), PropertyBinding(editorSettings::isShowQuickDocOnMouseOverElement, editorSettings::setShowQuickDocOnMouseOverElement)) private val cdKeepTrailingSpacesOnCaretLine get() = CheckboxDescriptor(message("editor.settings.keep.trailing.spaces.on.caret.line"), PropertyBinding(editorSettings::isKeepTrailingSpacesOnCaretLine, editorSettings::setKeepTrailingSpacesOnCaretLine)) private val cdStripTrailingSpacesEnabled get() = CheckboxDescriptor(message("combobox.strip.trailing.spaces.on.save"), PropertyBinding(stripTrailingSpacesProxy::isEnabled, stripTrailingSpacesProxy::setEnabled)) // @formatter:on internal val optionDescriptors: List<OptionDescription> get() { return sequenceOf( myCbHonorCamelHumpsWhenSelectingByClicking, enableWheelFontChange, enableDnD, virtualSpace, caretInsideTabs, virtualPageAtBottom, highlightBraces, highlightScope, highlightIdentifierUnderCaret, renameLocalVariablesInplace, preselectCheckBox, showInlineDialogForCheckBox ) .map(CheckboxDescriptor::asUiOptionDescriptor) .toList() } private val EP_NAME = ExtensionPointName<GeneralEditorOptionsProviderEP>("com.intellij.generalEditorOptionsExtension") class EditorOptionsPanel : BoundCompositeConfigurable<UnnamedConfigurable>(message("title.editor"), ID), WithEpDependencies { companion object { const val ID = "preferences.editor" private fun clearAllIdentifierHighlighters() { for (project in ProjectManager.getInstance().openProjects) { for (fileEditor in FileEditorManager.getInstance(project).allEditors) { if (fileEditor is TextEditor) { val document = fileEditor.editor.document IdentifierHighlighterPass.clearMyHighlights(document, project) } } } } @JvmStatic fun reinitAllEditors() { EditorFactory.getInstance().refreshAllEditors() } @JvmStatic fun restartDaemons() { for (project in ProjectManager.getInstance().openProjects) { DaemonCodeAnalyzer.getInstance(project).settingsChanged() } } } override fun createConfigurables(): List<UnnamedConfigurable> = ConfigurableWrapper.createConfigurables(EP_NAME) override fun getDependencies(): Collection<BaseExtensionPointName<*>> = setOf(EP_NAME) override fun createPanel(): DialogPanel { lateinit var chkEnableWheelFontSizeChange: JCheckBox return panel { titledRow(message("group.advanced.mouse.usages")) { row { checkBox(enableWheelFontChange).also { chkEnableWheelFontSizeChange = it.component } row { cell { buttonGroup({ editorSettings.isWheelFontChangePersistent }, { editorSettings.isWheelFontChangePersistent = it }) { radioButton(message("radio.enable.ctrl.mousewheel.changes.font.size.current"), false).enableIf(chkEnableWheelFontSizeChange.selected) radioButton(message("radio.enable.ctrl.mousewheel.changes.font.size.all"), true).enableIf(chkEnableWheelFontSizeChange.selected) } } } } row { cell(isFullWidth = true) { checkBox(enableDnD) commentNoWrap(message("checkbox.enable.drag.n.drop.functionality.in.editor.comment")).withLargeLeftGap() } } } titledRow(message("group.soft.wraps")) { row { val useSoftWraps = checkBox(cdUseSoftWrapsAtEditor) textField({ editorSettings.softWrapFileMasks }, { editorSettings.softWrapFileMasks = it }) .growPolicy(GrowPolicy.MEDIUM_TEXT) .applyToComponent { emptyText.text = message("soft.wraps.file.masks.empty.text") } .comment(message("soft.wraps.file.masks.hint"), forComponent = true) .enableIf(useSoftWraps.selected) } row { val useSoftWrapsIndent = checkBox(cdUseCustomSoftWrapIndent) row { cell(isFullWidth = true) { label(message("label.use.custom.soft.wraps.indent")) .enableIf(useSoftWrapsIndent.selected) intTextField(editorSettings::getCustomSoftWrapIndent, editorSettings::setCustomSoftWrapIndent, columns = 2) .enableIf(useSoftWrapsIndent.selected) label(message("label.use.custom.soft.wraps.indent.symbols.suffix")) } } } row { checkBox(cdShowSoftWrapsOnlyOnCaretLine) } } titledRow(message("group.virtual.space")) { row { cell(isFullWidth = true) { label(message("checkbox.allow.placement.of.caret.label")) checkBox(virtualSpace).withLargeLeftGap() checkBox(caretInsideTabs).withLargeLeftGap() } } row { checkBox(virtualPageAtBottom) } } titledRow(message("group.caret.movement")) { row(message("label.word.move.caret.actions.behavior")) { caretStopComboBox(CaretOptionMode.WORD, WordBoundary.values()) } row(message("label.word.move.caret.actions.behavior.at.line.break")) { caretStopComboBox(CaretOptionMode.LINE, LineBoundary.values()) } } titledRow(message("editor.options.scrolling")) { row { checkBox(cdSmoothScrolling) } row { buttonGroup(editorSettings::isRefrainFromScrolling, editorSettings::setRefrainFromScrolling) { checkBoxGroup(message("editor.options.prefer.scrolling.editor.label")) { row { radioButton(message("editor.options.prefer.scrolling.editor.canvas.to.keep.caret.line.centered"), value = false) } row { radioButton(message("editor.options.prefer.moving.caret.line.to.minimize.editor.scrolling"), value = true) } } } } } titledRow(message("group.richcopy")) { row { val copyShortcut = ActionManager.getInstance().getKeyboardShortcut(IdeActions.ACTION_COPY) val copyShortcutText = copyShortcut?.let { " (" + KeymapUtil.getShortcutText(it) + ")" } ?: "" cell(isFullWidth = true) { checkBox(CheckboxDescriptor(message("checkbox.enable.richcopy.label", copyShortcutText), PropertyBinding(richCopySettings::isEnabled, richCopySettings::setEnabled))) commentNoWrap(message("checkbox.enable.richcopy.comment")).withLargeLeftGap() } } row { cell(isFullWidth = true) { label(message("combobox.richcopy.color.scheme")) val schemes = listOf(RichCopySettings.ACTIVE_GLOBAL_SCHEME_MARKER) + EditorColorsManager.getInstance().allSchemes.map { Scheme.getBaseName(it.name) } comboBox<String>( DefaultComboBoxModel(schemes.toTypedArray()), richCopySettings::getSchemeName, richCopySettings::setSchemeName, renderer = SimpleListCellRenderer.create("") { when (it) { RichCopySettings.ACTIVE_GLOBAL_SCHEME_MARKER -> message("combobox.richcopy.color.scheme.active") EditorColorsScheme.DEFAULT_SCHEME_NAME -> EditorColorsScheme.DEFAULT_SCHEME_ALIAS else -> it } } ) } } } titledRow(message("editor.options.save.files.group")) { row { lateinit var stripEnabledBox: CellBuilder<JCheckBox> cell(isFullWidth = true) { stripEnabledBox = checkBox(cdStripTrailingSpacesEnabled) val model = DefaultComboBoxModel( arrayOf( EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED, EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE ) ) comboBox( model, stripTrailingSpacesProxy::getScope, {scope->stripTrailingSpacesProxy.setScope(scope, stripEnabledBox.selected.invoke())}, renderer = SimpleListCellRenderer.create("") { when (it) { EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED -> message("combobox.strip.modified.lines") EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE -> message("combobox.strip.all") else -> it } } ).enableIf(stripEnabledBox.selected) } row { checkBox(cdKeepTrailingSpacesOnCaretLine) .enableIf(stripEnabledBox.selected) largeGapAfter() } } row { checkBox(cdRemoveTrailingBlankLines) } row { checkBox(cdEnsureBlankLineBeforeCheckBox) } } for (configurable in configurables) { appendDslConfigurableRow(configurable) } } } override fun apply() { val wasModified = isModified super.apply() if (wasModified) { clearAllIdentifierHighlighters() reinitAllEditors() uiSettings.fireUISettingsChanged() restartDaemons() ApplicationManager.getApplication().messageBus.syncPublisher(EditorOptionsListener.OPTIONS_PANEL_TOPIC).changesApplied() } } } class EditorCodeEditingConfigurable : BoundCompositeConfigurable<ErrorOptionsProvider>(message("title.code.editing"), ID), WithEpDependencies { companion object { const val ID = "preferences.editor.code.editing" } override fun createConfigurables() = ConfigurableWrapper.createConfigurables(ErrorOptionsProviderEP.EP_NAME) override fun getDependencies() = setOf(ErrorOptionsProviderEP.EP_NAME) override fun createPanel(): DialogPanel { return panel { titledRow(message("group.brace.highlighting")) { row { checkBox(highlightBraces) } row { checkBox(highlightScope) } row { checkBox(highlightIdentifierUnderCaret) } } titledRow(message("group.quick.documentation")) { row { checkBox(cdShowQuickDocOnMouseMove) } } if (!EditorOptionsPageCustomizer.EP_NAME.extensions().anyMatch { it.shouldHideRefactoringsSection() }) { titledRow(message("group.refactorings")) { row { buttonGroup(editorSettings::isVariableInplaceRenameEnabled, editorSettings::setVariableInplaceRenameEnabled) { checkBoxGroup(message("radiogroup.rename.local.variables")) { row { radioButton(message("radiobutton.rename.local.variables.inplace"), value = true) } row { radioButton(message("radiobutton.rename.local.variables.in.dialog"), value = false) }.largeGapAfter() } } } row { checkBox(preselectCheckBox) } row { checkBox(showInlineDialogForCheckBox) } } } titledRow(message("group.error.highlighting")) { row { cell(isFullWidth = true) { label(message("editbox.error.stripe.mark.min.height")) intTextField(codeAnalyzerSettings::getErrorStripeMarkMinHeight, codeAnalyzerSettings::setErrorStripeMarkMinHeight, columns = 4) label(message("editbox.error.stripe.mark.min.height.pixels.suffix")) } } row { cell(isFullWidth = true) { label(message("editbox.autoreparse.delay")) intTextField(codeAnalyzerSettings::getAutoReparseDelay, codeAnalyzerSettings::setAutoReparseDelay, columns = 4) label(message("editbox.autoreparse.delay.ms.suffix")) } } row { cell(isFullWidth = true) { label(message("combobox.next.error.action.goes.to.label")) comboBox( DefaultComboBoxModel(arrayOf(true, false)), codeAnalyzerSettings::isNextErrorActionGoesToErrorsFirst, { codeAnalyzerSettings.isNextErrorActionGoesToErrorsFirst = it ?: true }, renderer = SimpleListCellRenderer.create("") { when (it) { true -> message("combobox.next.error.action.goes.to.errors") false -> message("combobox.next.error.action.goes.to.all.problems") else -> it.toString() } } ) } } for (configurable in configurables) { appendDslConfigurableRow(configurable) } } titledRow(message("group.editor.tooltips")) { row { cell(isFullWidth = true) { label(message("editor.options.tooltip.delay")) intTextField(editorSettings::getTooltipsDelay, editorSettings::setTooltipsDelay, range = TOOLTIPS_DELAY_RANGE.asRange(), columns = 4) label(message("editor.options.ms")) } } } } } } private fun <E : EditorCaretStopPolicyItem> Cell.caretStopComboBox(mode: CaretOptionMode, values: Array<E>): CellBuilder<ComboBox<E?>> { val model: DefaultComboBoxModel<E?> = SeparatorAwareComboBoxModel() var lastWasOsDefault = false for (item in values) { val isOsDefault = item.osDefault !== OsDefault.NONE if (lastWasOsDefault && !isOsDefault) model.addElement(null) lastWasOsDefault = isOsDefault val insertionIndex = if (item.osDefault.isIdeDefault) 0 else model.size model.insertElementAt(item, insertionIndex) } return component(ComboBox(model)) .applyToComponent { renderer = SeparatorAwareListItemRenderer() } .sizeGroup("caretStopComboBox") .withBinding( { val item = it.selectedItem as? EditorCaretStopPolicyItem item?.caretStopBoundary ?: mode.get(CaretStopOptionsTransposed.DEFAULT) }, { it, value -> it.selectedItem = mode.find(value) }, PropertyBinding( { val value = fromCaretStopOptions(editorSettings.caretStopOptions) mode.get(value) }, { val value = fromCaretStopOptions(editorSettings.caretStopOptions) editorSettings.caretStopOptions = mode.update(value, it).toCaretStopOptions() } ) ) } private class StripTrailingSpacesProxy { private val editorSettings = EditorSettingsExternalizable.getInstance() private var lastChoice: String? = getScope() fun isEnabled(): Boolean = EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE == editorSettings.stripTrailingSpaces || EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED == editorSettings.stripTrailingSpaces fun setEnabled(enable: Boolean) { if (enable != isEnabled()) { when { enable -> editorSettings.stripTrailingSpaces = lastChoice else -> { lastChoice = editorSettings.stripTrailingSpaces editorSettings.stripTrailingSpaces = EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE } } } } fun getScope(): String = when (editorSettings.stripTrailingSpaces) { EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE -> { val currChoice = lastChoice when { currChoice != null -> currChoice else -> EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED } } else -> editorSettings.stripTrailingSpaces } fun setScope(scope: String?, enabled: Boolean) = when { enabled -> editorSettings.stripTrailingSpaces = scope else -> setEnabled(false) } } private enum class CaretOptionMode { WORD { override fun find(boundary: CaretStopBoundary): WordBoundary = WordBoundary.itemForBoundary(boundary) override fun get(option: CaretStopOptionsTransposed): CaretStopBoundary = option.wordBoundary override fun update(option: CaretStopOptionsTransposed, value: CaretStopBoundary): CaretStopOptionsTransposed = CaretStopOptionsTransposed(value, option.lineBoundary) }, LINE { override fun find(boundary: CaretStopBoundary): LineBoundary = LineBoundary.itemForBoundary(boundary) override fun get(option: CaretStopOptionsTransposed): CaretStopBoundary = option.lineBoundary override fun update(option: CaretStopOptionsTransposed, value: CaretStopBoundary): CaretStopOptionsTransposed = CaretStopOptionsTransposed(option.wordBoundary, value) }; abstract fun find(boundary: CaretStopBoundary): EditorCaretStopPolicyItem abstract fun get(option: CaretStopOptionsTransposed): CaretStopBoundary abstract fun update(option: CaretStopOptionsTransposed, value: CaretStopBoundary): CaretStopOptionsTransposed }
apache-2.0
a2f192905cea9b0ab9c109f16f05e969
51.188437
355
0.699233
4.978754
false
false
false
false
jwren/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageSvgPreCompiler.kt
2
15478
// 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. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.images import com.intellij.openapi.util.text.Formats import com.intellij.ui.svg.ImageValue import com.intellij.ui.svg.SvgCacheManager import com.intellij.ui.svg.SvgTranscoder import com.intellij.ui.svg.createSvgDocument import com.intellij.util.io.DigestUtil import io.opentelemetry.api.GlobalOpenTelemetry import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import org.apache.batik.transcoder.TranscoderException import org.jetbrains.ikv.builder.IkvWriter import org.jetbrains.ikv.builder.sizeUnawareIkvWriter import org.jetbrains.intellij.build.io.ByteBufferAllocator import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.mvstore.DataUtil import org.jetbrains.mvstore.MVMap import org.jetbrains.mvstore.type.IntDataType import java.awt.image.BufferedImage import java.awt.image.DataBufferInt import java.nio.ByteBuffer import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.NotDirectoryException import java.nio.file.Path import java.util.concurrent.Callable import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ForkJoinTask import java.util.concurrent.atomic.AtomicInteger import kotlin.system.exitProcess private class FileInfo(val file: Path) { companion object { fun digest(file: Path) = digest(loadAndNormalizeSvgFile(file).toByteArray()) fun digest(fileNormalizedData: ByteArray): ByteArray = DigestUtil.sha512().digest(fileNormalizedData) } val checksum: ByteArray by lazy(LazyThreadSafetyMode.PUBLICATION) { digest(file) } } /** * Works together with [SvgCacheManager] to generate pre-cached icons */ internal class ImageSvgPreCompiler(private val compilationOutputRoot: Path? = null) { /// the 4.0 scale is used on retina macOS for product icon, adds few more scales for few icons //private val productIconScales = (scales + scales.map { it * 2 }).toSortedSet().toFloatArray() //private val productIconPrefixes = mutableListOf<String>() private val totalFiles = AtomicInteger(0) private val totalSize = AtomicInteger(0) companion object { @JvmStatic fun main(args: Array<String>) { try { mainImpl(args) } catch (e: Throwable) { System.err.println("Unexpected crash: ${e.message}") e.printStackTrace(System.err) exitProcess(1) } exitProcess(0) } @JvmStatic fun optimize(dbDir: Path, compilationOutputRoot: Path, dirs: List<Path>): List<Path> { return ImageSvgPreCompiler(compilationOutputRoot).compileIcons(dbDir, dirs) } private fun mainImpl(args: Array<String>) { println("Pre-building SVG images...") if (args.isEmpty()) { println("Usage: <tool> dbFile tasks_file product_icons*") println("") println("tasks_file: list of paths, every path on a new line: {<input dir>\\n}+") println("") exitProcess(1) } System.setProperty("java.awt.headless", "true") val dbDir = args.getOrNull(0) ?: error("only one parameter is supported") val argsFile = args.getOrNull(1) ?: error("only one parameter is supported") val dirs = Files.readAllLines(Path.of(argsFile)).map { Path.of(it) } val productIcons = args.drop(2).toSortedSet() println("Expecting product icons: $productIcons") val compiler = ImageSvgPreCompiler() // todo //productIcons.forEach(compiler::addProductIconPrefix) compiler.compileIcons(Path.of(dbDir), dirs) } } fun preCompileIcons(modules: List<JpsModule>, dbFile: Path) { val javaExtensionService = JpsJavaExtensionService.getInstance() compileIcons(dbFile, modules.mapNotNull { javaExtensionService.getOutputDirectory(it, false)?.toPath() }) } @Suppress("PropertyName") private class Stores(classifier: String, dbDir: Path) { val s1 = StoreContainer(1f, classifier, dbDir) val s1_25 = StoreContainer(1.25f, classifier, dbDir) val s1_5 = StoreContainer(1.5f, classifier, dbDir) val s2 = StoreContainer(2f, classifier, dbDir) val s2_5 = StoreContainer(2.5f, classifier, dbDir) fun close(list: MutableList<Path>) { s1.close() s1_25.close() s1_5.close() s2.close() s2_5.close() s1.file?.let { list.add(it) } s1_25.file?.let { list.add(it) } s1_5.file?.let { list.add(it) } s2.file?.let { list.add(it) } s2_5.file?.let { list.add(it) } } } private class StoreContainer(private val scale: Float, private val classifier: String, private val dbDir: Path) { @Volatile private var store: IkvWriter? = null var file: Path? = null private set fun getOrCreate() = store ?: getSynchronized() @Synchronized private fun getSynchronized(): IkvWriter { var store = store if (store == null) { val file = dbDir.resolve("icons-v1-$scale$classifier.db") this.file = file store = sizeUnawareIkvWriter(file) this.store = store } return store } fun close() { store?.close() } } fun compileIcons(dbDir: Path, dirs: List<Path>): List<Path> { Files.createDirectories(dbDir) val lightStores = Stores("", dbDir) val darkStores = Stores("-d", dbDir) val resultFiles = ArrayList<Path>() try { val mapBuilder = MVMap.Builder<Int, ImageValue>() mapBuilder.keyType(IntDataType.INSTANCE) mapBuilder.valueType(ImageValue.ImageValueSerializer()) val getMapByScale: (scale: Float, isDark: Boolean) -> IkvWriter = { scale, isDark -> val list = if (isDark) darkStores else lightStores when (scale) { 1f -> list.s1.getOrCreate() 1.25f -> list.s1_25.getOrCreate() 1.5f -> list.s1_5.getOrCreate() 2f -> list.s2.getOrCreate() 2.5f -> list.s2_5.getOrCreate() else -> throw UnsupportedOperationException("Scale $scale is not supported") } } val rootRobotData = IconRobotsData(parent = null, ignoreSkipTag = false, usedIconsRobots = null) val result = ForkJoinTask.invokeAll(dirs.map { dir -> ForkJoinTask.adapt(Callable { val result = mutableListOf<IconData>() processDir(dir, dir, 1, rootRobotData, result) result }) }).flatMap { it.rawResult } val array: Array<IconData?> = result.toTypedArray() array.sortBy { it!!.variants.first() } /// the expected scales of images that we have /// the macOS touch bar uses 2.5x scale /// the application icon (which one?) is 4x on macOS val scales = floatArrayOf( 1f, 1.25f, /*Windows*/ 1.5f, /*Windows*/ 2.0f, 2.5f /*macOS touchBar*/ ) val collisionGuard = ConcurrentHashMap<Int, FileInfo>() for ((index, icon) in array.withIndex()) { // key is the same for all variants // check collision only here - after sorting (so, we produce stable results as we skip same icon every time) if (checkCollision(icon!!.imageKey, icon.variants[0], icon.light1xData, collisionGuard)) { array[index] = null } } ForkJoinTask.invokeAll(scales.map { scale -> ForkJoinTask.adapt { ByteBufferAllocator().use { bufferAllocator -> for (icon in array) { processImage(icon = icon ?: continue, getMapByScale = getMapByScale, scale = scale, bufferAllocator = bufferAllocator) } } } }) //println("${Formats.formatFileSize(totalSize.get().toLong())} (${totalSize.get()}, iconCount=${totalFiles.get()}, resultSize=${result.size})") } catch (e: Throwable) { try { lightStores.close(resultFiles) darkStores.close(resultFiles) } catch (e1: Throwable) { e.addSuppressed(e) } throw e } val span = GlobalOpenTelemetry.getTracer("build-script") .spanBuilder("close rasterized SVG database") .setAttribute("path", dbDir.toString()) .setAttribute(AttributeKey.longKey("iconCount"), totalFiles.get().toLong()) .startSpan() try { lightStores.close(resultFiles) darkStores.close(resultFiles) span.setAttribute(AttributeKey.stringKey("fileSize"), Formats.formatFileSize(totalSize.get().toLong())) } finally { span.end() } resultFiles.sort() return resultFiles } private class IconData(val light1xData: ByteArray, val variants: List<Path>, val imageKey: Int) private fun processDir(dir: Path, rootDir: Path, level: Int, rootRobotData: IconRobotsData, result: MutableCollection<IconData>) { val stream = try { Files.newDirectoryStream(dir) } catch (e: NotDirectoryException) { return } catch (e: NoSuchFileException) { return } val idToVariants = stream.use { var idToVariants: MutableMap<String, MutableList<Path>>? = null val robotData = rootRobotData.fork(dir, dir) for (file in stream) { val fileName = file.fileName.toString() if (level == 1) { if (isBlacklistedTopDirectory(fileName)) { continue } } if (robotData.isSkipped(file)) { continue } if (fileName.endsWith(".svg")) { if (idToVariants == null) { idToVariants = HashMap() } idToVariants.computeIfAbsent(getImageCommonName(fileName)) { mutableListOf() }.add(file) } else if (!fileName.endsWith(".class")) { processDir(file, rootDir, level + 1, rootRobotData.fork(file, rootDir), result) } } idToVariants ?: return } val keys = idToVariants.keys.toTypedArray() keys.sort() for (commonName in keys) { val variants = idToVariants.get(commonName)!! variants.sort() val light1x = variants[0] val light1xPath = light1x.toString() if (light1xPath.endsWith("@2x.svg") || light1xPath.endsWith("_dark.svg")) { throw IllegalStateException("$light1x doesn't have 1x light icon") } val light1xData = loadAndNormalizeSvgFile(light1x) if (light1xData.contains("data:image")) { Span.current().addEvent("image $light1x uses data urls and will be skipped") continue } val light1xBytes = light1xData.toByteArray() val imageKey = getImageKey(light1xBytes, light1x.fileName.toString()) totalFiles.addAndGet(variants.size) try { result.add(IconData(light1xBytes, variants, imageKey)) } catch (e: TranscoderException) { throw RuntimeException("Cannot process $commonName (variants=$variants)", e) } } } private fun processImage(icon: IconData, getMapByScale: (scale: Float, isDark: Boolean) -> IkvWriter, scale: Float, bufferAllocator: ByteBufferAllocator) { //println("$id: ${variants.joinToString { rootDir.relativize(it).toString() }}") val variants = icon.variants // key is the same for all variants val imageKey = icon.imageKey val light2x = variants.find { it.toString().endsWith("@2x.svg") } var document = if (scale >= 2 && light2x != null) { createSvgDocument(null, Files.newInputStream(light2x)) } else { createSvgDocument(null, icon.light1xData) } addEntry(getMapByScale(scale, false), SvgTranscoder.createImage(scale, document, null), imageKey, totalSize, bufferAllocator) val dark2x = variants.find { it.toString().endsWith("@2x_dark.svg") } val dark1x = variants.find { it !== dark2x && it.toString().endsWith("_dark.svg") } ?: return document = createSvgDocument(null, Files.newInputStream(if (scale >= 2 && dark2x != null) dark2x else dark1x)) val image = SvgTranscoder.createImage(scale, document, null) addEntry(getMapByScale(scale, true), image, imageKey, totalSize, bufferAllocator) } private fun checkCollision(imageKey: Int, file: Path, fileNormalizedData: ByteArray, collisionGuard: ConcurrentHashMap<Int, FileInfo>): Boolean { val duplicate = collisionGuard.putIfAbsent(imageKey, FileInfo(file)) if (duplicate == null) { return false } if (duplicate.checksum.contentEquals(FileInfo.digest(fileNormalizedData))) { assert(duplicate.file !== file) Span.current().addEvent("${getRelativeToCompilationOutPath(duplicate.file)} duplicates ${getRelativeToCompilationOutPath(file)}") //println("${getRelativeToCompilationOutPath(duplicate.file)} duplicates ${getRelativeToCompilationOutPath(file)}") // skip - do not add return true } throw IllegalStateException("Hash collision:\n file1=${duplicate.file},\n file2=${file},\n imageKey=$imageKey") } private fun getRelativeToCompilationOutPath(file: Path): Path { if (compilationOutputRoot != null && file.startsWith(compilationOutputRoot)) { return compilationOutputRoot.relativize(file) } else { return file } } } private fun addEntry(map: IkvWriter, image: BufferedImage, imageKey: Int, totalSize: AtomicInteger, bufferAllocator: ByteBufferAllocator) { val w = image.width val h = image.height assert(image.type == BufferedImage.TYPE_INT_ARGB) assert(!image.colorModel.isAlphaPremultiplied) val data = (image.raster.dataBuffer as DataBufferInt).data val buffer = bufferAllocator.allocate(DataUtil.VAR_INT_MAX_SIZE * 2 + data.size * Int.SIZE_BYTES + 1) if (w == h) { if (w < 254) { buffer.put(w.toByte()) } else { buffer.put(255.toByte()) writeVar(buffer, w) } } else { buffer.put(254.toByte()) writeVar(buffer, w) writeVar(buffer, h) } buffer.asIntBuffer().put(data) buffer.position(buffer.position() + (data.size * Int.SIZE_BYTES)) buffer.flip() totalSize.addAndGet(buffer.remaining()) map.write(imageKey, buffer) } private fun writeVar(buf: ByteBuffer, value: Int) { if (value ushr 7 == 0) { buf.put(value.toByte()) } else if (value ushr 14 == 0) { buf.put((value and 127 or 128).toByte()) buf.put((value ushr 7).toByte()) } else if (value ushr 21 == 0) { buf.put((value and 127 or 128).toByte()) buf.put((value ushr 7 or 128).toByte()) buf.put((value ushr 14).toByte()) } else if (value ushr 28 == 0) { buf.put((value and 127 or 128).toByte()) buf.put((value ushr 7 or 128).toByte()) buf.put((value ushr 14 or 128).toByte()) buf.put((value ushr 21).toByte()) } else { buf.put((value and 127 or 128).toByte()) buf.put((value ushr 7 or 128).toByte()) buf.put((value ushr 14 or 128).toByte()) buf.put((value ushr 21 or 128).toByte()) buf.put((value ushr 28).toByte()) } } private fun getImageCommonName(fileName: String): String { for (p in listOf("@2x.svg", "@2x_dark.svg", "_dark.svg", ".svg")) { if (fileName.endsWith(p)) { return fileName.substring(0, fileName.length - p.length) } } throw IllegalStateException("Not a SVG: $fileName") }
apache-2.0
82025ad8eb2f3a715f763ed8b65d00e7
33.397778
158
0.655188
3.971773
false
false
false
false
jwren/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/refactorings/PythonRenameLesson.kt
5
6365
// 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.jetbrains.python.ift.lesson.refactorings import com.intellij.ide.DataManager import com.intellij.ide.actions.exclusion.ExclusionHandler import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.ui.tree.TreeVisitor import com.intellij.usageView.UsageViewBundle import com.intellij.util.ui.tree.TreeUtil import com.jetbrains.python.ift.PythonLessonsBundle import org.assertj.swing.fixture.JTreeFixture import training.dsl.* import training.learn.LessonsBundle import training.learn.course.KLesson import training.util.isToStringContains import javax.swing.JButton import javax.swing.JTree import javax.swing.tree.TreePath class PythonRenameLesson : KLesson("Rename", LessonsBundle.message("rename.lesson.name")) { override val testScriptProperties = TaskTestContext.TestScriptProperties(10) private val template = """ class Championship: def __init__(self): self.<name> = 0 def matches_count(self): return self.<name> * (self.<name> - 1) / 2 def add_new_team(self): self.<name> += 1 def team_matches(champ): champ.<name>() - 1 class Company: def __init__(self, t): self.teams = t def company_members(company): map(lambda team : team.name, company.teams) def teams(): return 16 c = Championship() c.<caret><name> = teams() print(c.<name>) """.trimIndent() + '\n' private val sample = parseLessonSample(template.replace("<name>", "teams")) override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) val dynamicWord = UsageViewBundle.message("usage.view.results.node.dynamic") var replace: String? = null var dynamicItem: String? = null task("RenameElement") { text(PythonLessonsBundle.message("python.rename.press.rename", action(it), code("teams"), code("teams_number"))) triggerUI().component { ui: NameSuggestionsField -> ui.addDataChangedListener { replace = ui.enteredName } true } triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> val pathStr = path.getPathComponent(1).toString() if (path.pathCount == 2 && pathStr.contains(dynamicWord)) { dynamicItem = pathStr true } else false } test { actions(it) dialog { type("teams_number") button("Refactor").click() } } } task { // Increase deterministic: collapse nodes before { (previous.ui as? JTree)?.let { tree -> TreeUtil.collapseAll(tree, 1) } } val dynamicReferencesString = "[$dynamicWord]" text(PythonLessonsBundle.message("python.rename.expand.dynamic.references", code("teams"), strong(dynamicReferencesString))) triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> path.pathCount == 6 && path.getPathComponent(5).isToStringContains("company_members") } showWarningIfFindToolbarClosed() test { //TODO: Fix tree access val jTree = previous.ui as? JTree ?: return@test val di = dynamicItem ?: return@test ideFrame { val jTreeFixture = JTreeFixture(robot, jTree) jTreeFixture.replaceSeparator("@@@") jTreeFixture.expandPath(di) // WARNING: several exception will be here because of UsageNode#toString inside info output during this operation } } } task { text(PythonLessonsBundle.message("python.rename.exclude.item", code("company_members"), action("EditorDelete"))) stateCheck { val tree = previous.ui as? JTree ?: return@stateCheck false val last = pathToExclude(tree) ?: return@stateCheck false val dataContext = DataManager.getInstance().getDataContext(tree) val exclusionProcessor: ExclusionHandler<*> = ExclusionHandler.EXCLUSION_HANDLER.getData(dataContext) ?: return@stateCheck false val leafToBeExcluded = last.lastPathComponent @Suppress("UNCHECKED_CAST") fun <T : Any?> castHack(processor: ExclusionHandler<T>): Boolean { return processor.isNodeExclusionAvailable(leafToBeExcluded as T) && processor.isNodeExcluded(leafToBeExcluded as T) } castHack(exclusionProcessor) } showWarningIfFindToolbarClosed() test { ideFrame { type("come") invokeActionViaShortcut("DELETE") } } } val confirmRefactoringButton = RefactoringBundle.message("usageView.doAction").dropMnemonic() task { triggerAndBorderHighlight().component { button: JButton -> button.text.isToStringContains(confirmRefactoringButton) } } task { val result = replace?.let { template.replace("<name>", it).replace("<caret>", "") } text(PythonLessonsBundle.message("python.rename.finish.refactoring", strong(confirmRefactoringButton))) stateCheck { editor.document.text == result } showWarningIfFindToolbarClosed() test(waitEditorToBeReady = false) { ideFrame { button(confirmRefactoringButton).click() } } } } private fun pathToExclude(tree: JTree): TreePath? { return TreeUtil.promiseVisit(tree, TreeVisitor { path -> if (path.pathCount == 7 && path.getPathComponent(6).isToStringContains("lambda")) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }).blockingGet(200) } private fun TaskContext.showWarningIfFindToolbarClosed() { showWarning(PythonLessonsBundle.message("python.rename.find.window.closed.warning", action("ActivateFindToolWindow")), restoreTaskWhenResolved = true) { previous.ui?.isShowing != true } } override val suitableTips = listOf("Rename") override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("rename.help.link"), LessonUtil.getHelpLink("rename-refactorings.html")), ) }
apache-2.0
2f33ab04f2796f63fe5e57717f297ee2
34.165746
140
0.652632
4.72181
false
false
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/translators/CircularProgressIndicatorTranslator.kt
3
2231
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.translators import android.os.Build import android.widget.RemoteViews import androidx.glance.appwidget.LayoutType import androidx.glance.appwidget.TranslationContext import androidx.glance.appwidget.applyModifiers import androidx.glance.appwidget.insertView import androidx.core.widget.RemoteViewsCompat.setProgressBarIndeterminateTintList import androidx.compose.ui.graphics.toArgb import android.content.res.ColorStateList import androidx.glance.unit.FixedColorProvider import androidx.glance.unit.ResourceColorProvider import androidx.glance.appwidget.EmittableCircularProgressIndicator internal fun RemoteViews.translateEmittableCircularProgressIndicator( translationContext: TranslationContext, element: EmittableCircularProgressIndicator ) { val viewDef = insertView(translationContext, LayoutType.CircularProgressIndicator, element.modifier) setProgressBar(viewDef.mainViewId, 0, 0, true) if (Build.VERSION.SDK_INT >= 31) { when (val indicatorColor = element.color) { is FixedColorProvider -> { setProgressBarIndeterminateTintList( viewId = viewDef.mainViewId, tint = ColorStateList.valueOf(indicatorColor.color.toArgb()) ) } is ResourceColorProvider -> { setProgressBarIndeterminateTintList( viewId = viewDef.mainViewId, tint = ColorStateList.valueOf(indicatorColor.resId) ) } } } applyModifiers(translationContext, this, element.modifier, viewDef) }
apache-2.0
3896892a0cfdb6b6c914ce0596f9e0d5
37.465517
81
0.738682
4.881838
false
false
false
false
androidx/androidx
fragment/integration-tests/testapp/src/main/java/androidx/fragment/testapp/kittenfragmenttransitions/DetailsFragment.kt
3
2328
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.testapp.kittenfragmenttransitions import android.os.Bundle import android.view.View import android.widget.ImageView import androidx.annotation.IntRange import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.testapp.R /** * Display details for a given kitten */ class DetailsFragment : Fragment(R.layout.kitten_details_fragment) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val image = view.findViewById<ImageView>(R.id.image) val args = arguments val kittenNumber = when { args == null -> 0 args.containsKey(ARG_KITTEN_NUMBER) -> args.getInt(ARG_KITTEN_NUMBER) else -> 1 } when (kittenNumber) { 1 -> image.setImageResource(R.drawable.placekitten_1) 2 -> image.setImageResource(R.drawable.placekitten_2) 3 -> image.setImageResource(R.drawable.placekitten_3) 4 -> image.setImageResource(R.drawable.placekitten_4) 5 -> image.setImageResource(R.drawable.placekitten_5) 6 -> image.setImageResource(R.drawable.placekitten_6) } } companion object { private const val ARG_KITTEN_NUMBER = "argKittenNumber" /** * Create a new DetailsFragment * * @param kittenNumber The number (between 1 and 6) of the kitten to display */ @JvmStatic fun newInstance(@IntRange(from = 1, to = 6) kittenNumber: Int) = DetailsFragment().apply { arguments = bundleOf(ARG_KITTEN_NUMBER to kittenNumber) } } }
apache-2.0
dec1ce2a2c877227d807ad9e152d1a98
35.952381
84
0.67311
4.202166
false
false
false
false
robfletcher/keiko
keiko-mem/src/main/kotlin/com/netflix/spinnaker/q/memory/InMemoryQueue.kt
1
5563
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.q.memory import com.netflix.spinnaker.q.DeadMessageCallback import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.q.metrics.EventPublisher import com.netflix.spinnaker.q.metrics.MessageAcknowledged import com.netflix.spinnaker.q.metrics.MessageDead import com.netflix.spinnaker.q.metrics.MessageDuplicate import com.netflix.spinnaker.q.metrics.MessageProcessing import com.netflix.spinnaker.q.metrics.MessagePushed import com.netflix.spinnaker.q.metrics.MessageRetried import com.netflix.spinnaker.q.metrics.MonitorableQueue import com.netflix.spinnaker.q.metrics.QueuePolled import com.netflix.spinnaker.q.metrics.QueueState import com.netflix.spinnaker.q.metrics.RetryPolled import com.netflix.spinnaker.q.metrics.fire import org.slf4j.Logger import org.slf4j.LoggerFactory.getLogger import org.springframework.scheduling.annotation.Scheduled import org.threeten.extra.Temporals.chronoUnit import java.time.Clock import java.time.Duration import java.time.Instant import java.time.temporal.TemporalAmount import java.util.UUID import java.util.UUID.randomUUID import java.util.concurrent.DelayQueue import java.util.concurrent.Delayed import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.TimeUnit.NANOSECONDS class InMemoryQueue( private val clock: Clock, override val ackTimeout: TemporalAmount = Duration.ofMinutes(1), override val deadMessageHandlers: List<DeadMessageCallback>, override val publisher: EventPublisher ) : MonitorableQueue { private val log: Logger = getLogger(javaClass) private val queue = DelayQueue<Envelope>() private val unacked = DelayQueue<Envelope>() override fun poll(callback: (Message, () -> Unit) -> Unit) { fire(QueuePolled) queue.poll()?.let { envelope -> val messageAckTimeout = if (envelope.payload.ackTimeoutMs == null) { ackTimeout } else { Duration.ofMillis(envelope.payload.ackTimeoutMs as Long) } unacked.put(envelope.copy(scheduledTime = clock.instant().plus(messageAckTimeout))) fire(MessageProcessing(envelope.payload, envelope.scheduledTime, clock.instant())) callback.invoke(envelope.payload) { ack(envelope.id) fire(MessageAcknowledged) } } } override fun push(message: Message, delay: TemporalAmount) { val existed = queue.removeIf { it.payload == message } queue.put(Envelope(message, clock.instant().plus(delay), clock)) if (existed) { fire(MessageDuplicate(message)) } else { fire(MessagePushed(message)) } } override fun reschedule(message: Message, delay: TemporalAmount) { val existed = queue.removeIf { it.payload == message } if (existed) { queue.put(Envelope(message, clock.instant().plus(delay), clock)) } } override fun ensure(message: Message, delay: TemporalAmount) { if (queue.none { it.payload == message } && unacked.none { it.payload == message }) { push(message, delay) } } @Scheduled(fixedDelayString = "\${queue.retry.frequency.ms:10000}") override fun retry() { val now = clock.instant() fire(RetryPolled) unacked.pollAll { message -> if (message.count >= Queue.maxRetries) { deadMessageHandlers.forEach { it.invoke(this, message.payload) } fire(MessageDead) } else { val existed = queue.removeIf { it.payload == message.payload } log.warn("redelivering unacked message ${message.payload}") queue.put(message.copy(scheduledTime = now, count = message.count + 1)) if (existed) { fire(MessageDuplicate(message.payload)) } else { fire(MessageRetried) } } } } override fun readState() = QueueState( depth = queue.size, ready = queue.count { it.getDelay(NANOSECONDS) <= 0 }, unacked = unacked.size ) override fun containsMessage(predicate: (Message) -> Boolean): Boolean = queue.map(Envelope::payload).any(predicate) private fun ack(messageId: UUID) { unacked.removeIf { it.id == messageId } } private fun <T : Delayed> DelayQueue<T>.pollAll(block: (T) -> Unit) { var done = false while (!done) { val value = poll() if (value == null) { done = true } else { block.invoke(value) } } } } internal data class Envelope( val id: UUID, val payload: Message, val scheduledTime: Instant, val clock: Clock, val count: Int = 1 ) : Delayed { constructor(payload: Message, scheduledTime: Instant, clock: Clock) : this(randomUUID(), payload, scheduledTime, clock) override fun compareTo(other: Delayed) = getDelay(MILLISECONDS).compareTo(other.getDelay(MILLISECONDS)) override fun getDelay(unit: TimeUnit) = clock.instant().until(scheduledTime, unit.toChronoUnit()) } private fun TimeUnit.toChronoUnit() = chronoUnit(this)
apache-2.0
b16cc28c003b65397e80339a4d40e801
31.91716
89
0.714183
3.970735
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/smart/ClassLiteralItems.kt
4
3923
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.smart import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.completion.BasicLookupElementFactory import org.jetbrains.kotlin.idea.completion.createLookupElementForType import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.core.fuzzyType import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import java.util.* object ClassLiteralItems { fun addToCollection( collection: MutableCollection<LookupElement>, expectedInfos: Collection<ExpectedInfo>, lookupElementFactory: BasicLookupElementFactory, isJvmModule: Boolean ) { val typeAndSuffixToExpectedInfos = LinkedHashMap<Pair<KotlinType, String>, MutableList<ExpectedInfo>>() for (expectedInfo in expectedInfos) { val fuzzyType = expectedInfo.fuzzyType ?: continue if (fuzzyType.freeParameters.isNotEmpty()) continue val typeConstructor = fuzzyType.type.constructor val klass = typeConstructor.declarationDescriptor as? ClassDescriptor ?: continue val typeArgument = fuzzyType.type.arguments.singleOrNull() ?: continue if (typeArgument.projectionKind != Variance.INVARIANT) continue if (KotlinBuiltIns.isKClass(klass)) { typeAndSuffixToExpectedInfos.getOrPut(typeArgument.type to "::class") { ArrayList() }.add(expectedInfo) } if (isJvmModule && klass.importableFqName?.asString() == "java.lang.Class") { typeAndSuffixToExpectedInfos.getOrPut(typeArgument.type to "::class.java") { ArrayList() }.add(expectedInfo) } } for ((pair, matchedExpectedInfos) in typeAndSuffixToExpectedInfos) { val (type, suffix) = pair val typeToUse = if (KotlinBuiltIns.isArray(type)) { type.makeNotNullable() } else { val classifier = (type.constructor.declarationDescriptor as? ClassDescriptor) ?: continue classifier.defaultType } var lookupElement = lookupElementFactory.createLookupElementForType(typeToUse) ?: continue lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) presentation.itemText += suffix } override fun handleInsert(context: InsertionContext) { super.handleInsert(context) PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(context.document) val offset = context.tailOffset context.document.insertString(offset, suffix) context.editor.moveCaret(offset + suffix.length) } } lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CLASS_LITERAL) lookupElement = lookupElement.addTailAndNameSimilarity(matchedExpectedInfos, emptyList()) collection.add(lookupElement) } } }
apache-2.0
b23a530c021e84261f672b25b2fe6929
47.444444
158
0.706092
5.596291
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vscode/parsers/GeneralSettingsParser.kt
2
2802
package com.intellij.ide.customize.transferSettings.providers.vscode.parsers import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.JsonNodeType import com.fasterxml.jackson.databind.node.ObjectNode import com.intellij.ide.customize.transferSettings.db.KnownLafs import com.intellij.ide.customize.transferSettings.models.ILookAndFeel import com.intellij.ide.customize.transferSettings.models.Settings import com.intellij.ide.customize.transferSettings.models.SystemDarkThemeDetectorLookAndFeel import com.intellij.ide.customize.transferSettings.providers.vscode.mappings.ThemesMappings import com.intellij.openapi.diagnostic.logger import java.io.File private val logger = logger<GeneralSettingsParser>() class GeneralSettingsParser(private val settings: Settings) { companion object { private const val COLOR_THEME = "workbench.colorTheme" private const val AUTODETECT_THEME = "window.autoDetectColorScheme" private const val PREFERRED_DARK_THEME = "workbench.preferredDarkColorTheme" private const val PREFERRED_LIGHT_THEME = "workbench.preferredLightColorTheme" } fun process(file: File) = try { logger.info("Processing a general settings file: $file") val root = ObjectMapper(JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS)).readTree(file) as? ObjectNode ?: error("Unexpected JSON data; expected: ${JsonNodeType.OBJECT}") processThemeAndScheme(root) processAutodetectTheme(root) } catch (t: Throwable) { logger.warn(t) } private fun processThemeAndScheme(root: ObjectNode) { try { val theme = root[COLOR_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(theme) settings.laf = laf } catch (t: Throwable) { logger.warn(t) } } private fun processAutodetectTheme(root: ObjectNode) { var lightLaf: ILookAndFeel? = null var darkLaf: ILookAndFeel? = null try { val preferredDarkTheme = root[PREFERRED_DARK_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(preferredDarkTheme) darkLaf = laf } catch (t: Throwable) { logger.warn(t) } try { val preferredLightTheme = root[PREFERRED_LIGHT_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(preferredLightTheme) lightLaf = laf } catch (t: Throwable) { logger.warn(t) } try { val autodetectTheme = root[AUTODETECT_THEME]?.booleanValue() ?: return if (autodetectTheme) { settings.laf = SystemDarkThemeDetectorLookAndFeel(darkLaf ?: KnownLafs.Darcula, lightLaf ?: KnownLafs.Light) } } catch (t: Throwable) { logger.warn(t) } } }
apache-2.0
dfea86168b9b5e1bd7c74b34990cb2d4
34.0375
116
0.731977
4.169643
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/openapi/observable/util/ListenerUiUtil.kt
1
9045
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ListenerUiUtil") @file:Suppress("unused") package com.intellij.openapi.observable.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.ui.DocumentAdapter import com.intellij.ui.PopupMenuListenerAdapter import com.intellij.ui.components.DropDownLink import com.intellij.ui.table.TableView import com.intellij.util.ui.TableViewModel import com.intellij.util.ui.tree.TreeModelAdapter import org.jetbrains.annotations.ApiStatus.Experimental import java.awt.Component import java.awt.ItemSelectable import java.awt.event.* import javax.swing.* import javax.swing.event.* import javax.swing.text.Document import javax.swing.text.JTextComponent import javax.swing.tree.TreeModel fun <T> JComboBox<T>.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { (this as ItemSelectable).whenItemSelected(parentDisposable, listener) } fun <T> DropDownLink<T>.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { (this as ItemSelectable).whenItemSelected(parentDisposable, listener) } fun <T> ItemSelectable.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { whenStateChanged(parentDisposable) { event -> if (event.stateChange == ItemEvent.SELECTED) { @Suppress("UNCHECKED_CAST") listener(event.item as T) } } } fun ItemSelectable.whenStateChanged(parentDisposable: Disposable? = null, listener: (ItemEvent) -> Unit) { addItemListener(parentDisposable, ItemListener { event -> listener(event) }) } fun JComboBox<*>.whenPopupMenuWillBecomeInvisible(parentDisposable: Disposable? = null, listener: (PopupMenuEvent) -> Unit) { addPopupMenuListener(parentDisposable, object : PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent) = listener(e) }) } fun ListModel<*>.whenListChanged(parentDisposable: Disposable? = null, listener: (ListDataEvent) -> Unit) { addListDataListener(parentDisposable, object : ListDataListener { override fun intervalAdded(e: ListDataEvent) = listener(e) override fun intervalRemoved(e: ListDataEvent) = listener(e) override fun contentsChanged(e: ListDataEvent) = listener(e) }) } fun JTree.whenTreeChanged(parentDisposable: Disposable? = null, listener: (TreeModelEvent) -> Unit) { model.whenTreeChanged(parentDisposable, listener) } fun TreeModel.whenTreeChanged(parentDisposable: Disposable? = null, listener: (TreeModelEvent) -> Unit) { addTreeModelListener(parentDisposable, TreeModelAdapter.create { event, _ -> listener(event) }) } fun TableView<*>.whenTableChanged(parentDisposable: Disposable? = null, listener: (TableModelEvent) -> Unit) { tableViewModel.whenTableChanged(parentDisposable, listener) } fun TableViewModel<*>.whenTableChanged(parentDisposable: Disposable? = null, listener: (TableModelEvent) -> Unit) { addTableModelListener(parentDisposable, TableModelListener { event -> listener(event) }) } fun TextFieldWithBrowseButton.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { textField.whenTextChanged(parentDisposable, listener) } fun JTextComponent.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { document.whenTextChanged(parentDisposable, listener) } fun Document.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { addDocumentListener(parentDisposable, object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) = listener(e) }) } fun JTextComponent.whenCaretMoved(parentDisposable: Disposable? = null, listener: (CaretEvent) -> Unit) { addCaretListener(parentDisposable, CaretListener { event -> listener(event) }) } fun Component.whenFocusGained(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusGained(e: FocusEvent) = listener(e) }) } fun Component.whenFocusLost(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusLost(e: FocusEvent) = listener(e) }) } fun Component.onceWhenFocusGained(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusGained(e: FocusEvent) { removeFocusListener(this) listener(e) } }) } fun Component.whenMousePressed(parentDisposable: Disposable? = null, listener: (MouseEvent) -> Unit) { addMouseListener(parentDisposable, object : MouseAdapter() { override fun mousePressed(e: MouseEvent) = listener(e) }) } fun Component.whenMouseReleased(parentDisposable: Disposable? = null, listener: (MouseEvent) -> Unit) { addMouseListener(parentDisposable, object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) = listener(e) }) } fun Component.whenKeyTyped(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyTyped(e: KeyEvent) = listener(e) }) } fun Component.whenKeyPressed(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyPressed(e: KeyEvent) = listener(e) }) } fun Component.whenKeyReleased(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyReleased(e: KeyEvent) = listener(e) }) } fun ItemSelectable.addItemListener(parentDisposable: Disposable? = null, listener: ItemListener) { addItemListener(listener) parentDisposable?.whenDisposed { removeItemListener(listener) } } fun JComboBox<*>.addPopupMenuListener(parentDisposable: Disposable? = null, listener: PopupMenuListener) { addPopupMenuListener(listener) parentDisposable?.whenDisposed { removePopupMenuListener(listener) } } fun ListModel<*>.addListDataListener(parentDisposable: Disposable? = null, listener: ListDataListener) { addListDataListener(listener) parentDisposable?.whenDisposed { removeListDataListener(listener) } } fun TreeModel.addTreeModelListener(parentDisposable: Disposable? = null, listener: TreeModelListener) { addTreeModelListener(listener) parentDisposable?.whenDisposed { removeTreeModelListener(listener) } } fun TableViewModel<*>.addTableModelListener(parentDisposable: Disposable? = null, listener: TableModelListener) { addTableModelListener(listener) parentDisposable?.whenDisposed { removeTableModelListener(listener) } } fun Document.addDocumentListener(parentDisposable: Disposable? = null, listener: DocumentListener) { addDocumentListener(listener) parentDisposable?.whenDisposed { removeDocumentListener(listener) } } fun JTextComponent.addCaretListener(parentDisposable: Disposable? = null, listener: CaretListener) { addCaretListener(listener) parentDisposable?.whenDisposed { removeCaretListener(listener) } } fun Component.addFocusListener(parentDisposable: Disposable? = null, listener: FocusListener) { addFocusListener(listener) parentDisposable?.whenDisposed { removeFocusListener(listener) } } fun Component.addMouseListener(parentDisposable: Disposable? = null, listener: MouseListener) { addMouseListener(listener) parentDisposable?.whenDisposed { removeMouseListener(listener) } } fun Component.addKeyListener(parentDisposable: Disposable? = null, listener: KeyListener) { addKeyListener(listener) parentDisposable?.whenDisposed { removeKeyListener(listener) } } @Experimental fun <T> JComboBox<T>.whenItemSelectedFromUi(parentDisposable: Disposable? = null, listener: (T) -> Unit) { whenPopupMenuWillBecomeInvisible(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { selectedItem?.let { @Suppress("UNCHECKED_CAST") listener(it as T) } } } } @Experimental fun TextFieldWithBrowseButton.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit) { textField.whenTextChangedFromUi(parentDisposable, listener) } @Experimental fun JTextComponent.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit) { whenKeyReleased(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { listener(text) } } } @Experimental fun JCheckBox.whenStateChangedFromUi(parentDisposable: Disposable? = null, listener: (Boolean) -> Unit) { whenMouseReleased(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { listener(isSelected) } } }
apache-2.0
01bd65937bad1e471ff57fb38852931d
34.05814
125
0.766722
4.542943
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/ConvertMemberToExtensionIntention.kt
1
14352
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.declarations import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.SmartList import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addIfNotNull private val LOG = Logger.getInstance(ConvertMemberToExtensionIntention::class.java) class ConvertMemberToExtensionIntention : SelfTargetingRangeIntention<KtCallableDeclaration>( KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("convert.member.to.extension") ), LowPriorityAction { private fun isApplicable(element: KtCallableDeclaration): Boolean { val classBody = element.parent as? KtClassBody ?: return false if (classBody.parent !is KtClass) return false if (element.receiverTypeReference != null) return false if (element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false when (element) { is KtProperty -> if (element.hasInitializer() || element.hasDelegate()) return false is KtSecondaryConstructor -> return false } return true } override fun applicabilityRange(element: KtCallableDeclaration): TextRange? { if (!element.withExpectedActuals().all { it is KtCallableDeclaration && isApplicable(it) }) return null return (element.nameIdentifier ?: return null).textRange } override fun startInWriteAction() = false //TODO: local class override fun applyTo(element: KtCallableDeclaration, editor: Editor?) { var allowExpected = true element.liftToExpected()?.actualsForExpected()?.let { if (it.isEmpty()) { allowExpected = askIfExpectedIsAllowed(element.containingKtFile) } } runWriteAction { val (extension, bodyTypeToSelect) = createExtensionCallableAndPrepareBodyToSelect(element, allowExpected) editor?.apply { unblockDocument() if (extension.isValid) { if (bodyTypeToSelect != GeneratedBodyType.NOTHING) { val bodyToSelect = getBodyForSelection(extension, bodyTypeToSelect) if (bodyToSelect != null) { val range = bodyToSelect.textRange moveCaret(range.startOffset, ScrollType.CENTER) val parent = bodyToSelect.parent val lastSibling = if (parent is KtBlockExpression) parent.rBrace?.siblings(forward = false, withItself = false)?.first { it !is PsiWhiteSpace } else bodyToSelect.siblings(forward = true, withItself = false).lastOrNull() val endOffset = lastSibling?.endOffset ?: range.endOffset selectionModel.setSelection(range.startOffset, endOffset) } else { LOG.error("Extension created with new method body for $bodyToSelect but this body was not found after document commit. Extension text: \"${extension.text}\"") moveCaret(extension.textOffset, ScrollType.CENTER) } } else { moveCaret(extension.textOffset, ScrollType.CENTER) } } else { LOG.error("Extension invalidated during document commit. Extension text \"${extension.text}\"") } } } } private fun getBodyForSelection(extension: KtCallableDeclaration, bodyTypeToSelect: GeneratedBodyType): KtExpression? { fun selectBody(declaration: KtDeclarationWithBody): KtExpression? { if (!declaration.hasBody()) return extension return declaration.bodyExpression?.let { (it as? KtBlockExpression)?.statements?.singleOrNull() ?: it } } return when (bodyTypeToSelect) { GeneratedBodyType.FUNCTION -> (extension as? KtFunction)?.let { selectBody(it) } GeneratedBodyType.GETTER -> (extension as? KtProperty)?.getter?.let { selectBody(it) } GeneratedBodyType.SETTER -> (extension as? KtProperty)?.setter?.let { selectBody(it) } else -> null } } private enum class GeneratedBodyType { NOTHING, FUNCTION, SETTER, GETTER } private fun processSingleDeclaration( element: KtCallableDeclaration, allowExpected: Boolean ): Pair<KtCallableDeclaration, GeneratedBodyType> { val descriptor = element.unsafeResolveToDescriptor() val containingClass = descriptor.containingDeclaration as ClassDescriptor val isEffectivelyExpected = allowExpected && element.isExpectDeclaration() val file = element.containingKtFile val project = file.project val outermostParent = KtPsiUtil.getOutermostParent(element, file, false) val ktFilesToAddImports = LinkedHashSet<KtFile>() val javaCallsToFix = SmartList<PsiMethodCallExpression>() for (ref in ReferencesSearch.search(element)) { when (ref) { is KtReference -> { val refFile = ref.element.containingKtFile if (refFile != file) { ktFilesToAddImports.add(refFile) } } is PsiReferenceExpression -> javaCallsToFix.addIfNotNull(ref.parent as? PsiMethodCallExpression) } } val typeParameterList = newTypeParameterList(element) val psiFactory = KtPsiFactory(element) val extension = file.addAfter(element, outermostParent) as KtCallableDeclaration file.addAfter(psiFactory.createNewLine(), outermostParent) file.addAfter(psiFactory.createNewLine(), outermostParent) element.delete() extension.setReceiverType(containingClass.defaultType) if (typeParameterList != null) { if (extension.typeParameterList != null) { extension.typeParameterList!!.replace(typeParameterList) } else { extension.addBefore(typeParameterList, extension.receiverTypeReference) extension.addBefore(psiFactory.createWhiteSpace(), extension.receiverTypeReference) } } extension.modifierList?.getModifier(KtTokens.PROTECTED_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.ABSTRACT_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.OPEN_KEYWORD)?.delete() extension.modifierList?.getModifier(KtTokens.FINAL_KEYWORD)?.delete() if (isEffectivelyExpected && !extension.hasExpectModifier()) { extension.addModifier(KtTokens.EXPECT_KEYWORD) } var bodyTypeToSelect = GeneratedBodyType.NOTHING val bodyText = getFunctionBodyTextFromTemplate( project, if (extension is KtFunction) TemplateKind.FUNCTION else TemplateKind.PROPERTY_INITIALIZER, extension.name, extension.getReturnTypeReference()?.text ?: "Unit", extension.containingClassOrObject?.fqName ) when (extension) { is KtFunction -> { if (!extension.hasBody() && !isEffectivelyExpected) { //TODO: methods in PSI for setBody extension.add(psiFactory.createBlock(bodyText)) bodyTypeToSelect = GeneratedBodyType.FUNCTION } } is KtProperty -> { val templateProperty = psiFactory.createDeclaration<KtProperty>("var v: Any\nget()=$bodyText\nset(value){\n$bodyText\n}") if (!isEffectivelyExpected) { val templateGetter = templateProperty.getter!! val templateSetter = templateProperty.setter!! var getter = extension.getter if (getter == null) { getter = extension.addAfter(templateGetter, extension.typeReference) as KtPropertyAccessor extension.addBefore(psiFactory.createNewLine(), getter) bodyTypeToSelect = GeneratedBodyType.GETTER } else if (!getter.hasBody()) { getter = getter.replace(templateGetter) as KtPropertyAccessor bodyTypeToSelect = GeneratedBodyType.GETTER } if (extension.isVar) { var setter = extension.setter if (setter == null) { setter = extension.addAfter(templateSetter, getter) as KtPropertyAccessor extension.addBefore(psiFactory.createNewLine(), setter) if (bodyTypeToSelect == GeneratedBodyType.NOTHING) { bodyTypeToSelect = GeneratedBodyType.SETTER } } else if (!setter.hasBody()) { setter.replace(templateSetter) as KtPropertyAccessor if (bodyTypeToSelect == GeneratedBodyType.NOTHING) { bodyTypeToSelect = GeneratedBodyType.SETTER } } } } } } if (ktFilesToAddImports.isNotEmpty()) { val newDescriptor = extension.unsafeResolveToDescriptor() val importInsertHelper = ImportInsertHelper.getInstance(project) for (ktFileToAddImport in ktFilesToAddImports) { importInsertHelper.importDescriptor(ktFileToAddImport, newDescriptor) } } if (javaCallsToFix.isNotEmpty()) { val lightMethod = extension.toLightMethods().first() for (javaCallToFix in javaCallsToFix) { javaCallToFix.methodExpression.qualifierExpression?.let { val argumentList = javaCallToFix.argumentList argumentList.addBefore(it, argumentList.expressions.firstOrNull()) } val newRef = javaCallToFix.methodExpression.bindToElement(lightMethod) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newRef) } } return extension to bodyTypeToSelect } private fun askIfExpectedIsAllowed(file: KtFile): Boolean { if (ApplicationManager.getApplication().isUnitTestMode) { return file.allChildren.any { it is PsiComment && it.text.trim() == "// ALLOW_EXPECT_WITHOUT_ACTUAL" } } return Messages.showYesNoDialog( KotlinBundle.message("do.you.want.to.make.new.extension.an.expected.declaration"), text, Messages.getQuestionIcon() ) == Messages.YES } private fun createExtensionCallableAndPrepareBodyToSelect( element: KtCallableDeclaration, allowExpected: Boolean = true ): Pair<KtCallableDeclaration, GeneratedBodyType> { val expectedDeclaration = element.liftToExpected() as? KtCallableDeclaration if (expectedDeclaration != null) { element.withExpectedActuals().filterIsInstance<KtCallableDeclaration>().forEach { if (it != element) { processSingleDeclaration(it, allowExpected) } } } val classVisibility = element.containingClass()?.visibilityModifierType() val (extension, bodyTypeToSelect) = processSingleDeclaration(element, allowExpected) if (classVisibility != null && extension.visibilityModifier() == null) { extension.addModifier(classVisibility) } return extension to bodyTypeToSelect } private fun newTypeParameterList(member: KtCallableDeclaration): KtTypeParameterList? { val classElement = member.parent.parent as KtClass val classParams = classElement.typeParameters if (classParams.isEmpty()) return null val allTypeParameters = classParams + member.typeParameters val text = allTypeParameters.joinToString(",", "<", ">") { it.text } return KtPsiFactory(member).createDeclaration<KtFunction>("fun $text foo()").typeParameterList } companion object { fun convert(element: KtCallableDeclaration): KtCallableDeclaration = ConvertMemberToExtensionIntention().createExtensionCallableAndPrepareBodyToSelect(element).first } }
apache-2.0
988bacf73251479207ead165290448ce
43.99373
186
0.641235
5.955187
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/workers/freeze6.kt
2
3496
/* * Copyright 2010-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 runtime.workers.freeze6 import kotlin.test.* import kotlin.native.concurrent.* import kotlin.native.ref.* data class Hi(val s: String) data class Nested(val hi: Hi) @Test fun ensureNeverFrozenNoFreezeChild(){ val noFreeze = Hi("qwert") noFreeze.ensureNeverFrozen() val nested = Nested(noFreeze) assertFails { nested.freeze() } println("OK") } @Test fun ensureNeverFrozenFailsTarget(){ val noFreeze = Hi("qwert") noFreeze.ensureNeverFrozen() assertFalse(noFreeze.isFrozen) assertFails { noFreeze.freeze() } assertFalse(noFreeze.isFrozen) println("OK") } fun createRef1(): FreezableAtomicReference<Any?> { val ref = FreezableAtomicReference<Any?>(null) ref.value = ref ref.freeze() ref.value = null return ref } var global = 0 @Test fun ensureFreezableHandlesCycles1() { val ref = createRef1() kotlin.native.internal.GC.collect() val obj: Any = ref global = obj.hashCode() } class Node(var ref: Any?) /** * ref1 -> Node <- ref3 * | /\ * V | * ref2 --- */ fun createRef2(): Pair<FreezableAtomicReference<Node?>, Any> { val ref1 = FreezableAtomicReference<Node?>(null) val node = Node(null) val ref3 = FreezableAtomicReference<Any?>(node) val ref2 = FreezableAtomicReference<Any?>(ref3) node.ref = ref2 ref1.value = node ref1.freeze() ref3.value = null assertTrue(node.isFrozen) assertTrue(ref1.isFrozen) assertTrue(ref2.isFrozen) assertTrue(ref3.isFrozen) return ref1 to ref2 } @Test fun ensureFreezableHandlesCycles2() { val (ref, obj) = createRef2() kotlin.native.internal.GC.collect() assertTrue(obj.toString().length > 0) global = ref.value!!.ref!!.hashCode() } fun createRef3(): FreezableAtomicReference<Any?> { val ref = FreezableAtomicReference<Any?>(null) val node = Node(ref) ref.value = node ref.freeze() assertTrue(node.isFrozen) assertTrue(ref.isFrozen) return ref } @Test fun ensureFreezableHandlesCycles3() { val ref = createRef3() ref.value = null kotlin.native.internal.GC.collect() val obj: Any = ref assertTrue(obj.toString().length > 0) global = obj.hashCode() } lateinit var weakRef: WeakReference<Any> fun createRef4(): FreezableAtomicReference<Any?> { val ref = FreezableAtomicReference<Any?>(null) val node = Node(ref) weakRef = WeakReference(node) ref.value = node ref.freeze() assertTrue(weakRef.get() != null) return ref } @Test fun ensureWeakRefNotLeaks1() { val ref = createRef4() ref.value = null // We cannot check weakRef.get() here, as value read will be stored in the stack slot, // and thus hold weak reference from release. kotlin.native.internal.GC.collect() assertTrue(weakRef.get() == null) } lateinit var node1: Node lateinit var weakNode2: WeakReference<Node> fun createRef5() { val ref = FreezableAtomicReference<Any?>(null) node1 = Node(ref) val node2 = Node(node1) weakNode2 = WeakReference(node2) ref.value = node2 node1.freeze() assertTrue(weakNode2.get() != null) ref.value = null } @Test fun ensureWeakRefNotLeaks2() { createRef5() kotlin.native.internal.GC.collect() assertTrue(weakNode2.get() == null) }
apache-2.0
5c9f4e8714a6ea3ec1f952ccc66148c9
20.993711
101
0.66619
3.622798
false
true
false
false
kosiakk/Android-Books
app/src/main/java/com/kosenkov/androidbooks/LazyBooksList.kt
1
1669
package com.kosenkov.androidbooks import android.support.v7.widget.RecyclerView import android.util.Log import com.kosenkov.androidbooks.books.GoogleBooks import com.kosenkov.androidbooks.books.GoogleBooksCache import com.kosenkov.androidbooks.books.GoogleBooksHttp import com.kosenkov.androidbooks.collections.LazyPagedList import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * Global singleton in order to share the cache */ val booksApi = GoogleBooksCache(GoogleBooksHttp()) /** * Loads Google Books search results in the background thread. * * The first page is loaded synchronously in the constructor. * Other pages are loaded in the background in demand. */ class LazyBooksList(val searchQuery: String, val callback: RecyclerView.Adapter<*>) : LazyPagedList<GoogleBooks.Volume>(booksApi.pageSize) { private val totalItems: Int init { val firstPage = booksApi.search(searchQuery) totalItems = firstPage.totalItems setPageData(0, firstPage.items) } override val size: Int get() = totalItems override fun enqueueFetch(pageIndex: Int) { Log.v("LazyList", "enqueueFetch(pageIndex=$pageIndex)") doAsync { val startIndex = pageIndex * pageSize // blocking call val result = booksApi.search(searchQuery, startIndex) // provide downloaded data back to the list setPageData(pageIndex, result.items) uiThread { // Schedule items redraw using the new data callback.notifyItemRangeChanged(startIndex, pageSize) } } } }
gpl-3.0
f21e8b3f671e9cd07cdc2b651f50c3a4
29.363636
69
0.692031
4.523035
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt
7
4388
// 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.debugger import com.intellij.openapi.application.ApplicationManager import com.intellij.xdebugger.XDebuggerBundle import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.frame.XValueGroup import org.jetbrains.concurrency.onError import org.jetbrains.concurrency.onSuccess import org.jetbrains.concurrency.thenAsyncAccept class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?, val firstScope: Boolean? = null) : XValueGroup(scope.createScopeNodeName()) { private val context = createVariableContext(scope, parentContext, callFrame) private val callFrame = if (scope.type == ScopeType.LOCAL) callFrame else null override fun isAutoExpand(): Boolean = scope.type == ScopeType.BLOCK || scope.type == ScopeType.LOCAL || scope.type == ScopeType.CATCH || firstScope == true override fun getComment(): String? { val className = scope.description return if ("Object" == className) null else className } override fun computeChildren(node: XCompositeNode) { ApplicationManager.getApplication().executeOnPooledThread { val promise = processScopeVariables(scope, node, context, callFrame == null) if (callFrame == null) { return@executeOnPooledThread } promise .onSuccess(node) { context.memberFilter .thenAsyncAccept(node) { if (it.hasNameMappings()) { it.sourceNameToRaw(RECEIVER_NAME)?.let { return@thenAsyncAccept callFrame.evaluateContext.evaluate(it) .onSuccess(node) { VariableImpl(RECEIVER_NAME, it.value, null) node.addChildren(XValueChildrenList.singleton(VariableView( VariableImpl(RECEIVER_NAME, it.value, null), context)), true) } } } context.viewSupport.computeReceiverVariable(context, callFrame, node) } .onError(node) { context.viewSupport.computeReceiverVariable(context, callFrame, node) } } } } } fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) { val list = XValueChildrenList(scopes.size) for (scope in scopes) { list.addBottomGroup(ScopeVariablesGroup(scope, context, callFrame, scope == scopes[0])) } node.addChildren(list, true) } fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext { if (callFrame == null || scope.type == ScopeType.LIBRARY) { // functions scopes - we can watch variables only from global scope return ParentlessVariableContext(parentContext, scope, scope.type == ScopeType.GLOBAL) } else { return VariableContextWrapper(parentContext, scope) } } private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) { override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression } private fun Scope.createScopeNodeName(): String { when (type) { ScopeType.GLOBAL -> return XDebuggerBundle.message("scope.global") ScopeType.LOCAL -> return XDebuggerBundle.message("scope.local") ScopeType.WITH -> return XDebuggerBundle.message("scope.with") ScopeType.CLOSURE -> return XDebuggerBundle.message("scope.closure") ScopeType.CATCH -> return XDebuggerBundle.message("scope.catch") ScopeType.LIBRARY -> return XDebuggerBundle.message("scope.library") ScopeType.INSTANCE -> return XDebuggerBundle.message("scope.instance") ScopeType.CLASS -> return XDebuggerBundle.message("scope.class") ScopeType.BLOCK -> return XDebuggerBundle.message("scope.block") ScopeType.SCRIPT -> return XDebuggerBundle.message("scope.script") ScopeType.UNKNOWN -> return XDebuggerBundle.message("scope.unknown") else -> throw IllegalArgumentException(type.name) } }
apache-2.0
b5bf2433c239ebbca43dd1498c61d2ba
44.247423
188
0.700091
5.186761
false
false
false
false
ianhanniballake/muzei
android-client-common/src/main/java/com/google/android/apps/muzei/render/ImageUtil.kt
2
1437
/* * Copyright 2014 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.android.apps.muzei.render import android.graphics.Bitmap import android.graphics.Color fun Bitmap?.darkness(): Float { if (this == null || width == 0 || height == 0) { return 0f } var totalLum = 0 var n = 0 var x: Int var y = 0 var color: Int while (y < height) { x = 0 while (x < width) { ++n color = getPixel(x, y) totalLum += (0.21f * Color.red(color) + 0.71f * Color.green(color) + 0.07f * Color.blue(color)).toInt() x++ } y++ } return totalLum / n / 256f } fun Int.sampleSize(targetSize: Int): Int { var sampleSize = 1 while (this / (sampleSize shl 1) > targetSize) { sampleSize = sampleSize shl 1 } return sampleSize }
apache-2.0
7c272feb69952258080972422c1ba5bb
25.611111
75
0.605428
3.832
false
false
false
false
sksamuel/ktest
kotest-extensions/src/jvmTest/kotlin/com/sksamuel/kt/extensions/system/SystemEnvironmentExtensionTest.kt
1
3141
package com.sksamuel.kt.extensions.system import io.kotest.core.listeners.TestListener import io.kotest.core.spec.AutoScan import io.kotest.core.spec.Spec import io.kotest.core.spec.style.FreeSpec import io.kotest.core.spec.style.WordSpec import io.kotest.core.spec.style.scopes.FreeSpecContainerContext import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.extensions.system.OverrideMode import io.kotest.extensions.system.SystemEnvironmentTestListener import io.kotest.extensions.system.withEnvironment import io.kotest.inspectors.forAll import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import kotlin.reflect.KClass class SystemEnvironmentExtensionTest : FreeSpec() { private val key = "SystemEnvironmentExtensionTestFoo" private val value = "SystemEnvironmentExtensionTestBar" private val mode: OverrideMode = mockk { every { override(any(), any()) } answers { firstArg<Map<String, String>>().plus(secondArg<Map<String, String>>()).toMutableMap() } } init { "Should set environment to specific map" - { executeOnAllEnvironmentOverloads { System.getenv(key) shouldBe value } } "Should return original environment to its place after execution" - { val before = System.getenv().toMap() executeOnAllEnvironmentOverloads { System.getenv() shouldNotBe before } System.getenv() shouldBe before } "Should return the computed value" - { val results = executeOnAllEnvironmentOverloads { "RETURNED" } results.forAll { it shouldBe "RETURNED" } } } private suspend fun <T> FreeSpecContainerContext.executeOnAllEnvironmentOverloads(block: suspend () -> T): List<T> { val results = mutableListOf<T>() "String String overload" { results += withEnvironment(key, value, mode) { block() } } "Pair overload" { results += withEnvironment(key to value, mode) { block() } } "Map overload" { results += withEnvironment(mapOf(key to value), mode) { block() } } return results } } @AutoScan object SysEnvTestListener : TestListener { override val name: String get() = "SysEnvTestListener" override suspend fun prepareSpec(kclass: KClass<out Spec>) { if (kclass == SystemEnvironmentTestListenerTest::class) { System.getenv("mop") shouldBe null } } override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) { if (kclass == SystemEnvironmentTestListenerTest::class) { System.getenv("mop") shouldBe null } } } class SystemEnvironmentTestListenerTest : WordSpec() { val setl = SystemEnvironmentTestListener("mop", "dop", mode = OverrideMode.SetOrOverride) override fun listeners() = listOf(setl) init { "sys environment extension" should { "set environment variable" { System.getenv("mop") shouldBe "dop" } } } }
mit
7a688e48c8a31f06311cc71b6ceda4d9
27.816514
119
0.679401
4.344398
false
true
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/toolbar/main/UrlBarBase.kt
1
4560
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.toolbar.main import android.content.Context import android.view.Gravity import android.view.LayoutInflater import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToPx import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.manager.ActionController import jp.hazuki.yuzubrowser.legacy.action.manager.ActionIconManager import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionArrayManager import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionManager import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData import jp.hazuki.yuzubrowser.legacy.toolbar.ButtonToolbarController import jp.hazuki.yuzubrowser.legacy.utils.view.swipebutton.SwipeTextButton import jp.hazuki.yuzubrowser.ui.extensions.decodePunyCodeUrl import jp.hazuki.yuzubrowser.ui.settings.AppPrefs import jp.hazuki.yuzubrowser.ui.theme.ThemeData abstract class UrlBarBase(context: Context, controller: ActionController, iconManager: ActionIconManager, layout: Int, request_callback: RequestCallback) : ToolbarBase(context, AppPrefs.toolbar_url, request_callback) { private val mLeftButtonController: ButtonToolbarController private val mRightButtonController: ButtonToolbarController protected val centerUrlButton: SwipeTextButton init { LayoutInflater.from(context).inflate(layout, this) val toolbarSizeY = context.convertDpToPx(AppPrefs.toolbar_url.size.get()) val softbtnManager = SoftButtonActionManager.getInstance(context) mLeftButtonController = ButtonToolbarController(findViewById(R.id.leftLinearLayout), controller, iconManager, toolbarSizeY) mRightButtonController = ButtonToolbarController(findViewById(R.id.rightLinearLayout), controller, iconManager, toolbarSizeY) centerUrlButton = findViewById(R.id.centerUrlButton) centerUrlButton.setActionData(softbtnManager.btn_url_center, controller, iconManager) ButtonToolbarController.settingButtonSize(centerUrlButton, toolbarSizeY) addButtons() } override fun onPreferenceReset() { super.onPreferenceReset() addButtons() centerUrlButton.notifyChangeState() centerUrlButton.setSense(AppPrefs.swipebtn_sensitivity.get()) centerUrlButton.textSize = AppPrefs.toolbar_text_size_url.get().toFloat() } override fun applyTheme(themeData: ThemeData?) { super.applyTheme(themeData) applyTheme(mLeftButtonController) applyTheme(mRightButtonController) } private fun addButtons() { val manager = SoftButtonActionArrayManager.getInstance(context) mLeftButtonController.addButtons(manager.btn_url_left.list) mRightButtonController.addButtons(manager.btn_url_right.list) onThemeChanged(ThemeData.getInstance())// TODO } override fun notifyChangeWebState(data: MainTabData?) { super.notifyChangeWebState(data) mLeftButtonController.notifyChangeState() mRightButtonController.notifyChangeState() centerUrlButton.notifyChangeState() if (data != null) changeTitle(data) } override fun resetToolBar() { mLeftButtonController.resetIcon() mRightButtonController.resetIcon() } fun changeTitle(data: MainTabData) { //need post Runnable? post { if (!AppPrefs.toolbar_always_show_url.get() && data.title != null && !data.isInPageLoad) { centerUrlButton.run { setTypeUrl(false) text = data.title gravity = Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL } } else { centerUrlButton.run { setTypeUrl(true) text = data.url.decodePunyCodeUrl() gravity = Gravity.START or Gravity.CENTER_VERTICAL } } } } }
apache-2.0
aab51c6d4edd56cd5234adb14bb24b1e
39.353982
218
0.724342
4.505929
false
false
false
false
spinnaker/kork
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/update/repository/Front50UpdateRepository.kt
3
3553
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.plugins.update.repository import com.netflix.spinnaker.kork.exceptions.SystemException import com.netflix.spinnaker.kork.plugins.update.internal.Front50Service import com.netflix.spinnaker.kork.plugins.update.internal.SpinnakerPluginInfo import io.github.resilience4j.retry.Retry import java.net.URL import org.pf4j.update.FileDownloader import org.pf4j.update.FileVerifier import org.pf4j.update.SimpleFileDownloader import org.pf4j.update.UpdateRepository import org.pf4j.update.verifier.CompoundVerifier import org.slf4j.LoggerFactory /** * Optional [UpdateRepository]. * * Wired up if the property `spinnaker.extensibility.repositories.front50.enabled` is `true`. * Pulls Front50 plugin info objects and populates the available plugin info cache in * [org.pf4j.update.UpdateManager]. */ class Front50UpdateRepository( private val repositoryName: String, private val url: URL, private val downloader: FileDownloader = SimpleFileDownloader(), private val verifier: FileVerifier = CompoundVerifier(), private val front50Service: Front50Service ) : UpdateRepository { private val log by lazy { LoggerFactory.getLogger(javaClass) } private var plugins: MutableMap<String, SpinnakerPluginInfo> = mutableMapOf() override fun getUrl(): URL { return url } override fun getId(): String { return repositoryName } override fun getPlugins(): MutableMap<String, SpinnakerPluginInfo> { return plugins.ifEmpty { log.debug("Populating plugin info cache from front50") val response = retry.executeSupplier { front50Service.listAll().execute() } if (!response.isSuccessful) { // We can't throw an exception here when we fail to talk to Front50 because it will prevent a service from // starting. We would rather a Spinnaker service start and be potentially misconfigured than have a hard // startup dependency on front50. log.error( "Failed listing plugin info from front50. This service may not download plugins that it needs: {}", response.errorBody()?.string() ?: response.message() ) return mutableMapOf() } response.body()!!.associateByTo(plugins) { it.id } } } override fun getPlugin(id: String): SpinnakerPluginInfo { return plugins.getOrPut( id, { val response = front50Service.getById(id).execute() if (!response.isSuccessful) { throw SystemException( "Unable to get the requested plugin info `$id` from front50", response.message() ) } response.body()!! } ) } override fun getFileVerifier(): FileVerifier { return verifier } override fun getFileDownloader(): FileDownloader { return downloader } override fun refresh() { plugins.clear() } companion object { private val retry = Retry.ofDefaults("front50-update-repository") } }
apache-2.0
3dbd1d5e2d8a6b6fd226fe9dd89c3bd9
31.3
114
0.718266
4.424658
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/SaveScreenshotSingleAction.kt
1
3160
/* * Copyright (C) 2017-2021 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.item import android.os.Parcel import android.os.Parcelable import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.ui.settings.AppPrefs import java.io.IOException class SaveScreenshotSingleAction : SingleAction, Parcelable { private var mSsType = SS_TYPE_PART val type: Int get() = if (AppPrefs.slow_rendering.get()) mSsType else SS_TYPE_PART @Throws(IOException::class) constructor(id: Int, reader: JsonReader?) : super(id) { if (reader != null) { if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return reader.beginObject() while (reader.hasNext()) { if (reader.peek() != JsonReader.Token.NAME) return when (reader.nextName()) { FIELD_NAME_SS_TYPE -> { if (reader.peek() != JsonReader.Token.NUMBER) return mSsType = reader.nextInt() } FIELD_NAME_SAVE_FOLDER -> { if (reader.peek() != JsonReader.Token.STRING) return } else -> reader.skipValue() } } reader.endObject() } } @Throws(IOException::class) override fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.beginObject() writer.name(FIELD_NAME_SS_TYPE) writer.value(mSsType) writer.endObject() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeInt(mSsType) } private constructor(source: Parcel) : super(source.readInt()) { mSsType = source.readInt() } companion object { private const val FIELD_NAME_SS_TYPE = "0" private const val FIELD_NAME_SAVE_FOLDER = "1" const val SS_TYPE_ALL = 0 const val SS_TYPE_PART = 1 @JvmField val CREATOR: Parcelable.Creator<SaveScreenshotSingleAction> = object : Parcelable.Creator<SaveScreenshotSingleAction> { override fun createFromParcel(source: Parcel): SaveScreenshotSingleAction { return SaveScreenshotSingleAction(source) } override fun newArray(size: Int): Array<SaveScreenshotSingleAction?> { return arrayOfNulls(size) } } } }
apache-2.0
ff86c28552090e7e3f5223a874337178
32.617021
127
0.62057
4.48227
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/ui/AbstractEncryptionParamsFragment.kt
1
2111
package io.oversec.one.crypto.ui import android.app.Fragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.oversec.one.crypto.EncryptionMethod import io.oversec.one.crypto.ui.util.StandaloneTooltipView abstract class AbstractEncryptionParamsFragment : Fragment(), WithHelp { protected var mPackageName: String? = null protected var mIsForTextEncryption: Boolean = false protected var mView: View? = null; protected var mTooltip: StandaloneTooltipView? = null protected var mArrowPosition: Int = 0 protected lateinit var mContract: EncryptionParamsActivityContract protected var mHideToolTip: Boolean = false abstract val method: EncryptionMethod override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { mContract = activity as EncryptionParamsActivityContract val bundle = this.arguments if (bundle != null) { mPackageName = bundle.getString(EXTRA_PACKAGENAME) mIsForTextEncryption = bundle.getBoolean(EXTRA_ISFORTEXT) } return mView } fun setArgs(packageName: String?, isForTextEncryption: Boolean, state: Bundle?) { val bundle = state ?: Bundle() bundle.putString(EXTRA_PACKAGENAME, packageName) bundle.putBoolean(EXTRA_ISFORTEXT, isForTextEncryption) arguments = bundle } fun setToolTipPosition(i: Int) { mArrowPosition = i if (mTooltip != null) { mTooltip!!.setArrowPosition(i) } } // public abstract void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data); abstract fun getTabTitle(ctx: Context): String abstract fun saveState(b: Bundle) fun setToolTipVisible(b: Boolean) { mHideToolTip = !b } companion object { private const val EXTRA_PACKAGENAME = "EXTRA_PACKAGENAME" private const val EXTRA_ISFORTEXT = "EXTRA_ISFORTEXT" } }
gpl-3.0
933f4d2f4f9341332285ccabb29cc68b
28.732394
110
0.702984
4.629386
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/models/Constants.kt
1
532
package com.sonnyrodriguez.fittrainer.fittrainerbasic.models class MuscleConstants { companion object { val biceps = "Biceps" val quads = "Quadriceps" val back = "Back" val shoulders = "Shoulders" val hamstrings = "Hamstrings" val calves = "Calves" val triceps = "Triceps" val abs = "Abdominal" val pecs = "Pectorals" } } class ConverterStrings { companion object { val amountSeparator = "_:_" val entrySeparator ="__,__" } }
apache-2.0
b85a7bf20cda41ebeda90f0f0533b09f
23.181818
60
0.586466
3.72028
false
false
false
false
TonnyTao/Acornote
Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/model/NoteLabelCrossRef.kt
1
741
package tonnysunm.com.acornote.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE @Entity( tableName = "note_label_table", primaryKeys = ["label_id", "note_id"], foreignKeys = [ForeignKey( onDelete = CASCADE, entity = Label::class, parentColumns = ["id"], childColumns = ["label_id"] ), ForeignKey( onDelete = CASCADE, entity = Note::class, parentColumns = ["id"], childColumns = ["note_id"] )] ) data class NoteLabelCrossRef( @ColumnInfo(name = "label_id", index = true) var labelId: Int, @ColumnInfo(name = "note_id", index = true) var noteId: Int )
apache-2.0
296ade19d77cc57594f5a2774fbce1f7
24.586207
48
0.632928
4.027174
false
false
false
false
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/filter/InPlaceRoundFilter.kt
2
3639
/* * 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.imagepipeline.filter import android.graphics.Bitmap import com.facebook.common.internal.Preconditions import com.facebook.imageutils.BitmapUtil /** * Modified midpoint circle algorithm. Clients that look for better performances should use the * native implementation of this algorithm in NativeRoundingFilter. */ object InPlaceRoundFilter { /** * An implementation for rounding a given bitmap to a circular shape. The underlying * implementation uses a modified midpoint circle algorithm but instead of drawing a circle, it * clears all pixels starting from the circle all the way to the bitmap edges. * * @param bitmap The input [Bitmap] */ @JvmStatic fun roundBitmapInPlace(bitmap: Bitmap) { Preconditions.checkNotNull(bitmap) val w = bitmap.width val h = bitmap.height val radius = Math.min(w, h) / 2 val centerX = w / 2 val centerY = h / 2 // Nothing to do if the radius is equal to 0. if (radius == 0) { return } Preconditions.checkArgument(radius >= 1) Preconditions.checkArgument(w > 0 && w <= BitmapUtil.MAX_BITMAP_SIZE) Preconditions.checkArgument(h > 0 && h <= BitmapUtil.MAX_BITMAP_SIZE) Preconditions.checkArgument(centerX > 0 && centerX < w) Preconditions.checkArgument(centerY > 0 && centerY < h) val pixels = IntArray(w * h) bitmap.getPixels(pixels, 0, w, 0, 0, w, h) var x = radius - 1 var y = 0 val maxX = centerX + x val maxY = centerY + x val minX = centerX - x val minY = centerY - x Preconditions.checkArgument(minX >= 0 && minY >= 0 && maxX < w && maxY < h) var dx = 1 var dy = 1 val rInc = -radius * 2 val transparentColor = IntArray(w) var err = dx + rInc var cXpX: Int var cXmX: Int var cXpY: Int var cXmY: Int var cYpX: Int var cYmX: Int var cYpY: Int var cYmY: Int var offA: Int var offB: Int var offC: Int var offD: Int while (x >= y) { cXpX = centerX + x cXmX = centerX - x cXpY = centerX + y cXmY = centerX - y cYpX = centerY + x cYmX = centerY - x cYpY = centerY + y cYmY = centerY - y Preconditions.checkArgument(x >= 0 && cXpY < w && cXmY >= 0 && cYpY < h && cYmY >= 0) offA = w * cYpY offB = w * cYmY offC = w * cYpX offD = w * cYmX // Clear left System.arraycopy(transparentColor, 0, pixels, offA, cXmX) System.arraycopy(transparentColor, 0, pixels, offB, cXmX) System.arraycopy(transparentColor, 0, pixels, offC, cXmY) System.arraycopy(transparentColor, 0, pixels, offD, cXmY) // Clear right System.arraycopy(transparentColor, 0, pixels, offA + cXpX, w - cXpX) System.arraycopy(transparentColor, 0, pixels, offB + cXpX, w - cXpX) System.arraycopy(transparentColor, 0, pixels, offC + cXpY, w - cXpY) System.arraycopy(transparentColor, 0, pixels, offD + cXpY, w - cXpY) if (err <= 0) { y++ dy += 2 err += dy } if (err > 0) { x-- dx += 2 err += dx + rInc } } // Clear top / bottom if height > width for (i in centerY - radius downTo 0) { System.arraycopy(transparentColor, 0, pixels, i * w, w) } for (i in centerY + radius until h) { System.arraycopy(transparentColor, 0, pixels, i * w, w) } bitmap.setPixels(pixels, 0, w, 0, 0, w, h) } }
mit
06797c0654cd8f7ecf59152e8a7aec21
30.102564
97
0.620225
3.475645
false
false
false
false
SourceUtils/steam-toolkit
src/main/kotlin/com/timepath/steam/webapi/Main.kt
1
4672
package com.timepath.steam.webapi import com.timepath.Logger import com.timepath.web.api.base.Connection import com.timepath.web.api.base.RequestBuilder import org.json.JSONObject import java.math.BigInteger import java.net.URI import java.security.KeyFactory import java.security.spec.RSAPublicKeySpec import java.util.logging.Level import javax.crypto.Cipher import javax.imageio.ImageIO import javax.swing.ImageIcon import javax.swing.SwingUtilities import javax.swing.WindowConstants import kotlin.platform.platformStatic import kotlin.properties.Delegates import java.util.logging.Logger as JLogger /** * http://code.google.com/p/pidgin-opensteamworks/source/browse/trunk/steam-mobile */ public class Main { val dlg = object : LoginDialog(null, true) { var prevUser: String? = null var cipherData: ByteArray by Delegates.notNull() var rsatimestamp: String by Delegates.notNull() var emailsteamid = "" var gid = -1L override fun login() { LOG.info { "Logging in" } val user = userInput.getText() val pass = String(passInput.getPassword()).toByteArray() val retry = prevUser?.let { it.equals(user, ignoreCase = true) } ?: false if (!retry) { prevUser = user val enc = encrypt(user, pass) cipherData = enc.first rsatimestamp = enc.second pass.fill(0) } JLogger.getLogger(javaClass<Connection>().getName()).setLevel(Level.WARNING) dologin(user, cipherData, rsatimestamp, emailsteamid, steamguardInput.getText(), gid, captchaInput.getText()).let { LOG.info { it.toString() } if (!it.getBoolean("success") || !it.has("oauth")) { messageLabel.setText(it.getString("message")) if (it.optBoolean("emailauth_needed")) { emailsteamid = it.getString("emailsteamid") } else if (it.optBoolean("captcha_needed")) { gid = it.getLong("captcha_gid") val address = "https://steamcommunity.com/public/captcha.php?gid=$gid" captchaLabel.setIcon(ImageIcon(ImageIO.read(URI.create(address).toURL()))) } LOG.info { "Login failed" } return } dispose() run { val token = it.getString("oauth").let { JSONObject(it) }.getString("oauth_token") logon(token).let { if (it.error != "OK") { println(it.error) } LOG.info { it.toString() } var lmid = it.message while (true) { Thread.sleep(1000) poll(token, lmid).let { if (it.error != "OK") { println(it.error) } lmid = it.messagelast it.messages.forEach { println(it) } } } } } } } } companion object { val LOG = Logger() fun encrypt(username: String, password: ByteArray): Pair<ByteArray, String> { val ret = RequestBuilder.fromArray(arrayOf(arrayOf("username", username))).let { Endpoint.COMMUNITY.postget("login/getrsakey", it.toString()) }.let { JSONObject(it) } val keySpec = RSAPublicKeySpec( BigInteger(ret.getString("publickey_mod"), 16), BigInteger(ret.getString("publickey_exp"), 16) ) val key = KeyFactory.getInstance("RSA").generatePublic(keySpec) val cipher = Cipher.getInstance(key.getAlgorithm()) cipher.init(Cipher.ENCRYPT_MODE, key) return cipher.doFinal(password) to ret.getString("timestamp") } public platformStatic fun main(args: Array<String>): Unit = SwingUtilities.invokeLater { Main().dlg.let { it.pack() it.setLocationRelativeTo(null) it.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) it.setVisible(true) it } } } }
artistic-2.0
27b671a0a56a97ef4b82157f3af5d62d
37.61157
101
0.514127
4.871741
false
false
false
false
fython/shadowsocks-android
mobile/src/main/java/com/github/shadowsocks/plugin/PluginConfiguration.kt
4
3464
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks.plugin import android.util.Log import com.github.shadowsocks.utils.Commandline import java.util.* class PluginConfiguration(val pluginsOptions: Map<String, PluginOptions>, val selected: String) { private constructor(plugins: List<PluginOptions>) : this( plugins.filter { it.id.isNotEmpty() }.associate { it.id to it }, if (plugins.isEmpty()) "" else plugins[0].id) constructor(plugin: String) : this(plugin.split('\n').map { line -> if (line.startsWith("kcptun ")) { val opt = PluginOptions() opt.id = "kcptun" try { val iterator = Commandline.translateCommandline(line).drop(1).iterator() while (iterator.hasNext()) { val option = iterator.next() when { option == "--nocomp" -> opt.put("nocomp", null) option.startsWith("--") -> opt.put(option.substring(2), iterator.next()) else -> throw IllegalArgumentException("Unknown kcptun parameter: " + option) } } } catch (exc: Exception) { Log.w("PluginConfiguration", exc.message) } opt } else PluginOptions(line) }) fun getOptions(id: String): PluginOptions = if (id.isEmpty()) PluginOptions() else pluginsOptions[id] ?: PluginOptions(id, PluginManager.fetchPlugins()[id]?.defaultConfig) val selectedOptions: PluginOptions get() = getOptions(selected) override fun toString(): String { val result = LinkedList<PluginOptions>() for ((id, opt) in pluginsOptions) if (id == this.selected) result.addFirst(opt) else result.addLast(opt) if (!pluginsOptions.contains(selected)) result.addFirst(selectedOptions) return result.joinToString("\n") { it.toString(false) } } }
gpl-3.0
deed42fb3d798874eeaf0581f9b911b0
54.870968
112
0.498557
5.162444
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dev/profiling/ProfilerWindow.kt
1
4542
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dev.profiling import com.almasb.fxgl.core.math.FXGLMath import com.almasb.fxgl.logging.Logger import com.almasb.fxgl.ui.MDIWindow import javafx.scene.canvas.Canvas import javafx.scene.canvas.GraphicsContext import javafx.scene.paint.Color import java.util.* /** * * @author Almas Baimagambetov ([email protected]) */ class ProfilerWindow(width: Double, height: Double, title: String) : MDIWindow() { private val log = Logger.get(javaClass) private val g: GraphicsContext var measuringUnitsName = "" var numYTicks = 10 /** * Number of seconds this chart is tracking. */ var durationX = 3.0 var maxBufferSize = 180 private val valueBuffer = LinkedList<Double>() /** * If current value is less than [preferredMaxValue] for 300 updates, * then set maxValue to [preferredMaxValue]. */ var preferredMaxValue = 0.0 private var preferredUpdateCounter = 0 var minValue = 0.0 var curValue = 0.0 var maxValue = 0.0 var bgColor = Color.color(0.25, 0.25, 0.25, 0.75) var textColor = Color.WHITESMOKE var chartColor = Color.RED /* For logging */ private var totalValue = 0.0 private var frames = 1 private var allTimeLow = Double.MAX_VALUE private var allTimeHigh = 0.0 init { isCloseable = false isMinimizable = true isMovable = true isManuallyResizable = false setPrefSize(width, height) this.title = title val canvas = Canvas(width, height) g = canvas.graphicsContext2D contentPane.children += canvas } fun update(value: Double) { frames++ totalValue += value valueBuffer.addLast(value) if (valueBuffer.size > maxBufferSize) valueBuffer.removeFirst() if (value > maxValue) maxValue = value if (value < minValue) minValue = value if (value > allTimeHigh) allTimeHigh = value if (value < allTimeLow) allTimeLow = value if (maxValue > preferredMaxValue && value < preferredMaxValue) { preferredUpdateCounter++ if (preferredUpdateCounter == 300) { maxValue = preferredMaxValue preferredUpdateCounter = 0 } } g.fill = bgColor g.fillRect(0.0, 0.0, g.canvas.width, g.canvas.height) g.fill = textColor g.stroke = Color.web("darkgray", 0.3) g.lineWidth = 1.0 val tickLength = (maxValue - minValue) * 1.0 / numYTicks for (i in numYTicks downTo 0) { val tickValue = minValue + i*tickLength val y = FXGLMath.map(i.toDouble(), numYTicks.toDouble(), 0.0, 15.0, g.canvas.height - 5) g.fillText("%.2f".format(tickValue), 0.0, y) g.strokeLine(0.0, y, g.canvas.width, y) } // render values g.stroke = chartColor g.lineWidth = 2.0 val dx = (g.canvas.width - 30) / maxBufferSize var x = 30.0 var lastX = 0.0 var lastY = 0.0 valueBuffer.forEach { x += dx val y = FXGLMath.map(it, maxValue, minValue, 15.0, g.canvas.height - 5) if (lastX != 0.0 && lastY != 0.0) { g.strokeLine(lastX, lastY, x, y) } lastX = x lastY = y } } fun log() { log.info("Profiler ($title) - $frames frames") log.info("Average: ${totalValue / frames}") log.info("Minimum: $allTimeLow") log.info("Maximum: $allTimeHigh") } } // // the debug data max chars is ~110, so just add a margin // // cache string builder to avoid object allocation // private val sb = StringBuilder(128) // // private fun buildInfoText(fps: Int): String { // // first clear the contents // sb.setLength(0) // sb.append("FPS: ").append(fps) // .append("\nAvg CPU (ms): ").append("%.1f".format(currentTimeTook / 1_000_000.0)) // .append("\nNow Mem (MB): ").append(currentMemoryUsageRounded) // .append("\nAvg Mem (MB): ").append(avgMemoryUsageRounded) // .append("\nMin Mem (MB): ").append(minMemoryUsageRounded) // .append("\nMax Mem (MB): ").append(maxMemoryUsageRounded) // // return sb.toString() // }
mit
e84a21c8f13b7e0102e2e1dbf3275550
25.412791
100
0.583003
3.882051
false
false
false
false
VladimirMiller/Kotlin-koans
src/v_builders/_39_HtmlBuilders.kt
1
1117
package v_builders import util.TODO import util.doc39 import v_builders.data.getProducts import v_builders.htmlLibrary.* fun getTitleColor() = "#b9c9fe" fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( """ Task 39. 1) Fill the table with the proper values from products. 2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to functions 'tr', 'td'. You can call the 'main' function in the 'htmlDemo.kt' to see the rendered table. """, documentation = doc39() ) fun renderProductTable(): String { return html { table { tr { td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() for (prod in products){ } } }.toString() }
mit
a526eb838968e856cabbdac95c37fe2e
25.595238
105
0.518353
4.312741
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/listener/PlayerQuitListener.kt
1
1480
package com.rpkit.economy.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.economy.bukkit.economy.RPKEconomyService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerQuitEvent class PlayerQuitListener : Listener { @EventHandler fun onPlayerQuit(event: PlayerQuitEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val economyService = Services[RPKEconomyService::class.java] ?: return minecraftProfileService.getMinecraftProfile(event.player).thenAccept getMinecraftProfile@{ minecraftProfile -> if (minecraftProfile == null) return@getMinecraftProfile characterService.getActiveCharacter(minecraftProfile).thenAccept getCharacter@{ character -> if (character == null) return@getCharacter // If a player relogs quickly, then by the time the data has been retrieved, the player is sometimes back // online. We only want to unload data if the player is offline. if (!minecraftProfile.isOnline) { economyService.unloadBalances(character) } } } } }
apache-2.0
41904c7fde674a5c8e27a99a721682eb
45.28125
121
0.723649
5.34296
false
false
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/Md5.kt
2
3100
package com.beust.kobalt.maven import com.beust.kobalt.misc.KFiles import com.beust.kobalt.misc.kobaltLog import java.io.File import java.security.MessageDigest import javax.xml.bind.DatatypeConverter class Md5 { companion object { // private fun md5(file: File) : String { // if (file.isDirectory) { // println("PROBLEM") // } // val md5 = MessageDigest.getInstance("MD5") // val bytes = file.readBytes() // md5.update(bytes, 0, bytes.size) // return DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() // } /** * Calculate a checksum for all the files/directories. The conversion from File to * bytes can be customized by the @param{toBytes} parameter. The default implementation calculates * a checksum of the last modified timestamp. */ fun toMd5Directories(filesOrDirectories: List<File>, toBytes: (File) -> ByteArray = { "${it.path} ${it.lastModified()} ${it.length()}".toByteArray() } ) : String? { if (filesOrDirectories.any(File::exists)) { MessageDigest.getInstance("MD5").let { md5 -> var fileCount = 0 filesOrDirectories.filter(File::exists).forEach { file -> if (file.isFile) { kobaltLog(3, " Calculating checksum of $file") val bytes = toBytes(file) md5.update(bytes, 0, bytes.size) fileCount++ } else { val files = KFiles.findRecursively(file) // , { f -> f.endsWith("java")}) kobaltLog(3, " Calculating checksum of ${files.size} files in $file") files.map { File(file, it) }.filter { it.isFile }.forEach { fileCount++ val bytes = toBytes(it) md5.update(bytes, 0, bytes.size) } } } // The output directory might exist but with no files in it, in which case // we must run the task if (fileCount > 0) { val result = DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() return result } else { return null } } } else { return null } } fun toMd5(file: File) = MessageDigest.getInstance("MD5").let { md5 -> file.forEachBlock { bytes, size -> md5.update(bytes, 0, size) } DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() } } }
apache-2.0
9be76245119a7614590116111b6f55ac
40.333333
115
0.458387
5.183946
false
false
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/Booter.kt
2
2328
package com.beust.kobalt.maven.aether import com.beust.kobalt.internal.KobaltSettings import com.google.common.eventbus.EventBus import com.beust.kobalt.Args import org.eclipse.aether.DefaultRepositorySystemSession import org.eclipse.aether.RepositorySystem import org.eclipse.aether.repository.LocalRepository import java.io.File object Booter { fun newRepositorySystem(): RepositorySystem { return ManualRepositorySystemFactory.newRepositorySystem() // return org.eclipse.aether.examples.guice.GuiceRepositorySystemFactory.newRepositorySystem(); // return org.eclipse.aether.examples.sisu.SisuRepositorySystemFactory.newRepositorySystem(); // return org.eclipse.aether.examples.plexus.PlexusRepositorySystemFactory.newRepositorySystem(); } // fun newRepositorySystemSession(system: RepositorySystem): DefaultRepositorySystemSession { // val session = org.apache.maven.repository.internal.MavenRepositorySystemUtils.newSession() // // val localRepo = LocalRepository("target/local-repo") // session.localRepositoryManager = system.newLocalRepositoryManager(session, localRepo) // // session.transferListener = ConsoleTransferListener() // session.repositoryListener = ConsoleRepositoryListener(System.out, EventBus()) // // // uncomment to generate dirty trees // // session.setDependencyGraphTransformer( null ); // // return session // } fun newRepositorySystemSession(system: RepositorySystem, repo: File, settings: KobaltSettings, args: Args, eventBus: EventBus): DefaultRepositorySystemSession { val session = MavenRepositorySystemUtils.newSession(settings) session.isOffline = args.offline val localRepo = LocalRepository(repo.absolutePath) session.localRepositoryManager = system.newLocalRepositoryManager(session, localRepo) session.transferListener = ConsoleTransferListener() session.repositoryListener = ConsoleRepositoryListener(eventBus = eventBus) // uncomment to generate dirty trees // session.setDependencyGraphTransformer( null ); return session } // fun newRepositories(repositories: Collection<String>) // = repositories.map { RemoteRepository.Builder("maven", "default", it).build() } }
apache-2.0
5120b4042516980032c7937b05033f2e
41.327273
105
0.748282
4.790123
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/TranslationPresenter.kt
1
4259
package cn.yiiguxing.plugin.translate import cn.yiiguxing.plugin.translate.TargetLanguageSelection.* import cn.yiiguxing.plugin.translate.trans.Lang import cn.yiiguxing.plugin.translate.trans.TranslateListener import cn.yiiguxing.plugin.translate.trans.Translation import cn.yiiguxing.plugin.translate.trans.Translator import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.diagnostic.Logger import java.lang.ref.WeakReference class TranslationPresenter(private val view: View, private val recordHistory: Boolean = true) : Presenter { private val translateService = TranslateService private val settings = Settings.instance private val appStorage = AppStorage.instance private var currentRequest: Presenter.Request? = null override val translator: Translator get() = translateService.translator override val histories: List<String> get() = appStorage.getHistories() override val primaryLanguage: Lang get() = translator.primaryLanguage override val supportedLanguages: SupportedLanguages get() = with(translator) { SupportedLanguages(supportedSourceLanguages, supportedTargetLanguages) } override fun isSupportedSourceLanguage(sourceLanguage: Lang): Boolean { return translator.supportedSourceLanguages.contains(sourceLanguage) } override fun isSupportedTargetLanguage(targetLanguage: Lang): Boolean { return translator.supportedTargetLanguages.contains(targetLanguage) } override fun getCache(text: String, srcLang: Lang, targetLang: Lang): Translation? { return translateService.getCache(text, srcLang, targetLang) } override fun getTargetLang(text: String): Lang { return when (settings.targetLanguageSelection) { DEFAULT -> Lang.AUTO.takeIf { isSupportedTargetLanguage(it) } ?: if (text.isEmpty() || text.any(NON_LATIN_CONDITION)) Lang.ENGLISH else primaryLanguage PRIMARY_LANGUAGE -> primaryLanguage LAST -> appStorage.lastLanguages.target.takeIf { isSupportedTargetLanguage(it) } ?: primaryLanguage } } override fun updateLastLanguages(srcLang: Lang, targetLang: Lang) { with(appStorage.lastLanguages) { source = srcLang target = targetLang } } override fun translate(text: String, srcLang: Lang, targetLang: Lang) { val request = Presenter.Request(text, srcLang, targetLang, translateService.translator.id) if (text.isBlank() || request == currentRequest) { return } TextToSpeech.stop() currentRequest = request if (recordHistory) { appStorage.addHistory(text) } getCache(text, srcLang, targetLang)?.let { cache -> onPostResult(request) { showTranslation(request, cache, true) } return } view.showStartTranslate(request, text) translateService.translate(text, srcLang, targetLang, ResultListener(this, request)) } private inline fun onPostResult(request: Presenter.Request, block: View.() -> Unit) { if (request == currentRequest && !view.disposed) { view.block() currentRequest = null } } private class ResultListener(presenter: TranslationPresenter, val request: Presenter.Request) : TranslateListener { private val presenterRef: WeakReference<TranslationPresenter> = WeakReference(presenter) override fun onSuccess(translation: Translation) { val presenter = presenterRef.get() if (presenter !== null) { presenter.onPostResult(request) { showTranslation(request, translation, false) } } else { LOGGER.w("We lost the presenter!") } } override fun onError(throwable: Throwable) { val presenter = presenterRef.get() if (presenter !== null) { presenter.onPostResult(request) { showError(request, throwable) } } else { LOGGER.w("We lost the presenter!") } } } companion object { private val LOGGER = Logger.getInstance(TranslationPresenter::class.java) } }
mit
f84091994e92d3185b81765a10a3a3c1
36.034783
119
0.673632
5.0047
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/monitorstorage/MonitorStorageImplV1.kt
1
17126
// // Calendar Notifications Plus // Copyright (C) 2017 Sergey Parshin ([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, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.monitorstorage import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteDatabase import com.github.quarck.calnotify.calendar.MonitorEventAlertEntry import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.utils.detailed //import com.github.quarck.calnotify.logs.Logger class MonitorStorageImplV1(val context: Context) : MonitorStorageImplInterface { override fun createDb(db: SQLiteDatabase) { val CREATE_PKG_TABLE = "CREATE " + "TABLE $TABLE_NAME " + "( " + "$KEY_CALENDAR_ID INTEGER, " + "$KEY_EVENTID INTEGER, " + "$KEY_ALERT_TIME INTEGER, " + "$KEY_INSTANCE_START INTEGER, " + "$KEY_INSTANCE_END INTEGER, " + "$KEY_ALL_DAY INTEGER, " + "$KEY_WE_CREATED_ALERT INTEGER, " + "$KEY_WAS_HANDLED INTEGER, " + "$KEY_RESERVED_INT1 INTEGER, " + "$KEY_RESERVED_INT2 INTEGER, " + "PRIMARY KEY ($KEY_EVENTID, $KEY_ALERT_TIME, $KEY_INSTANCE_START)" + " )" DevLog.debug(LOG_TAG, "Creating DB TABLE using query: " + CREATE_PKG_TABLE) db.execSQL(CREATE_PKG_TABLE) val CREATE_INDEX = "CREATE UNIQUE INDEX $INDEX_NAME ON $TABLE_NAME ($KEY_EVENTID, $KEY_ALERT_TIME, $KEY_INSTANCE_START)" DevLog.debug(LOG_TAG, "Creating DB INDEX using query: " + CREATE_INDEX) db.execSQL(CREATE_INDEX) } override fun addAlert(db: SQLiteDatabase, entry: MonitorEventAlertEntry) { //DevLog.debug(LOG_TAG, "addAlert $entry") val values = recordToContentValues(entry) try { db.insertOrThrow(TABLE_NAME, // table null, // nullColumnHack values) // key/value -> keys = column names/ values = column // values } catch (ex: SQLiteConstraintException) { DevLog.debug(LOG_TAG, "This entry (${entry.eventId} / ${entry.alertTime}) is already in the DB!, updating instead") updateAlert(db, entry) } catch (ex: Exception) { DevLog.error(LOG_TAG, "addAlert($entry): exception ${ex.detailed}") } } override fun addAlerts(db: SQLiteDatabase, entries: Collection<MonitorEventAlertEntry>) { try { db.beginTransaction() for (entry in entries) addAlert(db, entry) db.setTransactionSuccessful() } finally { db.endTransaction() } } override fun deleteAlert(db: SQLiteDatabase, eventId: Long, alertTime: Long, instanceStart: Long) { //DevLog.debug(LOG_TAG, "deleteAlert $eventId / $alertTime") try { db.delete( TABLE_NAME, "$KEY_EVENTID = ? AND $KEY_ALERT_TIME = ? AND $KEY_INSTANCE_START = ?", arrayOf(eventId.toString(), alertTime.toString(), instanceStart.toString())) } catch (ex: Exception) { DevLog.error(LOG_TAG, "deleteAlert($eventId, $alertTime): exception ${ex.detailed}") } } override fun deleteAlerts(db: SQLiteDatabase, entries: Collection<MonitorEventAlertEntry>) { try { db.beginTransaction() for (entry in entries) deleteAlert(db, entry.eventId, entry.alertTime, entry.instanceStartTime) db.setTransactionSuccessful() } finally { db.endTransaction() } } override fun deleteAlertsMatching(db: SQLiteDatabase, filter: (MonitorEventAlertEntry) -> Boolean) { try { val alerts = getAlerts(db) db.beginTransaction() for (alert in alerts) { if (filter(alert)) deleteAlert(db, alert.eventId, alert.alertTime, alert.instanceStartTime) } db.setTransactionSuccessful() } catch (ex: Exception) { DevLog.error(LOG_TAG, "deleteAlertsMatching: exception ${ex.detailed}") } finally { db.endTransaction() } } override fun updateAlert(db: SQLiteDatabase, entry: MonitorEventAlertEntry) { val values = recordToContentValues(entry) //DevLog.debug(LOG_TAG, "Updating alert entry, eventId=${entry.eventId}, alertTime =${entry.alertTime}"); db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_ALERT_TIME = ? AND $KEY_INSTANCE_START = ?", arrayOf(entry.eventId.toString(), entry.alertTime.toString(), entry.instanceStartTime.toString())) } override fun updateAlerts(db: SQLiteDatabase, entries: Collection<MonitorEventAlertEntry>) { //DevLog.debug(LOG_TAG, "Updating ${entries.size} alerts"); try { db.beginTransaction() for (entry in entries) { //DevLog.debug(LOG_TAG, "Updating alert entry, eventId=${entry.eventId}, alertTime =${entry.alertTime}"); val values = recordToContentValues(entry) db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_ALERT_TIME = ? AND $KEY_INSTANCE_START = ?", arrayOf(entry.eventId.toString(), entry.alertTime.toString(), entry.instanceStartTime.toString())) } db.setTransactionSuccessful() } finally { db.endTransaction() } } override fun getAlert(db: SQLiteDatabase, eventId: Long, alertTime: Long, instanceStart: Long): MonitorEventAlertEntry? { var ret: MonitorEventAlertEntry? = null var cursor: Cursor? = null try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names "$KEY_EVENTID = ? AND $KEY_ALERT_TIME = ? AND $KEY_INSTANCE_START = ?", arrayOf(eventId.toString(), alertTime.toString(), instanceStart.toString()), null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { ret = cursorToRecord(cursor) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getAlert: exception $ex, stack: ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlert($eventId, $alertTime), returning ${ret}") return ret } override fun getNextAlert(db: SQLiteDatabase, since: Long): Long? { var ret: Long? = null; val query = "SELECT MIN($KEY_ALERT_TIME) FROM $TABLE_NAME WHERE $KEY_ALERT_TIME >= $since" var cursor: Cursor? = null try { cursor = db.rawQuery(query, null) if (cursor != null && cursor.moveToFirst()) ret = cursor.getLong(0) } catch (ex: Exception) { DevLog.error(LOG_TAG, "getNextAlert: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getNextAlert, returning $ret") return ret } override fun getAlertsAt(db: SQLiteDatabase, time: Long): List<MonitorEventAlertEntry> { val ret = arrayListOf<MonitorEventAlertEntry>() var cursor: Cursor? = null try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names "$KEY_ALERT_TIME = ?", arrayOf(time.toString()), null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { do { ret.add(cursorToRecord(cursor)) } while (cursor.moveToNext()) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getAlertsAt: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlertsAt($time), returning ${ret.size} requests") return ret } override fun getAlerts(db: SQLiteDatabase): List<MonitorEventAlertEntry> { val ret = arrayListOf<MonitorEventAlertEntry>() var cursor: Cursor? = null try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names null, // c. selections null, null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { do { ret.add(cursorToRecord(cursor)) } while (cursor.moveToNext()) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getAlertsAt: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlerts, returnint ${ret.size} requests") return ret } override fun getInstanceAlerts(db: SQLiteDatabase, eventId: Long, instanceStart: Long): List<MonitorEventAlertEntry> { val ret = arrayListOf<MonitorEventAlertEntry>() var cursor: Cursor? = null val selection = "$KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?" val selectionArgs = arrayOf(eventId.toString(), instanceStart.toString()) try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names selection, selectionArgs, null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { do { ret.add(cursorToRecord(cursor)) } while (cursor.moveToNext()) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getInstanceAlerts: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlerts, returnint ${ret.size} requests") return ret } override fun getAlertsForInstanceStartRange(db: SQLiteDatabase, scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> { val ret = arrayListOf<MonitorEventAlertEntry>() var cursor: Cursor? = null val selection = "$KEY_INSTANCE_START >= ? AND $KEY_INSTANCE_START <= ?" val selectionArgs = arrayOf(scanFrom.toString(), scanTo.toString()) try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names selection, selectionArgs, null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { do { ret.add(cursorToRecord(cursor)) } while (cursor.moveToNext()) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getAlertsAt: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlerts, returnint ${ret.size} requests") return ret } override fun getAlertsForAlertRange(db: SQLiteDatabase, scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> { val ret = arrayListOf<MonitorEventAlertEntry>() var cursor: Cursor? = null val selection = "$KEY_ALERT_TIME >= ? AND $KEY_ALERT_TIME <= ?" val selectionArgs = arrayOf(scanFrom.toString(), scanTo.toString()) try { cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names selection, selectionArgs, null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor != null && cursor.moveToFirst()) { do { ret.add(cursorToRecord(cursor)) } while (cursor.moveToNext()) } } catch (ex: Exception) { DevLog.error(LOG_TAG, "getAlertsAt: exception ${ex.detailed}") } finally { cursor?.close() } //DevLog.debug(LOG_TAG, "getAlerts, returnint ${ret.size} requests") return ret } private fun recordToContentValues(entry: MonitorEventAlertEntry): ContentValues { val values = ContentValues(); values.put(KEY_CALENDAR_ID, -1) values.put(KEY_EVENTID, entry.eventId); values.put(KEY_ALERT_TIME, entry.alertTime) values.put(KEY_INSTANCE_START, entry.instanceStartTime); values.put(KEY_INSTANCE_END, entry.instanceEndTime); values.put(KEY_ALL_DAY, if (entry.isAllDay) 1 else 0) values.put(KEY_WE_CREATED_ALERT, if (entry.alertCreatedByUs) 1 else 0) values.put(KEY_WAS_HANDLED, if (entry.wasHandled) 1 else 0) // Fill reserved keys with some placeholders values.put(KEY_RESERVED_INT1, 0L) values.put(KEY_RESERVED_INT2, 0L) return values; } private fun cursorToRecord(cursor: Cursor): MonitorEventAlertEntry { return MonitorEventAlertEntry( eventId = cursor.getLong(PROJECTION_KEY_EVENTID), alertTime = cursor.getLong(PROJECTION_KEY_ALERT_TIME), instanceStartTime = cursor.getLong(PROJECTION_KEY_INSTANCE_START), instanceEndTime = cursor.getLong(PROJECTION_KEY_INSTANCE_END), isAllDay = cursor.getInt(PROJECTION_KEY_ALL_DAY) != 0, alertCreatedByUs = cursor.getInt(PROJECTION_KEY_WE_CREATED_ALERT) != 0, wasHandled = cursor.getInt(PROJECTION_KEY_WAS_HANDLED) != 0 ) } companion object { private const val LOG_TAG = "MonitorStorageImplV1" private const val TABLE_NAME = "manualAlertsV1" private const val INDEX_NAME = "manualAlertsV1IdxV1" private const val KEY_CALENDAR_ID = "calendarId" private const val KEY_EVENTID = "eventId" private const val KEY_ALL_DAY = "allDay" private const val KEY_ALERT_TIME = "alertTime" private const val KEY_INSTANCE_START = "instanceStart" private const val KEY_INSTANCE_END = "instanceEnd" private const val KEY_WE_CREATED_ALERT = "alertCreatedByUs" private const val KEY_WAS_HANDLED = "wasHandled" private const val KEY_RESERVED_INT1 = "i1" private const val KEY_RESERVED_INT2 = "i2" private val SELECT_COLUMNS = arrayOf<String>( KEY_CALENDAR_ID, KEY_EVENTID, KEY_ALERT_TIME, KEY_INSTANCE_START, KEY_INSTANCE_END, KEY_ALL_DAY, KEY_WE_CREATED_ALERT, KEY_WAS_HANDLED ) const val PROJECTION_KEY_CALENDAR_ID = 0; const val PROJECTION_KEY_EVENTID = 1; const val PROJECTION_KEY_ALERT_TIME = 2; const val PROJECTION_KEY_INSTANCE_START = 3; const val PROJECTION_KEY_INSTANCE_END = 4; const val PROJECTION_KEY_ALL_DAY = 5; const val PROJECTION_KEY_WE_CREATED_ALERT = 6; const val PROJECTION_KEY_WAS_HANDLED = 7; } }
gpl-3.0
0914cbbf1c41e62014c38e4e1cfa7f03
32.847826
129
0.551267
4.491477
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/discord/EmojiCommand.kt
1
3728
package net.perfectdreams.loritta.morenitta.commands.vanilla.discord import com.github.kevinsawicki.http.HttpRequest import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.ImageUtils import net.perfectdreams.loritta.morenitta.utils.LorittaUtils import net.perfectdreams.loritta.morenitta.utils.isValidSnowflake import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.dv8tion.jda.api.entities.emoji.CustomEmoji import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.utils.Emotes import net.perfectdreams.loritta.morenitta.LorittaBot class EmojiCommand(loritta: LorittaBot) : AbstractCommand(loritta, "emoji", category = net.perfectdreams.loritta.common.commands.CommandCategory.DISCORD) { override fun getDescriptionKey() = LocaleKeyData("commands.command.emoji.description") // TODO: Fix Usage override fun getExamples(): List<String> { return listOf("😏") } override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { if (context.args.size == 1) { val arg0 = context.rawArgs[0] val firstEmote = context.message.mentions.customEmojis.firstOrNull() if (arg0 == firstEmote?.asMention) { // Emoji do Discord (via menção) downloadAndSendDiscordEmote(context, firstEmote) return } if (arg0.isValidSnowflake()) { val emote = loritta.lorittaShards.getEmoteById(arg0) if (emote != null) { // Emoji do Discord (via ID) downloadAndSendDiscordEmote(context, emote) return } else { context.reply( LorittaReply( locale["commands.command.emoji.notFoundId", "`$arg0`"], Constants.ERROR ) ) return } } val guild = context.guild val foundEmote = guild.getEmojisByName(arg0, true).firstOrNull() if (foundEmote != null) { // Emoji do Discord (via nome) downloadAndSendDiscordEmote(context, foundEmote) return } val isUnicodeEmoji = Constants.EMOJI_PATTERN.matcher(arg0).find() if (isUnicodeEmoji) { val value = ImageUtils.getTwitterEmojiUrlId(arg0) try { if (HttpRequest.get("https://twemoji.maxcdn.com/2/72x72/$value.png").code() != 200) { context.reply( LorittaReply( context.locale["commands.command.emoji.errorWhileDownloadingEmoji", Emotes.LORI_SHRUG], Constants.ERROR ) ) return } val emojiImage = LorittaUtils.downloadImage(loritta, "https://twemoji.maxcdn.com/2/72x72/$value.png") context.sendFile(emojiImage!!, "emoji.png", " ") } catch (e: Exception) { e.printStackTrace() } } else { context.explain() } } else { context.explain() } } suspend fun downloadAndSendDiscordEmote(context: CommandContext, emote: CustomEmoji) { val emojiUrl = emote.imageUrl try { val emojiImage = LorittaUtils.downloadFile(loritta, "$emojiUrl?size=2048", 5000) var fileName = emote.name if (emote.isAnimated) { fileName += ".gif" } else { fileName += ".png" } context.sendFile(emojiImage!!, fileName, MessageCreateBuilder().addContent(" ")) } catch (e: Exception) { e.printStackTrace() } } }
agpl-3.0
51a32314fdcbe5c7311abafbf2504e25
33.165138
155
0.68144
3.918947
false
false
false
false
vanniktech/Emoji
emoji-google/src/commonMain/kotlin/com/vanniktech/emoji/google/GoogleEmoji.kt
1
2397
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.google import com.vanniktech.emoji.Emoji import com.vanniktech.emoji.IgnoredOnParcel import com.vanniktech.emoji.Parcelable import com.vanniktech.emoji.Parcelize @Parcelize internal class GoogleEmoji internal constructor( override val unicode: String, override val shortcodes: List<String>, internal val x: Int, internal val y: Int, override val isDuplicate: Boolean, override val variants: List<GoogleEmoji> = emptyList(), private var parent: GoogleEmoji? = null, ) : Emoji, Parcelable { @IgnoredOnParcel override val base by lazy(LazyThreadSafetyMode.NONE) { var result = this while (result.parent != null) { result = result.parent!! } result } init { @Suppress("LeakingThis") for (variant in variants) { variant.parent = this } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GoogleEmoji if (unicode != other.unicode) return false if (shortcodes != other.shortcodes) return false if (x != other.x) return false if (y != other.y) return false if (isDuplicate != other.isDuplicate) return false if (variants != other.variants) return false return true } override fun hashCode(): Int { var result = unicode.hashCode() result = 31 * result + shortcodes.hashCode() result = 31 * result + x result = 31 * result + y result = 31 * result + isDuplicate.hashCode() result = 31 * result + variants.hashCode() return result } override fun toString(): String { return "GoogleEmoji(unicode='$unicode', shortcodes=$shortcodes, x=$x, y=$y, isDuplicate=$isDuplicate, variants=$variants)" } }
apache-2.0
00b6a9d6829bb69150745ed324a942c2
30.103896
126
0.699791
4.231449
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/fragment/ProfileActivityDetailsFragment.kt
1
8784
package com.newsblur.fragment import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemClickListener import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.newsblur.R import com.newsblur.activity.Profile import com.newsblur.database.BlurDatabaseHelper import com.newsblur.databinding.FragmentProfileactivityBinding import com.newsblur.databinding.RowLoadingThrobberBinding import com.newsblur.di.IconLoader import com.newsblur.domain.ActivityDetails import com.newsblur.domain.UserDetails import com.newsblur.network.APIManager import com.newsblur.util.* import com.newsblur.view.ActivityDetailsAdapter import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint abstract class ProfileActivityDetailsFragment : Fragment(), OnItemClickListener { @Inject lateinit var apiManager: APIManager @Inject lateinit var dbHelper: BlurDatabaseHelper @Inject @IconLoader lateinit var iconLoader: ImageLoader private lateinit var binding: FragmentProfileactivityBinding private lateinit var footerBinding: RowLoadingThrobberBinding private var adapter: ActivityDetailsAdapter? = null private var user: UserDetails? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_profileactivity, null) binding = FragmentProfileactivityBinding.bind(view) val colorsArray = intArrayOf(ContextCompat.getColor(requireContext(), R.color.refresh_1), ContextCompat.getColor(requireContext(), R.color.refresh_2), ContextCompat.getColor(requireContext(), R.color.refresh_3), ContextCompat.getColor(requireContext(), R.color.refresh_4)) binding.emptyViewLoadingThrob.setColors(*colorsArray) binding.profileDetailsActivitylist.setFooterDividersEnabled(false) binding.profileDetailsActivitylist.emptyView = binding.emptyView val footerView = inflater.inflate(R.layout.row_loading_throbber, null) footerBinding = RowLoadingThrobberBinding.bind(footerView) footerBinding.itemlistLoadingThrob.setColors(*colorsArray) binding.profileDetailsActivitylist.addFooterView(footerView, null, false) if (adapter != null) { displayActivities() } binding.profileDetailsActivitylist.setOnScrollListener(EndlessScrollListener()) binding.profileDetailsActivitylist.onItemClickListener = this return view } fun setUser(context: Context?, user: UserDetails?, iconLoader: ImageLoader) { this.user = user adapter = createAdapter(context, user, iconLoader) displayActivities() } protected abstract fun createAdapter(context: Context?, user: UserDetails?, iconLoader: ImageLoader): ActivityDetailsAdapter? private fun displayActivities() { binding.profileDetailsActivitylist.adapter = adapter loadPage(1) } private fun loadPage(pageNumber: Int) { lifecycleScope.executeAsyncTask( onPreExecute = { binding.emptyViewLoadingThrob.visibility = View.VISIBLE footerBinding.itemlistLoadingThrob.visibility = View.VISIBLE }, doInBackground = { // For the logged in user user.userId is null. // From the user intent user.userId is the number while user.id is prefixed with social: var id = user!!.userId if (id == null) { id = user!!.id } id?.let { loadActivityDetails(it, pageNumber) } }, onPostExecute = { if (it == null) { Log.w(javaClass.name, "couldn't load page from API") return@executeAsyncTask } if (pageNumber == 1 && it.isEmpty()) { val emptyView = binding.profileDetailsActivitylist.emptyView val textView = emptyView.findViewById<View>(R.id.empty_view_text) as TextView textView.setText(R.string.profile_no_interactions) } for (activity in it) { adapter!!.add(activity) } adapter!!.notifyDataSetChanged() binding.emptyViewLoadingThrob.visibility = View.GONE footerBinding.itemlistLoadingThrob.visibility = View.GONE } ) } protected abstract fun loadActivityDetails(id: String?, pageNumber: Int): Array<ActivityDetails>? override fun onItemClick(adapterView: AdapterView<*>?, view: View, position: Int, id: Long) { val activity = adapter!!.getItem(position) val context: Context = requireContext() if (activity!!.category == ActivityDetails.Category.FOLLOW) { val i = Intent(context, Profile::class.java) i.putExtra(Profile.USER_ID, activity.withUserId) context.startActivity(i) } else if (activity.category == ActivityDetails.Category.FEED_SUBSCRIPTION) { val feed = dbHelper.getFeed(activity.feedId) if (feed == null) { Toast.makeText(context, R.string.profile_feed_not_available, Toast.LENGTH_SHORT).show() } else { /* TODO: starting the feed view activity also requires both a feedset and a folder name in order to properly function. the latter, in particular, we could only guess at from the info we have here. at best, we would launch a feed view with somewhat unpredictable delete behaviour. */ //Intent intent = new Intent(context, FeedItemsList.class); //intent.putExtra(FeedItemsList.EXTRA_FEED, feed); //context.startActivity(intent); } } else if (activity.category == ActivityDetails.Category.STAR) { UIUtils.startReadingActivity(FeedSet.allSaved(), activity.storyHash, context) } else if (isSocialFeedCategory(activity)) { // Strip the social: prefix from feedId val socialFeedId = activity.feedId.substring(7) val feed = dbHelper.getSocialFeed(socialFeedId) if (feed == null) { Toast.makeText(context, R.string.profile_do_not_follow, Toast.LENGTH_SHORT).show() } else { UIUtils.startReadingActivity(FeedSet.singleSocialFeed(feed.userId, feed.username), activity.storyHash, context) } } } private fun isSocialFeedCategory(activity: ActivityDetails): Boolean { return activity.storyHash != null && (activity.category == ActivityDetails.Category.COMMENT_LIKE || activity.category == ActivityDetails.Category.COMMENT_REPLY || activity.category == ActivityDetails.Category.REPLY_REPLY || activity.category == ActivityDetails.Category.SHARED_STORY) } /** * Detects when user is close to the end of the current page and starts loading the next page * so the user will not have to wait (that much) for the next entries. * * @author Ognyan Bankov * * * https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_NetworkListView.java */ inner class EndlessScrollListener : AbsListView.OnScrollListener { // how many entries earlier to start loading next page private val visibleThreshold = 5 private var currentPage = 1 private var previousTotal = 0 private var loading = true override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { if (loading) { if (totalItemCount > previousTotal) { loading = false previousTotal = totalItemCount currentPage++ } } if (!loading && totalItemCount - visibleItemCount <= firstVisibleItem + visibleThreshold) { // I load the next page of gigs using a background task, // but you can call any function here. loadPage(currentPage) loading = true } } override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {} } }
mit
d479e28e1ca918a3cef2608f8c6bfbcf
44.994764
291
0.651867
5.065744
false
false
false
false
yole/jkid
src/main/kotlin/deserialization/ClassInfoCache.kt
2
3545
package ru.yole.jkid.deserialization import ru.yole.jkid.* import ru.yole.jkid.serialization.getSerializer import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.primaryConstructor import kotlin.reflect.jvm.javaType class ClassInfoCache { private val cacheData = mutableMapOf<KClass<*>, ClassInfo<*>>() @Suppress("UNCHECKED_CAST") operator fun <T : Any> get(cls: KClass<T>): ClassInfo<T> = cacheData.getOrPut(cls) { ClassInfo(cls) } as ClassInfo<T> } class ClassInfo<T : Any>(cls: KClass<T>) { private val className = cls.qualifiedName private val constructor = cls.primaryConstructor ?: throw JKidException("Class ${cls.qualifiedName} doesn't have a primary constructor") private val jsonNameToParamMap = hashMapOf<String, KParameter>() private val paramToSerializerMap = hashMapOf<KParameter, ValueSerializer<out Any?>>() private val jsonNameToDeserializeClassMap = hashMapOf<String, Class<out Any>?>() init { constructor.parameters.forEach { cacheDataForParameter(cls, it) } } private fun cacheDataForParameter(cls: KClass<*>, param: KParameter) { val paramName = param.name ?: throw JKidException("Class $className has constructor parameter without name") val property = cls.declaredMemberProperties.find { it.name == paramName } ?: return val name = property.findAnnotation<JsonName>()?.name ?: paramName jsonNameToParamMap[name] = param val deserializeClass = property.findAnnotation<DeserializeInterface>()?.targetClass?.java jsonNameToDeserializeClassMap[name] = deserializeClass val valueSerializer = property.getSerializer() ?: serializerForType(param.type.javaType) ?: return paramToSerializerMap[param] = valueSerializer } fun getConstructorParameter(propertyName: String): KParameter = jsonNameToParamMap[propertyName] ?: throw JKidException("Constructor parameter $propertyName is not found for class $className") fun getDeserializeClass(propertyName: String) = jsonNameToDeserializeClassMap[propertyName] fun deserializeConstructorArgument(param: KParameter, value: Any?): Any? { val serializer = paramToSerializerMap[param] if (serializer != null) return serializer.fromJsonValue(value) validateArgumentType(param, value) return value } private fun validateArgumentType(param: KParameter, value: Any?) { if (value == null && !param.type.isMarkedNullable) { throw JKidException("Received null value for non-null parameter ${param.name}") } if (value != null && value.javaClass != param.type.javaType) { throw JKidException("Type mismatch for parameter ${param.name}: " + "expected ${param.type.javaType}, found ${value.javaClass}") } } fun createInstance(arguments: Map<KParameter, Any?>): T { ensureAllParametersPresent(arguments) return constructor.callBy(arguments) } private fun ensureAllParametersPresent(arguments: Map<KParameter, Any?>) { for (param in constructor.parameters) { if (arguments[param] == null && !param.isOptional && !param.type.isMarkedNullable) { throw JKidException("Missing value for parameter ${param.name}") } } } } class JKidException(message: String) : Exception(message)
apache-2.0
9762112300ac9172e84df7659dc21499
40.22093
107
0.692243
4.784076
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/gettingstartedsolution/VerticalSpeller.kt
1
1722
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.gettingstartedsolution import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Style import com.facebook.litho.core.margin import com.facebook.litho.dp import com.facebook.litho.flexbox.flex import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.widget.collection.LazyList /** * Components which consists in a vertical list with all characters from the given sentence. * * @property text the sentence to be displayed vertically */ class VerticalSpeller(private val text: String) : KComponent() { override fun ComponentScope.render(): Component { return LazyList(style = Style.flex(grow = 1f)) { child(Text(text = "Spelling of $text")) // Using index as id is recommended here as we may have the same character twice in the text text.forEachIndexed { index, character -> child( id = index, component = Text(style = Style.margin(horizontal = 16.dp), text = character.toString())) } } } }
apache-2.0
99dcdad8378c4e49fcfe4d96a327e496
36.434783
100
0.73403
4.149398
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/theme/color/ColorTokens.kt
1
6054
package app.lawnchair.theme.color import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import app.lawnchair.preferences.PreferenceManager @Suppress("MemberVisibilityCanBePrivate", "unused") object ColorTokens { val Neutral1_0 = SwatchColorToken(Swatch.Neutral1, Shade.S0) val Neutral1_10 = SwatchColorToken(Swatch.Neutral1, Shade.S10) val Neutral1_50 = SwatchColorToken(Swatch.Neutral1, Shade.S50) val Neutral1_100 = SwatchColorToken(Swatch.Neutral1, Shade.S100) val Neutral1_200 = SwatchColorToken(Swatch.Neutral1, Shade.S200) val Neutral1_400 = SwatchColorToken(Swatch.Neutral1, Shade.S400) val Neutral1_500 = SwatchColorToken(Swatch.Neutral1, Shade.S500) val Neutral1_700 = SwatchColorToken(Swatch.Neutral1, Shade.S700) val Neutral1_800 = SwatchColorToken(Swatch.Neutral1, Shade.S800) val Neutral1_900 = SwatchColorToken(Swatch.Neutral1, Shade.S900) val Neutral2_50 = SwatchColorToken(Swatch.Neutral2, Shade.S50) val Neutral2_100 = SwatchColorToken(Swatch.Neutral2, Shade.S100) val Neutral2_200 = SwatchColorToken(Swatch.Neutral2, Shade.S200) val Neutral2_300 = SwatchColorToken(Swatch.Neutral2, Shade.S300) val Neutral2_500 = SwatchColorToken(Swatch.Neutral2, Shade.S500) val Neutral2_700 = SwatchColorToken(Swatch.Neutral2, Shade.S700) val Neutral2_800 = SwatchColorToken(Swatch.Neutral2, Shade.S800) val Accent1_50 = SwatchColorToken(Swatch.Accent1, Shade.S50) val Accent1_100 = SwatchColorToken(Swatch.Accent1, Shade.S100) val Accent1_200 = SwatchColorToken(Swatch.Accent1, Shade.S200) val Accent1_300 = SwatchColorToken(Swatch.Accent1, Shade.S300) val Accent1_500 = SwatchColorToken(Swatch.Accent1, Shade.S500) val Accent1_600 = SwatchColorToken(Swatch.Accent1, Shade.S600) val Accent2_50 = SwatchColorToken(Swatch.Accent2, Shade.S50) val Accent2_100 = SwatchColorToken(Swatch.Accent2, Shade.S100) val Accent2_500 = SwatchColorToken(Swatch.Accent2, Shade.S500) val Accent2_600 = SwatchColorToken(Swatch.Accent2, Shade.S600) val Accent3_50 = SwatchColorToken(Swatch.Accent3, Shade.S50) val Accent3_100 = SwatchColorToken(Swatch.Accent3, Shade.S100) val SurfaceLight = Neutral1_500.setLStar(98.0) val SurfaceDark = Neutral1_800 @JvmField val Surface = DayNightColorToken(SurfaceLight, SurfaceDark) val SurfaceVariantLight = Neutral2_100 val SurfaceVariantDark = Neutral1_700 @JvmField val ColorAccent = DayNightColorToken(Accent1_600, Accent1_100) @JvmField val ColorBackground = DayNightColorToken(Neutral1_50, Neutral1_900) @JvmField val ColorBackgroundFloating = DayNightColorToken(Neutral1_50, Neutral1_900) @JvmField val ColorPrimary = DayNightColorToken(Neutral1_50, Neutral1_900) @JvmField val TextColorPrimary = DayNightColorToken(Neutral1_900, Neutral1_50) @JvmField val TextColorPrimaryInverse = TextColorPrimary.inverse() @JvmField val TextColorSecondary = DayNightColorToken(StaticColorToken(0xde000000), Neutral2_200) @JvmField val AllAppsHeaderProtectionColor = DayNightColorToken(Neutral1_100, Neutral1_700) @JvmField val AllAppsScrimColor = ColorBackground @JvmField val AllAppsTabBackgroundSelected = DayNightColorToken(Accent1_100, Accent2_100) @JvmField val FocusHighlight = DayNightColorToken(Neutral1_0, Neutral1_700) @JvmField val GroupHighlight = Surface @JvmField val OverviewScrim = DayNightColorToken(Neutral2_500.setLStar(87.0), Neutral1_800) .withPreferences { prefs -> val translucent = prefs.recentsTranslucentBackground.get() if (translucent) setAlpha(0.8f) else this } @JvmField val SearchboxHighlight = DayNightColorToken(SurfaceVariantLight, Neutral1_800) @JvmField val FolderDotColor = Accent3_100 @JvmField val FolderBackgroundColor = DayNightColorToken(Neutral1_50.setLStar(98.0), Neutral2_50.setLStar(30.0)) @JvmField val FolderIconBorderColor = ColorPrimary @JvmField val FolderPaginationColor = DayNightColorToken(Accent1_600, Accent2_100) @JvmField val FolderPreviewColor = DayNightColorToken(Accent2_50.setLStar(80.0), Accent2_50.setLStar(30.0)) @JvmField val PopupColorPrimary = DayNightColorToken(Accent2_50, Neutral2_800) @JvmField val PopupColorSecondary = DayNightColorToken(Neutral2_100, Neutral1_900) @JvmField val PopupColorTertiary = DayNightColorToken(Neutral2_300, Neutral2_700) @JvmField val PopupShadeFirst = DayNightColorToken(PopupColorPrimary.setLStar(98.0), PopupColorPrimary.setLStar(20.0)) @JvmField val PopupShadeSecond = DayNightColorToken(PopupColorPrimary.setLStar(95.0), PopupColorPrimary.setLStar(15.0)) @JvmField val PopupShadeThird = DayNightColorToken(PopupColorPrimary.setLStar(90.0), PopupColorPrimary.setLStar(10.0)) @JvmField val QsbIconTintPrimary = DayNightColorToken(Accent3_50.setLStar(48.0), Accent3_100) @JvmField val QsbIconTintSecondary = DayNightColorToken(Accent1_50.setLStar(40.0), Accent1_300) @JvmField val QsbIconTintTertiary = DayNightColorToken(Accent2_50.setLStar(48.0), Accent2_50.setLStar(98.0)) @JvmField val QsbIconTintQuaternary = DayNightColorToken(Accent1_50.setLStar(35.0), Accent1_100) @JvmField val WallpaperPopupScrim = Neutral1_900 @JvmField val WidgetsPickerScrim = DayNightColorToken(Neutral1_200, Neutral1_900).setAlpha(0.8f) @JvmField val WorkspaceAccentColor = DarkTextColorToken(Accent1_100, Accent2_600) val SwitchThumbOn = Accent1_100 val SwitchThumbOff = DayNightColorToken(Neutral2_300, Neutral1_400) val SwitchThumbDisabled = DayNightColorToken(Neutral2_100, Neutral1_700) val SwitchTrackOn = DayNightColorToken(Accent1_600, Accent2_500.setLStar(51.0)) val SwitchTrackOff = DayNightColorToken(Neutral2_500.setLStar(45.0), Neutral1_700) } @Composable fun colorToken(token: ColorToken): Color { val context = LocalContext.current val intColor = token.resolveColor(context) return Color(intColor) }
gpl-3.0
0d792166d13e41df270cb4ce43336d77
54.036364
123
0.776511
3.337376
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/debug/SamplesScreen.kt
1
2793
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.ui.debug import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.Text import androidx.wear.compose.material.items import com.google.android.horologist.compose.focus.RequestFocusWhenActive import com.google.android.horologist.compose.rotaryinput.rotaryWithFling import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToPlayer import com.google.android.horologist.mediasample.R import com.google.android.horologist.mediasample.ui.settings.ActionSetting @Composable fun SamplesScreen( state: ScalingLazyListState, samplesScreenViewModel: SamplesScreenViewModel, navController: NavHostController, modifier: Modifier = Modifier ) { val uiState by samplesScreenViewModel.uiState.collectAsStateWithLifecycle() val focusRequester = remember { FocusRequester() } ScalingLazyColumn( modifier = modifier .fillMaxSize() .rotaryWithFling(focusRequester, state), state = state ) { item { Text( text = stringResource(id = R.string.sample_samples), modifier = Modifier.padding(bottom = 12.dp), style = MaterialTheme.typography.title3 ) } items(uiState.samples) { ActionSetting(text = it.name) { samplesScreenViewModel.playSamples(it.id) navController.navigateToPlayer() } } } RequestFocusWhenActive(focusRequester) }
apache-2.0
a6ac9dae8771f77a43f2d70e17b71115
36.743243
92
0.752238
4.717905
false
false
false
false
Ekito/koin
koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/ext/android/ViewModelStoreOwnerExt.kt
1
2391
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.androidx.viewmodel.ext.android import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelStoreOwner import org.koin.androidx.viewmodel.ViewModelOwner.Companion.from import org.koin.androidx.viewmodel.koin.getViewModel import org.koin.androidx.viewmodel.scope.BundleDefinition import org.koin.core.context.GlobalContext import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import kotlin.reflect.KClass /** * ViewModelStoreOwner extensions to help for ViewModel * * @author Arnaud Giuliani */ inline fun <reified T : ViewModel> ViewModelStoreOwner.viewModel( qualifier: Qualifier? = null, noinline state: BundleDefinition? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getViewModel<T>(qualifier, state, parameters) } } fun <T : ViewModel> ViewModelStoreOwner.viewModel( qualifier: Qualifier? = null, state: BundleDefinition? = null, clazz: KClass<T>, parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getViewModel(qualifier, state, clazz, parameters) } } inline fun <reified T : ViewModel> ViewModelStoreOwner.getViewModel( qualifier: Qualifier? = null, noinline state: BundleDefinition? = null, noinline parameters: ParametersDefinition? = null ): T { return getViewModel(qualifier, state, T::class, parameters) } fun <T : ViewModel> ViewModelStoreOwner.getViewModel( qualifier: Qualifier? = null, state: BundleDefinition? = null, clazz: KClass<T>, parameters: ParametersDefinition? = null ): T { return GlobalContext.get().getViewModel(qualifier, state, { from(this, null) }, clazz, parameters) }
apache-2.0
91ad1fb10708a28f3b6ff9ac2ad914c9
34.701493
102
0.750732
4.355191
false
false
false
false